2 Star 6 Fork 0

秩启/Lox++

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Environment.h 1.97 KB
一键复制 编辑 原始数据 按行查看 历史
秩启 提交于 2022-05-07 15:52 . Support calling superclass methods
//
// Created by Gorun on 2022/5/3.
//
#ifndef LOXPP_ENVIRONMENT_H
#define LOXPP_ENVIRONMENT_H
#include <any>
#include <map>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include "Error.h"
#include "Token.h"
using namespace std;
class Environment: public enable_shared_from_this<Environment> {
private:
map<string, any> values;
public:
shared_ptr<Environment> enclosing;
Environment() {
enclosing = nullptr;
}
explicit Environment(shared_ptr<Environment> enclosing) {
this->enclosing = std::move(enclosing);
}
any get(const Token& name) {
auto element = values.find(name.lexeme);
if (element!=values.end()) { //Then there's a variable named by, well, name
return element->second;
}
if (enclosing!=nullptr)
return enclosing->get(name);
throw RuntimeError(name, "Undefined variable '"+name.lexeme+"'.");
}
any getAt(int distance, const string& name) {
return ancestor(distance)->values[name];
}
void assign(const Token& name, any value) {
auto element = values.find(name.lexeme);
if (element!=values.end()) {
element->second = move(value);
return;
}
if (enclosing!=nullptr) {
enclosing->assign(name, value);
return;
}
throw RuntimeError(name, "Undefined variable '"+name.lexeme+"'.");
}
void assignAt(int distance, const Token& name, any value) {
ancestor(distance)->values[name.lexeme]=move(value);
}
//!Attention! This method moves value away!
void define(const string& name, any value) {
values[name]=move(value);
}
shared_ptr<Environment> ancestor(int distance) {
shared_ptr<Environment> environment = shared_from_this();
for (int i=0; i<distance; i++) {
environment=environment->enclosing;
}
return environment;
}
};
#endif //LOXPP_ENVIRONMENT_H
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/rankrev/loxpp.git
git@gitee.com:rankrev/loxpp.git
rankrev
loxpp
Lox++
master

搜索帮助