From 61b85f238240519373010ce502e57622a2af05cb Mon Sep 17 00:00:00 2001 From: kdx Date: Sun, 22 Jan 2023 03:16:15 +0100 Subject: handle comments and global declaration --- Token.h | 1 + baby.golem | 4 ---- lexer.c | 9 +++++++-- parse.c | 24 +++++++++++++++++++++++- 4 files changed, 31 insertions(+), 7 deletions(-) diff --git a/Token.h b/Token.h index 8f20b2e..7b4aa20 100644 --- a/Token.h +++ b/Token.h @@ -24,6 +24,7 @@ enum { TOK_INCREMENT, TOK_COMP_EQ, TOK_COMP_NEQ, + TOK_COMMENT, /* keywords */ TOK_KW_VAR, TOK_KW_CONST, diff --git a/baby.golem b/baby.golem index c5a9368..b936f53 100644 --- a/baby.golem +++ b/baby.golem @@ -1,8 +1,4 @@ // simple comment -/* multi - line - comment */ - var stack; var heap = 0; diff --git a/lexer.c b/lexer.c index e55f97e..dd97785 100644 --- a/lexer.c +++ b/lexer.c @@ -43,6 +43,7 @@ static unsigned int two_wide_tok(const char *s) case PAIR('+', '+'): return TOK_INCREMENT; case PAIR('=', '='): return TOK_COMP_EQ; case PAIR('!', '='): return TOK_COMP_NEQ; + case PAIR('/', '/'): return TOK_COMMENT; default: return TOK_NONE; } } @@ -73,6 +74,7 @@ Token *lexer(const char *s) toks[tok_i].column = column; toks[tok_i].line = line; const char *rem_s = s; + const int two_wide = two_wide_tok(s); if (*s == '"') { const char *end = strchr(s + 1, '"'); if (end == NULL) { @@ -120,8 +122,11 @@ Token *lexer(const char *s) toks[tok_i].type = TOK_INTEGER; tok_i += 1; s += len; - } else if (two_wide_tok(s) != TOK_NONE) { - toks[tok_i].type = two_wide_tok(s); + } else if (two_wide == TOK_COMMENT) { + while (*s != '\0' && *s != '\n') + s += 1; + } else if (two_wide != TOK_NONE) { + toks[tok_i].type = two_wide; toks[tok_i].v.c = *s; tok_i += 1; s += 2; diff --git a/parse.c b/parse.c index d562b57..922ce4d 100644 --- a/parse.c +++ b/parse.c @@ -3,6 +3,7 @@ #include static void *unexpected(const Token *tok, int n); +static const Token *expression(const Token *tok); static const Token *keyword_fn(const Token *tok); static const Token *keyword_var(const Token *tok); static const Token *keyword_const(const Token *tok); @@ -41,6 +42,17 @@ static void *unexpected(const Token *tok, int n) return NULL; } +static const Token *expression(const Token *tok) +{ + if (tok->type == TOK_INTEGER) + return tok + 1; + if (tok->type == TOK_STRING) + return tok + 1; + if (tok->type == TOK_WORD) + return tok + 1; + return unexpected(tok, 20); +} + static const Token *keyword_fn(const Token *tok) { tok += 1; @@ -73,8 +85,18 @@ static const Token *keyword_var(const Token *tok) const Token *name = tok; (void)name; tok += 1; - if (tok->type != TOK_SEMICOLON) + /* no initialization */ + if (tok->type == TOK_SEMICOLON) + return tok + 1; + if (tok->type != TOK_ASSIGN) return unexpected(tok, 11); + tok += 1; + /* expression */ + tok = expression(tok); + if (tok == NULL) + return NULL; + if (tok->type != TOK_SEMICOLON) + return unexpected(tok, 12); return tok + 1; } -- cgit v1.2.3