GSC Interpreter
A Turing-complete interpreter developed for a compiler course
Loading...
Searching...
No Matches
environment.cpp
Go to the documentation of this file.
1#include "gsc/environment.hpp"
2#include "gsc/runtimeError.hpp"
3
4Environment::Environment() : enclosing(nullptr) {}
5
6Environment::Environment(std::shared_ptr<Environment> enclosing)
7 : enclosing(std::move(enclosing)) {}
8
9std::any Environment::get(const Token &name) const {
10 auto it = values.find(name.getLexeme());
11 if (it != values.end()) {
12 return it->second;
13 }
14 if (enclosing) {
15 return enclosing->get(name);
16 }
17 throw RuntimeError(std::make_shared<Token>(name),
18 "Undefined variable '" + name.getLexeme() + "'.");
19}
20
21void Environment::assign(const Token &name, std::any value) {
22 auto it = values.find(name.getLexeme());
23 if (it != values.end()) {
24 it->second = std::move(value);
25 return;
26 }
27 if (enclosing) {
28 enclosing->assign(name, std::move(value));
29 return;
30 }
31 throw RuntimeError(std::make_shared<Token>(name),
32 "Undefined variable '" + name.getLexeme() + "'.");
33}
34
35void Environment::define(const std::string &name, std::any value) {
36 values[name] = std::move(value);
37}