/
ast.c
133 lines (123 loc) · 2.7 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <alloca.h>
#include "ast.h"
void nlist_init(nlist *list) {
list->size = list->max_size = 0;
list->instrs = NULL;
}
void nlist_add(nlist *list, ninstr* instr) {
if (list->size == list->max_size) {
if (list->max_size == 0)
list->max_size = 4;
list->max_size *= 2;
list->instrs = realloc(list->instrs, list->max_size*sizeof(ninstr));
}
list->instrs[list->size] = *instr;
++list->size;
}
void nlist_insert(nlist *list, ninstr *instr, int n) {
int i;
if (list->size == list->max_size) {
if (list->max_size == 0)
list->max_size = 4;
list->max_size *= 2;
list->instrs = realloc(list->instrs, list->max_size*sizeof(ninstr));
}
for (i = list->size; i > n; --i) {
list->instrs[i] = list->instrs[i-1];
}
list->instrs[n] = *instr;
++list->size;
}
void nlist_delete(nlist *list, int n) {
int i;
if (list->instrs[n].type == NLOOP) {
nlist_destroy(&list->instrs[n].loop.list);
}
list->size--;
for (i = n; i < list->size; ++i) {
list->instrs[i] = list->instrs[i+1];
}
}
void nlist_print_indent(nlist *list, int indent) {
int i;
char * spaces = alloca(indent+1);
spaces[indent] = '\0';
memset(spaces, ' ', indent);
int indented = 0;
for (i = 0; i < list->size; ++i) {
if (list->instrs[i].type != NLOOP && list->instrs[i].type != NFIXEDLOOP) {
char c;
switch(list->instrs[i].type) {
case NADD:
c = '+';
break;
case NSUB:
c = '-';
break;
case NMULTADD:
c = '*';
break;
case NMULTSUB:
c = '^';
break;
case NLEFT:
c = '<';
break;
case NRIGHT:
c = '>';
break;
case NINPUT:
c = ',';
break;
case NOUTPUT:
c = '.';
break;
case NLOOP:
case NFIXEDLOOP:
/* shouldn't happen */
break;
}
if (!indented) {
printf(spaces);
indented = 1;
}
if (list->instrs[i].amount == 1) {
if (list->instrs[i].offset)
printf("%d(%c)", list->instrs[i].offset, c);
else
printf("%c", c);
} else {
if (list->instrs[i].offset)
printf("%d(%d%c)", list->instrs[i].offset, list->instrs[i].amount, c);
else
printf("%d%c", list->instrs[i].amount, c);
}
} else {
if (list->instrs[i].loop.list.size == 0) {
/* shorten empty loops */
printf("[]");
} else {
printf("\n%s[\n", spaces);
nlist_print_indent(&list->instrs[i].loop.list, indent+2);
printf("%s]\n", spaces);
indented = 0;
}
}
}
printf("\n");
}
void nlist_print(nlist *list) {
nlist_print_indent(list, 0);
}
void nlist_destroy(nlist *list) {
int i;
for (i = 0; i < list->size; ++i) {
if (list->instrs[i].type == NLOOP) {
nlist_destroy(&list->instrs[i].loop.list);
}
}
free(list->instrs);
}