Skip to content

Commit bb0c7c4

Browse files
committed
Fixed 'uninitialized variable' problem in PL/0 interpreter
1 parent 41e3360 commit bb0c7c4

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

language/pl0/pl0.cc

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -206,14 +206,17 @@ struct Environment
206206
Environment(shared_ptr<SymbolScope> scope, shared_ptr<Environment> outer)
207207
: scope(scope), outer(outer) {}
208208

209-
int get_value(const string& ident) const {
209+
int get_value(const shared_ptr<AstPL0> ast, const string& ident) const {
210210
auto it = scope->constants.find(ident);
211211
if (it != scope->constants.end()) {
212212
return it->second;
213213
} else if (scope->variables.count(ident)) {
214+
if (variables.find(ident) == variables.end()) {
215+
throw_runtime_error(ast, "uninitialized variable '" + ident + "'...");
216+
}
214217
return variables.at(ident);
215218
}
216-
return outer->get_value(ident);
219+
return outer->get_value(ast, ident);
217220
}
218221

219222
void set_variable(const string& ident, int val) {
@@ -395,7 +398,7 @@ struct Interpreter
395398
}
396399

397400
static int eval_ident(const shared_ptr<AstPL0> ast, shared_ptr<Environment> env) {
398-
return env->get_value(ast->token);
401+
return env->get_value(ast, ast->token);
399402
}
400403

401404
static int eval_number(const shared_ptr<AstPL0> ast, shared_ptr<Environment> env) {
@@ -453,4 +456,3 @@ int main(int argc, const char** argv)
453456
}
454457

455458
// vim: et ts=4 sw=4 cin cino={1s ff=unix
456-

0 commit comments

Comments
 (0)