-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenv.c
76 lines (66 loc) · 1.23 KB
/
env.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
#include "env.h"
binding *find_binding(object *var, env *e, int use_parent)
{
binding *cur;
if (e->head == NULL && e->parent == NULL) {
return NULL;
}
else if (e->head == NULL && use_parent) {
return find_binding(var, e->parent, 1);
}
cur = e->head;
while (cur != NULL) {
if (cur->var == var) {
return cur;
}
cur = cur->next;
}
if (use_parent && e->parent != NULL) {
return find_binding(var, e->parent, 1);
}
else {
return NULL;
}
}
object *lookup(object *var, env *e)
{
binding *b = find_binding(var, e, 1);
if (b != NULL) {
return b->val;
}
else {
return NULL;
}
}
void update(object *var, object *val, env *e)
{
binding *b = find_binding(var, e, 1);
if (b != NULL) {
b->val = val;
return;
}
fprintf(stderr, "Variable not bound");
}
void insert(object *var, object *val, env *e)
{
binding *b = find_binding(var, e, 0);
if (b == NULL) {
binding *tmp = e->head;
e->head = malloc(sizeof(binding));
e->head->val = val;
e->head->var = var;
e->head->next = tmp;
}
else {
b->val = val;
}
}
void set_parent(env *child, env *parent)
{
child->parent = parent;
}
void init_env(env *e)
{
e->head = NULL;
e->parent = NULL;
}