A simple scripting language in C++
Ferenc Szontágh
2025-04-18 9a186053a690f2216b43355549c8aa7e2959583c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#ifndef UNARY_EXPRESSION_NODE_HPP
#define UNARY_EXPRESSION_NODE_HPP
 
#include <memory>
#include <string>
 
#include "ExpressionNode.hpp"
 
namespace Interpreter {
 
class UnaryExpressionNode : public ExpressionNode {
    std::string                     op_;
    std::unique_ptr<ExpressionNode> operand_;
 
  public:
    UnaryExpressionNode(std::string op, std::unique_ptr<ExpressionNode> operand) :
        op_(std::move(op)),
        operand_(std::move(operand)) {}
 
    Symbols::Value evaluate(Interpreter & interpreter) const override {
        auto value = operand_->evaluate(interpreter);
        auto type  = value.getType();
 
        if (type == Symbols::Variables::Type::INTEGER) {
            int v = value.get<int>();
            if (op_ == "-") {
                return Symbols::Value(-v);
            }
            if (op_ == "+") {
                return Symbols::Value(+v);
            }
        } else if (type == Symbols::Variables::Type::DOUBLE) {
            double v = value.get<double>();
            if (op_ == "-") {
                return Symbols::Value(-v);
            }
            if (op_ == "+") {
                return Symbols::Value(+v);
            }
        } else if (type == Symbols::Variables::Type::FLOAT) {
            float v = value.get<float>();
            if (op_ == "-") {
                return Symbols::Value(-v);
            }
            if (op_ == "+") {
                return Symbols::Value(+v);
            }
        } else if (type == Symbols::Variables::Type::BOOLEAN) {
            bool v = value.get<bool>();
            if (op_ == "!") {
                return Symbols::Value(!v);
            }
        } else if (type == Symbols::Variables::Type::STRING) {
            std::string s = value.get<std::string>();
            if (op_ == "-") {
                return Symbols::Value(s);
            }
            if (op_ == "+") {
                return Symbols::Value(s);
            }
        }
 
        throw std::runtime_error("Unsupported unary operator '" + op_ +
                                 "' for type: " + Symbols::Variables::TypeToString(type));
    }
 
    std::string toString() const override { return "(" + op_ + operand_->toString() + ")"; }
};
 
}  // namespace Interpreter
 
#endif  // UNARY_EXPRESSION_NODE_HPP