-
Notifications
You must be signed in to change notification settings - Fork 0
/
ast.c
68 lines (62 loc) · 1.71 KB
/
ast.c
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
60
61
62
63
64
65
66
67
68
#include <stdio.h>
#include <stdlib.h>
#include "ast.h"
void print_ast_rec(struct ast_node *node) {
switch (node->type) {
case A_APP:
if (node->val.app.left->type == A_FUNC) putchar('(');
print_ast_rec(node->val.app.left);
if (node->val.app.left->type == A_FUNC) putchar(')');
if (node->val.app.right->type != A_IDENT) putchar('(');
print_ast_rec(node->val.app.right);
if (node->val.app.right->type != A_IDENT) putchar(')');
break;
case A_FUNC:
printf("%c->", node->val.func.param);
print_ast_rec(node->val.func.body);
break;
case A_IDENT:
putchar(node->val.var.chr);
break;
}
}
struct ast_node *ast_new_app(struct ast_node* left, struct ast_node* right) {
struct ast_node *res = malloc(sizeof(struct ast_node));
res->type = A_APP;
res->val.app.left = left;
res->val.app.right = right;
return res;
}
struct ast_node *ast_new_func(char param, struct ast_node* body) {
struct ast_node *res = malloc(sizeof(struct ast_node));
res->type = A_FUNC;
res->val.func.param = param;
res->val.func.body = body;
return res;
}
struct ast_node *ast_new_var(char binding, unsigned debruijn) {
struct ast_node *res = malloc(sizeof(struct ast_node));
res->type = A_IDENT;
res->val.var.chr = binding;
res->val.var.debruijn = debruijn;
return res;
}
void free_ast(struct ast_node *node) {
if (node == NULL) return;
switch (node->type) {
case A_APP:
free_ast(node->val.app.left);
free_ast(node->val.app.right);
break;
case A_FUNC:
free_ast(node->val.func.body);
break;
case A_IDENT:
break;
}
free(node);
}
void print_ast(struct ast_node *node) {
print_ast_rec(node);
putchar('\n');
}