Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Default export of anonymous function declaration is misclassified as function expression #323

Open
jackschu opened this issue Jun 17, 2024 · 1 comment
Labels

Comments

@jackschu
Copy link
Contributor

jackschu commented Jun 17, 2024

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

export default function() {}

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

The output of tree-sitter parse is the following:

(program [0, 0] - [1, 0]
  (export_statement [0, 0] - [0, 28]
    value: (function_expression [0, 15] - [0, 28]
      parameters: (formal_parameters [0, 23] - [0, 25])
      body: (statement_block [0, 26] - [0, 28]))))

This example shows treesitter classifying this as a 'function_expression' when i think it should be classified as a 'function_declaration'.

This is because function declaration requires a name.

MDN mentions

As a special case, functions and classes are exported as declarations, not expressions, and these declarations can be anonymous. This means functions will be hoisted.

I havent dug through the spec but vaguely trust MDN, also Acorn parses this as a function declaration. Misclassifying it as a function expression can leave autoformatters wanting to parenthesize this expression and likely can leave highlighters to use the wrong color.

@jackschu jackschu added the bug label Jun 17, 2024
@jackschu jackschu changed the title Default export of function declarations are misclassified as function expressions Default export of anonymous function declaration is misclassified as function expression Jun 17, 2024
@jackschu
Copy link
Contributor Author

I'm not really sure if the right thing to do here is to

  1. Spawn another syntax node for 'function declaration that is part of a default export and therefore may be anonymous'
  2. Alias function_expression to function_declaration in the export_statement node
  3. Allow function_declaration to only optionally have a name

Happy to put up a PR but not sure on the direction

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant