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.
nudt-compiler-cpp/src/sem/SymbolTable.cpp

46 lines
1.1 KiB

// 维护局部变量声明的注册与查找。
#include "include/sem/SymbolTable.h"
void SymbolTable::EnterScope() { scopes_.emplace_back(); }
void SymbolTable::ExitScope() {
if (!scopes_.empty()) {
scopes_.pop_back();
}
}
void SymbolTable::Add(const std::string& name,
SysYParser::VarDefContext* decl) {
if (scopes_.empty()) {
EnterScope();
}
scopes_.back()[name] = decl;
}
bool SymbolTable::ContainsInCurrent(const std::string& name) const {
if (scopes_.empty()) {
return false;
}
return scopes_.back().find(name) != scopes_.back().end();
}
bool SymbolTable::Contains(const std::string& name) const {
for (auto it = scopes_.rbegin(); it != scopes_.rend(); ++it) {
if (it->find(name) != it->end()) {
return true;
}
}
return false;
}
SysYParser::VarDefContext* 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;
}