Skip to content

Commit

Permalink
Fix hoisting in for loop
Browse files Browse the repository at this point in the history
  • Loading branch information
fathyb committed Aug 26, 2018
1 parent 553be72 commit c4c4089
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 27 deletions.
41 changes: 15 additions & 26 deletions src/scope-hoisting/hoist.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,6 @@ module.exports = {
scope.push({id: exportsIdentifier, init: t.objectExpression([])});
}

let topDecls = [];

// Move all "var" variables to the top-level to prevent out of order definitions when wrapped.
for (let name in scope.bindings) {
let binding = scope.getBinding(name);
Expand All @@ -166,35 +164,26 @@ module.exports = {
let {parentPath} = binding.path;

if (!parentPath.removed) {
let {declarations} = parentPath.node;

if (declarations.length) {
parentPath.insertBefore(
declarations
.map(
decl =>
decl.init
? t.assignmentExpression('=', decl.id, decl.init)
: null
)
if (parentPath.node.declarations.length) {
binding.path.getStatementParent().insertBefore(
parentPath.node.declarations
.map(decl => {
binding.scope.removeBinding(decl.id.name);
scope.push({id: decl.id});

return decl.init
? t.assignmentExpression('=', decl.id, decl.init)
: null;
})
.filter(decl => decl !== null)
);

topDecls.push(
...declarations.map(decl => t.variableDeclarator(decl.id))
);
parentPath.remove();
}
} else if (!binding.path.removed) {
binding.path.remove();

parentPath.remove();
}
}
}

if (topDecls.length) {
path.unshiftContainer('body', [
t.variableDeclaration('var', topDecls)
]);
binding.path.remove();
}
}
}

Expand Down
12 changes: 11 additions & 1 deletion test/integration/scope-hoisting/commonjs/hoist-vars/b.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
if(process.env.NODE_ENV === 'test') {
module.exports = require('./c')
var c = require('./c')()

for(var i = 0, {length} = c, out = ''; i < length; i++) {
out += c[i]
}

module.exports = function() {
if(c != out) throw new Error()

return out
}
}

0 comments on commit c4c4089

Please sign in to comment.