1#include "symbol_table.h"
10 error_fatal(
"Memory allocation failed for symbol table");
14 table->table = calloc(SYMBOL_TABLE_SIZE,
sizeof(
Symbol*));
17 error_fatal(
"Memory allocation failed for symbol table array");
21 table->current_scope = 0;
28 for (
int i = 0; i < SYMBOL_TABLE_SIZE; i++) {
29 Symbol *symbol = table->table[i];
31 Symbol *next = symbol->next;
43 table->current_scope++;
51 for (
int i = 0; i < SYMBOL_TABLE_SIZE; i++) {
52 Symbol **current = &table->table[i];
54 if ((*current)->scope_level == table->current_scope) {
55 Symbol *to_remove = *current;
56 *current = (*current)->next;
57 free(to_remove->name);
60 current = &(*current)->next;
65 if (table->current_scope > 0) {
66 table->current_scope--;
70unsigned int symbol_table_hash(
const char *name) {
73 unsigned int hash = 0;
74 for (
int i = 0; name[i] !=
'\0'; i++) {
75 hash = hash * 31 + name[i];
77 return hash % SYMBOL_TABLE_SIZE;
80bool symbol_table_insert(
SymbolTable *table,
const char *name, SymbolType symbol_type,
DataType data_type) {
81 if (!table || !name)
return false;
84 if (symbol_table_lookup_current_scope(table, name)) {
88 unsigned int index = symbol_table_hash(name);
92 error_fatal(
"Memory allocation failed for symbol");
96 symbol->name = safe_strdup(name);
102 symbol->symbol_type = symbol_type;
103 symbol->data_type = data_type;
104 symbol->scope_level = table->current_scope;
105 symbol->next = table->table[index];
107 table->table[index] = symbol;
113 if (!table || !name)
return NULL;
115 unsigned int index = symbol_table_hash(name);
116 Symbol *symbol = table->table[index];
119 if (strcmp(symbol->name, name) == 0) {
122 symbol = symbol->next;
129 if (!table || !name)
return NULL;
131 unsigned int index = symbol_table_hash(name);
132 Symbol *symbol = table->table[index];
135 if (strcmp(symbol->name, name) == 0 && symbol->scope_level == table->current_scope) {
138 symbol = symbol->next;
146 printf(
"Symbol table is NULL\n");
150 printf(
"=== Symbol Table ===\n");
151 printf(
"Current scope: %d\n", table->current_scope);
153 for (
int i = 0; i < SYMBOL_TABLE_SIZE; i++) {
154 Symbol *symbol = table->table[i];
156 const char *symbol_type_str;
157 switch (symbol->symbol_type) {
158 case SYMBOL_VARIABLE: symbol_type_str =
"VARIABLE";
break;
159 case SYMBOL_FUNCTION: symbol_type_str =
"FUNCTION";
break;
160 case SYMBOL_PARAMETER: symbol_type_str =
"PARAMETER";
break;
161 default: symbol_type_str =
"UNKNOWN";
break;
164 printf(
" %s: %s %s (scope %d)\n",
166 data_type_to_string(symbol->data_type),
168 symbol->scope_level);
170 symbol = symbol->next;
173 printf(
"=== End Symbol Table ===\n");
DataType
Data types supported by the compiler.