munificent / craftinginterpreters

Repository for the book "Crafting Interpreters"
http://www.craftinginterpreters.com/
Other
8.43k stars 1.01k forks source link

Why is `use_local_in_initializer` an error? #1083

Closed ajeetdsouza closed 1 year ago

ajeetdsouza commented 1 year ago

Hi, I was taking a look at the use_local_in_initializer test:

var a = "outer";
{
  var a = a; // Error at 'a': Can't read local variable in its own initializer.
}

Is there any reason why this is an error? IMO, since the a is available in the outer scope and is being supplied from there, this should not be an error.

nocturn9x commented 1 year ago

The way I understand it is that it's a limitation of the single pass compiler lox uses

chrisjbreisch commented 1 year ago

I think you're getting fooled by the variable names. I don't think the illegality here has anything to do with scope.

Consider:

var b = "outer";
{
  var a = a; // Error at 'a': Can't read local variable in its own initializer.
}

It's the var a = a; by itself that is problematic. a hasn't been assigned a value yet. You can't initialize a with an unassigned value.

ajeetdsouza commented 1 year ago

I found the answer here. Apparently this was a decision made to prevent accidental variable shadowing.

I got confused because the languages I'm used to do support this kind of syntax and there definitely are use cases for it, but all I wanted to clarify is that this error was not a bug and was occurring by design.