8 /* Some terminology used in function names:
9 * - initialize: These functions take a pointer and potentially some other arguments, and use those
10 * to initialize the value pointed to by self. Initialize functions DO NOT allocate the function,
11 * so they can be used to initialize stack-allocated variables.
12 * - construct: This allocates a value for a pointer, initializes it, and returns it. This is for
13 * heap-allocated values. It may be as simple as allocating the memory, calling an initialize, and
15 * - deinitialize: These functions dereference or free any objects pointed to by the self pointer's
16 * value, but they don't actually free the self pointer. This is useful for stack-allocated objects
17 * which point to heap-allocated objects.
18 * - destruct: This dereferences or frees memory pointed to by the self argument, and all the
19 * pointers on the self argument.
22 {% for standard_library in standard_libraries %}
23 #include <{{standard_library}}>
27 typedef enum Type Type;
29 typedef union Instance Instance;
31 typedef struct Object Object;
32 struct EnvironmentNode;
33 typedef struct EnvironmentNode EnvironmentNode;
35 typedef struct Environment Environment;
36 struct EnvironmentPool;
37 typedef struct EnvironmentPool EnvironmentPool;
39 typedef struct Stack Stack;
41 const char* const STRING_LITERAL_LIST[] = {
42 {% for string_literal in string_literal_list %}
43 "{{ string_literal }}",
47 const char* const SYMBOL_LIST[] = {
48 {% for symbol in symbol_list %}
66 typedef struct Closure Closure;
70 Object (*call)(EnvironmentPool*, Environment*, size_t, Stack*, jmp_buf);
74 typedef struct List List;
82 struct StringConcatenation;
83 typedef struct StringConcatenation StringConcatenation;
86 typedef struct Structure Structure;
89 size_t reference_count;
91 const char** symbol_list;
101 StringConcatenation* string_concatenation;
102 const char* string_literal;
103 Structure* structure;
112 const Object builtin$true = { BOOLEAN, (Instance)(bool){ true } };
113 const Object builtin$false = { BOOLEAN, (Instance)(bool){ false } };
114 const Object builtin$nil = { VOID, { 0 } };
116 struct StringConcatenation
118 size_t referenceCount;
123 Object List_construct(size_t allocate)
125 Object* items = malloc(sizeof(Object) * allocate);
126 Object result = { LIST, (Instance)(List){ allocate, 0, items } };
130 void List_append(Object* list, Object item)
132 assert(list->type == LIST);
134 if(list->instance.list.allocated == list->instance.list.length)
136 list->instance.list.allocated *= 2;
137 list->instance.list.items = realloc(
138 list->instance.list.items,
139 sizeof(Object) * list->instance.list.allocated
143 list->instance.list.items[list->instance.list.length] = item;
144 list->instance.list.length++;
147 Object List_get(Object* list, Object index)
149 assert(list->type == LIST);
150 assert(index.type == INTEGER);
152 return list->instance.list.items[index.instance.integer];
161 void Stack_initialize(Stack* self)
166 void Stack_push(Stack* self, Object item)
168 assert(self->length < 256);
169 self->items[self->length] = item;
173 Object Stack_pop(Stack* self)
175 assert(self->length > 0);
177 return self->items[self->length];
180 Object Object_rereference(Object self)
191 case STRING_CONCATENATION:
192 self.instance.string_concatenation->referenceCount++;
196 self.instance.structure->reference_count++;
204 Object Structure_construct(size_t length, const char** symbol_list, Object* value_list)
206 Structure* structure = malloc(sizeof(Structure));
207 structure->reference_count = 1;
208 structure->length = length;
209 structure->symbol_list = malloc(sizeof(const char*) * length);
210 structure->value_list = malloc(sizeof(Object) * length);
212 // TODO Don't allow assignment of mutable structures, as this screws up reference counting
213 for(size_t i = 0; i < length; i++)
215 structure->symbol_list[i] = symbol_list[i];
216 structure->value_list[i] = Object_rereference(value_list[i]);
219 Object result = { STRUCTURE, (Instance)structure };
224 Object Structure_get(Object* self, const char* symbol)
226 assert(self->type == STRUCTURE);
228 for(size_t i = 0; i < self->instance.structure->length; i++)
230 if(self->instance.structure->symbol_list[i] == symbol)
232 return self->instance.structure->value_list[i];
239 struct EnvironmentNode
243 EnvironmentNode* next;
252 EnvironmentNode* root;
255 void Environment_initialize(Environment* self, Environment* parent)
257 self->parent = parent;
260 // We are currently only ever initializing environments at the beginning of running functions, so
261 // for now at least we can assume that we want it to be live immediately.
265 void Object_deinitialize(Object* self)
281 for(size_t i = 0; i < self->instance.list.length; i++) {
282 Object_deinitialize(&(self->instance.list.items[i]));
285 free(self->instance.list.items);
288 case STRING_CONCATENATION:
289 self->instance.string_concatenation->referenceCount--;
291 if(self->instance.string_concatenation->referenceCount == 0)
293 Object_deinitialize(&(self->instance.string_concatenation->left));
294 Object_deinitialize(&(self->instance.string_concatenation->right));
295 free(self->instance.string_concatenation);
300 self->instance.structure->reference_count--;
302 if(self->instance.structure->reference_count == 0)
304 for(size_t i = 0; i < self->instance.structure->length; i++)
306 Object_deinitialize(&(self->instance.structure->value_list[i]));
308 free(self->instance.structure->symbol_list);
309 free(self->instance.structure->value_list);
310 free(self->instance.structure);
319 void Environment_deinitialize(Environment* self)
321 EnvironmentNode* next;
322 for(EnvironmentNode* node = self->root; node != NULL; node = next)
325 Object_deinitialize(&(node->value));
330 void Environment_setLive(Environment* self, bool live)
335 void Environment_mark(Environment* self)
337 if(self == NULL) return;
338 if(self->mark) return; // Prevents infinite recursion in the case of cycles
342 Environment_mark(self->parent);
344 for(EnvironmentNode* node = self->root; node != NULL; node = node->next)
346 switch(node->value.type)
355 Environment_mark(node->value.instance.closure.closed);
364 // This need not be thread safe because environments exist on one thread only
365 void Environment_set(Environment* self, const char* const key, Object value)
367 EnvironmentNode* node = malloc(sizeof(EnvironmentNode));
370 node->next = self->root;
374 Object Environment_get(Environment* self, const char* const symbol)
376 for(EnvironmentNode* node = self->root; node != NULL; node = node->next)
378 // We can compare pointers because pointers are unique in the SYMBOL_LIST
379 if(node->key == symbol)
385 if(self->parent != NULL)
387 return Environment_get(self->parent, symbol);
390 // TODO Handle symbol errors
394 # define POOL_SIZE 64
395 struct EnvironmentPool
398 bool allocatedFlags[POOL_SIZE];
399 Environment environments[POOL_SIZE];
400 EnvironmentPool* overflow;
403 EnvironmentPool* EnvironmentPool_construct();
404 void EnvironmentPool_initialize(EnvironmentPool*);
405 void EnvironmentPool_deinitialize(EnvironmentPool*);
406 void EnvironmentPool_destruct(EnvironmentPool*);
408 EnvironmentPool* EnvironmentPool_construct()
410 EnvironmentPool* result = malloc(sizeof(EnvironmentPool));
411 EnvironmentPool_initialize(result);
415 void EnvironmentPool_initialize(EnvironmentPool* self)
417 self->overflow = NULL;
420 for(size_t i = 0; i < POOL_SIZE; i++)
422 self->allocatedFlags[i] = false;
423 self->environments[i].live = false;
427 void EnvironmentPool_deinitialize(EnvironmentPool* self)
429 // We can assume if this is being called, none of the Environments are live
430 for(int8_t i = 0; i < POOL_SIZE; i++)
432 if(self->allocatedFlags[i]) Environment_deinitialize(&(self->environments[i]));
435 EnvironmentPool_destruct(self->overflow);
438 void EnvironmentPool_destruct(EnvironmentPool* self)
440 if(self == NULL) return;
441 EnvironmentPool_deinitialize(self);
445 void EnvironmentPool_GC(EnvironmentPool* self)
447 // Unmark all the environments
448 for(EnvironmentPool* current = self; current != NULL; current = current->overflow)
450 for(int8_t i = 0; i < POOL_SIZE; i++)
452 current->environments[i].mark = false;
456 // Mark live enviroments and environments referenced by live environments
457 for(EnvironmentPool* current = self; current != NULL; current = current->overflow)
459 for(int8_t i = 0; i < POOL_SIZE; i++)
461 if(current->environments[i].live)
463 Environment_mark(&(current->environments[i]));
468 // TODO We never free pools until the very end--we could free a pool if two pools are empty
469 for(EnvironmentPool* current = self; current != NULL; current = current->overflow)
471 for(int8_t i = POOL_SIZE - 1; i >= 0; i--)
473 if(!current->environments[i].mark && current->allocatedFlags[i])
475 Environment_deinitialize(&(current->environments[i]));
476 current->allocatedFlags[i] = false;
477 current->freeIndex = i;
483 Environment* EnvironmentPool_allocate(EnvironmentPool* self)
485 for(EnvironmentPool* current = self; current != NULL; current = current->overflow)
487 for(; current->freeIndex < POOL_SIZE; current->freeIndex++)
489 if(!current->allocatedFlags[current->freeIndex])
491 current->allocatedFlags[current->freeIndex] = true;
492 return &(current->environments[current->freeIndex]);
497 EnvironmentPool_GC(self);
499 EnvironmentPool* previous;
500 for(EnvironmentPool* current = self; current != NULL; current = current->overflow)
502 for(; current->freeIndex < POOL_SIZE; current->freeIndex++)
504 if(!current->allocatedFlags[current->freeIndex])
506 current->allocatedFlags[current->freeIndex] = true;
507 return &(current->environments[current->freeIndex]);
516 previous->overflow = EnvironmentPool_construct();
517 return EnvironmentPool_allocate(previous->overflow);
520 Object integerLiteral(int32_t literal)
523 result.type = INTEGER;
524 result.instance.integer = literal;
528 Object stringLiteral(const char* literal)
531 result.type = STRING_LITERAL;
532 result.instance.string_literal = literal;
536 // TODO Make this conditionally added
537 Object operator$negate(Object input)
539 assert(input.type == INTEGER);
542 result.type = INTEGER;
543 result.instance.integer = -input.instance.integer;
547 // TODO Make this conditionally added
548 Object operator$concatenate(Stack* stack, jmp_buf parent_jump, size_t line)
550 Object right = Stack_pop(stack);
551 Object left = Stack_pop(stack);
554 case STRING_CONCATENATION:
563 case STRING_CONCATENATION:
571 StringConcatenation* concatenation = malloc(sizeof(StringConcatenation));
572 concatenation->referenceCount = 1;
573 concatenation->left = Object_rereference(left);
574 concatenation->right = Object_rereference(right);
576 Object result = { STRING_CONCATENATION, (Instance)concatenation };
580 {% for id in infix_declarations %}
581 Object operator${{ id.name }}(Stack* stack, jmp_buf parent_jump, size_t line)
583 Object right = Stack_pop(stack);
584 Object left = Stack_pop(stack);
586 assert(left.type == {{ id.in_type.upper() }});
587 assert(right.type == {{ id.in_type.upper() }});
589 {% if id.name == 'integerDivide' or id.name == 'modularDivide' %}
590 if(right.instance.integer == 0)
592 fprintf(stderr, "DivisionByZeroError on line %zu\n", line);
593 longjmp(parent_jump, 1);
598 result.type = {{ id.out_type.upper() }};
599 result.instance.{{ id.out_type.lower() }} = left.instance.{{ id.in_type.lower() }} {{ id.operator }} right.instance.{{ id.in_type.lower() }};
604 {% if 'pow' in builtins %}
605 Object builtin$pow$implementation(EnvironmentPool* environmentPool, Environment* parent, size_t argc, Stack* stack, jmp_buf parent_jump)
607 // Must unload items in reverse order
608 Object exponent = Stack_pop(stack);
609 Object base = Stack_pop(stack);
611 assert(base.type == INTEGER);
612 assert(exponent.type == INTEGER);
615 result.type = INTEGER;
616 result.instance.integer = pow(base.instance.integer, exponent.instance.integer);
620 Object builtin$pow = { CLOSURE, (Instance)(Closure){ NULL, builtin$pow$implementation } };
623 {% if 'print' in builtins %}
624 Object builtin$print$implementation(EnvironmentPool* environmentPool, Environment* parent, size_t argc, Stack* stack, jmp_buf parent_jump)
627 Stack_initialize(&reverse_stack);
629 for(size_t i = 0; i < argc; i++)
631 Stack_push(&reverse_stack, Stack_pop(stack));
634 while(reverse_stack.length > 0)
636 Object output = Stack_pop(&reverse_stack);
640 fputs(output.instance.boolean ? "true" : "false", stdout);
644 // TODO Print something better
649 printf("%" PRId32, output.instance.integer);
652 case STRING_CONCATENATION:
653 Stack_push(stack, output.instance.string_concatenation->left);
654 builtin$print$implementation(NULL, NULL, 1, stack, parent_jump);
655 Stack_push(stack, output.instance.string_concatenation->right);
656 builtin$print$implementation(NULL, NULL, 1, stack, parent_jump);
660 // Using fwrite instead of printf to handle size_t length
661 printf("%s", output.instance.string_literal);
671 Object_deinitialize(&output);
674 // TODO Return something better
675 return builtin$false;
678 Object builtin$print = { CLOSURE, (Instance)(Closure){ NULL, builtin$print$implementation } };
680 {% for function_definition in function_definition_list %}
681 {{ function_definition }}
684 int main(int argc, char** argv)
686 EnvironmentPool* environmentPool = EnvironmentPool_construct();
687 Environment* environment = EnvironmentPool_allocate(environmentPool);
688 Environment_initialize(environment, NULL);
691 Stack* stack = &stackMemory;
692 Stack_initialize(stack);
695 if(setjmp(jump) != 0)
697 fprintf(stderr, "\tin __main__\n");
698 Environment_setLive(environment, false);
699 EnvironmentPool_destruct(environmentPool);
701 // TODO We would like to return something nonzero here, but that messes up Valgrind so we couldn't catch memory leaks
705 // TODO Use the symbol from SYMBOL_LIST
706 {% for builtin in builtins %}
707 Environment_set(environment, "{{ builtin }}", builtin${{ builtin }});
710 {% for statement in statements %}
714 Environment_setLive(environment, false);
715 EnvironmentPool_destruct(environmentPool);