Skip to content

Commit

Permalink
Don't throw when destructuring into a var named as an import
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolo-ribaudo committed Nov 2, 2019
1 parent 4b3a19e commit 65c0f1f
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 15 deletions.
Expand Up @@ -224,6 +224,10 @@ const rewriteReferencesVisitor = {
seen.add(path.node);

const left = path.get("left");

// No change needed
if (left.isMemberExpression()) return;

if (left.isIdentifier()) {
// Simple update-assign foo += 1; export { foo };
// => exports.foo = (foo += 1);
Expand All @@ -234,9 +238,9 @@ const rewriteReferencesVisitor = {
return;
}

const exportedNames = exported.get(localName) || [];
const exportedNames = exported.get(localName);
const importData = imported.get(localName);
if (exportedNames.length > 0 || importData) {
if (exportedNames?.length > 0 || importData) {
assert(path.node.operator === "=", "Path was not simplified");

const assignment = path.node;
Expand All @@ -259,13 +263,14 @@ const rewriteReferencesVisitor = {
);
requeueInParent(path);
}
} else if (left.isMemberExpression()) {
// No change needed
} else {
const ids = left.getOuterBindingIdentifiers();
const id = Object.keys(ids)
.filter(localName => imported.has(localName))
.pop();
const programScopeIds = Object.keys(ids).filter(
localName =>
scope.getBinding(localName) === path.scope.getBinding(localName),
);
const id = programScopeIds.find(localName => imported.has(localName));

if (id) {
path.node.right = t.sequenceExpression([
path.node.right,
Expand All @@ -276,14 +281,7 @@ const rewriteReferencesVisitor = {
// Complex ({a, b, c} = {}); export { a, c };
// => ({a, b, c} = {}), (exports.a = a, exports.c = c);
const items = [];
Object.keys(ids).forEach(localName => {
// redeclared in this scope
if (
scope.getBinding(localName) !== path.scope.getBinding(localName)
) {
return;
}

programScopeIds.forEach(localName => {
const exportedNames = exported.get(localName) || [];
if (exportedNames.length > 0) {
items.push(
Expand Down
@@ -0,0 +1,12 @@
import { foo } from "x";

function f(foo) {
foo = 2;
[foo] = [];
({ foo } = {});
}


foo = 2;
[foo] = [];
({ foo } = {});
@@ -0,0 +1,23 @@
"use strict";

var _x = require("x");

function f(foo) {
foo = 2;
[foo] = [];
({
foo
} = {});
}

_x.foo = (2, function () {
throw new Error('"' + "foo" + '" is read-only.');
}());
[foo] = ([], function () {
throw new Error('"' + "foo" + '" is read-only.');
}());
({
foo
} = ({}, function () {
throw new Error('"' + "foo" + '" is read-only.');
}()));

0 comments on commit 65c0f1f

Please sign in to comment.