Add error logging and corresponding tests for parser syntax errors

This commit is contained in:
2026-04-25 14:37:08 +02:00
parent 7c7e0c3272
commit 91593e12b7
8 changed files with 70 additions and 15 deletions
+18 -9
View File
@@ -1,25 +1,32 @@
#include "parser.h"
#include "log.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
Module* parser_parse(TokenStream* ts) {
Token t = tokenstream_next(ts);
if (t.token != TOKEN_MODULE) {
log_on_line(&t.location, t.location.column_end, "expected 'module' keyword");
return NULL;
}
t = tokenstream_next(ts);
if (t.token != TOKEN_IDENTIFIER) {
log_on_line(&t.location, t.location.column_end, "expected module name");
return NULL;
}
Module* module = (Module*)malloc(sizeof(Module));
if (module == NULL) return NULL;
if (module == NULL) {
fprintf(stderr, "Out of memory\n");
exit(1);
}
module->name = (char*)malloc(t.text.length + 1);
if (module->name == NULL) {
free(module);
return NULL;
fprintf(stderr, "Out of memory\n");
exit(1);
}
memcpy(module->name, t.text.data, t.text.length);
@@ -27,8 +34,8 @@ Module* parser_parse(TokenStream* ts) {
t = tokenstream_next(ts);
if (t.token != TOKEN_SEMICOLON) {
free(module->name);
free(module);
log_on_line(&t.location, t.location.column_end, "expected ';' after module name");
parser_free(module);
return NULL;
}
@@ -43,21 +50,22 @@ Module* parser_parse(TokenStream* ts) {
ImportDeclaration* new_imports = realloc(module->imports, (module->import_count + 1) * sizeof(ImportDeclaration));
if (!new_imports) {
parser_free(module);
return NULL;
fprintf(stderr, "Out of memory\n");
exit(1);
}
module->imports = new_imports;
t = tokenstream_next(ts);
if (t.token != TOKEN_IDENTIFIER) {
log_on_line(&t.location, t.location.column_end, "expected module name to import");
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;
fprintf(stderr, "Out of memory\n");
exit(1);
}
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';
@@ -65,6 +73,7 @@ Module* parser_parse(TokenStream* ts) {
t = tokenstream_next(ts);
if (t.token != TOKEN_SEMICOLON) {
log_on_line(&t.location, t.location.column_end, "expected ';' after import");
parser_free(module);
return NULL;
}