-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEvalVisitor.cpp
93 lines (79 loc) · 1.97 KB
/
EvalVisitor.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//
// Created by nalle on 8/15/2017.
//
#include "EvalVisitor.h"
#include <string>
#include <iostream>
using std::string;
string EvalVisitor::getResult()
{
return mResultStr;
}
void EvalVisitor::visit(std::shared_ptr<ASTNode> node)
{
}
void EvalVisitor::visit(std::shared_ptr<ASTExp> node)
{
}
void EvalVisitor::visit(std::shared_ptr<ASTOp> node)
{
}
void EvalVisitor::visit(std::shared_ptr<ASTAdd> node)
{
node->getRight()->accept(*this);
auto right = mTmpRes;
node->getLeft()->accept(*this);
mTmpRes += right;
mResultStr = std::to_string(mTmpRes);
}
void EvalVisitor::visit(std::shared_ptr<ASTSub> node)
{
node->getRight()->accept(*this);
auto right = mTmpRes;
node->getLeft()->accept(*this);
mTmpRes -= right;
mResultStr = std::to_string(mTmpRes);
}
void EvalVisitor::visit(std::shared_ptr<ASTMul> node)
{
node->getRight()->accept(*this);
auto right = mTmpRes;
node->getLeft()->accept(*this);
mTmpRes *= right;
mResultStr = std::to_string(mTmpRes);
}
void EvalVisitor::visit(std::shared_ptr<ASTDiv> node)
{
node->getRight()->accept(*this);
auto right = mTmpRes;
node->getLeft()->accept(*this);
mTmpRes /= right;
mResultStr = std::to_string(mTmpRes);
}
void EvalVisitor::visit(std::shared_ptr<ASTVar> node)
{
/* read value from var */
if ( mVarMap.find(node->getVarName()) != mVarMap.end() )
{
mTmpRes = mVarMap.at(node->getVarName());
mResultStr = std::to_string(mTmpRes);
}
else
{
std::cerr << "undefined variable " << node->getVarName() << "\n";
exit(1);
}
}
void EvalVisitor::visit(std::shared_ptr<ASTNum> node)
{
mTmpRes = std::stof(node->getValueStr());
mResultStr = std::to_string(mTmpRes);
}
void EvalVisitor::visit(std::shared_ptr<ASTAssign> node)
{
node->getRight()->accept(*this);
/* save variable value to map */
mVarMap[node->getLeft()->getVarName()] = mTmpRes;
/* assign does not need a printing */
mResultStr = "";
}