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 bool Stack_any(Stack* self)
168 return self->length > 0;
171 void Stack_push(Stack* self, Object item)
173 assert(self->length < 256);
174 self->items[self->length] = item;
178 Object Stack_pop(Stack* self)
180 assert(self->length > 0);
182 return self->items[self->length];
185 Object Object_rereference(Object self)
196 case STRING_CONCATENATION:
197 self.instance.string_concatenation->referenceCount++;
201 self.instance.structure->reference_count++;
209 Object Structure_construct(size_t length, const char** symbol_list, Object* value_list)
211 Structure* structure = malloc(sizeof(Structure));
212 structure->reference_count = 1;
213 structure->length = length;
214 structure->symbol_list = malloc(sizeof(const char*) * length);
215 structure->value_list = malloc(sizeof(Object) * length);
217 // TODO Don't allow assignment of mutable structures, as this screws up reference counting
218 for(size_t i = 0; i < length; i++)
220 structure->symbol_list[i] = symbol_list[i];
221 structure->value_list[i] = Object_rereference(value_list[i]);
224 Object result = { STRUCTURE, (Instance)structure };
229 Object Structure_get(Object* self, const char* symbol)
231 assert(self->type == STRUCTURE);
233 for(size_t i = 0; i < self->instance.structure->length; i++)
235 if(self->instance.structure->symbol_list[i] == symbol)
237 return self->instance.structure->value_list[i];
244 struct EnvironmentNode
248 EnvironmentNode* next;
257 EnvironmentNode* root;
260 void Environment_initialize(Environment* self, Environment* parent)
262 self->parent = parent;
265 // We are currently only ever initializing environments at the beginning of running functions, so
266 // for now at least we can assume that we want it to be live immediately.
270 void Object_deinitialize(Object* self)
286 for(size_t i = 0; i < self->instance.list.length; i++) {
287 Object_deinitialize(&(self->instance.list.items[i]));
290 free(self->instance.list.items);
293 case STRING_CONCATENATION:
294 self->instance.string_concatenation->referenceCount--;
296 if(self->instance.string_concatenation->referenceCount == 0)
298 Object_deinitialize(&(self->instance.string_concatenation->left));
299 Object_deinitialize(&(self->instance.string_concatenation->right));
300 free(self->instance.string_concatenation);
305 self->instance.structure->reference_count--;
307 if(self->instance.structure->reference_count == 0)
309 for(size_t i = 0; i < self->instance.structure->length; i++)
311 Object_deinitialize(&(self->instance.structure->value_list[i]));
313 free(self->instance.structure->symbol_list);
314 free(self->instance.structure->value_list);
315 free(self->instance.structure);
324 void Environment_deinitialize(Environment* self)
326 EnvironmentNode* next;
327 for(EnvironmentNode* node = self->root; node != NULL; node = next)
330 Object_deinitialize(&(node->value));
335 void Environment_setLive(Environment* self, bool live)
340 void Environment_mark(Environment* self)
342 if(self == NULL) return;
343 if(self->mark) return; // Prevents infinite recursion in the case of cycles
347 Environment_mark(self->parent);
349 for(EnvironmentNode* node = self->root; node != NULL; node = node->next)
351 switch(node->value.type)
360 Environment_mark(node->value.instance.closure.closed);
369 // This need not be thread safe because environments exist on one thread only
370 void Environment_set(Environment* self, const char* const key, Object value)
372 EnvironmentNode* node = malloc(sizeof(EnvironmentNode));
375 node->next = self->root;
379 Object Environment_get(Environment* self, const char* const symbol)
381 for(EnvironmentNode* node = self->root; node != NULL; node = node->next)
383 // We can compare pointers because pointers are unique in the SYMBOL_LIST
384 if(node->key == symbol)
390 if(self->parent != NULL)
392 return Environment_get(self->parent, symbol);
395 // TODO Handle symbol errors
399 # define POOL_SIZE 64
400 struct EnvironmentPool
403 bool allocatedFlags[POOL_SIZE];
404 Environment environments[POOL_SIZE];
405 EnvironmentPool* overflow;
408 EnvironmentPool* EnvironmentPool_construct();
409 void EnvironmentPool_initialize(EnvironmentPool*);
410 void EnvironmentPool_deinitialize(EnvironmentPool*);
411 void EnvironmentPool_destruct(EnvironmentPool*);
413 EnvironmentPool* EnvironmentPool_construct()
415 EnvironmentPool* result = malloc(sizeof(EnvironmentPool));
416 EnvironmentPool_initialize(result);
420 void EnvironmentPool_initialize(EnvironmentPool* self)
422 self->overflow = NULL;
425 for(size_t i = 0; i < POOL_SIZE; i++)
427 self->allocatedFlags[i] = false;
428 self->environments[i].live = false;
432 void EnvironmentPool_deinitialize(EnvironmentPool* self)
434 // We can assume if this is being called, none of the Environments are live
435 for(int8_t i = 0; i < POOL_SIZE; i++)
437 if(self->allocatedFlags[i]) Environment_deinitialize(&(self->environments[i]));
440 EnvironmentPool_destruct(self->overflow);
443 void EnvironmentPool_destruct(EnvironmentPool* self)
445 if(self == NULL) return;
446 EnvironmentPool_deinitialize(self);
450 void EnvironmentPool_GC(EnvironmentPool* self)
452 // Unmark all the environments
453 for(EnvironmentPool* current = self; current != NULL; current = current->overflow)
455 for(int8_t i = 0; i < POOL_SIZE; i++)
457 current->environments[i].mark = false;
461 // Mark live enviroments and environments referenced by live environments
462 for(EnvironmentPool* current = self; current != NULL; current = current->overflow)
464 for(int8_t i = 0; i < POOL_SIZE; i++)
466 if(current->environments[i].live)
468 Environment_mark(&(current->environments[i]));
473 // TODO We never free pools until the very end--we could free a pool if two pools are empty
474 for(EnvironmentPool* current = self; current != NULL; current = current->overflow)
476 for(int8_t i = POOL_SIZE - 1; i >= 0; i--)
478 if(!current->environments[i].mark && current->allocatedFlags[i])
480 Environment_deinitialize(&(current->environments[i]));
481 current->allocatedFlags[i] = false;
482 current->freeIndex = i;
488 Environment* EnvironmentPool_allocate(EnvironmentPool* self)
490 for(EnvironmentPool* current = self; current != NULL; current = current->overflow)
492 for(; current->freeIndex < POOL_SIZE; current->freeIndex++)
494 if(!current->allocatedFlags[current->freeIndex])
496 current->allocatedFlags[current->freeIndex] = true;
497 return &(current->environments[current->freeIndex]);
502 EnvironmentPool_GC(self);
504 EnvironmentPool* previous;
505 for(EnvironmentPool* current = self; current != NULL; current = current->overflow)
507 for(; current->freeIndex < POOL_SIZE; current->freeIndex++)
509 if(!current->allocatedFlags[current->freeIndex])
511 current->allocatedFlags[current->freeIndex] = true;
512 return &(current->environments[current->freeIndex]);
521 previous->overflow = EnvironmentPool_construct();
522 return EnvironmentPool_allocate(previous->overflow);
525 Object integerLiteral(int32_t literal)
528 result.type = INTEGER;
529 result.instance.integer = literal;
533 Object stringLiteral(const char* literal)
536 result.type = STRING_LITERAL;
537 result.instance.string_literal = literal;
541 // TODO Make this conditionally added
542 Object operator$negate(Object input)
544 assert(input.type == INTEGER);
547 result.type = INTEGER;
548 result.instance.integer = -input.instance.integer;
552 // TODO Make this conditionally added
553 Object operator$concatenate(Stack* stack, jmp_buf parentJump, size_t line)
555 Object right = Stack_pop(stack);
556 Object left = Stack_pop(stack);
559 case STRING_CONCATENATION:
568 case STRING_CONCATENATION:
576 StringConcatenation* concatenation = malloc(sizeof(StringConcatenation));
577 concatenation->referenceCount = 1;
578 concatenation->left = Object_rereference(left);
579 concatenation->right = Object_rereference(right);
581 Object result = { STRING_CONCATENATION, (Instance)concatenation };
585 {% for id in infix_declarations %}
586 Object operator${{ id.name }}(Stack* stack, jmp_buf parentJump, size_t line)
588 Object right = Stack_pop(stack);
589 Object left = Stack_pop(stack);
591 assert(left.type == {{ id.in_type.upper() }});
592 assert(right.type == {{ id.in_type.upper() }});
594 {% if id.name == 'integerDivide' or id.name == 'modularDivide' %}
595 if(right.instance.integer == 0)
597 fprintf(stderr, "DivisionByZeroError on line %zu\n", line);
598 longjmp(parentJump, 1);
603 result.type = {{ id.out_type.upper() }};
604 result.instance.{{ id.out_type.lower() }} = left.instance.{{ id.in_type.lower() }} {{ id.operator }} right.instance.{{ id.in_type.lower() }};
609 {% if 'pow' in builtins %}
610 Object builtin$pow$implementation(EnvironmentPool* environmentPool, Environment* parent, size_t argc, Stack* stack, jmp_buf parentJump)
612 // Must unload items in reverse order
613 Object exponent = Stack_pop(stack);
614 Object base = Stack_pop(stack);
616 assert(base.type == INTEGER);
617 assert(exponent.type == INTEGER);
620 result.type = INTEGER;
621 result.instance.integer = pow(base.instance.integer, exponent.instance.integer);
625 Object builtin$pow = { CLOSURE, (Instance)(Closure){ NULL, builtin$pow$implementation } };
628 {% if 'print' in builtins %}
629 Object builtin$print$implementation(EnvironmentPool* environmentPool, Environment* parent, size_t argc, Stack* stack, jmp_buf parentJump)
632 Stack_initialize(&reverse_stack);
634 for(size_t i = 0; i < argc; i++)
636 Stack_push(&reverse_stack, Stack_pop(stack));
639 while(reverse_stack.length > 0)
641 Object output = Stack_pop(&reverse_stack);
645 fputs(output.instance.boolean ? "true" : "false", stdout);
649 // TODO Print something better
654 printf("%" PRId32, output.instance.integer);
657 case STRING_CONCATENATION:
658 Stack_push(stack, output.instance.string_concatenation->left);
659 builtin$print$implementation(NULL, NULL, 1, stack, parentJump);
660 Stack_push(stack, output.instance.string_concatenation->right);
661 builtin$print$implementation(NULL, NULL, 1, stack, parentJump);
665 // Using fwrite instead of printf to handle size_t length
666 printf("%s", output.instance.string_literal);
676 Object_deinitialize(&output);
679 // TODO Return something better
680 return builtin$false;
683 Object builtin$print = { CLOSURE, (Instance)(Closure){ NULL, builtin$print$implementation } };
685 {% for function_definition in function_definition_list %}
686 {{ function_definition }}
689 int main(int argc, char** argv)
691 EnvironmentPool* environmentPool = EnvironmentPool_construct();
692 Environment* environment = EnvironmentPool_allocate(environmentPool);
693 Environment_initialize(environment, NULL);
696 Stack* stack = &stackMemory;
697 Stack_initialize(stack);
700 if(setjmp(jump) != 0)
702 fprintf(stderr, "\tin __main__\n");
704 while(Stack_any(stack))
706 Object item = Stack_pop(stack);
707 Object_deinitialize(&item);
709 Environment_setLive(environment, false);
710 EnvironmentPool_destruct(environmentPool);
712 // TODO We would like to return something nonzero here, but that messes up Valgrind so we couldn't catch memory leaks
716 // TODO Use the symbol from SYMBOL_LIST
717 {% for builtin in builtins %}
718 Environment_set(environment, "{{ builtin }}", builtin${{ builtin }});
721 {% for statement in statements %}
725 Environment_setLive(environment, false);
726 EnvironmentPool_destruct(environmentPool);