From 328e34077a2017d4017f907ac69c7ed5d6c160d4 Mon Sep 17 00:00:00 2001 From: David Phillips Date: Wed, 1 Aug 2018 20:21:37 +1200 Subject: Trim leading whitespace from contextual error, detect EOF Side-note that the token location tuple maintains the correct column number to include the whitespace in the source file. Side-side note: tabs are counted as one column but many editors will count them as whatever the tabstop/tabwidth is. --- parser.c | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) (limited to 'parser.c') diff --git a/parser.c b/parser.c index 618df1a..f16af6c 100644 --- a/parser.c +++ b/parser.c @@ -14,9 +14,16 @@ static FILE* fd; static struct token *cursor; static const char *filename; -#define emit(...) fprintf(stderr, "%s at (%zd,%zd): ", filename, cursor->loc.line, cursor->loc.column);\ - fprintf(stderr, __VA_ARGS__);\ - indicate_file_area(fd, cursor->loc.line, cursor->loc.column, cursor->span) +/* FIXME change to varadic fuction */ +#define emit(...) \ + if (cursor) { \ + fprintf(stderr, "%s at (%zd,%zd): ", filename, cursor->loc.line, cursor->loc.column); \ + fprintf(stderr, __VA_ARGS__); \ + indicate_file_area(fd, cursor->loc.line, cursor->loc.column - cursor->loc.leading_whitespace_len, cursor->span); \ + } else { \ + fprintf(stderr, "%s: ", filename); \ + fprintf(stderr, __VA_ARGS__); \ + } //static struct op_lookup uop_handlers[] = { @@ -42,9 +49,13 @@ expect(enum TOKEN_TYPE e) { char *expected_desc = "(internal error)"; char *observed_desc = "(internal error)"; - if (cursor->type != e) { + if (!cursor || cursor->type != e) { expected_desc = get_token_description(e); - observed_desc = get_token_description(cursor->type); + if (cursor) { + observed_desc = get_token_description(cursor->type); + } else { + observed_desc = "end of file"; + } emit("Error: Expected %s, got %s\n", expected_desc, observed_desc); return 1; } @@ -54,7 +65,9 @@ expect(enum TOKEN_TYPE e) { static void kerchunk() { - cursor = cursor->next; + if (cursor) { + cursor = cursor->next; + } } int @@ -64,6 +77,11 @@ parse(const char *fname, FILE *f, struct token *t) { filename = fname; cursor = t; + /* Eat leading EOL tokens */ + while (cursor && cursor->type == TOK_EOL) { + kerchunk(); + } + if (expect(TOK_MODULE)) { return 1; } -- cgit v1.1