-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluator.cpp
52 lines (41 loc) · 1.36 KB
/
evaluator.cpp
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
#include "evaluator.h"
#include "TreeNode.h"
#include <iostream>
using namespace std;
double ExpressionEvaluatorVisitor::visit(StatementListNode *node) {
for (TreeNode *statement : node->statements) {
auto result = statement->accept(this);
if (statement->isExpression()) {
cout << result << endl; // TODO: print expression.
}
}
return 0;
}
double ExpressionEvaluatorVisitor::visit(ConstantNode *node) {
const Number *number = node->value;
return number->getValue();
}
double ExpressionEvaluatorVisitor::visit(VariableNode *node) {
std::string name = node->name;
return variablesTable.at(name);
}
double ExpressionEvaluatorVisitor::visit(OperatorNode *node) {
auto leftResult = node->left->accept(this);
auto rightResult = node->right->accept(this);
return node->oper->apply(leftResult, rightResult);
}
double ExpressionEvaluatorVisitor::visit(AssignmentNode *node) {
auto variableName = node->variable->name;
auto result = node->expression->accept(this);
variablesTable[variableName] = result;
return result;
}
double ExpressionEvaluatorVisitor::visit(BranchNode *node) {
auto condition = node->condition->accept(this);
if (isTrue(condition)) {
node->ifTrue->accept(this);
} else if (node->ifFalse != nullptr) {
node->ifFalse->accept(this);
}
return 0;
}