Ark icon indicating copy to clipboard operation
Ark copied to clipboard

Loops don't have their own scope

Open SuperFola opened this issue 2 years ago • 0 comments

When writing a while loop we expect to have a new scope created:

(let a 12)
(while condition {
    (mut a "hello")  # working, mut is allowed to redefine variables
                     # (was made like this because of this loop problem)
    (let b 1)   # error, can not redefine a variable (not intended)
})

(print b)  # working, b is in this scope (not intended)

The problem comes from the fact that writing such a loop is just putting a POP_JUMP_IF_FALSE end and a JUMP top around the loop body. Because of this the scope used is the parent one, and variables leak from it. Variables in loops must also be defined as mutable to avoid redefinition each time the loop starts over.

Fixing this would imply multiple breaking changes:

  • new instructions (create a new scope, reset the current scope, pop the current scope)
  • compiler update

From the top of my head, I don't think existing code would break, as we would allow more things as before. Though one could argue that variables defined in loops could be used outside them by some code, and this use case would definitely not work anymore.

I tagged this "help wanted", to gather insight and know if this is needed / wanted / interesting / breaking your code / etc. IMO this would help the language being more consistent.

SuperFola avatar May 04 '22 09:05 SuperFola