From: David Kerkeslager Date: Sat, 24 Aug 2019 10:11:11 +0000 (-0400) Subject: Add environments X-Git-Url: https://code.kerkeslager.com/?a=commitdiff_plain;h=0fcd43d2a64af300f2a7c86ba818600b26ed3b68;p=fur Add environments --- diff --git a/c/environment.c b/c/environment.c new file mode 100644 index 0000000..f55567d --- /dev/null +++ b/c/environment.c @@ -0,0 +1,51 @@ +#ifndef ENVIRONMENT_C +#define ENVIRONMENT_C + +#include + +struct EnvironmentNode; +typedef struct EnvironmentNode EnvironmentNode; +struct EnvironmentNode { + Symbol* key; + Object* value; + EnvironmentNode* next; +}; + +struct Environment { + Environment* parent; + EnvironmentNode* root; +}; + +Environment* Environment_create(Environment* parent) { + Environment* result = malloc(sizeof(Environment)); + result->parent = parent; + result->root = NULL; + return result; +} + +EnvironmentGetResult Environment_get(Environment* self, Symbol* key) { + if(self == NULL) return (EnvironmentGetResult) { false, NULL }; + + for(EnvironmentNode* search = self->root; search != NULL; search = search->next) { + if(search->key == key) return (EnvironmentGetResult) { true, search->value }; + } + + return Environment_get(self->parent, key); +} + +bool Environment_set(Environment* self, Symbol* key, Object* value) { + assert(self != NULL); + + for(EnvironmentNode* search = self->root; search != NULL; search = search->next) { + if(search->key == key) return false; + } + + EnvironmentNode* node = malloc(sizeof(EnvironmentNode)); + node->key = key; + node->value = value; + node->next = self->root; + self->root = node; + return true; +} + +#endif diff --git a/c/environment.h b/c/environment.h new file mode 100644 index 0000000..ee4f784 --- /dev/null +++ b/c/environment.h @@ -0,0 +1,23 @@ +#ifndef ENVIRONMENT_H +#define ENVIRONMENT_H + +#include +#include "symbol.h" +#include "object.h" + +struct Environment; +typedef struct Environment Environment; + +Environment* Environment_create(Environment*); + +struct EnvironmentGetResult; +typedef struct EnvironmentGetResult EnvironmentGetResult; +struct EnvironmentGetResult { + bool found; + Object* value; +}; + +EnvironmentGetResult Environment_get(Environment*, Symbol*); +bool Environment_set(Environment*, Symbol*, Object*); + +#endif