From 62451acdd4dd4cf369a801b0603e2e0841bfb627 Mon Sep 17 00:00:00 2001 From: Ian Moffett Date: Sat, 23 May 2026 08:49:17 -0400 Subject: core: lexer: Add preprocessor tokens Signed-off-by: Ian Moffett --- core/lexer.c | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++ core/parser.c | 3 +++ include/cescal/token.h | 3 +++ 3 files changed, 58 insertions(+) diff --git a/core/lexer.c b/core/lexer.c index 1a62e71..6c7a4c9 100644 --- a/core/lexer.c +++ b/core/lexer.c @@ -189,6 +189,45 @@ lexer_check_kw(struct cescal_state *state, struct token *res) } } +/* + * Check if an identifier token is actually a directive + * + * @state: Compiler state + * @res: Token result is written here + */ +static int +lexer_check_direc(struct cescal_state *state, struct token *res) +{ + if (state == NULL || res == NULL) { + errno = EINVAL; + return -1; + } + + switch (*res->s) { + case 'd': + if (strcmp(res->s, "define") == 0) { + res->type = TT_DEFINE; + return 0; + } + + break; + case 'i': + if (strcmp(res->s, "ifndef") == 0) { + res->type = TT_IFNDEF; + return 0; + } + + if (strcmp(res->s, "ifdef") == 0) { + res->type = TT_IFDEF; + return 0; + } + + break; + } + + return -1; +} + /* * Skip anything after a comment * @@ -236,6 +275,19 @@ lexer_nom(struct cescal_state *state, struct token *res) case ',': res->type = TT_COMMA; res->c = c; + return 0; + case '#': + if ((c = lexer_consume_single(state, true)) == '\0') { + return -1; + } + + if (lexer_scan_ident(state, c, res) == 0) { + if (lexer_check_direc(state, res) != 0) { + cc_error("bad directive '%s'\n", res->s); + return -1; + } + } + return 0; case '/': if (lexer_consume_single(state, true) == '/') { diff --git a/core/parser.c b/core/parser.c index 5d64bb7..684a1ff 100644 --- a/core/parser.c +++ b/core/parser.c @@ -38,6 +38,9 @@ static const char *toktab[] = { [TT_RPAREN] = qtok(")"), [TT_COMMA] = qtok(","), [TT_ARROW] = qtok("->"), + [TT_DEFINE] = qtok("#define"), + [TT_IFNDEF] = qtok("#ifndef"), + [TT_IFDEF] = qtok("#ifdef"), [TT_RETURN] = qtok("return"), [TT_PUB] = qtok("pub"), [TT_PROC] = qtok("proc"), diff --git a/include/cescal/token.h b/include/cescal/token.h index e215371..21db2ac 100644 --- a/include/cescal/token.h +++ b/include/cescal/token.h @@ -18,6 +18,9 @@ typedef enum { TT_RPAREN, /* '( */ TT_COMMA, /* ',' */ TT_ARROW, /* '->' */ + TT_DEFINE, /* '#define' */ + TT_IFNDEF, /* '#ifndef' */ + TT_IFDEF, /* '#ifdef' */ TT_RETURN, /* 'return' */ TT_PUB, /* 'pub' */ TT_PROC, /* 'proc' */ -- cgit v1.2.3