xlang/bootstrap/scope.hh

43 lines
707 B
C++
Raw Normal View History

2023-01-07 07:54:53 +00:00
#pragma once
#include <optional>
#include <string>
#include <unordered_map>
#include <vector>
namespace xlang {
template <typename T>
class Scope {
std::vector<std::unordered_map<std::string, T>> stack;
public:
void enter() {
stack.emplace_back();
}
void leave() {
stack.pop_back();
}
void add(const std::string &name, T v) {
stack.back().emplace(name, v);
}
std::optional<T> get(const std::string &name) {
for (auto scope = stack.end() - 1;; scope--) {
auto it = scope->find(name);
if (it != scope->end()) {
return it->second;
}
if (scope == stack.begin()) {
break;
}
}
return {};
}
};
} // namespace xlang