rs-monkey-lang
rs-monkey-lang copied to clipboard
Cascading returns are not collapsed
Add the following test cases
("return if (true) { return 10; };", Some(Object::Int(10))),
("return if (true) { return if (true) { return 10; }; };", Some(Object::Int(10))),
("return if (true) { return if (false) { return 10; } else { return 5; }; };", Some(Object::Int(5))),
to the test_return_stmt function in src/evaluator/mod.rs to see what I mean.
For e.g. the tests fail as follows:
left: `Some(Int(10))`,
right: `Some(ReturnValue(Int(10)))`
left: `Some(Int(10))`,
right: `Some(ReturnValue(ReturnValue(Int(10))))`
left: `Some(Int(5))`,
right: `Some(ReturnValue(ReturnValue(Int(5))))`
Three possible solutions:
- Implement
EqforObjectsuch thatReturnValue(ReturnValue(Int(10))would be equal toInt(10)etc. For e.g. that approach taken here. - Add a smart constructor specifically for
ReturnValue, saymakeReturnValue v, such that ifvis already aReturnValuewe simply returnvotherwise we returnReturnValue v. - Collapse the
ReturnValuewhen the final output from the evaluator is aReturnValue.
Note: If these examples are tried in the online interpreter they will display the correct result because of how Display is implemented for Object. Hence, it hides the issue.
A related problem. Given,
[fn (x) { return [x]; }][0](4)[0]
it fails with:
uknown operator: [4] 0
But,
[fn (x) { [x] }][0](4)[0]
without the return statement gives the correct answer.