rs-monkey-lang icon indicating copy to clipboard operation
rs-monkey-lang copied to clipboard

Cascading returns are not collapsed

Open dwayne opened this issue 3 years ago • 1 comments

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:

  1. Implement Eq for Object such that ReturnValue(ReturnValue(Int(10)) would be equal to Int(10) etc. For e.g. that approach taken here.
  2. Add a smart constructor specifically for ReturnValue, say makeReturnValue v, such that if v is already a ReturnValue we simply return v otherwise we return ReturnValue v.
  3. Collapse the ReturnValue when the final output from the evaluator is a ReturnValue.

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.

dwayne avatar Mar 29 '22 22:03 dwayne

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.

dwayne avatar Apr 09 '22 11:04 dwayne