Skip to content

Commit 7f4dc3d

Browse files
authored
fix(dce): bail on non-constant replacement path (#755)
* 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
1 parent 61bcbaa commit 7f4dc3d

File tree

3 files changed

+49
-6
lines changed

3 files changed

+49
-6
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
function loop() {
2+
var end = 0;
3+
var start = end;
4+
while (end < 10) {
5+
console.log(start, end);
6+
var end = end + 1;
7+
}
8+
}
9+
loop();
10+
11+
function bar() {
12+
var x = 1;
13+
var y = x + 2;
14+
var x = 3;
15+
return x + y;
16+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
function loop() {
2+
var end = 0;
3+
var start = end;
4+
while (end < 10) {
5+
console.log(start, end);
6+
var end = end + 1;
7+
}
8+
}
9+
loop();
10+
11+
function bar() {
12+
var x = 1;
13+
var y = x + 2;
14+
var x = 3;
15+
return x + y;
16+
}

packages/babel-plugin-minify-dead-code-elimination/src/index.js

+17-6
Original file line numberDiff line numberDiff line change
@@ -349,9 +349,16 @@ module.exports = ({ types: t, traverse }) => {
349349
let bail = false;
350350

351351
if (replacementPath.isIdentifier()) {
352-
bail =
353-
refPath.scope.getBinding(replacement.name) !==
354-
scope.getBinding(replacement.name);
352+
const binding = scope.getBinding(replacement.name);
353+
// the reference should be in the same scope
354+
// and the replacement should be a constant - this is to
355+
// ensure that the duplication of replacement is not affected
356+
// https://github.com/babel/minify/issues/685
357+
bail = !(
358+
binding &&
359+
refPath.scope.getBinding(replacement.name) === binding &&
360+
binding.constantViolations.length === 0
361+
);
355362
} else {
356363
replacementPath.traverse({
357364
Function(path) {
@@ -362,9 +369,13 @@ module.exports = ({ types: t, traverse }) => {
362369
if (bail) {
363370
return;
364371
}
365-
bail =
366-
refPath.scope.getBinding(node.name) !==
367-
scope.getBinding(node.name);
372+
const binding = scope.getBinding(node.name);
373+
if (
374+
binding &&
375+
refPath.scope.getBinding(node.name) === binding
376+
) {
377+
bail = binding.constantViolations.length > 0;
378+
}
368379
}
369380
});
370381
}

0 commit comments

Comments
 (0)