Navigation Menu

Skip to content

Commit

Permalink
fix: don't convert var to let or const in a switch case (#136)
Browse files Browse the repository at this point in the history
Fixes decaffeinate/decaffeinate#1171

Potentially add-variable-declarations and esnext could be smarter in this case,
e.g. by declaring the variable outside the switch or even creating a block
scope, but the easy thing is to just keep the declaration as `var`. Since `var`
doesn't have a temporal dead zone, a declaration in any switch case will work
for all switch cases.
  • Loading branch information
alangpierce committed Aug 14, 2017
1 parent d12fa14 commit df09db7
Show file tree
Hide file tree
Showing 6 changed files with 108 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/utils/mostRestrictiveKindForDeclaration.js
Expand Up @@ -13,6 +13,10 @@ export default function mostRestrictiveKindForDeclaration(path: Path): Declarati
let { scope } = path;
let isConst = path.node.declarations.every(declaration => declaration.init);

if (t.isSwitchCase(path.parent)) {
return 'var';
}

for (let id in ids) {
let binding = scope.getBinding(id);

Expand Down
10 changes: 10 additions & 0 deletions test/form/declarations.block-scope/var-in-switch/_expected/main.js
@@ -0,0 +1,10 @@
switch (a) {
case 1:
var x = 1;
console.log(x);
break;
case 2:
x = 2;
console.log(x);
break;
}
@@ -0,0 +1,5 @@
{
"declarations.block-scope": {
"declarations": []
}
}
@@ -0,0 +1,76 @@
[
{
"node": {
"type": "VariableDeclaration",
"start": 27,
"end": 37,
"loc": {
"start": {
"line": 3,
"column": 4
},
"end": {
"line": 3,
"column": 14
}
},
"declarations": [
{
"type": "VariableDeclarator",
"start": 31,
"end": 36,
"loc": {
"start": {
"line": 3,
"column": 8
},
"end": {
"line": 3,
"column": 13
}
},
"id": {
"type": "Identifier",
"start": 31,
"end": 32,
"loc": {
"start": {
"line": 3,
"column": 8
},
"end": {
"line": 3,
"column": 9
},
"identifierName": "x"
},
"name": "x"
},
"init": {
"type": "NumericLiteral",
"start": 35,
"end": 36,
"loc": {
"start": {
"line": 3,
"column": 12
},
"end": {
"line": 3,
"column": 13
}
},
"extra": {
"rawValue": 1,
"raw": "1"
},
"value": 1
}
}
],
"kind": "var"
},
"type": "unsupported-declaration",
"message": "'var' declaration cannot be converted to block scope"
}
]
3 changes: 3 additions & 0 deletions test/form/declarations.block-scope/var-in-switch/config.json
@@ -0,0 +1,3 @@
{
"description": "does not convert `var` declarations within switch cases"
}
10 changes: 10 additions & 0 deletions test/form/declarations.block-scope/var-in-switch/main.js
@@ -0,0 +1,10 @@
switch (a) {
case 1:
var x = 1;
console.log(x);
break;
case 2:
x = 2;
console.log(x);
break;
}

0 comments on commit df09db7

Please sign in to comment.