iris

small scheme interpreter
git clone git@git.2f30.org/iris.git
Log | Files | Refs | LICENSE

sym.c (1331B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <stddef.h>
      3 #include <stdlib.h>
      4 #include <string.h>
      5 #include "sym.h"
      6 #include "util.h"
      7 
      8 #define NRMAXSYM 1024
      9 
     10 struct symentry {
     11 	char *s;
     12 	struct object *o;
     13 };
     14 
     15 struct env {
     16 	struct symtab {
     17 		struct symentry se[NRMAXSYM];
     18 		size_t sz;
     19 	} symtab;
     20 	struct env *next;
     21 };
     22 
     23 static struct env *topenv;
     24 
     25 struct object *
     26 addsym(char *s, struct object *o)
     27 {
     28 	struct symentry *se;
     29 	size_t i;
     30 
     31 	for (i = 0; i < topenv->symtab.sz; i++) {
     32 		se = &topenv->symtab.se[i];
     33 		if (strcmp(se->s, s) == 0) {
     34 			se->o = o;
     35 			return o;
     36 		}
     37 	}
     38 	if (topenv->symtab.sz + 1 > LEN(topenv->symtab.se))
     39 		return NULL;
     40 	se = &topenv->symtab.se[topenv->symtab.sz];
     41 	se->s = s;
     42 	se->o = o;
     43 	topenv->symtab.sz++;
     44 	return o;
     45 }
     46 
     47 struct object *
     48 lookupsym(char *s)
     49 {
     50 	struct env *e;
     51 	struct symentry *se;
     52 	size_t i;
     53 
     54 	for (e = topenv; e; e = e->next) {
     55 		for (i = 0; i < e->symtab.sz; i++) {
     56 			se = &e->symtab.se[i];
     57 			if (strcmp(se->s, s) == 0)
     58 				return se->o;
     59 		}
     60 	}
     61 	return NULL;
     62 }
     63 
     64 int
     65 initenv(void)
     66 {
     67 	if (!topenv)
     68 		topenv = ecalloc(1, sizeof(*topenv));
     69 	return 0;
     70 }
     71 
     72 void
     73 pushenv(void)
     74 {
     75 	struct env *e;
     76 
     77 	e = ecalloc(1, sizeof(*e));
     78 	e->next = topenv;
     79 	topenv = e;
     80 }
     81 
     82 void
     83 popenv(void)
     84 {
     85 	struct env *tmp;
     86 
     87 	if (topenv->next) {
     88 		tmp = topenv->next;
     89 		free(topenv);
     90 		topenv = tmp;
     91 	}
     92 }