Skip to content

Commit

Permalink
Do not unpack array patterns that update a referenced binding (babel#…
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolo-ribaudo authored and hzoo committed Sep 28, 2018
1 parent c32e0e0 commit c57ab14
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 8 deletions.
32 changes: 24 additions & 8 deletions 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
4 changes: 4 additions & 0 deletions test/fixtures/regression/8528/input.js
@@ -0,0 +1,4 @@
function isBetween(x, a, b) {
if (a > b) [a, b] = [b, a];
return x > a && x < b;
}
3 changes: 3 additions & 0 deletions test/fixtures/regression/8528/options.json
@@ -0,0 +1,3 @@
{
"plugins": ["transform-destructuring"]
}
9 changes: 9 additions & 0 deletions test/fixtures/regression/8528/output.js
@@ -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;
}

0 comments on commit c57ab14

Please sign in to comment.