Repository navigation
Expand file tree
/
Copy pathast.c
More file actions
59 lines (55 loc) · 1.39 KB
/
Copy pathast.c
File metadata and controls
59 lines (55 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// ==================== AST ====================
typedef enum {
AST_PROGRAM,
AST_FUNCTION,
AST_VAR_DECL,
AST_ASSIGNMENT,
AST_BINARY_OP,
AST_UNARY_OP,
AST_NUMBER,
AST_IDENTIFIER,
AST_CALL,
AST_RETURN,
AST_IF,
AST_SWITCH,
AST_CASE,
AST_LOOP,
AST_BREAK,
AST_CONTINUE,
AST_BLOCK,
AST_STRING,
AST_ARRAY_DECL,
AST_ARRAY_ACCESS,
AST_IMPORT,
AST_INCREMENT,
AST_DECREMENT
} ASTNodeType;
typedef struct ASTNode {
ASTNodeType type;
char value[256];
struct ASTNode *left;
struct ASTNode *right;
struct ASTNode **children;
int child_count;
int capacity;
} ASTNode;
ASTNode* ast_create_node(ASTNodeType type, char *value) {
ASTNode *node = (ASTNode*)malloc(sizeof(ASTNode));
node->type = type;
if (value) strcpy(node->value, value);
else node->value[0] = '\0';
node->left = NULL;
node->right = NULL;
node->children = NULL;
node->child_count = 0;
node->capacity = 0;
return node;
}
void ast_add_child(ASTNode *parent, ASTNode *child) {
if (parent->child_count >= parent->capacity) {
parent->capacity = parent->capacity == 0 ? 4 : parent->capacity * 2;
parent->children = (ASTNode**)realloc(parent->children,
parent->capacity * sizeof(ASTNode*));
}
parent->children[parent->child_count++] = child;
}