From a777a5d78089275f803866124316ee4ded38b0bd Mon Sep 17 00:00:00 2001 From: kdx Date: Sun, 22 Jan 2023 03:27:38 +0100 Subject: const declaration --- baby.golem | 2 ++ parse.c | 22 +++++++++++++++++++--- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/baby.golem b/baby.golem index b936f53..5e9fa57 100644 --- a/baby.golem +++ b/baby.golem @@ -1,6 +1,8 @@ // simple comment var stack; var heap = 0; +const dwidth = 396; +const dheight = 224; // prototypes fn hello(); diff --git a/parse.c b/parse.c index 922ce4d..d2e1bcd 100644 --- a/parse.c +++ b/parse.c @@ -31,6 +31,8 @@ int parse(const Token *tok) return 0; } +/* write unexpected token error to stderr before returning NULL, + * `n` is used to mark the error in code */ static void *unexpected(const Token *tok, int n) { fprintf(stderr, "[%d] unexpected %s %s%s%sat %u:%u\n", @@ -42,6 +44,7 @@ static void *unexpected(const Token *tok, int n) return NULL; } +/* any chain of instructions that results in a value */ static const Token *expression(const Token *tok) { if (tok->type == TOK_INTEGER) @@ -77,6 +80,7 @@ static const Token *keyword_fn(const Token *tok) return tok + 1; } +/* mutable variable declaration */ static const Token *keyword_var(const Token *tok) { tok += 1; @@ -90,9 +94,7 @@ static const Token *keyword_var(const Token *tok) return tok + 1; if (tok->type != TOK_ASSIGN) return unexpected(tok, 11); - tok += 1; - /* expression */ - tok = expression(tok); + tok = expression(tok + 1); if (tok == NULL) return NULL; if (tok->type != TOK_SEMICOLON) @@ -100,7 +102,21 @@ static const Token *keyword_var(const Token *tok) return tok + 1; } +/* constant variable declaration */ static const Token *keyword_const(const Token *tok) { + tok += 1; + if (tok->type != TOK_WORD) + return unexpected(tok, 10); + const Token *name = tok; + (void)name; + tok += 1; + if (tok->type != TOK_ASSIGN) + return unexpected(tok, 11); + tok = expression(tok + 1); + if (tok == NULL) + return NULL; + if (tok->type != TOK_SEMICOLON) + return unexpected(tok, 12); return tok + 1; } -- cgit v1.2.3