A simple scripting language in C++
Ferenc Szontágh
2025-04-18 fb8d8f9f5bb4a1f7736d927a346d4bf834a28ffa
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
 #ifndef INTERPRETER_CONDITIONAL_STATEMENT_NODE_HPP
 #define INTERPRETER_CONDITIONAL_STATEMENT_NODE_HPP
 
 #include <vector>
 #include <memory>
 #include <string>
 #include "Interpreter/StatementNode.hpp"
 #include "Interpreter/ExpressionNode.hpp"
 
 namespace Interpreter {
 
 /**
  * @brief Statement node representing an if-else conditional block.
  */
 class ConditionalStatementNode : public StatementNode {
     std::unique_ptr<ExpressionNode> condition_;
     std::vector<std::unique_ptr<StatementNode>> thenBranch_;
     std::vector<std::unique_ptr<StatementNode>> elseBranch_;
 
   public:
     ConditionalStatementNode(
         std::unique_ptr<ExpressionNode> condition,
         std::vector<std::unique_ptr<StatementNode>> thenBranch,
         std::vector<std::unique_ptr<StatementNode>> elseBranch,
         const std::string & file_name,
         int line,
         size_t column
     ) : StatementNode(file_name, line, column),
         condition_(std::move(condition)),
         thenBranch_(std::move(thenBranch)),
         elseBranch_(std::move(elseBranch)) {}
 
     void interpret(class Interpreter & interpreter) const override {
         // Evaluate condition
         auto val = condition_->evaluate(interpreter);
         bool cond = false;
         if (val.getType() == Symbols::Variables::Type::BOOLEAN) {
             cond = val.get<bool>();
         } else {
             throw std::runtime_error("Condition did not evaluate to boolean at " + filename_ +
                                      ":" + std::to_string(line_) + "," + std::to_string(column_));
         }
         // Execute appropriate branch
         const auto & branch = cond ? thenBranch_ : elseBranch_;
         for (const auto & stmt : branch) {
             stmt->interpret(interpreter);
         }
     }
 
     std::string toString() const override {
         return "ConditionalStatementNode at " + filename_ + ":" + std::to_string(line_);
     }
 };
 
 } // namespace Interpreter
 
 #endif // INTERPRETER_CONDITIONAL_STATEMENT_NODE_HPP