From 5825f5b316945de1049fdf9aba0dbd689a004d07 Mon Sep 17 00:00:00 2001 From: bog Date: Mon, 28 Aug 2023 14:49:42 +0200 Subject: [PATCH] ADD: syntaxic sugar for function definitions. --- src/compiler.c | 22 ++++++++++++++++ src/cstatic.c | 3 ++- src/node.h | 3 ++- src/parser.y | 62 +++++++++++++++++++++++++++++++--------------- tests/test_fun.wuz | 6 +++++ 5 files changed, 74 insertions(+), 22 deletions(-) diff --git a/src/compiler.c b/src/compiler.c index 0bb3b6c..51b87c6 100644 --- a/src/compiler.c +++ b/src/compiler.c @@ -167,6 +167,28 @@ void compile_node(compiler* self, node* root, program* prog) program_add_instr(prog, OP_ADEREF, NO_PARAM); } // Variables stuff + else if (root->type == NODE_FUNDECL) + { + cstatic cs; + cstatic_init(&cs); + type* ty = cstatic_resolve_new(&cs, + self->sym, + root->children.data[1]); + + size_t id = symtable_declare( + self->sym, + root->children.data[0]->value, + ty, + root->children.data[1] + ); + + compile_node(self, root->children.data[1], prog); + program_add_instr(prog, OP_STORE, id); + + type_free(ty); + free(ty); + cstatic_free(&cs); + } else if (root->type == NODE_CONSTDECL) { cstatic cs; diff --git a/src/cstatic.c b/src/cstatic.c index 1152089..abd1dfc 100644 --- a/src/cstatic.c +++ b/src/cstatic.c @@ -726,7 +726,8 @@ int cstatic_check(cstatic* self, node* ast, symtable* sym, char* msg, size_t siz return 1; } if (ast->type == NODE_VARDECL - || ast->type == NODE_CONSTDECL) + || ast->type == NODE_CONSTDECL + || ast->type == NODE_FUNDECL) { char const* name = ast->children.data[0]->value; symentry* entry = symtable_find(sym, name); diff --git a/src/node.h b/src/node.h index b04084b..936ee80 100644 --- a/src/node.h +++ b/src/node.h @@ -16,7 +16,8 @@ G(NODE_IF), G(NODE_ELSE), G(NODE_BLOCK), \ G(NODE_WHILE), G(NODE_CONTINUE), G(NODE_BREAK), \ G(NODE_COLON), G(NODE_FUN_TYPE), G(NODE_RETURN), G(NODE_FUN), \ - G(NODE_FUN_PARAM), G(NODE_FUN_RET), G(NODE_CALL), G(NODE_ARGS) + G(NODE_FUN_PARAM), G(NODE_FUN_RET), G(NODE_CALL), G(NODE_ARGS), \ + G(NODE_FUNDECL) #include "mutils.h" diff --git a/src/parser.y b/src/parser.y index 6fe396e..ec246fe 100644 --- a/src/parser.y +++ b/src/parser.y @@ -29,7 +29,7 @@ %token BREAK %left ASSERT %token TYPE BOOLEAN INTEGER FLOAT STRING IDENT -%type expr exprs prog array builtins +%type expr exprs prog array builtins fun_body %type expr_list type type_list ident if %type fun_rets fun_params fun_param fun %type fun_ret_list fun_call fun_args any instr @@ -595,33 +595,49 @@ fun_rets: ; fun: - FUN OPAR fun_params CPAR fun_rets block END { + FUN ident fun_body { node* n = malloc(sizeof(node)); node_init(n, NODE_FUN, "", line); - - node* block_node = stack_pop(); - assert(block_node); + size_t const SZ = $3; + node* all[SZ]; - node* ret_node = stack_pop(); - assert(ret_node); - - if ($3 > 0) + for (size_t i=0; i