aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorMustafa Quraish <[email protected]>2022-02-05 00:57:20 -0500
committerMustafa Quraish <[email protected]>2022-02-05 08:56:15 -0500
commit24dd666121e2786efb82854b05aa71d759e04ee6 (patch)
tree4420eda5e1cde0bfe7dfe8f4b160212d59ceeca3 /src
parentAdd `void` type and allow void* to be assigned to other ptr types (diff)
downloadcup-24dd666121e2786efb82854b05aa71d759e04ee6.tar.xz
cup-24dd666121e2786efb82854b05aa71d759e04ee6.zip
Add ability to initialize global variables
The code to initialize them is put right before calling `main()`
Diffstat (limited to 'src')
-rw-r--r--src/ast.c2
-rw-r--r--src/generator.c13
-rw-r--r--src/parser.c3
3 files changed, 14 insertions, 4 deletions
diff --git a/src/ast.c b/src/ast.c
index 62b8b6c..24885c2 100644
--- a/src/ast.c
+++ b/src/ast.c
@@ -199,7 +199,7 @@ void dump_func(Node *node, int depth)
printf("[[%lld]]", node->func.args[i].offset);
}
printf(")");
- if (node->func.return_type->type != TYPE_NONE) {
+ if (node->func.return_type->type != TYPE_VOID) {
// FIXME: Print return type properly
printf(" -> %s", type_to_str(node->func.return_type));
}
diff --git a/src/generator.c b/src/generator.c
index 5da0748..f5ae850 100644
--- a/src/generator.c
+++ b/src/generator.c
@@ -467,6 +467,19 @@ void generate_asm(Node *root, FILE *out)
fprintf(out, " mov rax, rdi\n");
fprintf(out, " push rax\n");
+ // Initialize global variables
+ for (int i = 0; i < root->block.num_children; i++) {
+ Node *child = root->block.children[i];
+ if (child->type == AST_VARDECL && child->var_decl.value) {
+ Node *expr = child->var_decl.value;
+ generate_expr_into_rax(expr, out);
+ i64 offset = child->var_decl.var.offset;
+ fprintf(out, " mov rbx, global_vars\n");
+ fprintf(out, " add rbx, %lld\n", offset);
+ fprintf(out, " mov [rbx], %s\n", subregister_for_type(expr->expr_type));
+ }
+ }
+
fprintf(out, " call func_main\n");
fprintf(out, " mov rdi, rax\n");
diff --git a/src/parser.c b/src/parser.c
index 49c9689..81c90da 100644
--- a/src/parser.c
+++ b/src/parser.c
@@ -375,9 +375,6 @@ Node *parse_var_declaration(Lexer *lexer)
}
if (token.type == TOKEN_ASSIGN) {
- if (is_global)
- die_location(token.loc, "Cannot initialize global variable `%s` outside function", node->var_decl.var.name);
-
node->var_decl.value = parse_expression(lexer);
if (is_missing_type) {