Add constant symbol list, which solves all the symbol allocation problems
[fur] / templates / program.c
index 64e0152..0f79b14 100644 (file)
@@ -25,6 +25,12 @@ struct String
   char* characters;
 };
 
+const char * const SYMBOL_LIST[] = {
+{% for symbol in symbol_list %}
+  "{{ symbol }}",
+{% endfor %}
+};
+
 enum Type
 {
   INTEGER,
@@ -43,6 +49,68 @@ struct Object
   Instance instance;
 };
 
+struct EnvironmentNode;
+typedef struct EnvironmentNode EnvironmentNode;
+struct EnvironmentNode
+{
+  const char* key;
+  Object value;
+  EnvironmentNode* next;
+};
+
+struct Environment;
+typedef struct Environment Environment;
+struct Environment
+{
+  EnvironmentNode* root;
+};
+
+Environment* Environment_construct()
+{
+  // TODO Handle malloc returning NULL
+  Environment* result = malloc(sizeof(Environment));
+  result->root = NULL;
+  return result;
+}
+
+void Environment_destruct(Environment* self)
+{
+  EnvironmentNode* next;
+  for(EnvironmentNode* node = self->root; node != NULL; node = next)
+  {
+    // We don't need to destruct the permanent strings, because those will be destructed at the end when the Runtime is destructed
+    // The above comment represents all heap-allocated objects currently, so we don't need to destruct Objects (yet)
+    next = node->next;
+    free(node);
+  }
+}
+
+// This need not be thread safe because environments exist on one thread only
+void Environment_set(Environment* self, const char* const key, Object value)
+{
+  EnvironmentNode* node = malloc(sizeof(EnvironmentNode));
+  node->key = key;
+  node->value = value;
+  node->next = self->root;
+  self->root = node;
+}
+
+Object Environment_get(Environment* self, const char* const symbol)
+{
+  for(EnvironmentNode* node = self->root; node != NULL; node = node->next)
+  {
+    // We can compare pointers because pointers are unique in the SYMBOLS_LIST
+    if(node->key == symbol)
+    {
+      return node->value;
+    }
+  }
+
+  // TODO Handle symbol errors
+  assert(false);
+}
+
+
 struct Runtime
 {
   size_t permanentStringsLength;
@@ -61,6 +129,11 @@ Runtime* Runtime_construct()
 
 void Runtime_destruct(Runtime* self)
 {
+  for(size_t i = 0; i < self->permanentStringsLength; i++)
+  {
+    free(self->permanentStrings[i]);
+  }
+
   free(self->permanentStrings);
   free(self);
 }
@@ -215,11 +288,13 @@ void builtin$print(Object output)
 int main(int argc, char** argv)
 {
   Runtime* runtime = Runtime_construct();
+  Environment* environment = Environment_construct();
 
   {% for statement in statements %}
   {{ statement }}
   {% endfor %}
 
+  Environment_destruct(environment);
   Runtime_destruct(runtime);
 
   return 0;