forked from NUDT-compiler/nudt-compiler-cpp
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
39 lines
966 B
39 lines
966 B
#include "sem/SymbolTable.h"
|
|
|
|
#include <stdexcept>
|
|
|
|
void SymbolTable::EnterScope() { scopes_.emplace_back(); }
|
|
|
|
void SymbolTable::ExitScope() {
|
|
if (scopes_.empty()) {
|
|
throw std::runtime_error("作用域栈为空,无法退出");
|
|
}
|
|
scopes_.pop_back();
|
|
}
|
|
|
|
bool SymbolTable::Declare(const std::string& name, const SymbolInfo* symbol) {
|
|
if (scopes_.empty()) {
|
|
EnterScope();
|
|
}
|
|
auto& scope = scopes_.back();
|
|
return scope.emplace(name, symbol).second;
|
|
}
|
|
|
|
const SymbolInfo* SymbolTable::Lookup(const std::string& name) const {
|
|
for (auto it = scopes_.rbegin(); it != scopes_.rend(); ++it) {
|
|
auto found = it->find(name);
|
|
if (found != it->end()) {
|
|
return found->second;
|
|
}
|
|
}
|
|
return nullptr;
|
|
}
|
|
|
|
const SymbolInfo* SymbolTable::LookupCurrent(const std::string& name) const {
|
|
if (scopes_.empty()) {
|
|
return nullptr;
|
|
}
|
|
auto found = scopes_.back().find(name);
|
|
return found == scopes_.back().end() ? nullptr : found->second;
|
|
}
|