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 void Environment_deinitialize(Environment* self)
338 EnvironmentNode* next;
339 for(EnvironmentNode* node = self->root; node != NULL; node = next)
342 Object_deinitialize(&(node->value));
347 void Environment_setLive(Environment* self, bool live)
352 void Environment_mark(Environment* self)
354 if(self == NULL) return;
355 if(self->mark) return; // Prevents infinite recursion in the case of cycles
359 Environment_mark(self->parent);
361 for(EnvironmentNode* node = self->root; node != NULL; node = node->next)
363 switch(node->value.type)
372 Environment_mark(node->value.instance.closure.closed);
381 // This need not be thread safe because environments exist on one thread only
382 void Environment_set(Environment* self, const char* const key, Object value)
384 EnvironmentNode* node = malloc(sizeof(EnvironmentNode));
387 node->next = self->root;
391 Object Environment_get(Environment* self, const char* const symbol)
393 for(EnvironmentNode* node = self->root; node != NULL; node = node->next)
395 // We can compare pointers because pointers are unique in the SYMBOL_LIST
396 if(node->key == symbol)
402 if(self->parent != NULL)
404 return Environment_get(self->parent, symbol);
407 // TODO Handle symbol errors
411 # define POOL_SIZE 64
412 struct EnvironmentPool
415 bool allocatedFlags[POOL_SIZE];
416 Environment environments[POOL_SIZE];
417 EnvironmentPool* overflow;
420 EnvironmentPool* EnvironmentPool_construct();
421 void EnvironmentPool_initialize(EnvironmentPool*);
422 void EnvironmentPool_deinitialize(EnvironmentPool*);
423 void EnvironmentPool_destruct(EnvironmentPool*);
425 EnvironmentPool* EnvironmentPool_construct()
427 EnvironmentPool* result = malloc(sizeof(EnvironmentPool));
428 EnvironmentPool_initialize(result);
432 void EnvironmentPool_initialize(EnvironmentPool* self)
434 self->overflow = NULL;
437 for(size_t i = 0; i < POOL_SIZE; i++)
439 self->allocatedFlags[i] = false;
440 self->environments[i].live = false;
444 void EnvironmentPool_deinitialize(EnvironmentPool* self)
446 // We can assume if this is being called, none of the Environments are live
447 for(int8_t i = 0; i < POOL_SIZE; i++)
449 if(self->allocatedFlags[i]) Environment_deinitialize(&(self->environments[i]));
452 EnvironmentPool_destruct(self->overflow);
455 void EnvironmentPool_destruct(EnvironmentPool* self)
457 if(self == NULL) return;
458 EnvironmentPool_deinitialize(self);
462 void EnvironmentPool_GC(EnvironmentPool* self)
464 // Unmark all the environments
465 for(EnvironmentPool* current = self; current != NULL; current = current->overflow)
467 for(int8_t i = 0; i < POOL_SIZE; i++)
469 current->environments[i].mark = false;
473 // Mark live enviroments and environments referenced by live environments
474 for(EnvironmentPool* current = self; current != NULL; current = current->overflow)
476 for(int8_t i = 0; i < POOL_SIZE; i++)
478 if(current->environments[i].live)
480 Environment_mark(&(current->environments[i]));
485 // TODO We never free pools until the very end--we could free a pool if two pools are empty
486 for(EnvironmentPool* current = self; current != NULL; current = current->overflow)
488 for(int8_t i = POOL_SIZE - 1; i >= 0; i--)
490 if(!current->environments[i].mark && current->allocatedFlags[i])
492 Environment_deinitialize(&(current->environments[i]));
493 current->allocatedFlags[i] = false;
494 current->freeIndex = i;
500 Environment* EnvironmentPool_allocate(EnvironmentPool* self)
502 for(EnvironmentPool* current = self; current != NULL; current = current->overflow)
504 for(; current->freeIndex < POOL_SIZE; current->freeIndex++)
506 if(!current->allocatedFlags[current->freeIndex])
508 current->allocatedFlags[current->freeIndex] = true;
509 return &(current->environments[current->freeIndex]);
514 EnvironmentPool_GC(self);
516 EnvironmentPool* previous;
517 for(EnvironmentPool* current = self; current != NULL; current = current->overflow)
519 for(; current->freeIndex < POOL_SIZE; current->freeIndex++)
521 if(!current->allocatedFlags[current->freeIndex])
523 current->allocatedFlags[current->freeIndex] = true;
524 return &(current->environments[current->freeIndex]);
533 previous->overflow = EnvironmentPool_construct();
534 return EnvironmentPool_allocate(previous->overflow);
537 Environment* Environment_construct(EnvironmentPool* environmentPool, Environment* parent)
539 Environment* environment = EnvironmentPool_allocate(environmentPool);
540 Environment_initialize(environment, parent);
544 Object integerLiteral(int32_t literal)
547 result.type = INTEGER;
548 result.instance.integer = literal;
552 Object stringLiteral(const char* literal)
555 result.type = STRING_LITERAL;
556 result.instance.string_literal = literal;
560 // TODO Make this conditionally added
561 Object operator$negate(Object input)
563 assert(input.type == INTEGER);
566 result.type = INTEGER;
567 result.instance.integer = -input.instance.integer;
571 // TODO Make this conditionally added
572 Object operator$concatenate(Stack* stack, jmp_buf parentJump, size_t line)
574 Object right = Stack_pop(stack);
575 Object left = Stack_pop(stack);
578 case STRING_CONCATENATION:
587 case STRING_CONCATENATION:
595 StringConcatenation* concatenation = malloc(sizeof(StringConcatenation));
596 concatenation->referenceCount = 1;
597 concatenation->left = Object_rereference(left);
598 concatenation->right = Object_rereference(right);
600 Object result = { STRING_CONCATENATION, (Instance)concatenation };
604 {% for id in infix_declarations %}
605 Object operator${{ id.name }}(Stack* stack, jmp_buf parentJump, size_t line)
607 Object right = Stack_pop(stack);
608 Object left = Stack_pop(stack);
610 assert(left.type == {{ id.in_type.upper() }});
611 assert(right.type == {{ id.in_type.upper() }});
613 {% if id.name == 'integerDivide' or id.name == 'modularDivide' %}
614 if(right.instance.integer == 0)
616 fprintf(stderr, "DivisionByZeroError on line %zu\n", line);
617 longjmp(parentJump, 1);
622 result.type = {{ id.out_type.upper() }};
623 result.instance.{{ id.out_type.lower() }} = left.instance.{{ id.in_type.lower() }} {{ id.operator }} right.instance.{{ id.in_type.lower() }};
628 {% if 'pow' in builtins %}
629 Object builtin$pow$implementation(EnvironmentPool* environmentPool, Environment* parent, size_t argc, Stack* stack, jmp_buf parentJump)
631 // Must unload items in reverse order
632 Object exponent = Stack_pop(stack);
633 Object base = Stack_pop(stack);
635 assert(base.type == INTEGER);
636 assert(exponent.type == INTEGER);
639 result.type = INTEGER;
640 result.instance.integer = pow(base.instance.integer, exponent.instance.integer);
644 Object builtin$pow = { CLOSURE, (Instance)(Closure){ NULL, builtin$pow$implementation } };
647 {% if 'print' in builtins %}
648 Object builtin$print$implementation(EnvironmentPool* environmentPool, Environment* parent, size_t argc, Stack* stack, jmp_buf parentJump)
651 Stack_initialize(&reverse_stack);
653 for(size_t i = 0; i < argc; i++)
655 Stack_push(&reverse_stack, Stack_pop(stack));
658 while(reverse_stack.length > 0)
660 Object output = Stack_pop(&reverse_stack);
664 fputs(output.instance.boolean ? "true" : "false", stdout);
668 // TODO Print something better
673 printf("%" PRId32, output.instance.integer);
676 case STRING_CONCATENATION:
677 Stack_push(stack, output.instance.string_concatenation->left);
678 builtin$print$implementation(NULL, NULL, 1, stack, parentJump);
679 Stack_push(stack, output.instance.string_concatenation->right);
680 builtin$print$implementation(NULL, NULL, 1, stack, parentJump);
684 // Using fwrite instead of printf to handle size_t length
685 printf("%s", output.instance.string_literal);
695 Object_deinitialize(&output);
698 // TODO Return something better
699 return builtin$false;
702 Object builtin$print = { CLOSURE, (Instance)(Closure){ NULL, builtin$print$implementation } };
704 {% for function_definition in function_definition_list %}
705 {{ function_definition }}
708 int main(int argc, char** argv)
710 EnvironmentPool* environmentPool = EnvironmentPool_construct();
711 Environment* environment = EnvironmentPool_allocate(environmentPool);
712 Environment_initialize(environment, NULL);
715 Stack* stack = &stackMemory;
716 Stack_initialize(stack);
719 if(setjmp(jump) != 0)
721 fprintf(stderr, "\tin __main__\n");
723 while(Stack_any(stack))
725 Object item = Stack_pop(stack);
726 Object_deinitialize(&item);
728 Environment_setLive(environment, false);
729 EnvironmentPool_destruct(environmentPool);
731 // TODO We would like to return something nonzero here, but that messes up Valgrind so we couldn't catch memory leaks
735 // TODO Use the symbol from SYMBOL_LIST
736 {% for builtin in builtins %}
737 Environment_set(environment, "{{ builtin }}", builtin${{ builtin }});
740 {% for statement in statements %}
744 Environment_setLive(environment, false);
745 EnvironmentPool_destruct(environmentPool);