Skip to content

Commit

Permalink
fix: remove bindings defined in blockScope when wrapped in closure
Browse files Browse the repository at this point in the history
  • Loading branch information
JLHwung committed Aug 16, 2019
1 parent 1f95f2e commit 0db9416
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 7 deletions.
15 changes: 10 additions & 5 deletions packages/babel-plugin-transform-block-scoping/src/index.js
Expand Up @@ -441,20 +441,25 @@ class BlockScoping {
}

updateScopeInfo(wrappedInClosure) {
const scope = this.scope;
const blockScope = this.blockPath.scope;

const parentScope = scope.getFunctionParent() || scope.getProgramParent();
const parentScope =
blockScope.getFunctionParent() || blockScope.getProgramParent();
const letRefs = this.letReferences;

for (const key of Object.keys(letRefs)) {
const ref = letRefs[key];
const binding = scope.getBinding(ref.name);
const binding = blockScope.getBinding(ref.name);
if (!binding) continue;
if (binding.kind === "let" || binding.kind === "const") {
binding.kind = "var";

if (!wrappedInClosure) {
scope.moveBindingTo(ref.name, parentScope);
if (wrappedInClosure) {
if (blockScope.hasOwnBinding(ref.name)) {
blockScope.removeBinding(ref.name);
}
} else {
blockScope.moveBindingTo(ref.name, parentScope);
}
}
}
Expand Down
@@ -0,0 +1,34 @@
const code = multiline([
"for (const {foo, ...bar} of { bar: [] }) {",
"() => foo;",
"const [qux] = bar;",
"try {} catch (e) {",
"let quux = qux;",
"}",
"}"
]);

transform(code, {
configFile: false,
plugins: [
"../../../../lib",
{
post({ path }) {
path.traverse({
Program(path) {
expect(Object.keys(path.scope.bindings)).toEqual(["foo", "bar"]);
},
ForOfStatement(path) {
// for declarations should be transformed to for bindings
expect(path.scope.bindings).toEqual({});
// The body should be wrapped into closure
expect(path.get("body").scope.bindings).toEqual({});
},
FunctionExpression(path) {
expect(Object.keys(path.scope.bindings)).toEqual(["foo", "bar", "qux", "quux"]);
}
})
}
}
]
});
@@ -1,4 +1,7 @@
for (const {foo, ...bar} of {}) {
() => foo;
bar;
const [qux] = bar;
try {} catch (e) {
const quux = qux;
}
}
Expand Up @@ -3,7 +3,11 @@ function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) r
var _loop = function (foo, bar) {
() => foo;

bar;
var [qux] = bar;

try {} catch (e) {
var quux = qux;
}
};

for (var _ref of {}) {
Expand Down

0 comments on commit 0db9416

Please sign in to comment.