Skip to content

Discrepancy in parsing of for statement condition #351

Closed as not planned
Closed as not planned

Description

@alexle0nte

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.

Activity

  1. jackschu commented on May 27, 2025

    @jackschu
    Contributor

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions