rework: AST now uses an arena for allocation

For now it works but i dont really like that i use ParseResult, i mean
is necessary but i think i will try to make it cleaner so that i can
just directly use like parse and pass tath into evaluate, that would
require to move the main evaluate funciton into evaluate_tree or
something  and evaluate takes the arena, uses evaluate_tree and frees
the arena, will try that the next commit but for now this version works
perfectly.
This commit is contained in:
2026-04-13 07:57:36 -06:00
parent fb27e1e34c
commit e4ec102cb9
8 changed files with 46 additions and 16 deletions

View File

@@ -1,6 +1,7 @@
#include "parser.h"
#include "lexer.h"
#include "arena.h"
#include <stdalign.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
@@ -61,19 +62,33 @@ bool ASTNodeSlice_is_valid(ASTNodeSlice *slice) {
return true;
}
AST parse(ASTNodeArray *arr) {
ParseResult parse(ASTNodeArray *arr) {
AST tree;
ASTNodeSlice context = {
.arr = arr,
.pos = 0,
};
Arena arena = arena_init(sizeof(ASTNode) * arr->len).arena;
tree.head = parse_expr(&context, 0);
return tree;
tree.head = parse_expr(&context, &arena, 0);
return (ParseResult) {.arena = &arena, .tree = tree};
}
ASTNode *parse_expr(ASTNodeSlice *slice, uint8_t min_bp) {
ASTNode *left_side = malloc(sizeof(ASTNode));
ASTNode *parse_expr(ASTNodeSlice *slice, Arena *arena, uint8_t min_bp) {
arena_ensure_capacity(
arena,
sizeof(ASTNode),
alignof(ASTNode)
);
ASTNode *left_side = arena_unwrap_pointer(
arena_alloc(
arena,
sizeof(ASTNode),
alignof(ASTNode)
)
);
*left_side = ASTNodeSlice_next(slice);
while (true) {
@@ -90,7 +105,7 @@ ASTNode *parse_expr(ASTNodeSlice *slice, uint8_t min_bp) {
}
ASTNodeSlice_next(slice);
ASTNode *right_side = parse_expr(slice, rbp);
ASTNode *right_side = parse_expr(slice, arena, rbp);
ASTNode *new_node = malloc(sizeof(ASTNode));
*new_node = operator;