-
Notifications
You must be signed in to change notification settings - Fork 0
/
symbolTable.c
121 lines (92 loc) · 2.24 KB
/
symbolTable.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
///file:symbolTable.c
///description: functions for the symbol table of the Fred interpreter
///author: avv8047 : Azhur Viano
#include "symbolTable.h"
///Create a new table
SymbolTable* CreateTable(void){
SymbolTable* table = malloc(sizeof(SymbolTable));
table->head = NULL;
table->size = 0;
return table;
}
///Free all memory associated with a symbol
///@param symbol a pointer to the symbol to free
static void DestroySymbol(Symbol* symbol){
free(symbol->name);
free(symbol);
return;
}
///Destroy a table
void DestroyTable(SymbolTable* table){
SymbolNode* cur = table->head;
SymbolNode* next;
while(cur){
next = cur->next;
DestroySymbol(cur->symbol);
free(cur);
cur = next;
}
free(table);
}
///Add a symbol to the table
int AddSymbol(SymbolTable* table, Symbol* symbol){
SymbolNode* cur = table->head;
SymbolNode* newNode = malloc(sizeof(SymbolNode));
newNode->symbol = symbol;
int result = 1;
if(!cur || (result = strcmp(cur->symbol->name, symbol->name)) >= 0){
if(result == 0){
free(newNode);
return 0;
}
newNode->next = cur;
table->head = newNode;
return 1;
}
SymbolNode* prev = cur;
cur = cur->next;
while(cur && (result = strcmp(cur->symbol->name, symbol->name)) < 0){
prev = cur;
cur = cur->next;
}
if(result == 0){
free(newNode);
return 0;
}
newNode->next = cur;
prev->next = newNode;
return 1;
}
///Get a symbol from the table
Symbol* GetSymbol(SymbolTable* table, char* name){
SymbolNode* cur = table->head;
while(cur){
if(strncmp(cur->symbol->name, name, MAX_SYM_LEN) == 0){
return cur->symbol;
}
cur = cur->next;
}
return NULL;
}
///Dump the table and its contents to standard output
void dumpTable(SymbolTable* table){
SymbolNode* cur = table->head;
printf("Symbol Table Contents\n");
printf("Name\tType\tValue\n");
printf("=====================\n");
while(cur){
printf("%s\t", cur->symbol->name);
switch(cur->symbol->type){
case Integer:
printf("integer\t%d\n", cur->symbol->value.iVal);
break;
case Float:
printf("real\t%.3f\n", cur->symbol->value.fVal);
break;
default:
printf("unknown\tunknown\n");
}
cur = cur->next;
}
return;
}