Fix for a crash which happened when a document couldn't be opened.
[AROS-Contrib.git] / fish / icalc / symbol.c
blob52ada9f0da6adc3bf76299acb0812c801e7da79c
1 /*
2 * symbol-table management routines for complex-number expression parser.
3 * MWS, March 17, 1991.
4 */
5 #include <stdio.h>
6 #include <string.h>
7 #include <stdlib.h>
8 #include "memory.h"
9 #include "complex.h"
10 #include "complex.tab.h"
12 extern void cprin(FILE *, char *prefix, char *suffix, Complex z);
14 /* Prototypes for static functions defined in symbol.c */
15 static void insert(Symbol **tree, Symbol *item);
16 static void traverse(Symbol *tree, short type, void (*visit)(Symbol *));
17 static void printval(Symbol *item);
18 static void printname(Symbol *item);
20 static Symbol *symtree = NULL; /* symbol table: binary tree */
22 Symbol *lookup(s) /* find s in symbol table */
23 char *s;
25 Symbol *sp = symtree;
26 int cmp;
28 while (sp)
30 cmp = strcmp(s, sp->name);
31 if (cmp == 0)
32 break;
33 else if (cmp < 0)
34 sp = sp->left;
35 else /* cmp > 0 */
36 sp = sp->right;
39 return sp;
42 static void insert(tree, item) /* no duplicate names permitted... */
43 Symbol **tree, *item;
45 if (*tree == NULL)
47 *tree = item;
48 item->left = item->right = NULL;
50 else if (strcmp(item->name, (*tree)->name) < 0)
51 insert(&(*tree)->left, item);
52 else
53 insert(&(*tree)->right, item);
56 Symbol *allocsym(s, t) /* allocate a symbol */
57 char *s;
58 int t;
60 Symbol *sp;
62 sp = (Symbol *) emalloc(sizeof(Symbol));
63 sp->name = emalloc(strlen(s)+1);
64 strcpy(sp->name, s);
65 sp->type = t;
67 return sp;
70 Symbol *install(s, t, cval) /* install s in symbol table */
71 char *s;
72 int t;
73 Complex cval;
75 Symbol *sp = allocsym(s, t);
76 sp->u.val = cval;
78 insert(&symtree, sp);
79 return sp;
82 static void traverse(Symbol *tree,short type, void (*visit)(Symbol *)) /* inorder traversal of tree */
84 if (tree)
86 traverse(tree->left, type, visit);
87 if (tree->type == type)
88 (*visit)(tree);
89 traverse(tree->right, type, visit);
93 static void printval(item)
94 Symbol *item;
96 fprintf(stdout, "\t%s\t= ", item->name);
97 cprin(stdout, NULL, "\n", item->u.val);
100 static void printname(item)
101 Symbol *item;
103 fprintf(stdout,"\t%s\n", item->name);
106 void printlist(type) /* print names of symbols with given type */
107 int type; /* simple-minded at moment */
109 if (type == CONST || type == VAR)
110 traverse(symtree, type, printval);
111 else
112 traverse(symtree, type, printname);