summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorQuinn Stephens <quinn@osmora.org>2025-06-09 22:02:58 -0400
committerQuinn Stephens <quinn@osmora.org>2025-06-09 22:02:58 -0400
commit13923af3ab57dbd826ce6f36b38228eea595590f (patch)
tree200afacf2c9c6bc8612c8bf5b4037c1bc4f11adf
parentc7c2e0dc65b0ea01d297de21983acbd1019df025 (diff)
parser: Parse uninitialized variable declarations
Signed-off-by: Quinn Stephens <quinn@osmora.org>
-rw-r--r--include/parser/ast.h3
-rw-r--r--src/main.c10
-rw-r--r--src/parser/parser.c21
3 files changed, 28 insertions, 6 deletions
diff --git a/include/parser/ast.h b/include/parser/ast.h
index 3449764..d4baf92 100644
--- a/include/parser/ast.h
+++ b/include/parser/ast.h
@@ -37,7 +37,8 @@
enum ast_node_kind {
NOK_UNKNOWN,
- NOK_FUNCTION
+ NOK_FUNCTION,
+ NOK_VARIABLE
};
struct ast_node {
diff --git a/src/main.c b/src/main.c
index 645656c..c06d83e 100644
--- a/src/main.c
+++ b/src/main.c
@@ -33,7 +33,7 @@
#include "parser.h"
#include "parser/ast.h"
-static const char *src = "void test();\nint main();";
+static const char *src = "int x;\nvoid test();\nint main();\n";
static void
print_func(struct ast_node *func)
@@ -42,6 +42,12 @@ print_func(struct ast_node *func)
}
static void
+print_var(struct ast_node *var)
+{
+ log_debug("found variable \"%.*s\" (type %s)\n", var->name_len, var->name, var->type->name);
+}
+
+static void
print_syms(struct hashmap *syms)
{
struct list *list;
@@ -55,6 +61,8 @@ print_syms(struct hashmap *syms)
while (node != (struct ast_node *)list) {
if (node->kind == NOK_FUNCTION) {
print_func(node);
+ } else if (node->kind == NOK_VARIABLE) {
+ print_var(node);
}
node = (struct ast_node *)node->hashmap_entry.list_entry.next;
diff --git a/src/parser/parser.c b/src/parser/parser.c
index 4f8543c..ccdc037 100644
--- a/src/parser/parser.c
+++ b/src/parser/parser.c
@@ -79,6 +79,20 @@ parse_func_decl(struct parser *ctx, struct ast_node *func)
}
static bool
+parse_var_decl(struct parser *ctx, struct ast_node *var)
+{
+ var->kind = NOK_VARIABLE;
+
+ /*
+ * TODO: Parse initial value.
+ */
+
+ hashmap_add(ctx->syms, &var->hashmap_entry);
+ parser_advance(ctx);
+ return true;
+}
+
+static bool
parse_decl(struct parser *ctx)
{
struct type *type;
@@ -118,12 +132,11 @@ parse_decl(struct parser *ctx)
parser_advance(ctx);
if (ctx->tok.kind == TOK_LPAREN) {
return parse_func_decl(ctx, node);
+ } else if (ctx->tok.kind == TOK_SEMICOLON) {
+ return parse_var_decl(ctx, node);
}
- /*
- * TODO: Parse variable declarations.
- */
- tok_error(&ctx->tok, "expected \"(\" after identifier\n");
+ tok_error(&ctx->tok, "expected \"(\" or \";\" after identifier\n");
free(node);
return false;
}