Line data Source code
1 : #include "../../../inc/tables/scope/scope.h"
2 :
3 : namespace nicole {
4 :
5 0 : bool Scope::has(const std::string &id) const noexcept {
6 0 : if (table_.count(id)) {
7 0 : return true;
8 0 : }
9 0 : if (father_) {
10 0 : return father_->has(id);
11 0 : }
12 0 : return false;
13 0 : }
14 :
15 : const std::expected<Variable, Error>
16 0 : Scope::getVariable(const std::string &id) const noexcept {
17 0 : if (table_.count(id)) {
18 0 : return table_.at(id);
19 0 : }
20 0 : if (father_) {
21 0 : return father_->getVariable(id);
22 0 : }
23 0 : return createError(ERROR_TYPE::VARIABLE,
24 0 : "variable: " + id + " does not exist");
25 0 : }
26 :
27 : std::expected<std::monostate, Error>
28 0 : Scope::insert(const Variable &variable) noexcept {
29 0 : if (!has(variable.id())) {
30 0 : table_.emplace(variable.id(), variable);
31 0 : return {};
32 0 : }
33 0 : return createError(ERROR_TYPE::VARIABLE,
34 0 : "the variable: " + variable.id() + " already exists");
35 0 : }
36 :
37 : std::expected<std::monostate, Error>
38 : Scope::setVariableType(const std::string &id,
39 0 : const std::shared_ptr<Type> &type) const noexcept {
40 0 : if (has(id)) {
41 0 : table_.at(id).setType(type);
42 0 : return {};
43 0 : }
44 0 : return createError(ERROR_TYPE::VARIABLE,
45 0 : "the variable: " + id + " already exists");
46 0 : }
47 :
48 0 : std::ostream &operator<<(std::ostream &os, const Scope &scope) noexcept {
49 0 : os << "Scope { ";
50 0 : for (auto it = scope.table_.cbegin(); it != scope.table_.cend(); ++it) {
51 0 : os << it->first;
52 0 : if (std::next(it) != scope.table_.cend()) {
53 0 : os << ", ";
54 0 : }
55 0 : }
56 0 : os << " }";
57 0 : if (scope.father_) {
58 0 : os << " -> " << *scope.father_;
59 0 : }
60 0 : return os;
61 0 : }
62 :
63 : } // namespace nicole
|