tree-sitter / tree-sitter-javascript

Javascript grammar for tree-sitter
MIT License
318 stars 107 forks source link

For-in loop allows any expression in LHS #206

Closed NotWearingPants closed 2 years ago

NotWearingPants commented 2 years ago

The following piece of code is invalid but it is parsed correctly:

for ((1+2) in 3);

Here's a link to the TypeScript Playground showing that the snippet above is invalid JavaScript or TypeScript

The output of tree-sitter playground is the following:

program [0, 0] - [1, 0]
  for_in_statement [0, 0] - [0, 17]
    left: parenthesized_expression [0, 5] - [0, 10]
      binary_expression [0, 6] - [0, 9]
        left: number [0, 6] - [0, 7]
        right: number [0, 8] - [0, 9]
    right: number [0, 14] - [0, 15]
    body: empty_statement [0, 16] - [0, 17]

This should be an error, the LHS of a for-in loop can't be an expression, only identifier/member_expression/destructuring.

aryx commented 2 years ago

I think it's sometimes hard to enforce with the grammar certain restrictions. Doing so can complicate a lot the grammar. Usually people do some of those checks after parsing.

maxbrunsfeld commented 2 years ago

Yeah, catching all possible errors is explicitly not a goal of the project. We're fine with allowing some invalid code if it makes the grammar simpler or the parse table smaller.

Looking at the link that you posted, you can actually see that the TypeScript compiler parses this successfully too. That's how it's able to report a semantic error message:

The left-hand side of a 'for .. in' statement must be of type string or any