Skip to content

Commit

Permalink
fix invalid transform on const (#1919)
Browse files Browse the repository at this point in the history
- preserve (re)assignment to `const` for runtime error
- suppress `cascade` on `const`, as runtime behaviour is ill-defined
  • Loading branch information
alexlamsl committed May 11, 2017
1 parent 13e5e33 commit aa7e878
Show file tree
Hide file tree
Showing 4 changed files with 106 additions and 1 deletion.
12 changes: 11 additions & 1 deletion lib/compress.js
Expand Up @@ -440,6 +440,14 @@ merge(Compressor.prototype, {
return fixed();
});

function is_reference_const(ref) {
if (!(ref instanceof AST_SymbolRef)) return false;
var orig = ref.definition().orig;
for (var i = orig.length; --i >= 0;) {
if (orig[i] instanceof AST_SymbolConst) return true;
}
}

function find_variable(compressor, name) {
var scope, i = 0;
while (scope = compressor.parent(i++)) {
Expand Down Expand Up @@ -1909,6 +1917,7 @@ merge(Compressor.prototype, {
&& node instanceof AST_Assign
&& node.operator == "="
&& node.left instanceof AST_SymbolRef
&& !is_reference_const(node.left)
&& scope === self) {
node.right.walk(tw);
return true;
Expand Down Expand Up @@ -3066,7 +3075,8 @@ merge(Compressor.prototype, {
}
if (left
&& !(left instanceof AST_SymbolRef
&& left.definition().orig[0] instanceof AST_SymbolLambda)) {
&& (left.definition().orig[0] instanceof AST_SymbolLambda
|| is_reference_const(left)))) {
var parent, field;
var cdr = self.cdr;
while (true) {
Expand Down
46 changes: 46 additions & 0 deletions test/compress/collapse_vars.js
Expand Up @@ -1592,3 +1592,49 @@ var_side_effects_3: {
}
expect_stdout: true
}

reassign_const_1: {
options = {
collapse_vars: true,
}
input: {
function f() {
const a = 1;
a = 2;
return a;
}
console.log(f());
}
expect: {
function f() {
const a = 1;
a = 2;
return a;
}
console.log(f());
}
expect_stdout: true
}

reassign_const_2: {
options = {
collapse_vars: true,
}
input: {
function f() {
const a = 1;
++a;
return a;
}
console.log(f());
}
expect: {
function f() {
const a = 1;
++a;
return a;
}
console.log(f());
}
expect_stdout: true
}
25 changes: 25 additions & 0 deletions test/compress/drop-unused.js
Expand Up @@ -1064,3 +1064,28 @@ issue_1830_2: {
}
expect_stdout: "1"
}

reassign_const: {
options = {
cascade: true,
sequences: true,
side_effects: true,
unused: true,
}
input: {
function f() {
const a = 1;
a = 2;
return a;
}
console.log(f());
}
expect: {
function f() {
const a = 1;
return a = 2, a;
}
console.log(f());
}
expect_stdout: true
}
24 changes: 24 additions & 0 deletions test/compress/sequences.js
Expand Up @@ -610,3 +610,27 @@ delete_seq_6: {
}
expect_stdout: true
}

reassign_const: {
options = {
cascade: true,
sequences: true,
side_effects: true,
}
input: {
function f() {
const a = 1;
a++;
return a;
}
console.log(f());
}
expect: {
function f() {
const a = 1;
return a++, a;
}
console.log(f());
}
expect_stdout: true
}

0 comments on commit aa7e878

Please sign in to comment.