Skip to content

Commit

Permalink
enhance functions (#5052)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexlamsl committed Jul 5, 2021
1 parent 6961c57 commit d0e3f69
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 21 deletions.
45 changes: 24 additions & 21 deletions lib/compress.js
Original file line number Diff line number Diff line change
Expand Up @@ -519,36 +519,39 @@ merge(Compressor.prototype, {
});
}

function walk_fn_def(tw, fn) {
var was_scanning = tw.fn_scanning;
tw.fn_scanning = fn;
fn.walk(tw);
tw.fn_scanning = was_scanning;
}

function mark_fn_def(tw, def, fn) {
if (!HOP(fn, "safe_ids")) return;
var marker = fn.safe_ids;
if (marker === false) return;
if (fn.parent_scope.resolve().may_call_this === return_true) return;
if (marker) {
var visited = member(fn, tw.fn_visited);
if (marker === tw.safe_ids) return !visited && walk_fn_def(tw, fn);
if (visited) {
fn.enclosed.forEach(function(d) {
if (fn.variables.get(d.name) === d) return;
if (safe_to_read(tw, d)) return;
d.single_use = false;
if (d.fixed instanceof AST_LambdaDefinition) return;
d.fixed = false;
});
return;
}
} else if (!tw.in_loop && !(tw.fn_scanning && tw.fn_scanning !== def.scope.resolve())) {
if (marker === tw.safe_ids) {
if (!visited) walk_fn_def(tw, fn);
} else if (!visited) {
fn.safe_ids = false;
} else fn.enclosed.forEach(function(d) {
if (fn.variables.get(d.name) === d) return;
if (safe_to_read(tw, d)) return;
d.single_use = false;
var fixed = d.fixed;
if (typeof fixed == "function") fixed = fixed();
if (fixed instanceof AST_Lambda && HOP(fixed, "safe_ids")) return;
d.fixed = false;
});
} else if (tw.fn_scanning && tw.fn_scanning !== def.scope.resolve()) {
fn.safe_ids = false;
} else {
fn.safe_ids = tw.safe_ids;
return walk_fn_def(tw, fn);
walk_fn_def(tw, fn);
}
fn.safe_ids = false;
}

function walk_fn_def(tw, fn) {
var was_scanning = tw.fn_scanning;
tw.fn_scanning = fn;
fn.walk(tw);
tw.fn_scanning = was_scanning;
}

function pop_scope(tw, scope) {
Expand Down
30 changes: 30 additions & 0 deletions test/compress/functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -2826,6 +2826,36 @@ functions_use_strict: {
expect_stdout: "a true 42 function function function"
}

functions_cross_scope_reference: {
options = {
functions: true,
reduce_vars: true,
toplevel: true,
unused: true,
}
input: {
log = function(fn) {
console.log(typeof fn());
};
var a = function() {};
function f() {
return a;
}
while (log(f));
}
expect: {
log = function(fn) {
console.log(typeof fn());
};
function a() {}
function f() {
return a;
}
while (log(f));
}
expect_stdout: "function"
}

functions_inner_var: {
options = {
functions: true,
Expand Down

0 comments on commit d0e3f69

Please sign in to comment.