the hito embeddable programming language
at main 57 lines 1.4 kB view raw
1#include "scope.h" 2#include <stdlib.h> 3#include <stdio.h> 4#include "util.h" 5struct scope { 6 intern_t *data; 7 size_t size; 8 size_t capacity; 9}; 10 11scope_t *scope_alloc(void) { 12 scope_t *s = malloc(sizeof(struct scope)); 13 if (s == NULL) 14 die("Out of memory: cannot allocate scope struct"); 15 s->size = 0; 16 s->capacity = 8; 17 s->data = malloc(s->capacity * sizeof(intern_t)); 18 if (s->data == NULL) 19 die("Out of memory: cannot allocate scope buffer"); 20 return s; 21} 22 23void scope_push(scope_t *scope, intern_t identifier) { 24 if (scope->size == scope->capacity) { 25 scope->capacity *= 2; 26 scope->data = realloc(scope->data, scope->capacity * sizeof(intern_t)); 27 if (scope->data == NULL) 28 die("Out of memory: cannot enlarge scope array"); 29 } 30 scope->data[scope->size++] = identifier; 31} 32 33void scope_pop(scope_t *scope, size_t amount) { 34 if (scope->size >= amount) 35 scope->size -= amount; 36} 37 38void scope_free(scope_t *scope) { 39 if (scope == NULL) return; 40 free(scope->data); 41 free(scope); 42} 43 44de_bruijn_t scope_lookup(scope_t *scope, intern_t identifier) { 45 for (size_t i = scope->size; i > 0; i--) 46 if (scope->data[i - 1] == identifier) 47 return (scope->size - i); 48 49 /* caller should decide what happens for "not found" */ 50 return (de_bruijn_t)-1; 51} 52 53void scope_debug_dump(scope_t *scope) { 54 for (size_t i = 0; i < scope->size; i++) 55 printf("%s, ", scope->data[i]); 56 printf("|-"); 57}