Browse Source

report lex errors

master
Martin Dørum 3 years ago
parent
commit
c82bc5349b
2 changed files with 30 additions and 7 deletions
  1. 1
    0
      include/lang2/parse/parse.h
  2. 29
    7
      lib/parse/error.c

+ 1
- 0
include/lang2/parse/parse.h View File

struct l2_parse_error { struct l2_parse_error {
int line; int line;
int ch; int ch;
int is_static;
char *message; char *message;
}; };



+ 29
- 7
lib/parse/error.c View File



void l2_parse_err(struct l2_parse_error *err, struct l2_token *tok, const char *fmt, ...) { void l2_parse_err(struct l2_parse_error *err, struct l2_token *tok, const char *fmt, ...) {
err->line = tok->line; err->line = tok->line;
err->is_static = 0;
err->ch = tok->ch; err->ch = tok->ch;
char buf[256];


if (tok->kind == L2_TOK_ERROR) {
l2_trace("Error token: %s", tok->v.str);
err->message = tok->v.str;
err->is_static = 1;
return;
}

char buf[256];
va_list va; va_list va;
va_start(va, fmt); va_start(va, fmt);
int n = vsnprintf(buf, sizeof(buf), fmt, va); int n = vsnprintf(buf, sizeof(buf), fmt, va);


if (n < 0) { if (n < 0) {
const char *message = "Failed to generate error message!";
err->message = malloc(strlen(message) + 1);
strcpy(err->message, message);
err->message = "Failed to generate error message!";
err->is_static = 1;
va_end(va); va_end(va);
l2_trace("Parse error: %s", err->message); l2_trace("Parse error: %s", err->message);
return; return;
} else if ((size_t)n + 1 < sizeof(buf)) { } else if ((size_t)n + 1 < sizeof(buf)) {
err->message = malloc(n + 1); err->message = malloc(n + 1);
strcpy(err->message, buf);
if (err->message == NULL) {
err->message = "Failed to allocate error message!";
err->is_static = 1;
} else {
strcpy(err->message, buf);
}

va_end(va); va_end(va);
l2_trace("Parse error: %s", err->message); l2_trace("Parse error: %s", err->message);
return; return;


// Need to allocate for this one // Need to allocate for this one
err->message = malloc(n + 1); err->message = malloc(n + 1);
vsnprintf(err->message, n + 1, fmt, va);
if (err->message == NULL) {
err->message = "Failed to allocate error message!";
err->is_static = 1;
} else {
vsnprintf(err->message, n + 1, fmt, va);
}

va_end(va); va_end(va);
l2_trace("Parse error: %s", err->message); l2_trace("Parse error: %s", err->message);
} }


void l2_parse_error_free(struct l2_parse_error *err) { void l2_parse_error_free(struct l2_parse_error *err) {
free(err->message);
if (!err->is_static) {
free(err->message);
}
} }

Loading…
Cancel
Save