babel: [Bug]: Parser throws when var declaration and function declaration in class static block

💻

  • Would you like to work on a fix?

How are you using Babel?

Programmatic API (babel.transform, babel.parse)

Input code

class X {
  static {
    var x;
    function x() {}
  }
}

REPL

Configuration file name

No response

Configuration

n/a

Current and expected behavior

I believe that the above code is legal. It happily runs in NodeJS.

Babel’s parser throws an error Identifier 'x' has already been declared.

This only applies within a class static block. The following parses correctly (when sourceType: 'script'):

var x; function x() {}
class X {
  foo() { var x; function x() {} }
  static foo() { var x; function x() {} }
}
function f() { var x; function x() {} }
() => { var x; function x() {} };
function f2() { 'use strict'; var x; function x() {} }
() => { 'use strict'; var x; function x() {} };

REPL

Environment

System:
  OS: macOS 10.15.7
Binaries:
  Node: 16.14.0 - ~/.nvm/versions/node/v16.14.0/bin/node
  npm: 8.3.1 - ~/.nvm/versions/node/v16.14.0/bin/npm
npmPackages:
  @babel/core: ^7.17.2 => 7.17.2
  @babel/generator: ^7.17.0 => 7.17.0
  @babel/helper-module-transforms: ^7.16.7 => 7.16.7
  @babel/helper-plugin-utils: ^7.16.7 => 7.16.7
  @babel/parser: ^7.17.0 => 7.17.0
  @babel/plugin-transform-arrow-functions: ^7.16.7 => 7.16.7
  @babel/plugin-transform-modules-commonjs: ^7.16.8 => 7.16.8
  @babel/plugin-transform-react-jsx: ^7.16.7 => 7.16.7
  @babel/plugin-transform-strict-mode: ^7.16.7 => 7.16.7
  @babel/traverse: ^7.17.0 => 7.17.0
  @babel/types: ^7.17.0 => 7.17.0
  babel-plugin-dynamic-import-node: ^2.3.3 => 2.3.3
  eslint: ^7.32.0 => 7.32.0
  jest: ^27.5.1 => 27.5.1

Possible solution

No response

Additional context

Happy to work on a PR. But could someone please point in right direction? I’m not at all familiar with the parser.

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 15 (14 by maintainers)

Commits related to this issue

Most upvoted comments

@Yokubjon-J Just want to say thanks loads for fixing this.

@Yokubjon-J Please run yarn to install dependencies. If you are developing on Windows, you can also run make bootstrap in the embedded Linux, mingw64 may not be well supported since we don’t run CI on mingw64 environment.

That might be a bug in our test runner; what does it say if you set the OVERWRITE=true environment variable when calling running out tests?

@Yokubjon-J I’d be very happy if you did! I was going to, but I’m unfamiliar with the parser code base, so will probably take me a while.