-
Notifications
You must be signed in to change notification settings - Fork 0
/
exp.cpp
81 lines (62 loc) · 2.14 KB
/
exp.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
#include "exp.h"
#include <math.h>
Expression::Expression() {}
Expression::~Expression() {}
/* Implementation notes: the ConstantExp subclass*/
ConstantExp::ConstantExp(int value) { this->value = value; }
int ConstantExp::eval(EvalState &state) { return value; }
QString ConstantExp::toQString() { return QString::number(value); }
ExpressionType ConstantExp::getType() { return CONSTANT; }
int ConstantExp::getValue() { return value; }
/* Implementation notes: the IdentifierExp subclass*/
IdentifierExp::IdentifierExp(QString name) {
if (name == "LET") throw("SYNTAX ERROR");
this->name = name;
}
int IdentifierExp::eval(EvalState &state) {
if (!state.isDefined(name)) throw("VARIABLE NOT DEFINED");
return state.getValue(name);
}
QString IdentifierExp::toQString() { return name; }
ExpressionType IdentifierExp::getType() { return IDENTIFIER; }
QString IdentifierExp::getName() { return name; }
/* Implementation notes: the CompoundExp subclass*/
CompoundExp::CompoundExp(QString op, Expression *lhs, Expression *rhs) {
this->op = op;
this->lhs = lhs;
this->rhs = rhs;
}
CompoundExp::~CompoundExp() {
delete lhs;
delete rhs;
}
int CompoundExp::eval(EvalState &state) {
if (op == "=") {
if (lhs->getType() != IDENTIFIER) {
throw("Illegal variable");
}
int val = rhs->eval(state);
state.setValue(((IdentifierExp *)lhs)->getName(), val);
return val;
}
int left = lhs->eval(state);
int right = rhs->eval(state);
if (op == "+") return left + right;
if (op == "-") return left - right;
if (op == "*") return left * right;
if (op == "/") {
if (right == 0) {
throw("DIVIDE BY ZERO");
}
return left / right;
}
if (op == "**") return (int)pow(left, right);
throw("Illegal operator in expression");
}
QString CompoundExp::toQString() {
return '(' + lhs->toQString() + ' ' + op + ' ' + rhs->toQString() + ')';
}
ExpressionType CompoundExp::getType() { return COMPOUND; }
QString CompoundExp::getOp() { return op; }
Expression *CompoundExp::getLHS() { return lhs; }
Expression *CompoundExp::getRHS() { return rhs; }