Skip to content

Commit

Permalink
Fix: Allow duplicated let declarations in prefer-const (fixes #7712)
Browse files Browse the repository at this point in the history
Due to acornjs/acorn#487, espree does not throw a syntax error for duplicate `let` or `const` declarations. Previously, the `prefer-const` rule assumed that a `let` variable would always have exactly one declaration. This adds a sanity check to avoid reporting (and possibly creating incorrect autofixes) a `let` variable if it has more than one declaration.
  • Loading branch information
not-an-aardvark committed Dec 8, 2016
1 parent a8489e2 commit eebf40a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
11 changes: 11 additions & 0 deletions lib/rules/prefer-const.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,17 @@ function getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign) {
return null;
}

/*
* Due to a bug in acorn, code such as `let foo = 1; let foo = 2;` will not throw a syntax error. As a sanity
* check, make sure that the variable only has one declaration. After the parsing bug is fixed, this check
* will no longer be necessary, because variables declared with `let` or `const` should always have exactly one
* declaration.
* https://github.com/ternjs/acorn/issues/487
*/
if (variable.defs.length > 1) {
return null;
}

// Finds the unique WriteReference.
let writer = null;
let isReadBeforeInit = false;
Expand Down
8 changes: 8 additions & 0 deletions tests/lib/rules/prefer-const.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,14 @@ ruleTester.run("prefer-const", rule, {
options: [{ignoreReadBeforeAssign: true}]
},

// https://github.com/eslint/eslint/issues/7712
// https://github.com/ternjs/acorn/issues/487
// This should be a SyntaxError, but espree parses it correctly. Don't throw an error if the variable has multiple declarations.
{
code: "let foo; const foo = 1;",
parserOptions: {ecmaVersion: 6},
errors: [{ message: "'foo' is never reassigned. Use 'const' instead.", type: "Identifier" }]
}

],
invalid: [
Expand Down

0 comments on commit eebf40a

Please sign in to comment.