From d0d750f0592246dfddc7ccef467f4dc8104d1934 Mon Sep 17 00:00:00 2001 From: Lorenzo Torres Date: Tue, 2 Dec 2025 21:47:00 +0100 Subject: [PATCH] implemented variable parsing --- lc.c | 3 ++- parser.c | 27 ++++++++++++++++++++++++++- parser.h | 7 +++++++ test.c | 4 +--- 4 files changed, 36 insertions(+), 5 deletions(-) diff --git a/lc.c b/lc.c index b76f2b9..5557c7a 100644 --- a/lc.c +++ b/lc.c @@ -138,7 +138,8 @@ void print_ast(ast_node *node, int depth) { printf("IfStmt (Fields missing in struct)\n"); break; case NODE_VAR_DECL: - printf("VarDecl (Fields missing in struct)\n"); + printf("VarDecl: %.*s: %.*s\n", (int)node->expr.var_decl.name_len, node->expr.var_decl.name, (int)node->expr.var_decl.type_len, node->expr.var_decl.type); + print_ast(node->expr.var_decl.value, depth + 1); break; case NODE_FUNCTION: printf("FunctionDef (Fields missing in struct)\n"); diff --git a/parser.c b/parser.c index 0040110..3d4b247 100644 --- a/parser.c +++ b/parser.c @@ -448,7 +448,7 @@ ast_node *parse_expression(parser *p) return node; } - if ((p->tokens->type >= TOKEN_DOUBLE_EQ && p->tokens->type <= TOKEN_NOT_EQ) || (p->tokens->type >= TOKEN_LSHIFT_EQ && p->tokens->type <= TOKEN_DOUBLE_AND)) + if (p->tokens && ((p->tokens->type >= TOKEN_DOUBLE_EQ && p->tokens->type <= TOKEN_NOT_EQ) || (p->tokens->type >= TOKEN_LSHIFT_EQ && p->tokens->type <= TOKEN_DOUBLE_AND))) { binary_op op; switch (p->tokens->type) @@ -777,6 +777,31 @@ static ast_node *parse_statement(parser *p) return parse_while(p); } } + else if (match_peek(p, TOKEN_IDENTIFIER) && p->tokens->next && p->tokens->next->type == TOKEN_IDENTIFIER) + { + /* Variable declaration. */ + ast_node *node = arena_alloc(p->allocator, sizeof(ast_node)); + node->type = NODE_VAR_DECL; + node->expr.var_decl.type = p->tokens->lexeme; + node->expr.var_decl.type_len = p->tokens->lexeme_len; + advance(p); + node->expr.var_decl.name = p->tokens->lexeme; + node->expr.var_decl.name_len = p->tokens->lexeme_len; + advance(p); + if (match(p, TOKEN_EQ)) { + node->expr.var_decl.value = parse_expression(p); + } else { + node->expr.var_decl.value = NULL; + } + + if (!match(p, TOKEN_SEMICOLON)) + { + error(p, "expected `;` after statement."); + return NULL; + } + + return node; + } else { ast_node *expr = parse_expression(p); diff --git a/parser.h b/parser.h index 54392f5..57068e7 100644 --- a/parser.h +++ b/parser.h @@ -170,6 +170,13 @@ typedef struct _ast_node { struct _ast_node **statements; usize stmt_len; } compound; + struct { + struct _ast_node *value; + char *name; + usize name_len; + char *type; + usize type_len; + } var_decl; } expr; } ast_node; diff --git a/test.c b/test.c index caf9248..0064f08 100644 --- a/test.c +++ b/test.c @@ -1,3 +1 @@ -loop i != 0 { - printf("%d\n", i); -} +u32 a = 3;