From 6d4925e61687c2221ab20a4dd2371d1a3e7acb2d Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Wed, 9 Oct 2019 14:26:04 +0100 Subject: Implement function definitions Functions can now be defined using the "def" construct. A "main" function has to be defined for LLVM to compile the program. Recursive function definitions are not supported, since all values are eagerly evaluated, causing infinite recursion of the non-base case. Recursive definitions can be supported either by including an if primitive that does not evaluate both sides, or by implementing support for lazy evalution. I'm interested in exploring the latter, but will probably implement the former for now. Similar to the if primitive above, the def primitive is currently an implementation which could potentially be altered into a function that manipulates meta-variables at compile time. This would require compile-time evaluation of functions, which would be really cool, but is also superfluous to the current goal. I might return to this idea after I'm happy with the base implementation of the language. --- scope.c | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 scope.c (limited to 'scope.c') diff --git a/scope.c b/scope.c new file mode 100644 index 0000000..249439d --- /dev/null +++ b/scope.c @@ -0,0 +1,62 @@ +#include +#include + +#include "scope.h" +#include "error.h" + +/* + * Guess we'll use a linked list of linked lists for now, though that certainly + * isn't the best option and should at some point be replaced by a hash table or + * something. + * TODO + */ + +void free_layer(scope_layer *layer) { + for (scope_entry *entry = layer->head; entry;) { + entry = entry->prev; + free(entry); + } + + free(layer); +} + +void scope_push_layer(scope *sc) { + scope_layer *new_layer = malloc(sizeof (*new_layer)); + if (!new_layer) error(GENERAL_ERROR, "cannot malloc?"); + + new_layer->prev = *sc; + new_layer->head = 0; + + *sc = new_layer; +} + +void scope_pop_layer(scope *sc) { + scope new_sc = (**sc).prev; + free_layer(*sc); + *sc = new_sc; +} + +void scope_add_entry(scope sc, char *id, LLVMValueRef val, LLVMTypeRef type) { + scope_entry *new_entry = malloc(sizeof (*new_entry)); + if (!new_entry) error(GENERAL_ERROR, "cannot malloc?"); + + new_entry->id = id; + new_entry->value = val; + new_entry->type = type; + + scope_layer *layer = sc; + new_entry->prev = layer->head; + layer->head = new_entry; +} + +scope_entry *scope_find(scope sc, char *id) { + for (scope_layer *layer = sc; layer; layer = layer->prev) { + for (scope_entry *entry = layer->head; entry; entry = entry->prev) { + if (!strcmp(entry->id, id)) { + return entry; + } + } + } + + return 0; +} -- cgit v1.2.1