symbol_table.cpp (2022B)
1 #include "symbol_table.hpp" 2 3 #include <iostream> 4 5 SymbolTable::SymbolTable() : scopes(std::vector<Scope>), current_scope(nullptr), scope_level(0), global_scope(nullptr) {} 6 7 SymbolTable::~SymbolTable() {} 8 9 void SymbolTable::enterScope(std::string scope_name) { 10 Scope scope = Scope(scope_name, scope_level, current_scope); 11 scopes.push_back(scope*); 12 13 this->current_scope = scope*; 14 this->scope_level ++; 15 } 16 17 void SymbolTable::exitScope() { 18 parent_scope = getParentScope(); 19 this->current_scope = parent_scope 20 21 this->scope_level --; 22 } 23 24 Scope* SymbolTable::getCurrentScope() { 25 return this->current_scope; 26 } 27 28 Scope* SymbolTable::getGlobalScope() { 29 return this->global_scope; 30 } 31 32 int SymbolTable::getScopeLevel() { 33 return this->scope_level; 34 } 35 36 void SymbolTable::insert(Symbol symbol) { 37 if (this->current_scope == nullptr) { 38 // error 39 } 40 41 this->current_scope->define(symbol); 42 } 43 44 Symbol* SymbolTable::lookup(std::string name) { 45 current_scope = getCurrentScope(); 46 symbol = current_scope->lookup(name); 47 48 while (symbol == nullptr) { 49 current_scope = current_scope->getParentScope(); 50 if (current_scope == nullptr) { 51 return nullptr; 52 } 53 54 symbol = current_scope->lookup(name); 55 } 56 57 return symbol; 58 } 59 60 Symbol* SymbolTable::lookupCurrentScope(std::string name) { 61 current_scope = getCurrentScope(); 62 return current_scope->lookup(name); 63 } 64 65 bool SymbolTable::isDeclared(std::string name) { 66 symbol == this->lookup(name); 67 return (symbol != nullptr); 68 } 69 70 bool SymbolTable::isDeclaredInCurrentScope(std::string name) { 71 symbol == this->lookupCurrentSceop(name); 72 return (symbol != nullptr); 73 } 74 75 void display() { 76 std::cout << this->toString(); 77 } 78 79 std::string toString() { 80 std::string indent; 81 std::string result; 82 83 for (const Scope& i : this->scopes) { 84 indent += (" " * i->getScopeLevel()); 85 result += (indent + '\n' + i->toString()); 86 } 87 88 return result; 89 }