#include "parser.h" #include #include Module* parser_parse(TokenStream* ts) { Token t = tokenstream_next(ts); if (t.token != TOKEN_MODULE) { return NULL; } t = tokenstream_next(ts); if (t.token != TOKEN_IDENTIFIER) { return NULL; } Module* module = (Module*)malloc(sizeof(Module)); if (module == NULL) return NULL; module->name = (char*)malloc(t.text.length + 1); if (module->name == NULL) { free(module); return NULL; } memcpy(module->name, t.text.data, t.text.length); module->name[t.text.length] = '\0'; t = tokenstream_next(ts); if (t.token != TOKEN_SEMICOLON) { free(module->name); free(module); return NULL; } module->imports = NULL; module->import_count = 0; while (1) { t = tokenstream_next(ts); if (t.token != TOKEN_IMPORT) { break; } ImportDeclaration* new_imports = realloc(module->imports, (module->import_count + 1) * sizeof(ImportDeclaration)); if (!new_imports) { parser_free(module); return NULL; } module->imports = new_imports; t = tokenstream_next(ts); if (t.token != TOKEN_IDENTIFIER) { parser_free(module); return NULL; } module->imports[module->import_count].module_name = (char*)malloc(t.text.length + 1); if (!module->imports[module->import_count].module_name) { parser_free(module); return NULL; } memcpy(module->imports[module->import_count].module_name, t.text.data, t.text.length); module->imports[module->import_count].module_name[t.text.length] = '\0'; module->import_count++; t = tokenstream_next(ts); if (t.token != TOKEN_SEMICOLON) { parser_free(module); return NULL; } } return module; } void parser_free(Module* module) { if (module == NULL) return; if (module->imports != NULL) { for (size_t i = 0; i < module->import_count; i++) { free(module->imports[i].module_name); } free(module->imports); } free(module->name); free(module); }