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 Stack* Stack_construct()
168 Stack* result = malloc(sizeof(Stack));
169 Stack_initialize(result);
173 void Stack_destruct(Stack* self)
178 bool Stack_any(Stack* self)
180 return self->length > 0;
183 void Stack_push(Stack* self, Object item)
185 assert(self->length < 256);
186 self->items[self->length] = item;
190 Object Stack_pop(Stack* self)
192 assert(self->length > 0);
194 return self->items[self->length];
197 Object Object_rereference(Object self)
208 case STRING_CONCATENATION:
209 self.instance.string_concatenation->referenceCount++;
213 self.instance.structure->reference_count++;
221 Object Structure_construct(size_t length, const char** symbol_list, Object* value_list)
223 Structure* structure = malloc(sizeof(Structure));
224 structure->reference_count = 1;
225 structure->length = length;
226 structure->symbol_list = malloc(sizeof(const char*) * length);
227 structure->value_list = malloc(sizeof(Object) * length);
229 // TODO Don't allow assignment of mutable structures, as this screws up reference counting
230 for(size_t i = 0; i < length; i++)
232 structure->symbol_list[i] = symbol_list[i];
233 structure->value_list[i] = Object_rereference(value_list[i]);
236 Object result = { STRUCTURE, (Instance)structure };
241 Object Structure_get(Object* self, const char* symbol)
243 assert(self->type == STRUCTURE);
245 for(size_t i = 0; i < self->instance.structure->length; i++)
247 if(self->instance.structure->symbol_list[i] == symbol)
249 return self->instance.structure->value_list[i];
256 struct EnvironmentNode
260 EnvironmentNode* next;
269 EnvironmentNode* root;
272 void Environment_initialize(Environment* self, Environment* parent)
274 self->parent = parent;
277 // We are currently only ever initializing environments at the beginning of running functions, so
278 // for now at least we can assume that we want it to be live immediately.
282 void Object_deinitialize(Object* self)
298 for(size_t i = 0; i < self->instance.list.length; i++) {
299 Object_deinitialize(&(self->instance.list.items[i]));
302 free(self->instance.list.items);
305 case STRING_CONCATENATION:
306 self->instance.string_concatenation->referenceCount--;
308 if(self->instance.string_concatenation->referenceCount == 0)
310 Object_deinitialize(&(self->instance.string_concatenation->left));
311 Object_deinitialize(&(self->instance.string_concatenation->right));
312 free(self->instance.string_concatenation);
317 self->instance.structure->reference_count--;
319 if(self->instance.structure->reference_count == 0)
321 for(size_t i = 0; i < self->instance.structure->length; i++)
323 Object_deinitialize(&(self->instance.structure->value_list[i]));
325 free(self->instance.structure->symbol_list);
326 free(self->instance.structure->value_list);
327 free(self->instance.structure);
336 typedef uint32_t StackSnapshot;
338 StackSnapshot Stack_takeSnapshot(Stack* self)
340 return (StackSnapshot) self->length;
343 void Stack_rewind(Stack* self, StackSnapshot snapshot)
345 while(self->length > snapshot)
347 Object item = Stack_pop(self);
348 Object_deinitialize(&item);
352 void Environment_deinitialize(Environment* self)
354 EnvironmentNode* next;
355 for(EnvironmentNode* node = self->root; node != NULL; node = next)
358 Object_deinitialize(&(node->value));
363 void Environment_setLive(Environment* self, bool live)
368 void Environment_mark(Environment* self)
370 if(self == NULL) return;
371 if(self->mark) return; // Prevents infinite recursion in the case of cycles
375 Environment_mark(self->parent);
377 for(EnvironmentNode* node = self->root; node != NULL; node = node->next)
379 switch(node->value.type)
388 Environment_mark(node->value.instance.closure.closed);
397 // This need not be thread safe because environments exist on one thread only
398 void Environment_set(Environment* self, const char* const key, Object value)
400 EnvironmentNode* node = malloc(sizeof(EnvironmentNode));
403 node->next = self->root;
407 Object Environment_get(Environment* self, const char* const symbol)
409 for(EnvironmentNode* node = self->root; node != NULL; node = node->next)
411 // We can compare pointers because pointers are unique in the SYMBOL_LIST
412 if(node->key == symbol)
418 if(self->parent != NULL)
420 return Environment_get(self->parent, symbol);
423 // TODO Handle symbol errors
427 # define POOL_SIZE 64
428 struct EnvironmentPool
431 bool allocatedFlags[POOL_SIZE];
432 Environment environments[POOL_SIZE];
433 EnvironmentPool* overflow;
436 EnvironmentPool* EnvironmentPool_construct();
437 void EnvironmentPool_initialize(EnvironmentPool*);
438 void EnvironmentPool_deinitialize(EnvironmentPool*);
439 void EnvironmentPool_destruct(EnvironmentPool*);
441 EnvironmentPool* EnvironmentPool_construct()
443 EnvironmentPool* result = malloc(sizeof(EnvironmentPool));
444 EnvironmentPool_initialize(result);
448 void EnvironmentPool_initialize(EnvironmentPool* self)
450 self->overflow = NULL;
453 for(size_t i = 0; i < POOL_SIZE; i++)
455 self->allocatedFlags[i] = false;
456 self->environments[i].live = false;
460 void EnvironmentPool_deinitialize(EnvironmentPool* self)
462 // We can assume if this is being called, none of the Environments are live
463 for(int8_t i = 0; i < POOL_SIZE; i++)
465 if(self->allocatedFlags[i]) Environment_deinitialize(&(self->environments[i]));
468 EnvironmentPool_destruct(self->overflow);
471 void EnvironmentPool_destruct(EnvironmentPool* self)
473 if(self == NULL) return;
474 EnvironmentPool_deinitialize(self);
478 void EnvironmentPool_GC(EnvironmentPool* self)
480 // Unmark all the environments
481 for(EnvironmentPool* current = self; current != NULL; current = current->overflow)
483 for(int8_t i = 0; i < POOL_SIZE; i++)
485 current->environments[i].mark = false;
489 // Mark live enviroments and environments referenced by live environments
490 for(EnvironmentPool* current = self; current != NULL; current = current->overflow)
492 for(int8_t i = 0; i < POOL_SIZE; i++)
494 if(current->environments[i].live)
496 Environment_mark(&(current->environments[i]));
501 // TODO We never free pools until the very end--we could free a pool if two pools are empty
502 for(EnvironmentPool* current = self; current != NULL; current = current->overflow)
504 for(int8_t i = POOL_SIZE - 1; i >= 0; i--)
506 if(!current->environments[i].mark && current->allocatedFlags[i])
508 Environment_deinitialize(&(current->environments[i]));
509 current->allocatedFlags[i] = false;
510 current->freeIndex = i;
516 Environment* EnvironmentPool_allocate(EnvironmentPool* self)
518 for(EnvironmentPool* current = self; current != NULL; current = current->overflow)
520 for(; current->freeIndex < POOL_SIZE; current->freeIndex++)
522 if(!current->allocatedFlags[current->freeIndex])
524 current->allocatedFlags[current->freeIndex] = true;
525 return &(current->environments[current->freeIndex]);
530 EnvironmentPool_GC(self);
532 EnvironmentPool* previous;
533 for(EnvironmentPool* current = self; current != NULL; current = current->overflow)
535 for(; current->freeIndex < POOL_SIZE; current->freeIndex++)
537 if(!current->allocatedFlags[current->freeIndex])
539 current->allocatedFlags[current->freeIndex] = true;
540 return &(current->environments[current->freeIndex]);
549 previous->overflow = EnvironmentPool_construct();
550 return EnvironmentPool_allocate(previous->overflow);
553 Environment* Environment_construct(EnvironmentPool* environmentPool, Environment* parent)
555 Environment* environment = EnvironmentPool_allocate(environmentPool);
556 Environment_initialize(environment, parent);
560 Object integerLiteral(int32_t literal)
563 result.type = INTEGER;
564 result.instance.integer = literal;
568 Object stringLiteral(const char* literal)
571 result.type = STRING_LITERAL;
572 result.instance.string_literal = literal;
576 // TODO Make this conditionally added
577 Object operator$negate(Object input)
579 assert(input.type == INTEGER);
582 result.type = INTEGER;
583 result.instance.integer = -input.instance.integer;
587 // TODO Make this conditionally added
588 Object operator$concatenate(Stack* stack, jmp_buf parentJump, size_t line)
590 Object right = Stack_pop(stack);
591 Object left = Stack_pop(stack);
594 case STRING_CONCATENATION:
603 case STRING_CONCATENATION:
611 StringConcatenation* concatenation = malloc(sizeof(StringConcatenation));
612 concatenation->referenceCount = 1;
613 concatenation->left = Object_rereference(left);
614 concatenation->right = Object_rereference(right);
616 Object result = { STRING_CONCATENATION, (Instance)concatenation };
620 {% for id in infix_declarations %}
621 Object operator${{ id.name }}(Stack* stack, jmp_buf parentJump, size_t line)
623 Object right = Stack_pop(stack);
624 Object left = Stack_pop(stack);
626 assert(left.type == {{ id.in_type.upper() }});
627 assert(right.type == {{ id.in_type.upper() }});
629 {% if id.name == 'integerDivide' or id.name == 'modularDivide' %}
630 if(right.instance.integer == 0)
632 fprintf(stderr, "DivisionByZeroError on line %zu\n", line);
633 longjmp(parentJump, 1);
638 result.type = {{ id.out_type.upper() }};
639 result.instance.{{ id.out_type.lower() }} = left.instance.{{ id.in_type.lower() }} {{ id.operator }} right.instance.{{ id.in_type.lower() }};
644 {% if 'pow' in builtins %}
645 Object builtin$pow$implementation(EnvironmentPool* environmentPool, Environment* parent, size_t argc, Stack* stack, jmp_buf parentJump)
647 // Must unload items in reverse order
648 Object exponent = Stack_pop(stack);
649 Object base = Stack_pop(stack);
651 assert(base.type == INTEGER);
652 assert(exponent.type == INTEGER);
655 result.type = INTEGER;
656 result.instance.integer = pow(base.instance.integer, exponent.instance.integer);
660 Object builtin$pow = { CLOSURE, (Instance)(Closure){ NULL, builtin$pow$implementation } };
663 {% if 'print' in builtins %}
664 Object builtin$print$implementation(EnvironmentPool* environmentPool, Environment* parent, size_t argc, Stack* stack, jmp_buf parentJump)
667 Stack_initialize(&reverse_stack);
669 for(size_t i = 0; i < argc; i++)
671 Stack_push(&reverse_stack, Stack_pop(stack));
674 while(reverse_stack.length > 0)
676 Object output = Stack_pop(&reverse_stack);
680 fputs(output.instance.boolean ? "true" : "false", stdout);
684 // TODO Print something better
689 printf("%" PRId32, output.instance.integer);
692 case STRING_CONCATENATION:
693 Stack_push(stack, output.instance.string_concatenation->left);
694 builtin$print$implementation(NULL, NULL, 1, stack, parentJump);
695 Stack_push(stack, output.instance.string_concatenation->right);
696 builtin$print$implementation(NULL, NULL, 1, stack, parentJump);
700 // Using fwrite instead of printf to handle size_t length
701 printf("%s", output.instance.string_literal);
711 Object_deinitialize(&output);
714 // TODO Return something better
715 return builtin$false;
718 Object builtin$print = { CLOSURE, (Instance)(Closure){ NULL, builtin$print$implementation } };
720 {% for function_definition in function_definition_list %}
721 {{ function_definition }}
724 int main(int argc, char** argv)
726 EnvironmentPool* environmentPool = EnvironmentPool_construct();
727 Environment* environment = EnvironmentPool_allocate(environmentPool);
728 Environment_initialize(environment, NULL);
731 Stack* stack = &stackMemory;
732 Stack_initialize(stack);
735 if(setjmp(jump) != 0)
737 fprintf(stderr, "\tin __main__\n");
739 while(Stack_any(stack))
741 Object item = Stack_pop(stack);
742 Object_deinitialize(&item);
744 Environment_setLive(environment, false);
745 EnvironmentPool_destruct(environmentPool);
747 // TODO We would like to return something nonzero here, but that messes up Valgrind so we couldn't catch memory leaks
751 // TODO Use the symbol from SYMBOL_LIST
752 {% for builtin in builtins %}
753 Environment_set(environment, "{{ builtin }}", builtin${{ builtin }});
756 {% for statement in statements %}
760 Environment_setLive(environment, false);
761 EnvironmentPool_destruct(environmentPool);