tree-sitter / tree-sitter-typescript

TypeScript grammar for tree-sitter
MIT License
359 stars 109 forks source link

<const> expression fails to parse (when JSX is disabled) #260

Closed apazzolini closed 8 months ago

apazzolini commented 1 year ago

The following piece of code is valid (when JSX is disabled) but it is parsed incorrectly:

const x = <const>{ a: 1, b: 2 };

Here's a link to the TypeScript Playground showing that the snippet above is valid JavaScript or TypeScript: https://www.typescriptlang.org/play?target=99&jsx=0&ts=5.2.2&ssl=1&ssc=33&pln=1&pc=1#code/MYewdgzgLgBAHjAvDAPKSUB8BvGBDALhgEYAaGAIyICYYBfAbiA

The output of tree-sitter parse is the following: (I copied this from the TS playground in nvim, I assume it's the same thing? Let me know if not and I'll figure out how to use the tree-sitter binary)

lexical_declaration [0, 0] - [0, 32]
  variable_declarator [0, 6] - [0, 7]
    name: identifier [0, 6] - [0, 7]
  ERROR [0, 8] - [0, 31]
    ERROR [0, 11] - [0, 17]
    object_type [0, 17] - [0, 31]
      property_signature [0, 19] - [0, 23]
        name: property_identifier [0, 19] - [0, 20]
        type: type_annotation [0, 20] - [0, 23]
          literal_type [0, 22] - [0, 23]
            number [0, 22] - [0, 23]
      property_signature [0, 25] - [0, 29]
        name: property_identifier [0, 25] - [0, 26]
        type: type_annotation [0, 26] - [0, 29]
          literal_type [0, 28] - [0, 29]
            number [0, 28] - [0, 29]

I bisected the change and #252 seems to have introduced the bug. Prior to that PR, the code is parsed as

lexical_declaration [0, 0] - [0, 32]
  variable_declarator [0, 6] - [0, 31]
    name: identifier [0, 6] - [0, 7]
    value: type_assertion [0, 10] - [0, 31]
      type_arguments [0, 10] - [0, 17]
        type_identifier [0, 11] - [0, 16]
      object [0, 17] - [0, 31]
        pair [0, 19] - [0, 23]
          key: property_identifier [0, 19] - [0, 20]
          value: number [0, 22] - [0, 23]
        pair [0, 25] - [0, 29]
          key: property_identifier [0, 25] - [0, 26]
          value: number [0, 28] - [0, 29]

Thanks!

ivanjermakov commented 8 months ago

I narrowed the cause to the addition of this rule, perhaps it messes up with token precedence https://github.com/tree-sitter/tree-sitter-typescript/blob/d847898fec3fe596798c9fda55cb8c05a799001a/common/define-grammar.js#L928 Without it <const> is parsed properly, but Functions with typed parameters test fails.