-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathast.c
80 lines (74 loc) · 1.72 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
69
70
71
72
73
74
75
76
77
78
79
80
#include "ast.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
so_expr *create_string_node(const char *s)
{
so_expr *e = malloc(sizeof(so_expr));
e->tag = SO_EXPR_STRING;
e->as.string = strdup(s);
return e;
}
so_expr *create_number_node(int n)
{
so_expr *e = malloc(sizeof(so_expr));
e->tag = SO_EXPR_INT;
e->as.number = n;
return e;
}
so_expr *create_call_node(const char *name, int nargs, so_expr *args[])
{
so_expr *e = malloc(sizeof(so_expr));
e->tag = SO_EXPR_CALL;
e->as.call = (so_expr_call){.name = strdup(name), .nargs = nargs};
for (int i = 0; i < nargs; i++)
e->as.call.args[i] = args[i];
return e;
}
so_expr *create_load_node(const char *name)
{
so_expr *e = malloc(sizeof(so_expr));
e->tag = SO_EXPR_LOAD;
e->as.load = (so_expr_load){.name = strdup(name)};
return e;
}
void print_ast(so_expr *e)
{
switch (e->tag)
{
case SO_EXPR_INT:
printf("%d\n", e->as.number);
break;
case SO_EXPR_STRING:
printf("%s\n", e->as.string);
break;
case SO_EXPR_LOAD:
printf("USE %s\n", e->as.load.name);
break;
case SO_EXPR_CALL:
printf("CALL %s (%d)\n", e->as.call.name, e->as.call.nargs);
break;
default:
assert(0 && "unhandled case in print_ast");
}
}
void free_ast(so_expr *e)
{
switch (e->tag)
{
case SO_EXPR_INT:
break;
case SO_EXPR_STRING:
free(e->as.string);
break;
case SO_EXPR_LOAD:
free(e->as.load.name);
break;
case SO_EXPR_CALL:
free(e->as.call.name);
for (int i = 0; i < e->as.call.nargs; i++)
free_ast(e->as.call.args[i]);
}
free(e);
}