Files
compiler-the-translators/symbol_table.c

102 lines
3.4 KiB
C

//Defining a symbol table
//Using a Linked List Structure. Head of linked List points to parent scope (if one exists)
//Tail of Linked List points to a Linked List of all the child scopes
//T
//*#include "symbol_table.h"
/*
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct ListOfTable{
struct SymbolTable* table;
//struct ListOfTable* prev;
struct ListOfTable* next;
}ListOfTable;
typedef union Value{
int* value_of_int;
void* value_of_pointer;
bool* value_of_bool;
char* value_of_char;
}Value;
typedef struct TableNode{
char* theType;
char* theName;
Value* value;
struct TableNode* next;
//this next value is an int for string types to tell you how far to traverse a buffer for the string
int StrLength;
}TableNode;
typedef struct SymbolTable{
TableNode* entries;
struct SymbolTable* Parent_Scope;
struct ListOfTable* Children_Scope;
int Line_Number;
int Column_Number;
}SymbolTable;
*/
SymbolTable* CreateScope(SymbolTable* ParentScope, int Line, int Column){
SymbolTable* table = (SymbolTable*)malloc(sizeof(SymbolTable));
table->Line_Number = Line;
table->Column_Number = Column;
table->Parent_Scope = ParentScope;
table->Children_Scope = NULL;
table->entries = NULL;
if(ParentScope != NULL){
if(ParentScope->Children_Scope == NULL){
ListOfTable* newEntry = (ListOfTable*)malloc(sizeof(ListOfTable));
newEntry->next = NULL;
//newEntry->prev = NULL;
newEntry->table = table;
ParentScope->Children_Scope = newEntry;
} else{
ListOfTable* newEntry = (ListOfTable*)malloc(sizeof(ListOfTable));
//newEntry->prev = NULL;
newEntry->table= table;
ListOfTable* oldEntry = ParentScope->Children_Scope;
ParentScope->Children_Scope = newEntry;
newEntry->next = oldEntry;
}
}
return table;
}
TableNode* CreateEntry(SymbolTable* table, char* typeOf, char* id, Value* value, int StringLength){
TableNode* newEntry = (TableNode*)malloc(sizeof(TableNode));
newEntry->theType = typeOf;
newEntry->theName = id;
newEntry->value = value;
newEntry->StrLength = StringLength;
if(table->entries == NULL){
table->entries = newEntry;
return newEntry;
} else{
TableNode* oldEntry = table->entries;
table->entries = newEntry;
newEntry->next = oldEntry;
return newEntry;
}
}
//uncomment the below main function along with the headers above for a simple standalone test of table and entry creation
/*
int main(){
char* String = "STRING";
char* X = "X";
Value* ofX = (Value*)malloc(sizeof(Value));
ofX->value_of_char = X;
SymbolTable* Second = CreateScope(NULL, 2,2);
printf("Line number is %d, Column number of scope is %d\n",Second->Line_Number,Second->Column_Number);
TableNode* First_Entry = CreateEntry(Second,String,X,ofX,-1);
printf("The value of the first entry is %s\n",First_Entry->value->value_of_char);
return 0;
}
*/