tree-sitter-javascript icon indicating copy to clipboard operation
tree-sitter-javascript copied to clipboard

Discrepancy in parsing of `for` statement condition

Open alexle0nte opened this issue 9 months ago • 1 comments

The following piece of code is valid but it is parsed incorrectly:

for (let i = 0; i < 10; i++) {}

Here's a link to the TypeScript Playground showing that the snippet above is valid JavaScript or TypeScript: https://www.typescriptlang.org/play/?#code/GYewTgBAFANgpgFwgSwgXggBgNwogHggEYcUBqMgSggG8BfIA

The output of tree-sitter parse is the following:

(program [0, 0] - [1, 0]
  (for_statement [0, 0] - [0, 31]
    initializer: (lexical_declaration [0, 5] - [0, 15]
      (variable_declarator [0, 9] - [0, 14]
        name: (identifier [0, 9] - [0, 10])
        value: (number [0, 13] - [0, 14])))
    condition: (binary_expression [0, 16] - [0, 22]
      left: (identifier [0, 16] - [0, 17])
      right: (number [0, 20] - [0, 22]))
    increment: (update_expression [0, 24] - [0, 27]
      argument: (identifier [0, 24] - [0, 25]))
    body: (statement_block [0, 29] - [0, 31])))

However, tree-sitter playground generates the following tree:

program [0, 0] - [1, 0]
  for_statement [0, 0] - [0, 31]
    for [0, 0] - [0, 3]
    ( [0, 4] - [0, 5]
    initializer: lexical_declaration [0, 5] - [0, 15]
      kind: let [0, 5] - [0, 8]
      variable_declarator [0, 9] - [0, 14]
        name: identifier [0, 9] - [0, 10]
        = [0, 11] - [0, 12]
        value: number [0, 13] - [0, 14]
      ; [0, 14] - [0, 15]
    condition: expression_statement [0, 16] - [0, 23]
      binary_expression [0, 16] - [0, 22]
        left: identifier [0, 16] - [0, 17]
        operator: < [0, 18] - [0, 19]
        right: number [0, 20] - [0, 22]
      ; [0, 22] - [0, 23]
    increment: update_expression [0, 24] - [0, 27]
      argument: identifier [0, 24] - [0, 25]
      operator: ++ [0, 25] - [0, 27]
    ) [0, 27] - [0, 28]
    body: statement_block [0, 29] - [0, 31]
      { [0, 29] - [0, 30]
      } [0, 30] - [0, 31]

In the playground tree, the condition i < 10; is wrapped inside an expression_statement, whereas in the tree generated by tree-sitter parse, it is directly a binary_expression. The expected behavior is that the tree-sitter parse output should match the playground tree, ensuring the condition is correctly wrapped inside an expression_statement.

alexle0nte avatar Mar 22 '25 17:03 alexle0nte

I think maybe you just has the 'show anonymous nodes' button selected in the playground and that fully explains the difference. I think this should be closed.

jackschu avatar May 27 '25 02:05 jackschu