Files
assm-test/src/symbols_table.c
T

103 lines
2.4 KiB
C

#include "../includes/symbols_table.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
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, int address, int resolved) {
Symbol* symbol = calloc(1, sizeof(Symbol));
if (!symbol) {
fprintf(stderr, "Failed to create Symbol '%s'. %s.\n", name, strerror(errno));
return NULL;
}
symbol->Address = address;
symbol->Name = name;
symbol->Resolved = resolved;
return symbol;
}
int TryGetSymbol(char* name, SymbolTable* table, Symbol** outSymbol) {
*outSymbol = NULL;
if (!name || !table) return 0;
for(int i = 0; i < table->Size; i++) {
if (strcmp(table->Symbols[i]->Name, name) == 0) {
*outSymbol = table->Symbols[i];
return 1;
}
}
return 0;
}
Symbol* AddSymbolToTable(char* name, int address, int resolved, 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);
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, address, resolved);
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);
}