rbtree
diff test/rbshell/sym.c @ 9:8d7233ff61d3
merged fixes with rbshell
author | John Tsiombikas <nuclear@member.fsf.org> |
---|---|
date | Mon, 16 Apr 2012 00:26:38 +0300 |
parents | |
children |
line diff
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/test/rbshell/sym.c Mon Apr 16 00:26:38 2012 +0300 1.3 @@ -0,0 +1,73 @@ 1.4 +#include <stdio.h> 1.5 +#include <stdlib.h> 1.6 +#include <string.h> 1.7 +#include "sym.h" 1.8 +#include "rbtree.h" 1.9 + 1.10 +struct symbol { 1.11 + char *name; 1.12 + int id, arity; 1.13 +}; 1.14 + 1.15 +static void del_func(struct rbnode *node, void *cls); 1.16 + 1.17 +struct rbtree *symbols; 1.18 + 1.19 +int init_sym(void) 1.20 +{ 1.21 + if(!(symbols = rb_create(RB_KEY_STRING))) { 1.22 + fprintf(stderr, "failed to create symbol table\n"); 1.23 + return -1; 1.24 + } 1.25 + rb_set_delete_func(symbols, del_func, 0); 1.26 + return 0; 1.27 +} 1.28 + 1.29 +void destroy_sym(void) 1.30 +{ 1.31 + rb_free(symbols); 1.32 +} 1.33 + 1.34 +int add_sym(const char *name, int id, int arity) 1.35 +{ 1.36 + struct symbol *sym; 1.37 + 1.38 + if(!(sym = malloc(sizeof *sym)) || !(sym->name = malloc(strlen(name) + 1))) { 1.39 + perror("failed to allocate symbol"); 1.40 + free(sym); 1.41 + return -1; 1.42 + } 1.43 + strcpy(sym->name, name); 1.44 + sym->id = id; 1.45 + sym->arity = arity; 1.46 + 1.47 + return rb_insert(symbols, sym->name, sym); 1.48 +} 1.49 + 1.50 +int sym_lookup(const char *str) 1.51 +{ 1.52 + struct rbnode *node; 1.53 + 1.54 + if(!(node = rb_find(symbols, (char*)str))) { 1.55 + fprintf(stderr, "undefined symbol: %s\n", str); 1.56 + return -1; 1.57 + } 1.58 + return ((struct symbol*)node->data)->id; 1.59 +} 1.60 + 1.61 +int sym_arity(const char *str) 1.62 +{ 1.63 + struct rbnode *node; 1.64 + 1.65 + if(!(node = rb_find(symbols, (char*)str))) { 1.66 + fprintf(stderr, "undefined symbol: %s\n", str); 1.67 + return -1; 1.68 + } 1.69 + return ((struct symbol*)node->data)->arity; 1.70 +} 1.71 + 1.72 +static void del_func(struct rbnode *node, void *cls) 1.73 +{ 1.74 + free(((struct symbol*)node->data)->name); 1.75 + free(node->data); 1.76 +}