From 7b0bfa91b400e89f32f19ef2987200562bbe3f8f Mon Sep 17 00:00:00 2001 From: Mustafa Quraish Date: Sat, 5 Feb 2022 22:34:44 -0500 Subject: [cup] Add support for builtin functions, add `print()` --- compiler/ast.cup | 11 ++++++++++- compiler/codegen.cup | 3 +++ compiler/main.cup | 4 +++- compiler/parser.cup | 8 ++++++++ 4 files changed, 24 insertions(+), 2 deletions(-) diff --git a/compiler/ast.cup b/compiler/ast.cup index 82e8477..2ba677b 100644 --- a/compiler/ast.cup +++ b/compiler/ast.cup @@ -1,5 +1,6 @@ -import "std/vector.cup" +import "compiler/tokens.cup" import "compiler/types.cup" +import "std/vector.cup" enum NodeType { // Unary @@ -149,6 +150,14 @@ fn node_from_int_literal(val: int): Node* { return node; } +fn variable_new(name: char*, typ: Type*, offset: int): Variable* { + let v: Variable* = malloc(sizeof(Variable)); + v.name = name; + v.typ = typ; + v.offset = offset; + return v; +} + fn block_add_child(block: Node*, child: Node*) { if (block.d.block.children == null) block.d.block.children = vector_new(); diff --git a/compiler/codegen.cup b/compiler/codegen.cup index d35f901..8c8ec95 100644 --- a/compiler/codegen.cup +++ b/compiler/codegen.cup @@ -1,3 +1,4 @@ +import "compiler/builtins.cup" import "compiler/ast.cup" import "std/file.cup" @@ -381,4 +382,6 @@ fn generate_program(ast: Node*, file: File*) { emit_asm(" call func_main\n"); emit_asm(" mov rdi, rax\n"); generate_syscall(SYS_exit); + + generate_builtins(); } \ No newline at end of file diff --git a/compiler/main.cup b/compiler/main.cup index a0a3476..6d7c3d8 100644 --- a/compiler/main.cup +++ b/compiler/main.cup @@ -1,5 +1,7 @@ import "std/file.cup" -import "compiler/lexer.cup" +// FIXME: The order of the following lines is important. +// Perhaps have multiple passes? +import "compiler/builtins.cup" import "compiler/parser.cup" import "compiler/codegen.cup" diff --git a/compiler/parser.cup b/compiler/parser.cup index 914c4e6..40df5a3 100644 --- a/compiler/parser.cup +++ b/compiler/parser.cup @@ -54,6 +54,7 @@ fn find_function_definition(token: Token*): Node* { fn identifier_exists(token: Token*): int { if (find_local_variable(token)) return true; if (find_function_definition(token)) return true; + if (find_builtin_function(token)) return true; return false; } @@ -160,6 +161,11 @@ fn parse_identifier(lexer: Lexer*): Node* { return parse_function_call_args(lexer, func); } + func = find_builtin_function(&token); + if (func != null) { + return parse_function_call_args(lexer, func); + } + die_loc2(&token.loc, "Unknown identifier in parse_identifier: ", token.value.as_string); } @@ -642,6 +648,8 @@ fn parse_function(lexer: Lexer*): Node* { } fn parse_program(lexer: Lexer*): Node* { + initialize_builtins(); + let node = node_new(AST_PROGRAM); node.d.block.children = vector_new(); -- cgit v1.2.3