From c566f7d4909ad3bf7321b1a66e8aa9b67b2ae6db Mon Sep 17 00:00:00 2001 From: Lorenzo Torres Date: Mon, 1 Dec 2025 11:02:13 +0100 Subject: [PATCH] implemented array subscript parsing --- lc.c | 5 +++++ parser.c | 14 ++++++++++++++ parser.h | 8 +++++--- test.c | 2 +- 4 files changed, 25 insertions(+), 4 deletions(-) diff --git a/lc.c b/lc.c index d3eae80..7eea773 100644 --- a/lc.c +++ b/lc.c @@ -77,6 +77,11 @@ void print_ast(ast_node *node, int depth) { print_ast(node->expr.binary.left, depth + 1); print_ast(node->expr.binary.right, depth + 1); break; + case NODE_ARRAY_SUBSCRIPT: + printf("Array subscript\n"); + print_ast(node->expr.subscript.expr, depth + 1); + print_ast(node->expr.subscript.index, depth + 1); + break; case NODE_UNARY: printf("UnaryOp (%s)\n", get_uop_str(node->expr.unary.operator)); print_ast(node->expr.unary.right, depth + 1); diff --git a/parser.c b/parser.c index 6c5b348..5b2b0c0 100644 --- a/parser.c +++ b/parser.c @@ -233,6 +233,20 @@ ast_node *parse_expression(parser *p) left = node; } + if (match(p, TOKEN_LSQUARE)) { + ast_node *index = parse_expression(p); + ast_node *node = arena_alloc(p->allocator, sizeof(ast_node)); + node->type = NODE_ARRAY_SUBSCRIPT; + node->expr.subscript.expr = left; + node->expr.subscript.index = index; + + if (!match(p, TOKEN_RSQUARE)) { + error(p, "expected `]`."); + return NULL; + } + return node; + } + return left; } diff --git a/parser.h b/parser.h index fc44856..746bf54 100644 --- a/parser.h +++ b/parser.h @@ -67,11 +67,9 @@ typedef enum { NODE_FLOAT, NODE_STRING, NODE_CHAR, - NODE_TERNARY, NODE_CAST, NODE_ARRAY_SUBSCRIPT, NODE_ACCESS, - NODE_ACCESS_PTR, NODE_CALL, NODE_POSTFIX, NODE_UNARY, @@ -93,8 +91,8 @@ typedef enum { NODE_VAR_DECL, NODE_FUNCTION_DEF, NODE_FUNCTION_DECL, + NODE_TERNARY, NODE_UNIT, - NODE_AS, } node_type; typedef struct _ast_node { @@ -126,6 +124,10 @@ typedef struct _ast_node { char *type; usize type_len; } cast; + struct { + struct _ast_node *expr; + struct _ast_node *index; + } subscript; struct { struct _ast_node *expr; struct _ast_node *next; diff --git a/test.c b/test.c index 955b7f9..039ccfe 100644 --- a/test.c +++ b/test.c @@ -1 +1 @@ -(u64) x +x[4