
#include "symboltable.h"


SymbolTable::SymbolTable()
{
    scope* globalScope = new scope();
    table.push_back(globalScope);
}

SymbolTable::~SymbolTable()
{
    for(scope* s : table)
        delete s;
}

void SymbolTable::push_scope()
{
    scope* s = new scope();
    table.push_back(s);
}

void SymbolTable::pop_scope()
{
    scope* current = table.back();
    table.pop_back();
    delete current;
}

void SymbolTable::insert(llvm::Type* type, const std::string& id, llvm::Value* decl)
{
    scope* current = table.back();
    auto x = current->find(id);
    if(x == current->end())
    {
        SymbolTableEntry* entry = new SymbolTableEntry();
        entry->type = type;
        entry->name = id;
        entry->ref = decl;
        (*current)[id] = entry;
    }
    else
    {
        // Handle error: variable already defined
    }
}

SymbolTableEntry* SymbolTable::lookup(const std::string& id)
{
    for(std::vector<scope*>::reverse_iterator sc = table.rbegin(); sc != table.rend(); sc++)
    {
        auto x = (*sc)->find(id);
        if(x != (*sc)->end())
            return x->second;
    }

    return nullptr;
}
