Dictu
Dictu copied to clipboard
[BUG] Redeclare `const` variable
Is there an existing issue for this?
- [X] I have searched the existing issues
Current Behavior
Currently, redeclaring a variable from const to var and trying to assign to it causes the variable to sort of "remember" it was a const variable before, therefore preventing the assignment, even though it's not a constant anymore. This problem only happens with global variables. A possible solution would be to check for redeclaration and delete the identifier from the constants table, thus allowing assignment later to it.
Related to this, importing from a file that declared global constants in the REPL brings this issue of declaration, because in the REPL the constants table isn't freed after every compilation.
Expected Behavior
The expected behaviour should be to allow the redeclaration into var and allowing assignment, or not allowing redeclaration entirely.
Steps To Reproduce
- Declare a
constvariable globally - Try to redeclare it as
var - Assign to the redeclared variable
Anything else?
No response
Just my 2c but I think I'd prefer there be a runtime error preventing the declaration of variable of the same name.
Yeah this is one that I've always questioned, it actually comes as a design decision from Lox:
This code doesn’t check to see if the key is already in the table. Lox is pretty lax with global variables and lets you redefine them without error. That’s useful in a REPL session, so the VM supports that by simply overwriting the value if the key happens to already be in the hash table.
https://craftinginterpreters.com/global-variables.html
If we are going to error this out, it'd be good to pick it up at compile time and even potentially switch the internals of the global variable to be the same as how local variables work
Completely agree. I wrote runtime but meant compile time. Given the amount of rope that scripting languages provide, so to speak, it's nice to know there's a safe guard like this.
Indeed, though perhaps checking for local variable redeclaration might be a bit more difficult compared to globals/module ones.