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.
40 lines
1023 B
40 lines
1023 B
// 维护对象符号的注册与按作用域查找。
|
|
|
|
#include "sem/SymbolTable.h"
|
|
|
|
#include <stdexcept>
|
|
|
|
SymbolTable::SymbolTable() : scopes_(1) {}
|
|
|
|
void SymbolTable::EnterScope() { scopes_.emplace_back(); }
|
|
|
|
void SymbolTable::ExitScope() {
|
|
if (scopes_.size() <= 1) {
|
|
throw std::runtime_error("symbol table scope underflow");
|
|
}
|
|
scopes_.pop_back();
|
|
}
|
|
|
|
bool SymbolTable::Add(const ObjectBinding& symbol) {
|
|
auto& scope = scopes_.back();
|
|
return scope.emplace(symbol.name, symbol).second;
|
|
}
|
|
|
|
bool SymbolTable::ContainsInCurrentScope(std::string_view name) const {
|
|
const auto& scope = scopes_.back();
|
|
return scope.find(std::string(name)) != scope.end();
|
|
}
|
|
|
|
const ObjectBinding* SymbolTable::Lookup(std::string_view name) const {
|
|
const std::string key(name);
|
|
for (auto it = scopes_.rbegin(); it != scopes_.rend(); ++it) {
|
|
auto found = it->find(key);
|
|
if (found != it->end()) {
|
|
return &found->second;
|
|
}
|
|
}
|
|
return nullptr;
|
|
}
|
|
|
|
size_t SymbolTable::Depth() const { return scopes_.size(); }
|