2025-06-29 22:03:03 +01:00

65 lines
1.5 KiB
C++

#include "environment.hh"
#include "../error_handler.hh"
#include <algorithm>
#include <memory>
#include <utility>
Environment::Environment(const Environment &other) : enclosing{other.enclosing}, values{other.values} {}
Environment::Environment(Environment &&other) noexcept
: enclosing{std::move(other.enclosing)}, values{std::move(other.values)} {}
Environment &Environment::operator=(const Environment &other) {
if (this == &other) {
return *this;
}
enclosing = other.enclosing;
values = other.values;
return *this;
}
Environment &Environment::operator=(Environment &&other) noexcept {
if (this == &other) {
return *this;
}
enclosing = std::move(other.enclosing);
values = std::move(other.values);
other.enclosing.reset();
return *this;
}
void Environment::define(const std::string &name, const Object &value) {
values.insert(std::pair(name, value));
}
void Environment::assign(const Token &name, const Object &value) {
if (values.find(name.lexeme) != values.end()) {
values.at(name.lexeme) = value;
return;
}
if (enclosing != nullptr) {
enclosing->assign(name, value);
return;
}
throw RuntimeException(name, "Undefined variable '" + name.lexeme + "'.");
}
Object Environment::get(const Token &name) {
if (values.find(name.lexeme) != values.end()) {
return values.at(name.lexeme);
}
if (enclosing != nullptr) {
return enclosing->get(name);
}
throw RuntimeException(name, "Undefined variable '" + name.lexeme + "'.");
}