nuclear@6: #include nuclear@6: #include nuclear@6: #include nuclear@6: #include "sym.h" nuclear@6: #include "rbtree.h" nuclear@6: nuclear@6: struct symbol { nuclear@6: char *name; nuclear@6: int id, arity; nuclear@6: }; nuclear@6: nuclear@6: static void del_func(struct rbnode *node, void *cls); nuclear@6: nuclear@6: struct rbtree *symbols; nuclear@6: nuclear@6: int init_sym(void) nuclear@6: { nuclear@6: if(!(symbols = rb_create(RB_KEY_STRING))) { nuclear@6: fprintf(stderr, "failed to create symbol table\n"); nuclear@6: return -1; nuclear@6: } nuclear@6: rb_set_delete_func(symbols, del_func, 0); nuclear@6: return 0; nuclear@6: } nuclear@6: nuclear@6: void destroy_sym(void) nuclear@6: { nuclear@6: rb_free(symbols); nuclear@6: } nuclear@6: nuclear@6: int add_sym(const char *name, int id, int arity) nuclear@6: { nuclear@6: struct symbol *sym; nuclear@6: nuclear@6: if(!(sym = malloc(sizeof *sym)) || !(sym->name = malloc(strlen(name) + 1))) { nuclear@6: perror("failed to allocate symbol"); nuclear@6: free(sym); nuclear@6: return -1; nuclear@6: } nuclear@6: strcpy(sym->name, name); nuclear@6: sym->id = id; nuclear@6: sym->arity = arity; nuclear@6: nuclear@6: return rb_insert(symbols, sym->name, sym); nuclear@6: } nuclear@6: nuclear@6: int sym_lookup(const char *str) nuclear@6: { nuclear@6: struct rbnode *node; nuclear@6: nuclear@6: if(!(node = rb_find(symbols, (char*)str))) { nuclear@6: fprintf(stderr, "undefined symbol: %s\n", str); nuclear@6: return -1; nuclear@6: } nuclear@6: return ((struct symbol*)node->data)->id; nuclear@6: } nuclear@6: nuclear@6: int sym_arity(const char *str) nuclear@6: { nuclear@6: struct rbnode *node; nuclear@6: nuclear@6: if(!(node = rb_find(symbols, (char*)str))) { nuclear@6: fprintf(stderr, "undefined symbol: %s\n", str); nuclear@6: return -1; nuclear@6: } nuclear@6: return ((struct symbol*)node->data)->arity; nuclear@6: } nuclear@6: nuclear@6: static void del_func(struct rbnode *node, void *cls) nuclear@6: { nuclear@6: free(((struct symbol*)node->data)->name); nuclear@6: free(node->data); nuclear@6: }