Skip to content

Commit

Permalink
fix(dce): bail on non-constant replacement path (#755)
Browse files Browse the repository at this point in the history
* fix(dce): bail on non-constant replacement path

In one use variable replacement, if the right hand side contains
constant violations, the left-hand side is supposed to be preserved, so
we detect this and bail out for this case

+ Fix #685

* Fix binding check and checks for not Identifier

* Add testcase for non-identifier replacementPaths
  • Loading branch information
boopathi authored Dec 11, 2017
1 parent 61bcbaa commit 7f4dc3d
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
function loop() {
var end = 0;
var start = end;
while (end < 10) {
console.log(start, end);
var end = end + 1;
}
}
loop();

function bar() {
var x = 1;
var y = x + 2;
var x = 3;
return x + y;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
function loop() {
var end = 0;
var start = end;
while (end < 10) {
console.log(start, end);
var end = end + 1;
}
}
loop();

function bar() {
var x = 1;
var y = x + 2;
var x = 3;
return x + y;
}
23 changes: 17 additions & 6 deletions packages/babel-plugin-minify-dead-code-elimination/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -349,9 +349,16 @@ module.exports = ({ types: t, traverse }) => {
let bail = false;

if (replacementPath.isIdentifier()) {
bail =
refPath.scope.getBinding(replacement.name) !==
scope.getBinding(replacement.name);
const binding = scope.getBinding(replacement.name);
// the reference should be in the same scope
// and the replacement should be a constant - this is to
// ensure that the duplication of replacement is not affected
// https://github.com/babel/minify/issues/685
bail = !(
binding &&
refPath.scope.getBinding(replacement.name) === binding &&
binding.constantViolations.length === 0
);
} else {
replacementPath.traverse({
Function(path) {
Expand All @@ -362,9 +369,13 @@ module.exports = ({ types: t, traverse }) => {
if (bail) {
return;
}
bail =
refPath.scope.getBinding(node.name) !==
scope.getBinding(node.name);
const binding = scope.getBinding(node.name);
if (
binding &&
refPath.scope.getBinding(node.name) === binding
) {
bail = binding.constantViolations.length > 0;
}
}
});
}
Expand Down

0 comments on commit 7f4dc3d

Please sign in to comment.