2de6b598e5fe39bf4a4133168e3a687a37c906e2
[fur] / templates / environment.c
1 struct _EnvironmentNode;
2 typedef struct _EnvironmentNode _EnvironmentNode;
3 struct _EnvironmentNode {
4   const char* symbol;
5   Object value;
6   _EnvironmentNode* next;
7 };
8
9 struct Environment {
10   _EnvironmentNode* top;
11 };
12
13 struct Environment_get_Result;
14 typedef struct Environment_get_Result Environment_get_Result;
15 struct Environment_get_Result {
16   bool found;
17   Object result;
18 };
19
20 void Environment_initialize(Environment* self) {
21   self->top = NULL;
22 }
23
24 void Environment_deinitialize(Environment* self) {
25   while(self->top != NULL) {
26     _EnvironmentNode* en = self->top;
27     self->top = en->next;
28     Object_deinitialize(&(en->value));
29     free(en);
30   }
31 }
32
33 Environment* Environment_construct() {
34   Environment* result = malloc(sizeof(Environment));
35   Environment_initialize(result);
36   return result;
37 }
38
39 void Environment_destruct(Environment* self) {
40   Environment_deinitialize(self);
41   free(self);
42 }
43
44 Environment_get_Result Environment_get(Environment* self, char* symbol) {
45   for(_EnvironmentNode* current = self->top; current != NULL; current = current->next) {
46     if(strcmp(current->symbol, symbol) == 0) {
47       return (Environment_get_Result) { true, current->value };
48     }
49   }
50   return (Environment_get_Result) { false, BUILTIN_NIL };
51 }
52
53 void Environment_set(Environment* self, char* symbol, Object value) {
54   assert(!(Environment_get(self, symbol).found));
55
56   _EnvironmentNode* en = malloc(sizeof(_EnvironmentNode));
57   en->symbol = symbol;
58   en->value = value;
59   en->next = self->top;
60   self->top = en;
61 }