URL
https://opencores.org/ocsvn/tms1000/tms1000/trunk
Subversion Repositories tms1000
[/] [tms1000/] [trunk/] [assembler/] [symtab.c] - Rev 2
Compare with Previous | Blame | View Log
/* symtab.c: a simple binary tree symbol table CASM is an assembler for the TMS1000 processor. */ #include <stdio.h> #include <string.h> #include "symtab.h" typedef struct sym { char *name; int value; int lineno; struct sym *left; struct sym *right; } sym; static char *newstr (char *orig) { int len; char *r; len = strlen (orig); r = (char *) malloc (len + 10); if (! r) { fprintf (stderr, "memory allocation failed\n"); exit (2); } memcpy (r, orig, len + 1); return (r); } t_symtab alloc_symbol_table (void) { sym **table; table = (sym **) calloc (1, sizeof (sym *)); return (table); } static void free_entry (sym *p) { if (p->left) free_entry (p->left); if (p->right) free_entry (p->right); free (p); } void free_symbol_table (t_symtab t) { sym **table = t; free_entry (*table); free (table); } static int insert_symbol (sym **p, sym *newsym) { int i; if (! *p) { (*p) = newsym; return (1); } i = stricmp (newsym->name, (*p)->name); if (i == 0) return (0); else if (i < 0) return (insert_symbol (& ((*p)->left), newsym)); else return (insert_symbol (& ((*p)->right), newsym)); } /* returns 1 for success, 0 if duplicate name */ int create_symbol (t_symtab t, char *name, int value, int lineno) { sym **table = t; sym *p = *table; sym *newsym; newsym = (sym *) calloc (1, sizeof (sym)); if (! newsym) { fprintf (stderr, "memory allocation failure\n"); exit (2); } newsym->name = newstr (name); newsym->value = value; newsym->lineno = lineno; return (insert_symbol (table, newsym)); } /* returns 1 for success, 0 if not found */ int lookup_symbol (t_symtab t, char *name, int *value) { sym **table = t; sym *p = *table; int i; while (p) { i = stricmp (name, p->name); if (i == 0) { *value = p->value; return (1); } if (i < 0) p = p->left; else p = p->right; } return (0); } static void print_symbols (FILE *f, sym *p) { if (! p) return; print_symbols (f, p->left); fprintf (f, "%03x %s %d\n", p->value, p->name, p->lineno); print_symbols (f, p->right); } void print_symbol_table (t_symtab t, FILE *f) { sym **table = t; print_symbols (f, *table); }