-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathast.c
131 lines (104 loc) · 1.99 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
#include "ast.h"
void _emit(char *s, ...)
{
#ifndef __YYEMIT
#else
va_list ap;
va_start(ap, s);
printf("rpn: ");
fprintf(stdout, s, va_arg(ap, char *));
fprintf(stdout, "\n");
fflush(stdout);
va_end(ap);
#endif
}
List *
lcons(void *datum, List *list)
{
assert(IsPointerList(list));
if (list == NIL)
list = new_list(T_List);
else
new_head_cell(list);
lfirst(list->head) = datum;
return list;
}
static List *
new_list(NodeTag type)
{
List *new_list;
ListCell *new_head;
new_head = (ListCell *)malloc(sizeof(*new_head));
new_head->next = NULL;
/* new_head->data is left undefined! */
new_list = (List *)malloc(sizeof(*new_list));
new_list->type = type;
new_list->length = 1;
new_list->head = new_head;
new_list->tail = new_head;
return new_list;
}
static void
new_head_cell(List *list)
{
ListCell *new_head;
new_head = (ListCell *)malloc(sizeof(*new_head));
new_head->next = list->head;
list->head = new_head;
list->length++;
}
static void
new_tail_cell(List *list)
{
ListCell *new_tail;
new_tail = (ListCell *)malloc(sizeof(*new_tail));
new_tail->next = NULL;
list->tail->next = new_tail;
list->tail = new_tail;
list->length++;
}
List *
lappend(List *list, void *datum)
{
assert(IsPointerList(list));
if (list == NIL)
list = new_list(T_List);
else
new_tail_cell(list);
lfirst(list->tail) = datum;
return list;
}
static void
check_list_invariants(const List *list)
{
if (list == NIL)
return;
assert(list->length > 0);
assert(list->head != NULL);
assert(list->tail != NULL);
if (list->length == 1)
assert(list->head == list->tail);
if (list->length == 2)
assert(list->head->next == list->tail);
assert(list->tail->next == NULL);
}
static void
list_free_private(List *list, bool deep)
{
ListCell *cell;
check_list_invariants(list);
cell = list_head(list);
while (cell != NULL)
{
ListCell *tmp = cell;
cell = lnext(cell);
if (deep)
FREE(lfirst(tmp));
FREE(tmp);
}
FREE(list);
}
void list_free(List *list)
{
list_free_private(list, true);
}