#include "../includes/symbols_table.h" #include #include #include SymbolTable* CreateSymbolTable(void){ SymbolTable* table = calloc(1, sizeof(SymbolTable)); if (!table) { fprintf(stderr, "Failed to calloc memory for a SymbolTable. %s.\n", strerror(errno)); return NULL; } table->Symbols = calloc(SYMBOLSTABLE_DEFAULT_CAPACITY, sizeof(Symbol*)); if (!table->Symbols) { fprintf(stderr, "Failed to calloc Symbol list. %s.\n", strerror(errno)); free(table); return NULL; } table->Capacity = SYMBOLSTABLE_DEFAULT_CAPACITY; table->Size = 0; return table; } Symbol* CreateSymbol(char* name, void* value, int length) { Symbol* symbol = calloc(1, sizeof(Symbol)); if (!symbol) { fprintf(stderr, "Failed to create Symbol '%s'. %s.\n", name, strerror(errno)); return NULL; } symbol->Length = length; symbol->Name = name; //symbol->Value = value; return symbol; } Symbol* TryGetSymbol(char* name, SymbolTable* table) { if (!name || !table) return NULL; for(int i = 0; i < table->Size; i++) { if (strcmp(table->Symbols[i]->Name, name) == 0) return table->Symbols[i]; } return NULL; } Symbol* AddSymbolToTable(char* name, void* value, int length, SymbolTable* table) { //if (!name || !value || !table || length == 0) return NULL; for(int i = 0; i < table->Size; i++) { if (strcmp(table->Symbols[i]->Name, name) == 0) { //TODO: Do we update or throw some kind of an error? return table->Symbols[i]; } } if (table->Capacity < table->Size + 1) { Symbol** newBlock = realloc(table->Symbols, sizeof(Symbol*) * table->Capacity * 2);//calloc(table->Size * 2, sizeof(Symbol*)); if (!newBlock) { fprintf(stderr, "Failed to realloc space for a new symbol '%s'. %s.\n", name, strerror(errno)); return NULL; } table->Capacity *= 2; table->Symbols = newBlock; } Symbol* symbol = CreateSymbol(name, value, length); table->Symbols[table->Size] = symbol; table->Size++; return symbol; } void FreeSymbolTable(SymbolTable* table) { if (!table) return; for(int i = 0; i < table->Size; i++) FreeSymbol(table->Symbols[i]); free(table); } void FreeSymbol(Symbol* symbol) { if (!symbol) return; free(symbol); }