diff options
author | Carlos Maniero <carlos@maniero.me> | 2023-05-11 15:00:10 -0300 |
---|---|---|
committer | Carlos Maniero <carlos@maniero.me> | 2023-05-11 15:29:57 -0300 |
commit | ea7f65fe1250be8f49edcaaedd3410aed1401648 (patch) | |
tree | ffe7d6ec48bc6018b5eea7e9ef573cd1bbd57c2f /src/ast.h | |
parent | 5042a4ffc1363d6f0f99a3afd79f76cf2da738d6 (diff) |
gas: implement recursion and late evaluation
Until now the below code was not valid for pipac.
fn main(): i32 {
return fib(13);
}
fn fib(n: i32): i32 {
if n <= 1 {
return n;
}
return fib(n - 1) + fib(n - 2);
}
Pipa's parser was adding a function to scope after they were fully
parsed which means that fib's self-reference would not work.
Also, functions were required to follow the be called in the order they
are declared for the same scope reason so, the main function was
required to be defined after fib.
And how it is working now?
When a TOKEN_NAME is not found in the scope, instead of returning an
error, an unknown token is created as placeholder. The parser stores the
node reference and the token it was trying to parse.
During type checks, if the parser detects an unknown node, instead of
returning an error, it stores in that node what was the expected type.
After the NS is fully parsed a reevaluation is made on those unknown
nodes by setting the lexer back on the node's token position and parsing
the TOKEN_NAME again.
Ps: There is a typo on the unknown token. It will be addressed in
another commit since this issue was not introduced by this change.
Signed-off-by: Carlos Maniero <carlos@maniero.me>
Diffstat (limited to 'src/ast.h')
-rw-r--r-- | src/ast.h | 12 |
1 files changed, 10 insertions, 2 deletions
@@ -16,6 +16,7 @@ */ #ifndef AST_H #define AST_H +#include "lexer.h" #include "string_view.h" #include "vector.h" #include <stdint.h> @@ -140,6 +141,12 @@ typedef struct ast_if_stmt_t ast_node_t *body; } ast_if_stmt_t; +typedef struct ast_unkown_token_t +{ + type_t expected_type; + token_t reference_token; +} ast_unkown_token_t; + typedef enum { AST_NAMESPACE, @@ -151,10 +158,10 @@ typedef enum AST_LITERAL, AST_RETURN_STMT, AST_IF_STMT, - AST_UNKOWN_NODE, AST_VARIABLE_DECLARATION, AST_VARIABLE_ASSIGNMENT, - AST_VARIABLE + AST_VARIABLE, + AST_UNKOWN_NODE } ast_node_kind_t; typedef union @@ -171,6 +178,7 @@ typedef union ast_variable_declaration_t variable_declaration; ast_variable_assignment_t variable_assignment; ast_variable_t variable; + ast_unkown_token_t unknown; } ast_node_data_t; typedef struct ast_node_t |