A surprising lua parse error

โ† Posts & Notes ยท 17/06/2025 ยท 1 minute

While working on my lua VM, I encountered the following parse error:

lune> function f()
        local x<const>
        x = nil
2:   local x<const>
3:   x = nil
       ^ error: AssignToConst

This error surprised me because the input is not parsable because the body of the function is never closed with an end. In the REPL of this VM, the parser is run every time a new line is added to see whether or not it should be executed, if there is a parse error from an incomplete token stream then a new line is added as the input is probably not complete. But in this case, the error is of type AssignToConst because we tried to assign to x. This error is more semantical than a parse error so this was surprising.

This happens because my VM is inspired by the Rio PUC Lua implementation which does not build an abstract syntax tree (AST). Instead it directly emits bytecode from the tokenizer.

And sure enough, when testing the canonical Rio PUC Lua implementation, I got a similar error.

> function f()
>> local x<const>
>> x = nil
stdin:3: attempt to assign to const variable 'x'