rbtree
annotate test/rbshell/sym.c @ 12:ea44ca011995
fixed the vis makefile
author | John Tsiombikas <nuclear@member.fsf.org> |
---|---|
date | Sat, 18 Jan 2014 15:26:11 +0200 |
parents | |
children |
rev | line source |
---|---|
nuclear@6 | 1 #include <stdio.h> |
nuclear@6 | 2 #include <stdlib.h> |
nuclear@6 | 3 #include <string.h> |
nuclear@6 | 4 #include "sym.h" |
nuclear@6 | 5 #include "rbtree.h" |
nuclear@6 | 6 |
nuclear@6 | 7 struct symbol { |
nuclear@6 | 8 char *name; |
nuclear@6 | 9 int id, arity; |
nuclear@6 | 10 }; |
nuclear@6 | 11 |
nuclear@6 | 12 static void del_func(struct rbnode *node, void *cls); |
nuclear@6 | 13 |
nuclear@6 | 14 struct rbtree *symbols; |
nuclear@6 | 15 |
nuclear@6 | 16 int init_sym(void) |
nuclear@6 | 17 { |
nuclear@6 | 18 if(!(symbols = rb_create(RB_KEY_STRING))) { |
nuclear@6 | 19 fprintf(stderr, "failed to create symbol table\n"); |
nuclear@6 | 20 return -1; |
nuclear@6 | 21 } |
nuclear@6 | 22 rb_set_delete_func(symbols, del_func, 0); |
nuclear@6 | 23 return 0; |
nuclear@6 | 24 } |
nuclear@6 | 25 |
nuclear@6 | 26 void destroy_sym(void) |
nuclear@6 | 27 { |
nuclear@6 | 28 rb_free(symbols); |
nuclear@6 | 29 } |
nuclear@6 | 30 |
nuclear@6 | 31 int add_sym(const char *name, int id, int arity) |
nuclear@6 | 32 { |
nuclear@6 | 33 struct symbol *sym; |
nuclear@6 | 34 |
nuclear@6 | 35 if(!(sym = malloc(sizeof *sym)) || !(sym->name = malloc(strlen(name) + 1))) { |
nuclear@6 | 36 perror("failed to allocate symbol"); |
nuclear@6 | 37 free(sym); |
nuclear@6 | 38 return -1; |
nuclear@6 | 39 } |
nuclear@6 | 40 strcpy(sym->name, name); |
nuclear@6 | 41 sym->id = id; |
nuclear@6 | 42 sym->arity = arity; |
nuclear@6 | 43 |
nuclear@6 | 44 return rb_insert(symbols, sym->name, sym); |
nuclear@6 | 45 } |
nuclear@6 | 46 |
nuclear@6 | 47 int sym_lookup(const char *str) |
nuclear@6 | 48 { |
nuclear@6 | 49 struct rbnode *node; |
nuclear@6 | 50 |
nuclear@6 | 51 if(!(node = rb_find(symbols, (char*)str))) { |
nuclear@6 | 52 fprintf(stderr, "undefined symbol: %s\n", str); |
nuclear@6 | 53 return -1; |
nuclear@6 | 54 } |
nuclear@6 | 55 return ((struct symbol*)node->data)->id; |
nuclear@6 | 56 } |
nuclear@6 | 57 |
nuclear@6 | 58 int sym_arity(const char *str) |
nuclear@6 | 59 { |
nuclear@6 | 60 struct rbnode *node; |
nuclear@6 | 61 |
nuclear@6 | 62 if(!(node = rb_find(symbols, (char*)str))) { |
nuclear@6 | 63 fprintf(stderr, "undefined symbol: %s\n", str); |
nuclear@6 | 64 return -1; |
nuclear@6 | 65 } |
nuclear@6 | 66 return ((struct symbol*)node->data)->arity; |
nuclear@6 | 67 } |
nuclear@6 | 68 |
nuclear@6 | 69 static void del_func(struct rbnode *node, void *cls) |
nuclear@6 | 70 { |
nuclear@6 | 71 free(((struct symbol*)node->data)->name); |
nuclear@6 | 72 free(node->data); |
nuclear@6 | 73 } |