rbtree

view test/rbshell/sym.c @ 14:1b8a3a6088b6

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