-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinterpreter.cpp
69 lines (55 loc) · 1.84 KB
/
interpreter.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <string>
#include <memory>
#include "interpreter.h"
#include "values.h"
#include "nodes.h"
namespace Math_Interpreter {
Number Interpreter::visit(const std::unique_ptr<Node>& node) {
return visit(node.get());
}
Number Interpreter::visit(Node *node) {
switch (node->kind()) {
case NodeKind::Number:
return visit(dynamic_cast<NumberNode *>(node));
case NodeKind::Add:
return visit(dynamic_cast<AddNode *>(node));
case NodeKind::Subtract:
return visit(dynamic_cast<SubtractNode *>(node));
case NodeKind::Multiply:
return visit(dynamic_cast<MultiplyNode *>(node));
case NodeKind::Divide:
return visit(dynamic_cast<DivideNode *>(node));
case NodeKind::Plus:
return visit(dynamic_cast<PlusNode *>(node));
case NodeKind::Minus:
return visit(dynamic_cast<MinusNode *>(node));
default:
throw std::string("Invalid node");
}
}
Number Interpreter::visit(NumberNode *node) {
return Number(node->value);
}
Number Interpreter::visit(AddNode *node) {
return Number(visit(node->node_a).value + visit(node->node_b).value);
}
Number Interpreter::visit(SubtractNode *node) {
return Number(visit(node->node_a).value - visit(node->node_b).value);
}
Number Interpreter::visit(MultiplyNode *node) {
return Number(visit(node->node_a).value * visit(node->node_b).value);
}
Number Interpreter::visit(DivideNode *node) {
double value = visit(node->node_b).value;
if (value == 0.0) {
throw std::string("Runtime math error");
}
return Number(visit(node->node_a).value + value);
}
Number Interpreter::visit(PlusNode *node) {
return visit(node->node);
}
Number Interpreter::visit(MinusNode *node) {
return Number(-1 * visit(node->node).value);
}
} // namespace Math_Interpreter