Add symbol and structure support
[fur] / c / environment.c
1 #ifndef ENVIRONMENT_C
2 #define ENVIRONMENT_C
3
4 #include<assert.h>
5
6 struct EnvironmentNode;
7 typedef struct EnvironmentNode EnvironmentNode;
8 struct EnvironmentNode {
9   Symbol* key;
10   Object* value;
11   EnvironmentNode* next;
12 };
13
14 struct Environment {
15   Environment* parent;
16   EnvironmentNode* root;
17 };
18
19 Environment* Environment_create(Environment* parent) {
20   Environment* result = malloc(sizeof(Environment));
21   result->parent = parent;
22   result->root = NULL;
23   return result;
24 }
25
26 EnvironmentGetResult Environment_get(Environment* self, Symbol* key) {
27   if(self == NULL) return (EnvironmentGetResult) { false, NULL };
28
29   for(EnvironmentNode* search = self->root; search != NULL; search = search->next) {
30     if(search->key == key) return (EnvironmentGetResult) { true, search->value };
31   }
32
33   return Environment_get(self->parent, key);
34 }
35
36 bool Environment_set(Environment* self, Symbol* key, Object* value) {
37   assert(self != NULL);
38
39   for(EnvironmentNode* search = self->root; search != NULL; search = search->next) {
40     if(search->key == key) return false;
41   }
42
43   EnvironmentNode* node = malloc(sizeof(EnvironmentNode));
44   node->key = key;
45   node->value = value;
46   node->next = self->root;
47   self->root = node;
48   return true;
49 }
50
51 #endif