Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not unpack array patterns that update a referenced binding #8535

Merged
merged 1 commit into from Sep 28, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 24 additions & 8 deletions packages/babel-plugin-transform-destructuring/src/index.js
Expand Up @@ -44,13 +44,23 @@ export default declare((api, options) => {
return false;
}

const arrayUnpackVisitor = {
ReferencedIdentifier(path, state) {
if (state.bindings[path.node.name]) {
state.deopt = true;
path.stop();
}
},
const STOP_TRAVERSAL = {};

// NOTE: This visitor is meant to be used via t.traverse
const arrayUnpackVisitor = (node, ancestors, state) => {
if (!ancestors.length) {
// Top-level node: this is the array literal.
return;
}

if (
t.isIdentifier(node) &&
t.isReferenced(node, ancestors[ancestors.length - 1]) &&
state.bindings[node.name]
) {
state.deopt = true;
throw STOP_TRAVERSAL;
}
};

class DestructuringTransformer {
Expand Down Expand Up @@ -282,7 +292,13 @@ export default declare((api, options) => {
// deopt on reference to left side identifiers
const bindings = t.getBindingIdentifiers(pattern);
const state = { deopt: false, bindings };
this.scope.traverse(arr, arrayUnpackVisitor, state);

try {
t.traverse(arr, arrayUnpackVisitor, state);
} catch (e) {
if (e !== STOP_TRAVERSAL) throw e;
}

return !state.deopt;
}

Expand Down
@@ -0,0 +1,4 @@
function isBetween(x, a, b) {
if (a > b) [a, b] = [b, a];
return x > a && x < b;
}
@@ -0,0 +1,3 @@
{
"plugins": ["transform-destructuring"]
}
@@ -0,0 +1,9 @@
function isBetween(x, a, b) {
if (a > b) {
var _ref = [b, a];
a = _ref[0];
b = _ref[1];
}

return x > a && x < b;
}