-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterpreter.cpp
More file actions
243 lines (209 loc) · 8.78 KB
/
Copy pathinterpreter.cpp
File metadata and controls
243 lines (209 loc) · 8.78 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
#include "interpreter.h"
#include <iostream>
#include <stdexcept>
#include <cmath>
// Utility functions to test if a numeric string is integer or float
static bool isIntRaw(const std::string& s) {
if (s.empty()) return false;
size_t i = (s[0] == '-') ? 1 : 0;
if (i >= s.size()) return false;
for (; i < s.size(); ++i) if (s[i] < '0' || s[i] > '9') return false;
return true;
}
static bool isFloatRaw(const std::string& s) {
if (s.empty()) return false;
bool dot = false, digit = false;
size_t i = (s[0] == '-') ? 1 : 0;
for (; i < s.size(); ++i) {
if (s[i] >= '0' && s[i] <= '9') digit = true;
else if (s[i] == '.' && !dot) dot = true;
else return false;
}
return digit && dot;
}
Interpreter::Interpreter() {
envStack.push_back(std::unordered_map<std::string, Value>()); // global scope
}
void Interpreter::run(const std::vector<StmtPtr>& program) {
for (const auto& s : program) exec(s.get());
}
// Map type names in source code to runtime ValueType
ValueType Interpreter::typeFromName(const std::string& t) const {
if (t == "int") return ValueType::INT;
if (t == "float") return ValueType::FLOAT;
if (t == "bool") return ValueType::BOOL;
if (t == "string") return ValueType::STRING;
if (t == "char") return ValueType::CHAR;
throw std::runtime_error("Unknown type: " + t);
}
bool Interpreter::hasVar(const std::string& name) const {
for (int i = (int)envStack.size() - 1; i >= 0; --i)
if (envStack[i].count(name)) return true;
return false;
}
Value Interpreter::getVar(const std::string& name) const {
for (int i = (int)envStack.size() - 1; i >= 0; --i) {
auto it = envStack[i].find(name);
if (it != envStack[i].end()) return it->second;
}
throw std::runtime_error("Undefined variable: " + name);
}
void Interpreter::setVar(const std::string& name, const Value& v) {
for (int i = (int)envStack.size() - 1; i >= 0; --i) {
auto it = envStack[i].find(name);
if (it != envStack[i].end()) { it->second = v; return; }
}
throw std::runtime_error("Undefined variable: " + name);
}
// Evaluate an expression and produce a Value
Value Interpreter::eval(const Expr* e) {
if (auto n = dynamic_cast<const NumberExpr*>(e)) {
if (isIntRaw(n->raw)) return Value::Int(std::stoll(n->raw));
if (isFloatRaw(n->raw)) return Value::Float(std::stod(n->raw));
return Value::String(n->raw);
}
if (auto b = dynamic_cast<const BoolExpr*>(e)) return Value::Bool(b->v);
if (auto s = dynamic_cast<const StringExpr*>(e)) return Value::String(s->v);
if (auto c = dynamic_cast<const CharExpr*>(e)) return Value::Char(c->v);
if (auto v = dynamic_cast<const VarExpr*>(e)) return getVar(v->name);
if (auto u = dynamic_cast<const UnaryExpr*>(e)) {
Value r = eval(u->right.get());
if (u->op == "!") {
bool bb = castTo(r, ValueType::BOOL).b;
return Value::Bool(!bb);
}
if (u->op == "-") {
if (r.type == ValueType::FLOAT) return Value::Float(-r.f);
if (r.type == ValueType::INT) return Value::Int(-r.i);
Value rr = castTo(r, ValueType::FLOAT);
return Value::Float(-rr.f);
}
throw std::runtime_error("Unsupported unary op: " + u->op);
}
if (auto bin = dynamic_cast<const BinaryExpr*>(e)) {
Value L = eval(bin->left.get());
Value R = eval(bin->right.get());
const std::string& op = bin->op;
if (op == "&&") return Value::Bool(castTo(L, ValueType::BOOL).b && castTo(R, ValueType::BOOL).b);
if (op == "||") return Value::Bool(castTo(L, ValueType::BOOL).b || castTo(R, ValueType::BOOL).b);
if (op == "==" || op == "!=") {
bool eq;
if (L.type == ValueType::STRING || R.type == ValueType::STRING)
eq = castTo(L, ValueType::STRING).s == castTo(R, ValueType::STRING).s;
else if (L.type == ValueType::FLOAT || R.type == ValueType::FLOAT)
eq = castTo(L, ValueType::FLOAT).f == castTo(R, ValueType::FLOAT).f;
else
eq = castTo(L, ValueType::INT).i == castTo(R, ValueType::INT).i;
return Value::Bool(op == "==" ? eq : !eq);
}
if (op == "<" || op == "<=" || op == ">" || op == ">=") {
double a = castTo(L, ValueType::FLOAT).f;
double b = castTo(R, ValueType::FLOAT).f;
bool res = false;
if (op == "<") res = a < b;
else if (op == "<=") res = a <= b;
else if (op == ">") res = a > b;
else res = a >= b;
return Value::Bool(res);
}
if (op == "+" && (L.type == ValueType::STRING || R.type == ValueType::STRING)) {
return Value::String(castTo(L, ValueType::STRING).s + castTo(R, ValueType::STRING).s);
}
bool floaty = (L.type == ValueType::FLOAT || R.type == ValueType::FLOAT);
if (floaty) {
double a = castTo(L, ValueType::FLOAT).f;
double b = castTo(R, ValueType::FLOAT).f;
if (op == "+") return Value::Float(a + b);
if (op == "-") return Value::Float(a - b);
if (op == "*") return Value::Float(a * b);
if (op == "/") return Value::Float(a / b);
if (op == "%") return Value::Float(std::fmod(a, b));
} else {
long long a = castTo(L, ValueType::INT).i;
long long b = castTo(R, ValueType::INT).i;
if (op == "+") return Value::Int(a + b);
if (op == "-") return Value::Int(a - b);
if (op == "*") return Value::Int(a * b);
if (op == "/") return Value::Int(b == 0 ? 0 : a / b);
if (op == "%") return Value::Int(b == 0 ? 0 : a % b);
}
throw std::runtime_error("Unsupported binary op: " + op);
}
if (auto call = dynamic_cast<const CallExpr*>(e)) {
if (call->callee == "input") {
if (!call->args.empty()) throw std::runtime_error("input() takes no args");
std::string line;
std::getline(std::cin, line);
return Value::String(line);
}
auto it = functions.find(call->callee);
if (it == functions.end()) throw std::runtime_error("Undefined function: " + call->callee);
const FuncDeclStmt* fn = it->second;
if (fn->params.size() != call->args.size())
throw std::runtime_error("Arg count mismatch for " + call->callee);
envStack.push_back(std::unordered_map<std::string, Value>());
for (size_t i = 0; i < fn->params.size(); ++i)
envStack.back()[fn->params[i]] = eval(call->args[i].get());
for (const auto& st : fn->body) exec(st.get());
Value ret = eval(fn->returnExpr.get());
envStack.pop_back();
return ret;
}
throw std::runtime_error("Unknown expression type");
}
// Execute a statement. Dispatch based on dynamic type.
void Interpreter::exec(const Stmt* s) {
if (auto v = dynamic_cast<const VarDeclStmt*>(s)) {
ValueType t = typeFromName(v->typeName);
Value init;
if (v->init) init = eval(v->init.get());
envStack.back()[v->name] = castTo(init, t);
return;
}
if (auto a = dynamic_cast<const AssignStmt*>(s)) {
if (!hasVar(a->name)) throw std::runtime_error("Undefined variable: " + a->name);
Value old = getVar(a->name);
Value nv = eval(a->value.get());
setVar(a->name, castTo(nv, old.type));
return;
}
if (auto p = dynamic_cast<const PrintStmt*>(s)) {
std::cout << eval(p->value.get()).toString() << "\n";
return;
}
if (auto e = dynamic_cast<const ExprStmt*>(s)) {
(void)eval(e->expr.get());
return;
}
if (auto f = dynamic_cast<const FuncDeclStmt*>(s)) {
functions[f->name] = f;
return;
}
// loop: while
if (auto w = dynamic_cast<const WhileStmt*>(s)) {
while (castTo(eval(w->condition.get()), ValueType::BOOL).b) {
for (const auto& st : w->body) exec(st.get());
}
return;
}
// loop: for
if (auto fr = dynamic_cast<const ForStmt*>(s)) {
if (fr->init) exec(fr->init.get());
while (castTo(eval(fr->condition.get()), ValueType::BOOL).b) {
for (const auto& st : fr->body) exec(st.get());
if (fr->step) exec(fr->step.get());
}
return;
}
// conditional: if / else
if (auto ifs = dynamic_cast<const IfStmt*>(s)) {
bool cond = castTo(eval(ifs->condition.get()), ValueType::BOOL).b;
if (cond) {
for (const auto& st : ifs->thenBody) exec(st.get());
} else {
for (const auto& st : ifs->elseBody) exec(st.get());
}
return;
}
throw std::runtime_error("Unknown statement type");
}