wishthis/node_modules/uglify-js/lib/compress.js

14242 lines
620 KiB
JavaScript
Raw Normal View History

2022-01-21 08:28:41 +00:00
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AS IS AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
***********************************************************************/
"use strict";
function Compressor(options, false_by_default) {
if (!(this instanceof Compressor))
return new Compressor(options, false_by_default);
TreeTransformer.call(this, this.before, this.after);
this.options = defaults(options, {
annotations : !false_by_default,
arguments : !false_by_default,
arrows : !false_by_default,
assignments : !false_by_default,
awaits : !false_by_default,
booleans : !false_by_default,
collapse_vars : !false_by_default,
comparisons : !false_by_default,
conditionals : !false_by_default,
dead_code : !false_by_default,
default_values : !false_by_default,
directives : !false_by_default,
drop_console : false,
drop_debugger : !false_by_default,
evaluate : !false_by_default,
expression : false,
functions : !false_by_default,
global_defs : false,
hoist_exports : !false_by_default,
hoist_funs : false,
hoist_props : !false_by_default,
hoist_vars : false,
ie : false,
if_return : !false_by_default,
imports : !false_by_default,
inline : !false_by_default,
join_vars : !false_by_default,
keep_fargs : false_by_default,
keep_fnames : false,
keep_infinity : false,
loops : !false_by_default,
merge_vars : !false_by_default,
2022-06-08 10:36:39 +00:00
module : false,
2022-01-21 08:28:41 +00:00
negate_iife : !false_by_default,
objects : !false_by_default,
optional_chains : !false_by_default,
passes : 1,
properties : !false_by_default,
pure_funcs : null,
pure_getters : !false_by_default && "strict",
reduce_funcs : !false_by_default,
reduce_vars : !false_by_default,
rests : !false_by_default,
sequences : !false_by_default,
side_effects : !false_by_default,
spreads : !false_by_default,
strings : !false_by_default,
switches : !false_by_default,
templates : !false_by_default,
top_retain : null,
2022-06-08 10:36:39 +00:00
toplevel : !!(options && (options["module"] || options["top_retain"])),
2022-01-21 08:28:41 +00:00
typeofs : !false_by_default,
unsafe : false,
unsafe_comps : false,
unsafe_Function : false,
unsafe_math : false,
unsafe_proto : false,
unsafe_regexp : false,
unsafe_undefined: false,
unused : !false_by_default,
varify : !false_by_default,
webkit : false,
yields : !false_by_default,
}, true);
var evaluate = this.options["evaluate"];
this.eval_threshold = /eager/.test(evaluate) ? 1 / 0 : +evaluate;
var global_defs = this.options["global_defs"];
if (typeof global_defs == "object") for (var key in global_defs) {
if (/^@/.test(key) && HOP(global_defs, key)) {
2022-02-07 14:48:46 +00:00
global_defs[key.slice(1)] = parse(global_defs[key], { expression: true });
2022-01-21 08:28:41 +00:00
}
}
2022-02-07 14:48:46 +00:00
if (this.options["inline"] === true) this.options["inline"] = 4;
2022-01-21 08:28:41 +00:00
this.drop_fargs = this.options["keep_fargs"] ? return_false : function(lambda, parent) {
if (lambda.length_read) return false;
var name = lambda.name;
if (!name) return parent && parent.TYPE == "Call" && parent.expression === lambda;
if (name.fixed_value() !== lambda) return false;
var def = name.definition();
if (def.direct_access) return false;
var escaped = def.escaped;
return escaped && escaped.depth != 1;
};
2022-06-08 10:36:39 +00:00
if (this.options["module"]) this.directives["use strict"] = true;
2022-01-21 08:28:41 +00:00
var pure_funcs = this.options["pure_funcs"];
if (typeof pure_funcs == "function") {
this.pure_funcs = pure_funcs;
} else if (typeof pure_funcs == "string") {
this.pure_funcs = function(node) {
var expr;
if (node instanceof AST_Call) {
expr = node.expression;
} else if (node instanceof AST_Template) {
expr = node.tag;
}
return !(expr && pure_funcs === expr.print_to_string());
};
} else if (Array.isArray(pure_funcs)) {
this.pure_funcs = function(node) {
var expr;
if (node instanceof AST_Call) {
expr = node.expression;
} else if (node instanceof AST_Template) {
expr = node.tag;
}
return !(expr && member(expr.print_to_string(), pure_funcs));
};
} else {
this.pure_funcs = return_true;
}
var sequences = this.options["sequences"];
this.sequences_limit = sequences == 1 ? 800 : sequences | 0;
var top_retain = this.options["top_retain"];
if (top_retain instanceof RegExp) {
this.top_retain = function(def) {
return top_retain.test(def.name);
};
} else if (typeof top_retain == "function") {
this.top_retain = top_retain;
} else if (top_retain) {
if (typeof top_retain == "string") {
top_retain = top_retain.split(/,/);
}
this.top_retain = function(def) {
return member(def.name, top_retain);
};
}
var toplevel = this.options["toplevel"];
this.toplevel = typeof toplevel == "string" ? {
funcs: /funcs/.test(toplevel),
vars: /vars/.test(toplevel)
} : {
funcs: toplevel,
vars: toplevel
};
}
Compressor.prototype = new TreeTransformer(function(node, descend, in_list) {
if (node._squeezed) return node;
var is_scope = node instanceof AST_Scope;
if (is_scope) {
2022-09-30 13:48:25 +00:00
if (this.option("arrows") && is_arrow(node) && node.value) {
node.body = [ node.first_statement() ];
node.value = null;
}
2022-01-21 08:28:41 +00:00
node.hoist_properties(this);
node.hoist_declarations(this);
2022-03-14 15:40:45 +00:00
node.process_returns(this);
2022-01-21 08:28:41 +00:00
}
// Before https://github.com/mishoo/UglifyJS/pull/1602 AST_Node.optimize()
// would call AST_Node.transform() if a different instance of AST_Node is
// produced after OPT().
// This corrupts TreeWalker.stack, which cause AST look-ups to malfunction.
// Migrate and defer all children's AST_Node.transform() to below, which
// will now happen after this parent AST_Node has been properly substituted
// thus gives a consistent AST snapshot.
descend(node, this);
// Existing code relies on how AST_Node.optimize() worked, and omitting the
// following replacement call would result in degraded efficiency of both
// output and performance.
descend(node, this);
var opt = node.optimize(this);
if (is_scope && opt === node && !this.has_directive("use asm") && !opt.pinned()) {
opt.drop_unused(this);
if (opt.merge_variables(this)) opt.drop_unused(this);
descend(opt, this);
}
if (opt === node) opt._squeezed = true;
return opt;
});
Compressor.prototype.option = function(key) {
return this.options[key];
};
Compressor.prototype.exposed = function(def) {
if (def.exported) return true;
if (def.undeclared) return true;
if (!(def.global || def.scope.resolve() instanceof AST_Toplevel)) return false;
var toplevel = this.toplevel;
return !all(def.orig, function(sym) {
return toplevel[sym instanceof AST_SymbolDefun ? "funcs" : "vars"];
});
};
Compressor.prototype.compress = function(node) {
node = node.resolve_defines(this);
node.hoist_exports(this);
2022-03-14 15:40:45 +00:00
if (this.option("expression")) node.process_expression(true);
2022-01-21 08:28:41 +00:00
var merge_vars = this.options.merge_vars;
var passes = +this.options.passes || 1;
var min_count = 1 / 0;
var stopping = false;
var mangle = { ie: this.option("ie") };
for (var pass = 0; pass < passes; pass++) {
node.figure_out_scope(mangle);
if (pass > 0 || this.option("reduce_vars"))
node.reset_opt_flags(this);
this.options.merge_vars = merge_vars && (stopping || pass == passes - 1);
node = node.transform(this);
if (passes > 1) {
var count = 0;
node.walk(new TreeWalker(function() {
count++;
}));
AST_Node.info("pass {pass}: last_count: {min_count}, count: {count}", {
pass: pass,
min_count: min_count,
count: count,
});
if (count < min_count) {
min_count = count;
stopping = false;
} else if (stopping) {
break;
} else {
stopping = true;
}
}
}
2022-03-14 15:40:45 +00:00
if (this.option("expression")) node.process_expression(false);
2022-01-21 08:28:41 +00:00
return node;
};
(function(OPT) {
OPT(AST_Node, function(self, compressor) {
return self;
});
AST_Toplevel.DEFMETHOD("hoist_exports", function(compressor) {
if (!compressor.option("hoist_exports")) return;
var body = this.body, props = [];
for (var i = 0; i < body.length; i++) {
var stat = body[i];
if (stat instanceof AST_ExportDeclaration) {
body[i] = stat = stat.body;
if (stat instanceof AST_Definitions) {
stat.definitions.forEach(function(defn) {
defn.name.match_symbol(export_symbol, true);
});
} else {
export_symbol(stat.name);
}
} else if (stat instanceof AST_ExportReferences) {
body.splice(i--, 1);
[].push.apply(props, stat.properties);
}
}
if (props.length) body.push(make_node(AST_ExportReferences, this, { properties: props }));
function export_symbol(sym) {
if (!(sym instanceof AST_SymbolDeclaration)) return;
2022-08-31 14:34:36 +00:00
var node = make_node(AST_SymbolExport, sym);
2022-08-05 07:44:52 +00:00
node.alias = make_node(AST_String, node, { value: node.name });
2022-01-21 08:28:41 +00:00
props.push(node);
}
});
AST_Scope.DEFMETHOD("process_expression", function(insert, transform) {
var self = this;
var tt = new TreeTransformer(function(node) {
2022-03-14 15:40:45 +00:00
if (insert) {
if (node instanceof AST_Directive) node = make_node(AST_SimpleStatement, node, {
2022-08-31 14:34:36 +00:00
body: make_node(AST_String, node),
2022-03-14 15:40:45 +00:00
});
if (node instanceof AST_SimpleStatement) {
return transform ? transform(node) : make_node(AST_Return, node, { value: node.body });
}
} else if (node instanceof AST_Return) {
if (transform) return transform(node);
var value = node.value;
2022-08-31 14:34:36 +00:00
if (value instanceof AST_String) return make_node(AST_Directive, value);
2022-03-14 15:40:45 +00:00
return make_node(AST_SimpleStatement, node, {
body: value || make_node(AST_UnaryPrefix, node, {
2022-01-21 08:28:41 +00:00
operator: "void",
expression: make_node(AST_Number, node, { value: 0 }),
}),
});
}
if (node instanceof AST_Block) {
if (node instanceof AST_Lambda) {
if (node !== self) return node;
} else if (insert === "awaits" && node instanceof AST_Try) {
if (node.bfinally) return node;
}
for (var index = node.body.length; --index >= 0;) {
var stat = node.body[index];
if (!is_declaration(stat, true)) {
node.body[index] = stat.transform(tt);
break;
}
}
} else if (node instanceof AST_If) {
node.body = node.body.transform(tt);
2022-03-14 15:40:45 +00:00
if (node.alternative) node.alternative = node.alternative.transform(tt);
2022-01-21 08:28:41 +00:00
} else if (node instanceof AST_With) {
node.body = node.body.transform(tt);
}
return node;
});
self.transform(tt);
});
2022-08-31 14:34:36 +00:00
AST_Toplevel.DEFMETHOD("unwrap_expression", function() {
var self = this;
switch (self.body.length) {
case 0:
return make_node(AST_UnaryPrefix, self, {
operator: "void",
expression: make_node(AST_Number, self, { value: 0 }),
});
case 1:
var stat = self.body[0];
if (stat instanceof AST_Directive) return make_node(AST_String, stat);
if (stat instanceof AST_SimpleStatement) return stat.body;
default:
return make_node(AST_Call, self, {
expression: make_node(AST_Function, self, {
argnames: [],
body: self.body,
}).init_vars(self),
args: [],
});
}
});
AST_Node.DEFMETHOD("wrap_expression", function() {
var self = this;
if (!is_statement(self)) self = make_node(AST_SimpleStatement, self, { body: self });
if (!(self instanceof AST_Toplevel)) self = make_node(AST_Toplevel, self, { body: [ self ] });
return self;
});
2022-01-21 08:28:41 +00:00
function read_property(obj, node) {
var key = node.get_property();
if (key instanceof AST_Node) return;
var value;
if (obj instanceof AST_Array) {
var elements = obj.elements;
if (key == "length") return make_node_from_constant(elements.length, obj);
if (typeof key == "number" && key in elements) value = elements[key];
} else if (obj instanceof AST_Lambda) {
if (key == "length") {
obj.length_read = true;
return make_node_from_constant(obj.argnames.length, obj);
}
} else if (obj instanceof AST_Object) {
key = "" + key;
var props = obj.properties;
for (var i = props.length; --i >= 0;) {
var prop = props[i];
if (!can_hoist_property(prop)) return;
if (!value && props[i].key === key) value = props[i].value;
}
}
return value instanceof AST_SymbolRef && value.fixed_value() || value;
}
function is_read_only_fn(value, name) {
if (value instanceof AST_Boolean) return native_fns.Boolean[name];
if (value instanceof AST_Number) return native_fns.Number[name];
if (value instanceof AST_String) return native_fns.String[name];
if (name == "valueOf") return false;
if (value instanceof AST_Array) return native_fns.Array[name];
if (value instanceof AST_Lambda) return native_fns.Function[name];
if (value instanceof AST_Object) return native_fns.Object[name];
if (value instanceof AST_RegExp) return native_fns.RegExp[name] && !value.value.global;
}
function is_modified(compressor, tw, node, value, level, immutable, recursive) {
var parent = tw.parent(level);
if (compressor.option("unsafe") && parent instanceof AST_Dot && is_read_only_fn(value, parent.property)) {
return;
}
var lhs = is_lhs(node, parent);
if (lhs) return lhs;
if (level == 0 && value && value.is_constant()) return;
if (parent instanceof AST_Array) return is_modified(compressor, tw, parent, parent, level + 1);
if (parent instanceof AST_Assign) switch (parent.operator) {
case "=":
return is_modified(compressor, tw, parent, value, level + 1, immutable, recursive);
case "&&=":
case "||=":
case "??=":
return is_modified(compressor, tw, parent, parent, level + 1);
default:
return;
}
if (parent instanceof AST_Binary) {
if (!lazy_op[parent.operator]) return;
return is_modified(compressor, tw, parent, parent, level + 1);
}
if (parent instanceof AST_Call) {
return !immutable
&& parent.expression === node
&& !parent.is_expr_pure(compressor)
&& (!(value instanceof AST_LambdaExpression) || !(parent instanceof AST_New) && value.contains_this());
}
if (parent instanceof AST_Conditional) {
if (parent.condition === node) return;
return is_modified(compressor, tw, parent, parent, level + 1);
}
if (parent instanceof AST_ForEnumeration) return parent.init === node;
if (parent instanceof AST_ObjectKeyVal) {
if (parent.value !== node) return;
var obj = tw.parent(level + 1);
return is_modified(compressor, tw, obj, obj, level + 2);
}
if (parent instanceof AST_PropAccess) {
if (parent.expression !== node) return;
var prop = read_property(value, parent);
return (!immutable || recursive) && is_modified(compressor, tw, parent, prop, level + 1);
}
if (parent instanceof AST_Sequence) {
if (parent.tail_node() !== node) return;
return is_modified(compressor, tw, parent, value, level + 1, immutable, recursive);
}
}
function is_lambda(node) {
return node instanceof AST_Class || node instanceof AST_Lambda;
}
function safe_for_extends(node) {
return node instanceof AST_Class || node instanceof AST_Defun || node instanceof AST_Function;
}
function is_arguments(def) {
return def.name == "arguments" && def.scope.uses_arguments;
}
function cross_scope(def, sym) {
do {
if (def === sym) return false;
if (sym instanceof AST_Scope) return true;
} while (sym = sym.parent_scope);
}
function can_drop_symbol(ref, compressor, keep_lambda) {
var def = ref.redef || ref.definition();
if (ref.in_arg && is_funarg(def)) return false;
return all(def.orig, function(sym) {
if (sym instanceof AST_SymbolConst || sym instanceof AST_SymbolLet) {
2022-02-07 14:48:46 +00:00
if (sym instanceof AST_SymbolImport) return true;
2022-01-21 08:28:41 +00:00
return compressor && can_varify(compressor, sym);
}
return !(keep_lambda && sym instanceof AST_SymbolLambda);
});
}
function has_escaped(d, scope, node, parent) {
if (parent instanceof AST_Assign) return parent.operator == "=" && parent.right === node;
if (parent instanceof AST_Call) return parent.expression !== node || parent instanceof AST_New;
2022-10-10 08:26:02 +00:00
if (parent instanceof AST_ClassField) return parent.value === node && !parent.static;
2022-01-21 08:28:41 +00:00
if (parent instanceof AST_Exit) return parent.value === node && scope.resolve() !== d.scope.resolve();
if (parent instanceof AST_VarDef) return parent.value === node;
}
2022-11-30 12:56:09 +00:00
function make_ref(ref, fixed) {
var node = make_node(AST_SymbolRef, ref);
node.fixed = fixed || make_node(AST_Undefined, ref);
return node;
}
function replace_ref(resolve, fixed) {
return function(node) {
var ref = resolve(node);
var node = make_ref(ref, fixed);
var def = ref.definition();
def.references.push(node);
def.replaced++;
return node;
};
}
2022-01-21 08:28:41 +00:00
var RE_POSITIVE_INTEGER = /^(0|[1-9][0-9]*)$/;
(function(def) {
def(AST_Node, noop);
function reset_def(tw, compressor, def) {
def.assignments = 0;
2022-03-14 15:40:45 +00:00
def.bool_return = 0;
def.drop_return = 0;
2022-01-21 08:28:41 +00:00
def.cross_loop = false;
def.direct_access = false;
def.escaped = [];
def.fixed = !def.const_redefs
&& !def.scope.pinned()
&& !compressor.exposed(def)
&& !(def.init instanceof AST_LambdaExpression && def.init !== def.scope)
&& def.init;
def.reassigned = 0;
def.recursive_refs = 0;
def.references = [];
def.single_use = undefined;
}
function reset_block_variables(tw, compressor, scope) {
scope.variables.each(function(def) {
reset_def(tw, compressor, def);
});
}
function reset_variables(tw, compressor, scope) {
scope.fn_defs = [];
scope.variables.each(function(def) {
reset_def(tw, compressor, def);
var init = def.init;
if (init instanceof AST_LambdaDefinition) {
scope.fn_defs.push(init);
init.safe_ids = null;
}
if (def.fixed === null) {
def.safe_ids = tw.safe_ids;
mark(tw, def);
} else if (def.fixed) {
tw.loop_ids[def.id] = tw.in_loop;
mark(tw, def);
}
});
scope.may_call_this = function() {
scope.may_call_this = scope.contains_this() ? return_true : return_false;
};
if (scope.uses_arguments) scope.each_argname(function(node) {
node.definition().last_ref = false;
});
if (compressor.option("ie")) scope.variables.each(function(def) {
var d = def.orig[0].definition();
if (d !== def) d.fixed = false;
});
}
function safe_to_visit(tw, fn) {
var marker = fn.safe_ids;
return marker === undefined || marker === tw.safe_ids;
}
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 revisit_fn_def(tw, fn) {
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 && fixed.safe_ids !== undefined) return;
d.fixed = false;
});
}
function mark_fn_def(tw, def, fn) {
var marker = fn.safe_ids;
if (marker === undefined) return;
if (marker === false) return;
if (fn.parent_scope.resolve().may_call_this === return_true) {
if (member(fn, tw.fn_visited)) revisit_fn_def(tw, fn);
} else if (marker) {
var visited = member(fn, tw.fn_visited);
if (marker === tw.safe_ids) {
if (!visited) walk_fn_def(tw, fn);
} else if (visited) {
revisit_fn_def(tw, fn);
} else {
fn.safe_ids = false;
}
} else if (tw.fn_scanning && tw.fn_scanning !== def.scope.resolve()) {
fn.safe_ids = false;
} else {
fn.safe_ids = tw.safe_ids;
walk_fn_def(tw, fn);
}
}
function pop_scope(tw, scope) {
var fn_defs = scope.fn_defs;
var tangled = scope.may_call_this === return_true ? fn_defs : fn_defs.filter(function(fn) {
if (fn.safe_ids === false) return true;
fn.safe_ids = tw.safe_ids;
walk_fn_def(tw, fn);
return false;
});
pop(tw);
tangled.forEach(function(fn) {
fn.safe_ids = tw.safe_ids;
walk_fn_def(tw, fn);
});
fn_defs.forEach(function(fn) {
fn.safe_ids = undefined;
});
scope.fn_defs = undefined;
scope.may_call_this = undefined;
}
2022-09-30 13:48:25 +00:00
function push(tw, sequential) {
var safe_ids = Object.create(tw.safe_ids);
if (!sequential) safe_ids.seq = {};
tw.safe_ids = safe_ids;
2022-01-21 08:28:41 +00:00
}
function pop(tw) {
tw.safe_ids = Object.getPrototypeOf(tw.safe_ids);
}
function mark(tw, def) {
tw.safe_ids[def.id] = {};
}
function push_ref(def, ref) {
def.references.push(ref);
if (def.last_ref !== false) def.last_ref = ref;
}
function safe_to_read(tw, def) {
if (def.single_use == "m") return false;
var safe = tw.safe_ids[def.id];
if (safe) {
var in_order = HOP(tw.safe_ids, def.id);
2022-09-30 13:48:25 +00:00
if (!in_order) {
var seq = tw.safe_ids.seq;
if (!safe.read) {
safe.read = seq;
} else if (safe.read !== seq) {
safe.read = true;
}
}
2022-01-21 08:28:41 +00:00
if (def.fixed == null) {
if (is_arguments(def)) return false;
if (def.global && def.name == "arguments") return false;
tw.loop_ids[def.id] = null;
def.fixed = make_node(AST_Undefined, def.orig[0]);
if (in_order) def.safe_ids = undefined;
return true;
}
return !safe.assign || safe.assign === tw.safe_ids;
}
return def.fixed instanceof AST_LambdaDefinition;
}
function safe_to_assign(tw, def, declare) {
if (!declare) {
if (is_funarg(def) && def.scope.uses_arguments && !tw.has_directive("use strict")) return false;
if (!all(def.orig, function(sym) {
return !(sym instanceof AST_SymbolConst);
})) return false;
}
if (def.fixed === undefined) return declare || all(def.orig, function(sym) {
return !(sym instanceof AST_SymbolLet);
});
if (def.fixed === false || def.fixed === 0) return false;
var safe = tw.safe_ids[def.id];
if (def.safe_ids) {
def.safe_ids[def.id] = false;
def.safe_ids = undefined;
return def.fixed === null || HOP(tw.safe_ids, def.id) && !safe.read;
}
if (!HOP(tw.safe_ids, def.id)) {
if (!safe) return false;
2022-05-29 09:24:36 +00:00
if (safe.read || tw.in_loop) {
2022-01-21 08:28:41 +00:00
var scope = tw.find_parent(AST_BlockScope);
if (scope instanceof AST_Class) return false;
if (def.scope.resolve() !== scope.resolve()) return false;
}
safe.assign = safe.assign && safe.assign !== tw.safe_ids ? true : tw.safe_ids;
}
if (def.fixed != null && safe.read) {
2022-09-30 13:48:25 +00:00
if (safe.read !== tw.safe_ids.seq) return false;
2022-01-21 08:28:41 +00:00
if (tw.loop_ids[def.id] !== tw.in_loop) return false;
}
return safe_to_read(tw, def) && all(def.orig, function(sym) {
return !(sym instanceof AST_SymbolLambda);
});
}
function ref_once(compressor, def) {
return compressor.option("unused")
&& !def.scope.pinned()
&& def.single_use !== false
&& def.references.length - def.recursive_refs == 1
&& !(is_funarg(def) && def.scope.uses_arguments);
}
function is_immutable(value) {
if (!value) return false;
if (value instanceof AST_Assign) {
var op = value.operator;
return op == "=" ? is_immutable(value.right) : !lazy_op[op.slice(0, -1)];
}
if (value instanceof AST_Sequence) return is_immutable(value.tail_node());
return value.is_constant() || is_lambda(value) || value instanceof AST_ObjectIdentity;
}
function value_in_use(node, parent) {
if (parent instanceof AST_Array) return true;
if (parent instanceof AST_Binary) return lazy_op[parent.operator];
if (parent instanceof AST_Conditional) return parent.condition !== node;
if (parent instanceof AST_Sequence) return parent.tail_node() === node;
if (parent instanceof AST_Spread) return true;
}
function mark_escaped(tw, d, scope, node, value, level, depth) {
var parent = tw.parent(level);
if (value && value.is_constant()) return;
if (has_escaped(d, scope, node, parent)) {
d.escaped.push(parent);
if (depth > 1 && !(value && value.is_constant_expression(scope))) depth = 1;
if (!d.escaped.depth || d.escaped.depth > depth) d.escaped.depth = depth;
if (d.scope.resolve() !== scope.resolve()) d.escaped.cross_scope = true;
if (d.fixed) d.fixed.escaped = d.escaped;
return;
} else if (value_in_use(node, parent)) {
mark_escaped(tw, d, scope, parent, parent, level + 1, depth);
} else if (parent instanceof AST_ObjectKeyVal && parent.value === node) {
var obj = tw.parent(level + 1);
mark_escaped(tw, d, scope, obj, obj, level + 2, depth);
} else if (parent instanceof AST_PropAccess && parent.expression === node) {
value = read_property(value, parent);
mark_escaped(tw, d, scope, parent, value, level + 1, depth + 1);
if (value) return;
}
if (level > 0) return;
if (parent instanceof AST_Call && parent.expression === node) return;
if (parent instanceof AST_Sequence && parent.tail_node() !== node) return;
if (parent instanceof AST_SimpleStatement) return;
if (parent instanceof AST_Unary && !unary_side_effects[parent.operator]) return;
d.direct_access = true;
if (d.fixed) d.fixed.direct_access = true;
}
function mark_assignment_to_arguments(node) {
if (!(node instanceof AST_Sub)) return;
var expr = node.expression;
if (!(expr instanceof AST_SymbolRef)) return;
var def = expr.definition();
if (!is_arguments(def)) return;
var key = node.property;
if (key.is_constant()) key = key.value;
if (!(key instanceof AST_Node) && !RE_POSITIVE_INTEGER.test(key)) return;
def.reassigned++;
(key instanceof AST_Node ? def.scope.argnames : [ def.scope.argnames[key] ]).forEach(function(argname) {
if (argname instanceof AST_SymbolFunarg) argname.definition().fixed = false;
});
}
2022-04-11 08:07:00 +00:00
function make_fixed(save, fn) {
var prev_save, prev_value;
return function() {
var current = save();
if (prev_save !== current) {
prev_save = current;
prev_value = fn(current);
}
return prev_value;
};
}
function make_fixed_default(compressor, node, save) {
var prev_save, prev_seq;
return function() {
2022-06-08 10:36:39 +00:00
if (prev_seq === node) return node;
2022-04-11 08:07:00 +00:00
var current = save();
2022-06-08 10:36:39 +00:00
var ev = fuzzy_eval(compressor, current, true);
if (ev instanceof AST_Node) {
prev_seq = node;
} else if (prev_save !== current) {
2022-04-11 08:07:00 +00:00
prev_save = current;
2022-06-08 10:36:39 +00:00
prev_seq = ev === undefined ? make_sequence(node, [ current, node.value ]) : current;
2022-04-11 08:07:00 +00:00
}
return prev_seq;
};
}
2022-01-21 08:28:41 +00:00
function scan_declaration(tw, compressor, lhs, fixed, visit) {
var scanner = new TreeWalker(function(node) {
if (node instanceof AST_DefaultValue) {
reset_flags(node);
2022-09-30 13:48:25 +00:00
push(tw, true);
2022-01-21 08:28:41 +00:00
node.value.walk(tw);
pop(tw);
var save = fixed;
2022-04-11 08:07:00 +00:00
if (save) fixed = make_fixed_default(compressor, node, save);
2022-01-21 08:28:41 +00:00
node.name.walk(scanner);
fixed = save;
return true;
}
if (node instanceof AST_DestructuredArray) {
reset_flags(node);
var save = fixed;
node.elements.forEach(function(node, index) {
if (node instanceof AST_Hole) return reset_flags(node);
2022-04-11 08:07:00 +00:00
if (save) fixed = make_fixed(save, function(value) {
2022-01-21 08:28:41 +00:00
return make_node(AST_Sub, node, {
2022-04-11 08:07:00 +00:00
expression: value,
2022-01-21 08:28:41 +00:00
property: make_node(AST_Number, node, { value: index }),
});
2022-04-11 08:07:00 +00:00
});
2022-01-21 08:28:41 +00:00
node.walk(scanner);
});
if (node.rest) {
var fixed_node;
2022-04-11 08:07:00 +00:00
if (save) fixed = compressor.option("rests") && make_fixed(save, function(value) {
2022-01-21 08:28:41 +00:00
if (!(value instanceof AST_Array)) return node;
2022-02-07 14:48:46 +00:00
for (var i = 0, len = node.elements.length; i < len; i++) {
if (value.elements[i] instanceof AST_Spread) return node;
}
2022-08-31 14:34:36 +00:00
if (!fixed_node) fixed_node = make_node(AST_Array, node, {});
2022-02-07 14:48:46 +00:00
fixed_node.elements = value.elements.slice(len);
2022-01-21 08:28:41 +00:00
return fixed_node;
2022-04-11 08:07:00 +00:00
});
2022-01-21 08:28:41 +00:00
node.rest.walk(scanner);
}
fixed = save;
return true;
}
if (node instanceof AST_DestructuredObject) {
reset_flags(node);
var save = fixed;
node.properties.forEach(function(node) {
reset_flags(node);
if (node.key instanceof AST_Node) {
push(tw);
node.key.walk(tw);
pop(tw);
}
2022-04-11 08:07:00 +00:00
if (save) fixed = make_fixed(save, function(value) {
2022-01-21 08:28:41 +00:00
var key = node.key;
var type = AST_Sub;
if (typeof key == "string") {
if (is_identifier_string(key)) {
type = AST_Dot;
} else {
key = make_node_from_constant(key, node);
}
}
return make_node(type, node, {
2022-04-11 08:07:00 +00:00
expression: value,
property: key,
2022-01-21 08:28:41 +00:00
});
2022-04-11 08:07:00 +00:00
});
2022-01-21 08:28:41 +00:00
node.value.walk(scanner);
});
if (node.rest) {
fixed = false;
node.rest.walk(scanner);
}
fixed = save;
return true;
}
visit(node, fixed, function() {
var save_len = tw.stack.length;
for (var i = 0, len = scanner.stack.length - 1; i < len; i++) {
tw.stack.push(scanner.stack[i]);
}
node.walk(tw);
tw.stack.length = save_len;
});
return true;
});
lhs.walk(scanner);
}
function reduce_iife(tw, descend, compressor) {
var fn = this;
fn.inlined = false;
var iife = tw.parent();
2022-09-30 13:48:25 +00:00
var sequential = !is_async(fn) && !is_generator(fn);
var hit = !sequential;
2022-01-21 08:28:41 +00:00
var aborts = false;
fn.walk(new TreeWalker(function(node) {
if (hit) return aborts = true;
if (node instanceof AST_Return) return hit = true;
if (node instanceof AST_Scope && node !== fn) return true;
}));
2022-09-30 13:48:25 +00:00
if (aborts) push(tw, sequential);
2022-01-21 08:28:41 +00:00
reset_variables(tw, compressor, fn);
// Virtually turn IIFE parameters into variable definitions:
// (function(a,b) {...})(c,d) ---> (function() {var a=c,b=d; ...})()
// So existing transformation rules can work on them.
var safe = !fn.uses_arguments || tw.has_directive("use strict");
fn.argnames.forEach(function(argname, i) {
var value = iife.args[i];
scan_declaration(tw, compressor, argname, function() {
var j = fn.argnames.indexOf(argname);
var arg = j < 0 ? value : iife.args[j];
if (arg instanceof AST_Sequence && arg.expressions.length < 2) arg = arg.expressions[0];
return arg || make_node(AST_Undefined, iife);
}, visit);
});
var rest = fn.rest, fixed_node;
if (rest) scan_declaration(tw, compressor, rest, compressor.option("rests") && function() {
if (fn.rest !== rest) return rest;
2022-08-31 14:34:36 +00:00
if (!fixed_node) fixed_node = make_node(AST_Array, fn, {});
2022-01-21 08:28:41 +00:00
fixed_node.elements = iife.args.slice(fn.argnames.length);
return fixed_node;
}, visit);
walk_lambda(fn, tw);
var safe_ids = tw.safe_ids;
pop_scope(tw, fn);
if (!aborts) tw.safe_ids = safe_ids;
return true;
function visit(node, fixed) {
var d = node.definition();
if (fixed && safe && d.fixed === undefined) {
mark(tw, d);
tw.loop_ids[d.id] = tw.in_loop;
d.fixed = fixed;
d.fixed.assigns = [ node ];
} else {
d.fixed = false;
}
}
}
def(AST_Assign, function(tw, descend, compressor) {
var node = this;
var left = node.left;
var right = node.right;
var ld = left instanceof AST_SymbolRef && left.definition();
var scan = ld || left instanceof AST_Destructured;
switch (node.operator) {
case "=":
2022-08-05 07:44:52 +00:00
if (left.equals(right) && !left.has_side_effects(compressor)) {
2022-01-21 08:28:41 +00:00
right.walk(tw);
walk_prop(left);
node.redundant = true;
return true;
}
if (ld && right instanceof AST_LambdaExpression) {
walk_assign();
right.parent_scope.resolve().fn_defs.push(right);
right.safe_ids = null;
if (!ld.fixed || !node.write_only) mark_fn_def(tw, ld, right);
return true;
}
if (scan) {
right.walk(tw);
walk_assign();
return true;
}
mark_assignment_to_arguments(left);
return;
case "&&=":
case "||=":
case "??=":
var lazy = true;
default:
if (!scan) {
mark_assignment_to_arguments(left);
return walk_lazy();
}
ld.assignments++;
var fixed = ld.fixed;
if (is_modified(compressor, tw, node, node, 0)) {
ld.fixed = false;
return walk_lazy();
}
var safe = safe_to_read(tw, ld);
2022-09-30 13:48:25 +00:00
if (lazy) push(tw, true);
2022-01-21 08:28:41 +00:00
right.walk(tw);
if (lazy) pop(tw);
if (safe && !left.in_arg && safe_to_assign(tw, ld)) {
push_ref(ld, left);
mark(tw, ld);
if (ld.single_use) ld.single_use = false;
left.fixed = ld.fixed = function() {
return make_node(AST_Binary, node, {
operator: node.operator.slice(0, -1),
left: make_ref(left, fixed),
right: node.right,
});
};
2022-02-07 14:48:46 +00:00
left.fixed.assigns = !fixed || !fixed.assigns ? [ ld.orig[0] ] : fixed.assigns.slice();
2022-01-21 08:28:41 +00:00
left.fixed.assigns.push(node);
2022-11-30 12:56:09 +00:00
left.fixed.to_binary = replace_ref(function(node) {
return node.left;
}, fixed);
2022-01-21 08:28:41 +00:00
} else {
left.walk(tw);
ld.fixed = false;
}
return true;
}
function walk_prop(lhs) {
2022-09-30 13:48:25 +00:00
reset_flags(lhs);
2022-01-21 08:28:41 +00:00
if (lhs instanceof AST_Dot) {
walk_prop(lhs.expression);
} else if (lhs instanceof AST_Sub) {
walk_prop(lhs.expression);
lhs.property.walk(tw);
} else if (lhs instanceof AST_SymbolRef) {
var d = lhs.definition();
push_ref(d, lhs);
if (d.fixed) {
lhs.fixed = d.fixed;
if (lhs.fixed.assigns) {
lhs.fixed.assigns.push(node);
} else {
lhs.fixed.assigns = [ node ];
}
}
} else {
lhs.walk(tw);
}
}
function walk_assign() {
var recursive = ld && recursive_ref(tw, ld);
var modified = is_modified(compressor, tw, node, right, 0, is_immutable(right), recursive);
scan_declaration(tw, compressor, left, function() {
return node.right;
}, function(sym, fixed, walk) {
if (!(sym instanceof AST_SymbolRef)) {
mark_assignment_to_arguments(sym);
walk();
return;
}
var d = sym.definition();
d.assignments++;
if (!fixed || sym.in_arg || !safe_to_assign(tw, d)) {
walk();
d.fixed = false;
} else {
push_ref(d, sym);
mark(tw, d);
if (left instanceof AST_Destructured
|| d.orig.length == 1 && d.orig[0] instanceof AST_SymbolDefun) {
d.single_use = false;
}
tw.loop_ids[d.id] = tw.in_loop;
2022-09-30 13:48:25 +00:00
d.fixed = modified ? 0 : fixed;
sym.fixed = fixed;
2022-01-21 08:28:41 +00:00
sym.fixed.assigns = [ node ];
mark_escaped(tw, d, sym.scope, node, right, 0, 1);
}
});
}
function walk_lazy() {
if (!lazy) return;
left.walk(tw);
2022-09-30 13:48:25 +00:00
push(tw, true);
2022-01-21 08:28:41 +00:00
right.walk(tw);
pop(tw);
return true;
}
});
def(AST_Binary, function(tw) {
if (!lazy_op[this.operator]) return;
this.left.walk(tw);
2022-09-30 13:48:25 +00:00
push(tw, true);
2022-01-21 08:28:41 +00:00
this.right.walk(tw);
pop(tw);
return true;
});
def(AST_BlockScope, function(tw, descend, compressor) {
reset_block_variables(tw, compressor, this);
});
def(AST_Call, function(tw, descend) {
var node = this;
var exp = node.expression;
if (exp instanceof AST_LambdaExpression) {
var iife = is_iife_single(node);
node.args.forEach(function(arg) {
arg.walk(tw);
if (arg instanceof AST_Spread) iife = false;
});
if (iife) exp.reduce_vars = reduce_iife;
exp.walk(tw);
if (iife) delete exp.reduce_vars;
return true;
}
2022-03-14 15:40:45 +00:00
if (node.TYPE == "Call") switch (tw.in_boolean_context()) {
case "d":
var drop = true;
case true:
mark_refs(exp, drop);
2022-01-21 08:28:41 +00:00
}
exp.walk(tw);
var optional = node.optional;
2022-09-30 13:48:25 +00:00
if (optional) push(tw, true);
2022-01-21 08:28:41 +00:00
node.args.forEach(function(arg) {
arg.walk(tw);
});
if (optional) pop(tw);
var fixed = exp instanceof AST_SymbolRef && exp.fixed_value();
if (fixed instanceof AST_Lambda) {
mark_fn_def(tw, exp.definition(), fixed);
} else {
tw.find_parent(AST_Scope).may_call_this();
}
return true;
2022-03-14 15:40:45 +00:00
function mark_refs(node, drop) {
if (node instanceof AST_Assign) {
if (node.operator != "=") return;
mark_refs(node.left, drop);
mark_refs(node.right, drop);
} else if (node instanceof AST_Binary) {
if (!lazy_op[node.operator]) return;
mark_refs(node.left, drop);
mark_refs(node.right, drop);
} else if (node instanceof AST_Conditional) {
mark_refs(node.consequent, drop);
mark_refs(node.alternative, drop);
} else if (node instanceof AST_SymbolRef) {
var def = node.definition();
def.bool_return++;
if (drop) def.drop_return++;
}
}
2022-01-21 08:28:41 +00:00
});
def(AST_Class, function(tw, descend, compressor) {
var node = this;
reset_block_variables(tw, compressor, node);
if (node.extends) node.extends.walk(tw);
var props = node.properties.filter(function(prop) {
reset_flags(prop);
2022-10-10 08:26:02 +00:00
if (prop.key instanceof AST_Node) {
tw.push(prop);
prop.key.walk(tw);
tw.pop();
}
2022-01-21 08:28:41 +00:00
return prop.value;
});
if (node.name) {
var d = node.name.definition();
var parent = tw.parent();
if (parent instanceof AST_ExportDeclaration || parent instanceof AST_ExportDefault) d.single_use = false;
if (safe_to_assign(tw, d, true)) {
mark(tw, d);
tw.loop_ids[d.id] = tw.in_loop;
d.fixed = function() {
return node;
};
d.fixed.assigns = [ node ];
if (!is_safe_lexical(d)) d.single_use = false;
} else {
d.fixed = false;
}
}
props.forEach(function(prop) {
2022-10-10 08:26:02 +00:00
tw.push(prop);
2022-07-11 11:25:19 +00:00
if (!prop.static || is_static_field_or_init(prop) && prop.value.contains_this()) {
2022-01-21 08:28:41 +00:00
push(tw);
prop.value.walk(tw);
pop(tw);
} else {
prop.value.walk(tw);
}
2022-10-10 08:26:02 +00:00
tw.pop();
2022-01-21 08:28:41 +00:00
});
return true;
});
2022-07-11 11:25:19 +00:00
def(AST_ClassInitBlock, function(tw, descend, compressor) {
var node = this;
2022-09-30 13:48:25 +00:00
push(tw, true);
2022-07-11 11:25:19 +00:00
reset_variables(tw, compressor, node);
descend();
pop_scope(tw, node);
return true;
});
2022-01-21 08:28:41 +00:00
def(AST_Conditional, function(tw) {
this.condition.walk(tw);
2022-09-30 13:48:25 +00:00
push(tw, true);
2022-01-21 08:28:41 +00:00
this.consequent.walk(tw);
pop(tw);
2022-09-30 13:48:25 +00:00
push(tw, true);
2022-01-21 08:28:41 +00:00
this.alternative.walk(tw);
pop(tw);
return true;
});
def(AST_DefaultValue, function(tw) {
2022-09-30 13:48:25 +00:00
push(tw, true);
2022-01-21 08:28:41 +00:00
this.value.walk(tw);
pop(tw);
2022-09-30 13:48:25 +00:00
this.name.walk(tw);
2022-01-21 08:28:41 +00:00
return true;
});
def(AST_Do, function(tw) {
var save_loop = tw.in_loop;
tw.in_loop = this;
push(tw);
this.body.walk(tw);
if (has_loop_control(this, tw.parent())) {
pop(tw);
push(tw);
}
this.condition.walk(tw);
pop(tw);
tw.in_loop = save_loop;
return true;
});
def(AST_For, function(tw, descend, compressor) {
var node = this;
reset_block_variables(tw, compressor, node);
if (node.init) node.init.walk(tw);
var save_loop = tw.in_loop;
tw.in_loop = node;
push(tw);
if (node.condition) node.condition.walk(tw);
node.body.walk(tw);
if (node.step) {
if (has_loop_control(node, tw.parent())) {
pop(tw);
push(tw);
}
node.step.walk(tw);
}
pop(tw);
tw.in_loop = save_loop;
return true;
});
def(AST_ForEnumeration, function(tw, descend, compressor) {
var node = this;
reset_block_variables(tw, compressor, node);
node.object.walk(tw);
var save_loop = tw.in_loop;
tw.in_loop = node;
push(tw);
var init = node.init;
if (init instanceof AST_Definitions) {
init.definitions[0].name.mark_symbol(function(node) {
if (node instanceof AST_SymbolDeclaration) {
var def = node.definition();
def.assignments++;
def.fixed = false;
}
}, tw);
} else if (init instanceof AST_Destructured || init instanceof AST_SymbolRef) {
init.mark_symbol(function(node) {
if (node instanceof AST_SymbolRef) {
var def = node.definition();
push_ref(def, node);
def.assignments++;
if (!node.is_immutable()) def.fixed = false;
}
}, tw);
} else {
init.walk(tw);
}
node.body.walk(tw);
pop(tw);
tw.in_loop = save_loop;
return true;
});
def(AST_If, function(tw) {
this.condition.walk(tw);
2022-09-30 13:48:25 +00:00
push(tw, true);
2022-01-21 08:28:41 +00:00
this.body.walk(tw);
pop(tw);
if (this.alternative) {
2022-09-30 13:48:25 +00:00
push(tw, true);
2022-01-21 08:28:41 +00:00
this.alternative.walk(tw);
pop(tw);
}
return true;
});
def(AST_LabeledStatement, function(tw) {
2022-09-30 13:48:25 +00:00
push(tw, true);
2022-01-21 08:28:41 +00:00
this.body.walk(tw);
pop(tw);
return true;
});
def(AST_Lambda, function(tw, descend, compressor) {
var fn = this;
if (!safe_to_visit(tw, fn)) return true;
if (!push_uniq(tw.fn_visited, fn)) return true;
fn.inlined = false;
push(tw);
reset_variables(tw, compressor, fn);
descend();
pop_scope(tw, fn);
if (fn.name) mark_escaped(tw, fn.name.definition(), fn, fn.name, fn, 0, 1);
return true;
});
def(AST_LambdaDefinition, function(tw, descend, compressor) {
var fn = this;
var def = fn.name.definition();
var parent = tw.parent();
if (parent instanceof AST_ExportDeclaration || parent instanceof AST_ExportDefault) def.single_use = false;
if (!safe_to_visit(tw, fn)) return true;
if (!push_uniq(tw.fn_visited, fn)) return true;
fn.inlined = false;
push(tw);
reset_variables(tw, compressor, fn);
descend();
pop_scope(tw, fn);
return true;
});
def(AST_Sub, function(tw) {
if (!this.optional) return;
this.expression.walk(tw);
2022-09-30 13:48:25 +00:00
push(tw, true);
2022-01-21 08:28:41 +00:00
this.property.walk(tw);
pop(tw);
return true;
});
def(AST_Switch, function(tw, descend, compressor) {
var node = this;
reset_block_variables(tw, compressor, node);
node.expression.walk(tw);
var first = true;
node.body.forEach(function(branch) {
if (branch instanceof AST_Default) return;
branch.expression.walk(tw);
if (first) {
first = false;
2022-09-30 13:48:25 +00:00
push(tw, true);
2022-01-21 08:28:41 +00:00
}
})
if (!first) pop(tw);
walk_body(node, tw);
return true;
});
def(AST_SwitchBranch, function(tw) {
2022-09-30 13:48:25 +00:00
push(tw, true);
2022-01-21 08:28:41 +00:00
walk_body(this, tw);
pop(tw);
return true;
});
def(AST_SymbolCatch, function() {
this.definition().fixed = false;
});
def(AST_SymbolImport, function() {
this.definition().fixed = false;
});
def(AST_SymbolRef, function(tw, descend, compressor) {
2022-09-30 13:48:25 +00:00
var ref = this;
var d = ref.definition();
var fixed = d.fixed || d.last_ref && d.last_ref.fixed;
push_ref(d, ref);
2022-01-21 08:28:41 +00:00
if (d.references.length == 1 && !d.fixed && d.orig[0] instanceof AST_SymbolDefun) {
tw.loop_ids[d.id] = tw.in_loop;
}
var recursive = recursive_ref(tw, d);
if (recursive) recursive.enclosed.forEach(function(def) {
if (d === def) return;
if (def.scope.resolve() === recursive) return;
var assigns = def.fixed && def.fixed.assigns;
if (!assigns) return;
if (assigns[assigns.length - 1] instanceof AST_VarDef) return;
var safe = tw.safe_ids[def.id];
if (!safe) return;
safe.assign = true;
});
2022-09-30 13:48:25 +00:00
if (d.single_use == "m" && d.fixed) {
d.fixed = 0;
d.single_use = false;
}
switch (d.fixed) {
case 0:
if (!safe_to_read(tw, d)) d.fixed = false;
case false:
2022-01-21 08:28:41 +00:00
var redef = d.redefined();
2022-09-30 13:48:25 +00:00
if (redef && cross_scope(d.scope, ref.scope)) redef.single_use = false;
break;
case undefined:
2022-01-21 08:28:41 +00:00
d.fixed = false;
2022-09-30 13:48:25 +00:00
break;
default:
if (!safe_to_read(tw, d)) {
d.fixed = false;
break;
}
if (ref.in_arg && d.orig[0] instanceof AST_SymbolLambda) ref.fixed = d.scope;
var value = ref.fixed_value();
2022-01-21 08:28:41 +00:00
if (recursive) {
d.recursive_refs++;
} else if (value && ref_once(compressor, d)) {
d.in_loop = tw.loop_ids[d.id] !== tw.in_loop;
d.single_use = is_lambda(value)
&& !value.pinned()
&& (!d.in_loop || tw.parent() instanceof AST_Call)
|| !d.in_loop
2022-09-30 13:48:25 +00:00
&& d.scope === ref.scope.resolve()
2022-01-21 08:28:41 +00:00
&& value.is_constant_expression();
} else {
d.single_use = false;
}
2022-09-30 13:48:25 +00:00
if (is_modified(compressor, tw, ref, value, 0, is_immutable(value), recursive)) {
2022-01-21 08:28:41 +00:00
if (d.single_use) {
d.single_use = "m";
} else {
d.fixed = 0;
}
}
if (d.fixed && tw.loop_ids[d.id] !== tw.in_loop) d.cross_loop = true;
2022-09-30 13:48:25 +00:00
mark_escaped(tw, d, ref.scope, ref, value, 0, 1);
break;
2022-01-21 08:28:41 +00:00
}
2022-09-30 13:48:25 +00:00
if (!ref.fixed) ref.fixed = d.fixed === 0 ? fixed : d.fixed;
2022-01-21 08:28:41 +00:00
var parent;
if (value instanceof AST_Lambda
2022-09-30 13:48:25 +00:00
&& !((parent = tw.parent()) instanceof AST_Call && parent.expression === ref)) {
2022-01-21 08:28:41 +00:00
mark_fn_def(tw, d, value);
}
});
def(AST_Template, function(tw, descend) {
var node = this;
var tag = node.tag;
if (!tag) return;
if (tag instanceof AST_LambdaExpression) {
node.expressions.forEach(function(exp) {
exp.walk(tw);
});
tag.walk(tw);
return true;
}
tag.walk(tw);
node.expressions.forEach(function(exp) {
exp.walk(tw);
});
var fixed = tag instanceof AST_SymbolRef && tag.fixed_value();
if (fixed instanceof AST_Lambda) {
mark_fn_def(tw, tag.definition(), fixed);
} else {
tw.find_parent(AST_Scope).may_call_this();
}
return true;
});
def(AST_Toplevel, function(tw, descend, compressor) {
var node = this;
node.globals.each(function(def) {
reset_def(tw, compressor, def);
});
2022-09-30 13:48:25 +00:00
push(tw, true);
2022-01-21 08:28:41 +00:00
reset_variables(tw, compressor, node);
descend();
pop_scope(tw, node);
return true;
});
def(AST_Try, function(tw, descend, compressor) {
var node = this;
reset_block_variables(tw, compressor, node);
2022-09-30 13:48:25 +00:00
push(tw, true);
2022-01-21 08:28:41 +00:00
walk_body(node, tw);
pop(tw);
if (node.bcatch) {
2022-09-30 13:48:25 +00:00
push(tw, true);
2022-01-21 08:28:41 +00:00
node.bcatch.walk(tw);
pop(tw);
}
if (node.bfinally) node.bfinally.walk(tw);
return true;
});
def(AST_Unary, function(tw, descend) {
var node = this;
if (!UNARY_POSTFIX[node.operator]) return;
var exp = node.expression;
if (!(exp instanceof AST_SymbolRef)) {
mark_assignment_to_arguments(exp);
return;
}
var d = exp.definition();
d.assignments++;
var fixed = d.fixed;
if (safe_to_read(tw, d) && !exp.in_arg && safe_to_assign(tw, d)) {
push_ref(d, exp);
mark(tw, d);
if (d.single_use) d.single_use = false;
d.fixed = function() {
return make_node(AST_Binary, node, {
operator: node.operator.slice(0, -1),
left: make_node(AST_UnaryPrefix, node, {
operator: "+",
2022-02-07 14:48:46 +00:00
expression: make_ref(exp, fixed),
2022-01-21 08:28:41 +00:00
}),
2022-02-07 14:48:46 +00:00
right: make_node(AST_Number, node, { value: 1 }),
2022-01-21 08:28:41 +00:00
});
};
d.fixed.assigns = fixed && fixed.assigns ? fixed.assigns.slice() : [];
d.fixed.assigns.push(node);
if (node instanceof AST_UnaryPrefix) {
exp.fixed = d.fixed;
} else {
exp.fixed = function() {
return make_node(AST_UnaryPrefix, node, {
operator: "+",
2022-02-07 14:48:46 +00:00
expression: make_ref(exp, fixed),
2022-01-21 08:28:41 +00:00
});
};
exp.fixed.assigns = fixed && fixed.assigns;
2022-11-30 12:56:09 +00:00
exp.fixed.to_prefix = replace_ref(function(node) {
return node.expression;
}, d.fixed);
2022-01-21 08:28:41 +00:00
}
} else {
exp.walk(tw);
d.fixed = false;
}
return true;
});
def(AST_VarDef, function(tw, descend, compressor) {
var node = this;
var value = node.value;
if (value instanceof AST_LambdaExpression && node.name instanceof AST_SymbolDeclaration) {
walk_defn();
value.parent_scope.resolve().fn_defs.push(value);
value.safe_ids = null;
var ld = node.name.definition();
if (!ld.fixed) mark_fn_def(tw, ld, value);
} else if (value) {
value.walk(tw);
walk_defn();
} else if (tw.parent() instanceof AST_Let) {
walk_defn();
}
return true;
function walk_defn() {
scan_declaration(tw, compressor, node.name, function() {
return node.value || make_node(AST_Undefined, node);
}, function(name, fixed) {
var d = name.definition();
if (fixed && safe_to_assign(tw, d, true)) {
mark(tw, d);
tw.loop_ids[d.id] = tw.in_loop;
d.fixed = fixed;
d.fixed.assigns = [ node ];
if (name instanceof AST_SymbolConst && d.redefined()
|| !(can_drop_symbol(name) || is_safe_lexical(d))) {
d.single_use = false;
}
} else {
d.fixed = false;
}
});
}
});
def(AST_While, function(tw, descend) {
var save_loop = tw.in_loop;
tw.in_loop = this;
push(tw);
descend();
pop(tw);
tw.in_loop = save_loop;
return true;
});
})(function(node, func) {
node.DEFMETHOD("reduce_vars", func);
});
function reset_flags(node) {
node._squeezed = false;
node._optimized = false;
if (node instanceof AST_BlockScope) node._var_names = undefined;
if (node instanceof AST_SymbolRef) node.fixed = undefined;
}
AST_Toplevel.DEFMETHOD("reset_opt_flags", function(compressor) {
var tw = new TreeWalker(compressor.option("reduce_vars") ? function(node, descend) {
reset_flags(node);
return node.reduce_vars(tw, descend, compressor);
} : reset_flags);
// Flow control for visiting lambda definitions
tw.fn_scanning = null;
tw.fn_visited = [];
// Record the loop body in which `AST_SymbolDeclaration` is first encountered
tw.in_loop = null;
tw.loop_ids = Object.create(null);
// Stack of look-up tables to keep track of whether a `SymbolDef` has been
// properly assigned before use:
// - `push()` & `pop()` when visiting conditional branches
// - backup & restore via `save_ids` when visiting out-of-order sections
tw.safe_ids = Object.create(null);
2022-09-30 13:48:25 +00:00
tw.safe_ids.seq = {};
2022-01-21 08:28:41 +00:00
this.walk(tw);
});
2022-09-30 13:48:25 +00:00
AST_Symbol.DEFMETHOD("fixed_value", function(ref_only) {
var def = this.definition();
var fixed = def.fixed;
2022-01-21 08:28:41 +00:00
if (fixed) {
if (this.fixed) fixed = this.fixed;
2022-02-07 14:48:46 +00:00
return (fixed instanceof AST_Node ? fixed : fixed()).tail_node();
2022-01-21 08:28:41 +00:00
}
fixed = fixed === 0 && this.fixed;
if (!fixed) return fixed;
2022-02-07 14:48:46 +00:00
var value = (fixed instanceof AST_Node ? fixed : fixed()).tail_node();
2022-09-30 13:48:25 +00:00
if (ref_only && def.escaped.depth != 1 && is_object(value, true)) return value;
if (value.is_constant()) return value;
2022-01-21 08:28:41 +00:00
});
AST_SymbolRef.DEFMETHOD("is_immutable", function() {
var def = this.redef || this.definition();
2022-06-08 10:36:39 +00:00
if (!(def.orig[0] instanceof AST_SymbolLambda)) return false;
if (def.orig.length == 1) return true;
if (!this.in_arg) return false;
return !(def.orig[1] instanceof AST_SymbolFunarg);
2022-01-21 08:28:41 +00:00
});
AST_Node.DEFMETHOD("convert_symbol", noop);
function convert_destructured(type, process) {
return this.transform(new TreeTransformer(function(node, descend) {
if (node instanceof AST_DefaultValue) {
node = node.clone();
node.name = node.name.transform(this);
return node;
}
if (node instanceof AST_Destructured) {
node = node.clone();
descend(node, this);
return node;
}
if (node instanceof AST_DestructuredKeyVal) {
node = node.clone();
node.value = node.value.transform(this);
return node;
}
return node.convert_symbol(type, process);
}));
}
AST_DefaultValue.DEFMETHOD("convert_symbol", convert_destructured);
AST_Destructured.DEFMETHOD("convert_symbol", convert_destructured);
function convert_symbol(type, process) {
2022-08-31 14:34:36 +00:00
var node = make_node(type, this);
2022-07-11 11:25:19 +00:00
return process(node, this) || node;
2022-01-21 08:28:41 +00:00
}
AST_SymbolDeclaration.DEFMETHOD("convert_symbol", convert_symbol);
AST_SymbolRef.DEFMETHOD("convert_symbol", convert_symbol);
2022-02-07 14:48:46 +00:00
function process_to_assign(ref) {
var def = ref.definition();
def.assignments++;
def.references.push(ref);
}
2022-01-21 08:28:41 +00:00
function mark_destructured(process, tw) {
var marker = new TreeWalker(function(node) {
if (node instanceof AST_DefaultValue) {
node.value.walk(tw);
node.name.walk(marker);
return true;
}
if (node instanceof AST_DestructuredKeyVal) {
if (node.key instanceof AST_Node) node.key.walk(tw);
node.value.walk(marker);
return true;
}
return process(node);
});
this.walk(marker);
}
AST_DefaultValue.DEFMETHOD("mark_symbol", mark_destructured);
AST_Destructured.DEFMETHOD("mark_symbol", mark_destructured);
function mark_symbol(process) {
return process(this);
}
AST_SymbolDeclaration.DEFMETHOD("mark_symbol", mark_symbol);
AST_SymbolRef.DEFMETHOD("mark_symbol", mark_symbol);
AST_Node.DEFMETHOD("match_symbol", function(predicate) {
return predicate(this);
});
function match_destructured(predicate, ignore_side_effects) {
var found = false;
var tw = new TreeWalker(function(node) {
if (found) return true;
if (node instanceof AST_DefaultValue) {
if (!ignore_side_effects) return found = true;
node.name.walk(tw);
return true;
}
if (node instanceof AST_DestructuredKeyVal) {
if (!ignore_side_effects && node.key instanceof AST_Node) return found = true;
node.value.walk(tw);
return true;
}
if (predicate(node)) return found = true;
});
this.walk(tw);
return found;
}
AST_DefaultValue.DEFMETHOD("match_symbol", match_destructured);
AST_Destructured.DEFMETHOD("match_symbol", match_destructured);
function in_async_generator(scope) {
return scope instanceof AST_AsyncGeneratorDefun || scope instanceof AST_AsyncGeneratorFunction;
}
function find_scope(compressor) {
2022-09-30 13:48:25 +00:00
var level = 0, node = compressor.self();
do {
2022-01-21 08:28:41 +00:00
if (node.variables) return node;
2022-09-30 13:48:25 +00:00
} while (node = compressor.parent(level++));
2022-01-21 08:28:41 +00:00
}
2022-08-05 07:44:52 +00:00
function find_try(compressor, level, node, scope, may_throw, sync) {
for (var parent; parent = compressor.parent(level++); node = parent) {
if (parent === scope) return false;
if (sync && parent instanceof AST_Lambda) {
if (parent.name || is_async(parent) || is_generator(parent)) return true;
} else if (parent instanceof AST_Try) {
if (parent.bfinally && parent.bfinally !== node) return true;
if (may_throw && parent.bcatch && parent.bcatch !== node) return true;
}
}
return false;
}
2022-01-21 08:28:41 +00:00
var identifier_atom = makePredicate("Infinity NaN undefined");
function is_lhs_read_only(lhs, compressor) {
2022-10-10 08:26:02 +00:00
if (lhs instanceof AST_Atom) return true;
2022-01-21 08:28:41 +00:00
if (lhs instanceof AST_ObjectIdentity) return true;
if (lhs instanceof AST_PropAccess) {
if (lhs.property === "__proto__") return true;
lhs = lhs.expression;
if (lhs instanceof AST_SymbolRef) {
if (lhs.is_immutable()) return false;
lhs = lhs.fixed_value();
}
if (!lhs) return true;
if (lhs.tail_node().is_constant()) return true;
return is_lhs_read_only(lhs, compressor);
}
if (lhs instanceof AST_SymbolRef) {
if (lhs.is_immutable()) return true;
var def = lhs.definition();
return compressor.exposed(def) && identifier_atom[def.name];
}
return false;
}
function make_node(ctor, orig, props) {
2022-08-31 14:34:36 +00:00
if (props) {
props.start = orig.start;
props.end = orig.end;
} else {
props = orig;
2022-01-21 08:28:41 +00:00
}
return new ctor(props);
}
function make_sequence(orig, expressions) {
if (expressions.length == 1) return expressions[0];
2022-08-31 14:34:36 +00:00
return make_node(AST_Sequence, orig, { expressions: expressions.reduce(merge_sequence, []) });
2022-01-21 08:28:41 +00:00
}
function make_node_from_constant(val, orig) {
switch (typeof val) {
case "string":
2022-02-07 14:48:46 +00:00
return make_node(AST_String, orig, { value: val });
2022-01-21 08:28:41 +00:00
case "number":
if (isNaN(val)) return make_node(AST_NaN, orig);
if (isFinite(val)) {
return 1 / val < 0 ? make_node(AST_UnaryPrefix, orig, {
operator: "-",
2022-08-31 14:34:36 +00:00
expression: make_node(AST_Number, orig, { value: -val }),
2022-01-21 08:28:41 +00:00
}) : make_node(AST_Number, orig, { value: val });
}
return val < 0 ? make_node(AST_UnaryPrefix, orig, {
operator: "-",
2022-02-07 14:48:46 +00:00
expression: make_node(AST_Infinity, orig),
2022-01-21 08:28:41 +00:00
}) : make_node(AST_Infinity, orig);
case "boolean":
return make_node(val ? AST_True : AST_False, orig);
case "undefined":
return make_node(AST_Undefined, orig);
default:
if (val === null) {
2022-02-07 14:48:46 +00:00
return make_node(AST_Null, orig);
2022-01-21 08:28:41 +00:00
}
if (val instanceof RegExp) {
return make_node(AST_RegExp, orig, { value: val });
}
2022-08-31 14:34:36 +00:00
throw new Error(string_template("Can't handle constant of type: {type}", { type: typeof val }));
2022-01-21 08:28:41 +00:00
}
}
2022-08-31 14:34:36 +00:00
function needs_unbinding(val) {
2022-01-21 08:28:41 +00:00
return val instanceof AST_PropAccess
|| is_undeclared_ref(val) && val.name == "eval";
}
// we shouldn't compress (1,func)(something) to
// func(something) because that changes the meaning of
// the func (becomes lexical instead of global).
2022-08-31 14:34:36 +00:00
function maintain_this_binding(parent, orig, val) {
2022-01-21 08:28:41 +00:00
var wrap = false;
if (parent.TYPE == "Call") {
2022-08-31 14:34:36 +00:00
wrap = parent.expression === orig && needs_unbinding(val);
2022-01-21 08:28:41 +00:00
} else if (parent instanceof AST_Template) {
2022-08-31 14:34:36 +00:00
wrap = parent.tag === orig && needs_unbinding(val);
2022-01-21 08:28:41 +00:00
} else if (parent instanceof AST_UnaryPrefix) {
wrap = parent.operator == "delete"
|| parent.operator == "typeof" && is_undeclared_ref(val);
}
return wrap ? make_sequence(orig, [ make_node(AST_Number, orig, { value: 0 }), val ]) : val;
}
2022-09-30 13:48:25 +00:00
function merge_expression(base, target) {
var fixed_by_id = new Dictionary();
base.walk(new TreeWalker(function(node) {
if (!(node instanceof AST_SymbolRef)) return;
var def = node.definition();
var fixed = node.fixed;
if (!fixed || !fixed_by_id.has(def.id)) {
fixed_by_id.set(def.id, fixed);
} else if (fixed_by_id.get(def.id) !== fixed) {
fixed_by_id.set(def.id, false);
}
}));
if (fixed_by_id.size() > 0) target.walk(new TreeWalker(function(node) {
if (!(node instanceof AST_SymbolRef)) return;
var def = node.definition();
var fixed = node.fixed;
if (!fixed || !fixed_by_id.has(def.id)) return;
if (fixed_by_id.get(def.id) !== fixed) node.fixed = false;
}));
return target;
}
2022-01-21 08:28:41 +00:00
function merge_sequence(array, node) {
if (node instanceof AST_Sequence) {
2022-02-07 14:48:46 +00:00
[].push.apply(array, node.expressions);
2022-01-21 08:28:41 +00:00
} else {
array.push(node);
}
return array;
}
function is_lexical_definition(stat) {
return stat instanceof AST_Const || stat instanceof AST_DefClass || stat instanceof AST_Let;
}
function safe_to_trim(stat) {
if (stat instanceof AST_LambdaDefinition) {
var def = stat.name.definition();
var scope = stat.name.scope;
return def.scope === scope || all(def.references, function(ref) {
var s = ref.scope;
do {
if (s === scope) return true;
} while (s = s.parent_scope);
});
}
return !is_lexical_definition(stat);
}
function as_statement_array(thing) {
if (thing === null) return [];
if (thing instanceof AST_BlockStatement) return all(thing.body, safe_to_trim) ? thing.body : [ thing ];
if (thing instanceof AST_EmptyStatement) return [];
if (is_statement(thing)) return [ thing ];
throw new Error("Can't convert thing to statement array");
}
function is_empty(thing) {
if (thing === null) return true;
if (thing instanceof AST_EmptyStatement) return true;
if (thing instanceof AST_BlockStatement) return thing.body.length == 0;
return false;
}
function has_declarations_only(block) {
return all(block.body, function(stat) {
return is_empty(stat)
|| stat instanceof AST_Defun
|| stat instanceof AST_Var && declarations_only(stat);
});
}
function loop_body(x) {
if (x instanceof AST_IterationStatement) {
return x.body instanceof AST_BlockStatement ? x.body : x;
}
return x;
}
function is_iife_call(node) {
if (node.TYPE != "Call") return false;
do {
node = node.expression;
} while (node instanceof AST_PropAccess);
return node instanceof AST_LambdaExpression ? !is_arrow(node) : is_iife_call(node);
}
function is_iife_single(call) {
var exp = call.expression;
if (exp.name) return false;
if (!(call instanceof AST_New)) return true;
var found = false;
exp.walk(new TreeWalker(function(node) {
if (found) return true;
if (node instanceof AST_NewTarget) return found = true;
if (node instanceof AST_Scope && node !== exp) return true;
}));
return !found;
}
function is_undeclared_ref(node) {
return node instanceof AST_SymbolRef && node.definition().undeclared;
}
var global_names = makePredicate("Array Boolean clearInterval clearTimeout console Date decodeURI decodeURIComponent encodeURI encodeURIComponent Error escape eval EvalError Function isFinite isNaN JSON Map Math Number parseFloat parseInt RangeError ReferenceError RegExp Object Set setInterval setTimeout String SyntaxError TypeError unescape URIError WeakMap WeakSet");
AST_SymbolRef.DEFMETHOD("is_declared", function(compressor) {
return this.defined
|| !this.definition().undeclared
|| compressor.option("unsafe") && global_names[this.name];
});
2022-07-11 11:25:19 +00:00
function is_static_field_or_init(prop) {
return prop.static && prop.value && (prop instanceof AST_ClassField || prop instanceof AST_ClassInit);
}
2022-01-21 08:28:41 +00:00
function declarations_only(node) {
return all(node.definitions, function(var_def) {
return !var_def.value;
});
}
function is_declaration(stat, lexical) {
if (stat instanceof AST_DefClass) return lexical && !stat.extends && all(stat.properties, function(prop) {
if (prop.key instanceof AST_Node) return false;
2022-07-11 11:25:19 +00:00
return !is_static_field_or_init(prop);
2022-01-21 08:28:41 +00:00
});
if (stat instanceof AST_Definitions) return (lexical || stat instanceof AST_Var) && declarations_only(stat);
if (stat instanceof AST_ExportDeclaration) return is_declaration(stat.body, lexical);
if (stat instanceof AST_ExportDefault) return is_declaration(stat.body, lexical);
return stat instanceof AST_LambdaDefinition;
}
function is_last_statement(body, stat) {
var index = body.lastIndexOf(stat);
if (index < 0) return false;
while (++index < body.length) {
if (!is_declaration(body[index], true)) return false;
}
return true;
}
2022-02-07 14:48:46 +00:00
// Certain combination of unused name + side effect leads to invalid AST:
// https://github.com/mishoo/UglifyJS/issues/44
// https://github.com/mishoo/UglifyJS/issues/1838
// https://github.com/mishoo/UglifyJS/issues/3371
// We fix it at this stage by moving the `var` outside the `for`.
function patch_for_init(node, in_list) {
var block;
if (node.init instanceof AST_BlockStatement) {
block = node.init;
node.init = block.body.pop();
block.body.push(node);
}
if (node.init instanceof AST_Defun) {
if (!block) block = make_node(AST_BlockStatement, node, { body: [ node ] });
block.body.splice(-1, 0, node.init);
node.init = null;
} else if (node.init instanceof AST_SimpleStatement) {
node.init = node.init.body;
} else if (is_empty(node.init)) {
node.init = null;
}
if (!block) return;
return in_list ? List.splice(block.body) : block;
}
2022-01-21 08:28:41 +00:00
function tighten_body(statements, compressor) {
2022-02-07 14:48:46 +00:00
var in_lambda = last_of(compressor, function(node) {
return node instanceof AST_Lambda;
});
2022-08-05 07:44:52 +00:00
var block_scope, iife_in_try, in_iife_single, in_loop, in_try, scope;
2022-01-21 08:28:41 +00:00
find_loop_scope_try();
2022-02-07 14:48:46 +00:00
var changed, last_changed, max_iter = 10;
2022-01-21 08:28:41 +00:00
do {
2022-02-07 14:48:46 +00:00
last_changed = changed;
changed = 0;
if (eliminate_spurious_blocks(statements)) changed = 1;
if (!changed && last_changed == 1) break;
2022-01-21 08:28:41 +00:00
if (compressor.option("dead_code")) {
2022-02-07 14:48:46 +00:00
if (eliminate_dead_code(statements, compressor)) changed = 2;
if (!changed && last_changed == 2) break;
2022-01-21 08:28:41 +00:00
}
if (compressor.option("if_return")) {
2022-02-07 14:48:46 +00:00
if (handle_if_return(statements, compressor)) changed = 3;
if (!changed && last_changed == 3) break;
}
if (compressor.option("awaits") && compressor.option("side_effects")) {
if (trim_awaits(statements, compressor)) changed = 4;
if (!changed && last_changed == 4) break;
}
if (compressor.option("inline") >= 4) {
if (inline_iife(statements, compressor)) changed = 5;
if (!changed && last_changed == 5) break;
2022-01-21 08:28:41 +00:00
}
if (compressor.sequences_limit > 0) {
2022-02-07 14:48:46 +00:00
if (sequencesize(statements, compressor)) changed = 6;
if (!changed && last_changed == 6) break;
if (sequencesize_2(statements, compressor)) changed = 7;
if (!changed && last_changed == 7) break;
2022-01-21 08:28:41 +00:00
}
if (compressor.option("join_vars")) {
2022-02-07 14:48:46 +00:00
if (join_consecutive_vars(statements)) changed = 8;
if (!changed && last_changed == 8) break;
2022-01-21 08:28:41 +00:00
}
if (compressor.option("collapse_vars")) {
2022-02-07 14:48:46 +00:00
if (collapse(statements, compressor)) changed = 9;
2022-01-21 08:28:41 +00:00
}
2022-02-07 14:48:46 +00:00
} while (changed && max_iter-- > 0);
2022-01-21 08:28:41 +00:00
return statements;
2022-02-07 14:48:46 +00:00
function last_of(compressor, predicate) {
2022-08-05 07:44:52 +00:00
var block = compressor.self(), level = 0, stat;
2022-02-07 14:48:46 +00:00
do {
2022-07-11 11:25:19 +00:00
if (block instanceof AST_Catch) {
block = compressor.parent(level++);
} else if (block instanceof AST_LabeledStatement) {
block = block.body;
2022-08-31 14:34:36 +00:00
} else if (block instanceof AST_SwitchBranch) {
var branches = compressor.parent(level);
if (branches.body[branches.body.length - 1] === block || has_break(block.body)) {
level++;
block = branches;
}
2022-07-11 11:25:19 +00:00
}
2022-08-05 07:44:52 +00:00
do {
2022-07-11 11:25:19 +00:00
stat = block;
2022-08-05 07:44:52 +00:00
if (predicate(stat)) return stat;
block = compressor.parent(level++);
} while (block instanceof AST_If);
2022-07-11 11:25:19 +00:00
} while (stat
&& (block instanceof AST_BlockStatement
|| block instanceof AST_Catch
|| block instanceof AST_Scope
2022-08-31 14:34:36 +00:00
|| block instanceof AST_SwitchBranch
2022-07-11 11:25:19 +00:00
|| block instanceof AST_Try)
2022-02-07 14:48:46 +00:00
&& is_last_statement(block.body, stat));
2022-08-31 14:34:36 +00:00
function has_break(stats) {
for (var i = stats.length; --i >= 0;) {
if (stats[i] instanceof AST_Break) return true;
}
return false;
}
2022-02-07 14:48:46 +00:00
}
2022-01-21 08:28:41 +00:00
function find_loop_scope_try() {
var node = compressor.self(), level = 0;
do {
2022-02-07 14:48:46 +00:00
if (!block_scope && node.variables) block_scope = node;
2022-01-21 08:28:41 +00:00
if (node instanceof AST_Catch) {
if (compressor.parent(level).bfinally) {
if (!in_try) in_try = {};
in_try.bfinally = true;
}
level++;
} else if (node instanceof AST_Finally) {
level++;
} else if (node instanceof AST_IterationStatement) {
in_loop = true;
} else if (node instanceof AST_Scope) {
scope = node;
break;
} else if (node instanceof AST_Try) {
if (!in_try) in_try = {};
if (node.bcatch) in_try.bcatch = true;
if (node.bfinally) in_try.bfinally = true;
}
} while (node = compressor.parent(level++));
}
// Search from right to left for assignment-like expressions:
// - `var a = x;`
// - `a = x;`
// - `++a`
// For each candidate, scan from left to right for first usage, then try
// to fold assignment into the site for compression.
// Will not attempt to collapse assignments into or past code blocks
// which are not sequentially executed, e.g. loops and conditionals.
function collapse(statements, compressor) {
2022-02-07 14:48:46 +00:00
if (scope.pinned()) return;
2022-01-21 08:28:41 +00:00
var args;
var assignments = new Dictionary();
var candidates = [];
2022-02-07 14:48:46 +00:00
var changed = false;
2022-01-21 08:28:41 +00:00
var declare_only = new Dictionary();
var force_single;
var stat_index = statements.length;
var scanner = new TreeTransformer(function(node, descend) {
if (abort) return node;
// Skip nodes before `candidate` as quickly as possible
if (!hit) {
if (node !== hit_stack[hit_index]) return node;
hit_index++;
if (hit_index < hit_stack.length) return handle_custom_scan_order(node, scanner);
hit = true;
stop_after = (value_def ? find_stop_value : find_stop)(node, 0);
if (stop_after === node) abort = true;
return node;
}
var parent = scanner.parent();
// Stop only if candidate is found within conditional branches
if (!stop_if_hit && in_conditional(node, parent)) {
stop_if_hit = parent;
}
2022-02-07 14:48:46 +00:00
// Cascade compound assignments
if (compound && scan_lhs && can_replace && !stop_if_hit
2022-08-05 07:44:52 +00:00
&& node instanceof AST_Assign && node.operator != "=" && node.left.equals(lhs)) {
2022-02-07 14:48:46 +00:00
replaced++;
changed = true;
2022-08-31 14:34:36 +00:00
AST_Node.info("Cascading {this} [{start}]", node);
2022-02-07 14:48:46 +00:00
can_replace = false;
lvalues = get_lvalues(lhs);
node.right.transform(scanner);
clear_write_only(candidate);
var folded;
if (abort) {
folded = candidate;
} else {
abort = true;
folded = make_node(AST_Binary, candidate, {
operator: compound,
2022-11-30 12:56:09 +00:00
left: lhs.fixed && lhs.definition().fixed ? lhs.fixed.to_binary(candidate) : lhs,
2022-02-07 14:48:46 +00:00
right: rvalue,
});
}
return make_node(AST_Assign, node, {
operator: "=",
left: node.left,
right: make_node(AST_Binary, node, {
operator: node.operator.slice(0, -1),
left: folded,
right: node.right,
}),
});
}
// Stop immediately if these node types are encountered
if (should_stop(node, parent)) {
abort = true;
return node;
}
2022-01-21 08:28:41 +00:00
// Skip transient nodes caused by single-use variable replacement
2022-08-05 07:44:52 +00:00
if (node.single_use) return node;
2022-01-21 08:28:41 +00:00
// Replace variable with assignment when found
var hit_rhs;
if (!(node instanceof AST_SymbolDeclaration)
2022-08-05 07:44:52 +00:00
&& (scan_lhs && lhs.equals(node)
2022-01-21 08:28:41 +00:00
|| scan_rhs && (hit_rhs = scan_rhs(node, this)))) {
if (!can_replace || stop_if_hit && (hit_rhs || !lhs_local || !replace_all)) {
if (!hit_rhs && !value_def) abort = true;
return node;
}
if (is_lhs(node, parent)) {
if (value_def && !hit_rhs) assign_used = true;
return node;
2022-04-11 08:07:00 +00:00
}
if (!hit_rhs && verify_ref && node.fixed !== lhs.fixed) {
abort = true;
return node;
}
if (value_def) {
2022-01-21 08:28:41 +00:00
if (stop_if_hit && assign_pos == 0) assign_pos = remaining - replaced;
if (!hit_rhs) replaced++;
return node;
}
2022-04-11 08:07:00 +00:00
replaced++;
2022-02-07 14:48:46 +00:00
changed = abort = true;
2022-08-31 14:34:36 +00:00
AST_Node.info("Collapsing {this} [{start}]", node);
2022-02-07 14:48:46 +00:00
if (candidate.TYPE == "Binary") {
update_symbols(candidate, node);
return make_node(AST_Assign, candidate, {
operator: "=",
left: candidate.right.left,
right: candidate.operator == "&&" ? make_node(AST_Conditional, candidate, {
condition: candidate.left,
consequent: candidate.right.right,
alternative: node,
}) : make_node(AST_Conditional, candidate, {
condition: candidate.left,
consequent: node,
alternative: candidate.right.right,
}),
});
}
if (candidate instanceof AST_UnaryPostfix) return make_node(AST_UnaryPrefix, candidate, {
operator: candidate.operator,
2022-11-30 12:56:09 +00:00
expression: lhs.fixed && lhs.definition().fixed ? lhs.fixed.to_prefix(candidate) : lhs,
2022-01-21 08:28:41 +00:00
});
2022-02-07 14:48:46 +00:00
if (candidate instanceof AST_UnaryPrefix) {
clear_write_only(candidate);
return candidate;
2022-01-21 08:28:41 +00:00
}
2022-02-07 14:48:46 +00:00
update_symbols(rvalue, node);
2022-01-21 08:28:41 +00:00
if (candidate instanceof AST_VarDef) {
var def = candidate.name.definition();
if (def.references.length - def.replaced == 1 && !compressor.exposed(def)) {
def.replaced++;
2022-08-31 14:34:36 +00:00
return maintain_this_binding(parent, node, rvalue);
2022-01-21 08:28:41 +00:00
}
return make_node(AST_Assign, candidate, {
operator: "=",
2022-02-07 14:48:46 +00:00
left: node,
right: rvalue,
2022-01-21 08:28:41 +00:00
});
}
2022-02-07 14:48:46 +00:00
clear_write_only(rvalue);
var assign = candidate.clone();
assign.right = rvalue;
return assign;
}
// Stop signals related to AST_SymbolRef
if (should_stop_ref(node, parent)) {
abort = true;
return node;
2022-01-21 08:28:41 +00:00
}
// These node types have child nodes that execute sequentially,
// but are otherwise not safe to scan into or beyond them.
if (is_last_node(node, parent) || may_throw(node)) {
stop_after = node;
if (node instanceof AST_Scope) abort = true;
}
// Scan but don't replace inside getter/setter
if (node instanceof AST_Accessor) {
var replace = can_replace;
can_replace = false;
descend(node, scanner);
can_replace = replace;
return signal_abort(node);
}
// Scan but don't replace inside destructuring expression
if (node instanceof AST_Destructured) {
var replace = can_replace;
can_replace = false;
descend(node, scanner);
can_replace = replace;
return signal_abort(node);
}
// Scan but don't replace inside default value
if (node instanceof AST_DefaultValue) {
node.name = node.name.transform(scanner);
var replace = can_replace;
can_replace = false;
node.value = node.value.transform(scanner);
can_replace = replace;
return signal_abort(node);
}
// Scan but don't replace inside block scope with colliding variable
if (node instanceof AST_BlockScope
&& !(node instanceof AST_Scope)
&& !(node.variables && node.variables.all(function(def) {
2022-02-07 14:48:46 +00:00
return !enclosed.has(def.name) && !lvalues.has(def.name);
2022-01-21 08:28:41 +00:00
}))) {
var replace = can_replace;
can_replace = false;
if (!handle_custom_scan_order(node, scanner)) descend(node, scanner);
can_replace = replace;
return signal_abort(node);
}
2022-07-11 11:25:19 +00:00
if (handle_custom_scan_order(node, scanner)) return signal_abort(node);
2022-01-21 08:28:41 +00:00
}, signal_abort);
var multi_replacer = new TreeTransformer(function(node) {
if (abort) return node;
// Skip nodes before `candidate` as quickly as possible
if (!hit) {
if (node !== hit_stack[hit_index]) return node;
hit_index++;
switch (hit_stack.length - hit_index) {
case 0:
hit = true;
if (assign_used) return node;
if (node !== candidate) return node;
if (node instanceof AST_VarDef) return node;
def.replaced++;
var parent = multi_replacer.parent();
if (parent instanceof AST_Sequence && parent.tail_node() !== node) {
value_def.replaced++;
2022-02-07 14:48:46 +00:00
if (rvalue === rhs_value) return List.skip;
return make_sequence(rhs_value, rhs_value.expressions.slice(0, -1));
2022-01-21 08:28:41 +00:00
}
return rvalue;
case 1:
if (!assign_used && node.body === candidate) {
hit = true;
def.replaced++;
value_def.replaced++;
return null;
}
default:
return handle_custom_scan_order(node, multi_replacer);
}
}
// Replace variable when found
if (node instanceof AST_SymbolRef && node.definition() === def) {
if (is_lhs(node, multi_replacer.parent())) return node;
if (!--replaced) abort = true;
2022-08-31 14:34:36 +00:00
AST_Node.info("Replacing {this} [{start}]", node);
2022-01-21 08:28:41 +00:00
var ref = rvalue.clone();
ref.scope = node.scope;
ref.reference();
if (replaced == assign_pos) {
abort = true;
return make_node(AST_Assign, candidate, {
operator: "=",
left: node,
right: ref,
});
}
def.replaced++;
return ref;
}
// Skip (non-executed) functions and (leading) default case in switch statements
if (node instanceof AST_Default || node instanceof AST_Scope) return node;
2022-02-07 14:48:46 +00:00
}, function(node) {
return patch_sequence(node, multi_replacer);
});
2022-01-21 08:28:41 +00:00
while (--stat_index >= 0) {
// Treat parameters as collapsible in IIFE, i.e.
// function(a, b){ ... }(x());
// would be translated into equivalent assignments:
// var a = x(), b = undefined;
if (stat_index == 0 && compressor.option("unused")) extract_args();
// Find collapsible assignments
var hit_stack = [];
extract_candidates(statements[stat_index]);
while (candidates.length > 0) {
hit_stack = candidates.pop();
var hit_index = 0;
var candidate = hit_stack[hit_stack.length - 1];
var assign_pos = -1;
var assign_used = false;
2022-04-11 08:07:00 +00:00
var verify_ref = false;
2022-01-21 08:28:41 +00:00
var remaining;
var value_def = null;
var stop_after = null;
var stop_if_hit = null;
var lhs = get_lhs(candidate);
var side_effects = lhs && lhs.has_side_effects(compressor);
2022-02-07 14:48:46 +00:00
var scan_lhs = lhs && (!side_effects || lhs instanceof AST_SymbolRef)
&& !is_lhs_read_only(lhs, compressor);
2022-01-21 08:28:41 +00:00
var scan_rhs = foldable(candidate);
if (!scan_lhs && !scan_rhs) continue;
2022-02-07 14:48:46 +00:00
var compound = candidate instanceof AST_Assign && candidate.operator.slice(0, -1);
2022-01-21 08:28:41 +00:00
var funarg = candidate.name instanceof AST_SymbolFunarg;
var may_throw = return_false;
if (candidate.may_throw(compressor)) {
if (funarg && is_async(scope)) continue;
may_throw = in_try ? function(node) {
return node.has_side_effects(compressor);
} : side_effects_external;
}
var read_toplevel = false;
var modify_toplevel = false;
// Locate symbols which may execute code outside of scanning range
2022-02-07 14:48:46 +00:00
var enclosed = new Dictionary();
2022-01-21 08:28:41 +00:00
var well_defined = true;
var lvalues = get_lvalues(candidate);
var lhs_local = is_lhs_local(lhs);
2022-02-07 14:48:46 +00:00
var rhs_value = get_rvalue(candidate);
2022-04-11 08:07:00 +00:00
var rvalue = rhs_value;
if (!side_effects) {
if (!compound && rvalue instanceof AST_Sequence) rvalue = rvalue.tail_node();
side_effects = value_has_side_effects();
}
2022-01-21 08:28:41 +00:00
var check_destructured = in_try || !lhs_local ? function(node) {
return node instanceof AST_Destructured;
} : return_false;
var replace_all = replace_all_symbols(candidate);
var hit = funarg;
var abort = false;
var replaced = 0;
var can_replace = !args || !hit;
if (!can_replace) {
for (var j = candidate.arg_index + 1; !abort && j < args.length; j++) {
if (args[j]) args[j].transform(scanner);
}
can_replace = true;
}
for (var i = stat_index; !abort && i < statements.length; i++) {
statements[i].transform(scanner);
}
if (value_def) {
if (!replaced || remaining > replaced + assign_used) {
candidates.push(hit_stack);
force_single = true;
continue;
}
if (replaced == assign_pos) assign_used = true;
var def = lhs.definition();
abort = false;
hit_index = 0;
hit = funarg;
for (var i = stat_index; !abort && i < statements.length; i++) {
if (!statements[i].transform(multi_replacer)) statements.splice(i--, 1);
}
replaced = candidate instanceof AST_VarDef
&& candidate === hit_stack[hit_stack.length - 1]
&& def.references.length == def.replaced
&& !compressor.exposed(def);
value_def.last_ref = false;
value_def.single_use = false;
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
}
2022-02-07 14:48:46 +00:00
if (replaced) remove_candidate(candidate);
2022-01-21 08:28:41 +00:00
}
}
2022-02-07 14:48:46 +00:00
return changed;
2022-01-21 08:28:41 +00:00
function signal_abort(node) {
if (abort) return node;
if (stop_after === node) abort = true;
if (stop_if_hit === node) stop_if_hit = null;
return node;
}
function handle_custom_scan_order(node, tt) {
2022-07-11 11:25:19 +00:00
if (!(node instanceof AST_BlockScope)) return;
2022-01-21 08:28:41 +00:00
// Skip (non-executed) functions
if (node instanceof AST_Scope) return node;
2022-07-11 11:25:19 +00:00
// Scan computed keys, static fields & initializers in class
if (node instanceof AST_Class) {
if (node.name) node.name = node.name.transform(tt);
if (!abort && node.extends) node.extends = node.extends.transform(tt);
var fields = [], stats = [];
for (var i = 0; !abort && i < node.properties.length; i++) {
var prop = node.properties[i];
if (prop.key instanceof AST_Node) prop.key = prop.key.transform(tt);
if (!prop.static) continue;
if (prop instanceof AST_ClassField) {
if (prop.value) fields.push(prop);
} else if (prop instanceof AST_ClassInit) {
[].push.apply(stats, prop.value.body);
}
}
for (var i = 0; !abort && i < stats.length; i++) {
stats[i].transform(tt);
}
for (var i = 0; !abort && i < fields.length; i++) {
var prop = fields[i];
prop.value = prop.value.transform(tt);
}
return node;
}
2022-01-21 08:28:41 +00:00
// Scan object only in a for-in/of statement
if (node instanceof AST_ForEnumeration) {
node.object = node.object.transform(tt);
abort = true;
return node;
}
// Scan first case expression only in a switch statement
if (node instanceof AST_Switch) {
node.expression = node.expression.transform(tt);
for (var i = 0; !abort && i < node.body.length; i++) {
var branch = node.body[i];
if (branch instanceof AST_Case) {
if (!hit) {
if (branch !== hit_stack[hit_index]) continue;
hit_index++;
}
branch.expression = branch.expression.transform(tt);
if (!replace_all) break;
scan_rhs = false;
}
}
abort = true;
return node;
}
}
function is_direct_assignment(node, parent) {
if (parent instanceof AST_Assign) return parent.operator == "=" && parent.left === node;
if (parent instanceof AST_DefaultValue) return parent.name === node;
if (parent instanceof AST_DestructuredArray) return true;
if (parent instanceof AST_DestructuredKeyVal) return parent.value === node;
}
function should_stop(node, parent) {
if (node === rvalue) return true;
if (parent instanceof AST_For) {
if (node !== parent.init) return true;
}
if (node instanceof AST_Assign) {
2022-08-05 07:44:52 +00:00
return node.operator != "=" && lhs.equals(node.left);
2022-01-21 08:28:41 +00:00
}
if (node instanceof AST_Call) {
if (!(lhs instanceof AST_PropAccess)) return false;
2022-08-05 07:44:52 +00:00
if (!lhs.equals(node.expression)) return false;
2022-01-21 08:28:41 +00:00
return !(rvalue instanceof AST_LambdaExpression && !rvalue.contains_this());
}
if (node instanceof AST_Class) return !compressor.has_directive("use strict");
if (node instanceof AST_Debugger) return true;
if (node instanceof AST_Defun) return funarg && lhs.name === node.name.name;
if (node instanceof AST_DestructuredKeyVal) return node.key instanceof AST_Node;
if (node instanceof AST_DWLoop) return true;
if (node instanceof AST_LoopControl) return true;
2022-02-07 14:48:46 +00:00
if (node instanceof AST_Try) return true;
if (node instanceof AST_With) return true;
return false;
}
function should_stop_ref(node, parent) {
if (!(node instanceof AST_SymbolRef)) return false;
if (node.is_declared(compressor)) {
if (node.fixed_value()) return false;
if (can_drop_symbol(node)) {
return !(parent instanceof AST_PropAccess && parent.expression === node)
&& is_arguments(node.definition());
2022-01-21 08:28:41 +00:00
}
2022-02-07 14:48:46 +00:00
} else if (is_direct_assignment(node, parent)) {
2022-01-21 08:28:41 +00:00
return false;
}
2022-02-07 14:48:46 +00:00
if (!replace_all) return true;
scan_rhs = false;
2022-01-21 08:28:41 +00:00
return false;
}
function in_conditional(node, parent) {
if (parent instanceof AST_Assign) return parent.left !== node && lazy_op[parent.operator.slice(0, -1)];
if (parent instanceof AST_Binary) return parent.left !== node && lazy_op[parent.operator];
if (parent instanceof AST_Call) return parent.optional && parent.expression !== node;
if (parent instanceof AST_Case) return parent.expression !== node;
if (parent instanceof AST_Conditional) return parent.condition !== node;
if (parent instanceof AST_If) return parent.condition !== node;
if (parent instanceof AST_Sub) return parent.optional && parent.expression !== node;
}
function is_last_node(node, parent) {
if (node instanceof AST_Await) return true;
2022-07-11 11:25:19 +00:00
if (node.TYPE == "Binary") return !can_drop_op(node.operator, node.right, compressor);
2022-01-21 08:28:41 +00:00
if (node instanceof AST_Call) {
var def, fn = node.expression;
if (fn instanceof AST_SymbolRef) {
def = fn.definition();
fn = fn.fixed_value();
}
if (!(fn instanceof AST_Lambda)) return !node.is_expr_pure(compressor);
if (def && recursive_ref(compressor, def, fn)) return true;
if (fn.collapse_scanning) return false;
fn.collapse_scanning = true;
var replace = can_replace;
can_replace = false;
var after = stop_after;
var if_hit = stop_if_hit;
2022-08-05 07:44:52 +00:00
for (var i = 0; !abort && i < fn.argnames.length; i++) {
if (arg_may_throw(reject, fn.argnames[i], node.args[i])) abort = true;
}
if (!abort) {
if (fn.rest && arg_may_throw(reject, fn.rest, make_node(AST_Array, node, {
elements: node.args.slice(i),
}))) {
abort = true;
} else if (is_arrow(fn) && fn.value) {
fn.value.transform(scanner);
} else for (var i = 0; !abort && i < fn.body.length; i++) {
var stat = fn.body[i];
if (stat instanceof AST_Return) {
if (stat.value) stat.value.transform(scanner);
break;
}
stat.transform(scanner);
2022-01-21 08:28:41 +00:00
}
}
stop_if_hit = if_hit;
stop_after = after;
can_replace = replace;
fn.collapse_scanning = false;
if (!abort) return false;
abort = false;
return true;
}
2022-06-08 10:36:39 +00:00
if (node instanceof AST_Class) {
if (!in_try) return false;
var base = node.extends;
if (!base) return false;
if (base instanceof AST_SymbolRef) base = base.fixed_value();
return !safe_for_extends(base);
}
2022-01-21 08:28:41 +00:00
if (node instanceof AST_Exit) {
if (in_try) {
if (in_try.bfinally) return true;
if (in_try.bcatch && node instanceof AST_Throw) return true;
}
return side_effects || lhs instanceof AST_PropAccess || may_modify(lhs);
}
if (node instanceof AST_Function) {
return compressor.option("ie") && node.name && lvalues.has(node.name.name);
}
if (node instanceof AST_ObjectIdentity) return symbol_in_lvalues(node, parent);
if (node instanceof AST_PropAccess) {
if (side_effects) return true;
var exp = node.expression;
if (exp instanceof AST_SymbolRef && is_arguments(exp.definition())) return true;
if (compressor.option("unsafe")) {
if (is_undeclared_ref(exp) && global_names[exp.name]) return false;
if (is_static_fn(exp)) return false;
}
if (!well_defined) return true;
if (value_def) return false;
if (!in_try && lhs_local) return false;
if (node.optional) return false;
return exp.may_throw_on_access(compressor);
}
if (node instanceof AST_Spread) return true;
if (node instanceof AST_SymbolRef) {
if (symbol_in_lvalues(node, parent)) return !is_direct_assignment(node, parent);
if (side_effects && may_modify(node)) return true;
var def = node.definition();
return (in_try || def.scope.resolve() !== scope) && !can_drop_symbol(node);
}
if (node instanceof AST_Template) return !node.is_expr_pure(compressor);
if (node instanceof AST_VarDef) {
if (check_destructured(node.name)) return true;
return (node.value || parent instanceof AST_Let) && node.name.match_symbol(function(node) {
return node instanceof AST_SymbolDeclaration
&& (lvalues.has(node.name) || side_effects && may_modify(node));
}, true);
}
if (node instanceof AST_Yield) return true;
var sym = is_lhs(node.left, node);
if (!sym) return false;
if (sym instanceof AST_PropAccess) return true;
if (check_destructured(sym)) return true;
return sym.match_symbol(function(node) {
return node instanceof AST_SymbolRef
&& (lvalues.has(node.name) || read_toplevel && compressor.exposed(node.definition()));
}, true);
2022-08-05 07:44:52 +00:00
function reject(node) {
node.transform(scanner);
return abort;
}
2022-01-21 08:28:41 +00:00
}
2022-08-05 07:44:52 +00:00
function arg_may_throw(reject, node, value) {
2022-01-21 08:28:41 +00:00
if (node instanceof AST_DefaultValue) {
2022-08-05 07:44:52 +00:00
return reject(node.value)
|| arg_may_throw(reject, node.name, node.value)
|| !is_undefined(value) && arg_may_throw(reject, node.name, value);
2022-01-21 08:28:41 +00:00
}
2022-08-05 07:44:52 +00:00
if (!value) return !(node instanceof AST_Symbol);
2022-01-21 08:28:41 +00:00
if (node instanceof AST_Destructured) {
2022-08-05 07:44:52 +00:00
if (node.rest && arg_may_throw(reject, node.rest)) return true;
2022-01-21 08:28:41 +00:00
if (node instanceof AST_DestructuredArray) {
2022-08-05 07:44:52 +00:00
if (value instanceof AST_Array) return !all(node.elements, function(element, index) {
return !arg_may_throw(reject, element, value[index]);
});
if (!value.is_string(compressor)) return true;
2022-01-21 08:28:41 +00:00
return !all(node.elements, function(element) {
2022-08-05 07:44:52 +00:00
return !arg_may_throw(reject, element);
2022-01-21 08:28:41 +00:00
});
}
if (node instanceof AST_DestructuredObject) {
2022-08-05 07:44:52 +00:00
if (value.may_throw_on_access(compressor)) return true;
2022-01-21 08:28:41 +00:00
return !all(node.properties, function(prop) {
2022-08-05 07:44:52 +00:00
if (prop.key instanceof AST_Node && reject(prop.key)) return false;
return !arg_may_throw(reject, prop.value);
2022-01-21 08:28:41 +00:00
});
}
}
}
function extract_args() {
2022-08-05 07:44:52 +00:00
if (in_iife_single === false) return;
var iife = compressor.parent(), fn = compressor.self();
if (in_iife_single === undefined) {
if (!(fn instanceof AST_LambdaExpression)
|| is_generator(fn)
|| fn.uses_arguments
|| fn.pinned()
|| !(iife instanceof AST_Call)
|| iife.expression !== fn
|| !all(iife.args, function(arg) {
return !(arg instanceof AST_Spread);
})) {
in_iife_single = false;
return;
}
if (!is_iife_single(iife)) return;
in_iife_single = true;
}
var fn_strict = fn.in_strict_mode(compressor)
&& !fn.parent_scope.resolve(true).in_strict_mode(compressor);
var has_await;
if (is_async(fn)) {
has_await = function(node) {
2022-01-21 08:28:41 +00:00
return node instanceof AST_Symbol && node.name == "await";
2022-08-05 07:44:52 +00:00
};
iife_in_try = true;
} else {
has_await = function(node) {
2022-01-21 08:28:41 +00:00
return node instanceof AST_Await && !tw.find_parent(AST_Scope);
};
2022-08-05 07:44:52 +00:00
if (iife_in_try === undefined) iife_in_try = find_try(compressor, 1, iife, null, true, true);
}
var arg_scope = null;
var tw = new TreeWalker(function(node, descend) {
if (!arg) return true;
if (has_await(node) || node instanceof AST_Yield) {
arg = null;
return true;
}
if (node instanceof AST_ObjectIdentity) {
if (fn_strict || !arg_scope) arg = null;
return true;
}
if (node instanceof AST_SymbolRef) {
var def;
if (node.in_arg && !is_safe_lexical(node.definition())
|| (def = fn.variables.get(node.name)) && def !== node.definition()) {
2022-01-21 08:28:41 +00:00
arg = null;
}
2022-08-05 07:44:52 +00:00
return true;
}
if (node instanceof AST_Scope && !is_arrow(node)) {
var save_scope = arg_scope;
arg_scope = node;
descend();
arg_scope = save_scope;
return true;
}
});
args = iife.args.slice();
var len = args.length;
var names = new Dictionary();
for (var i = fn.argnames.length; --i >= 0;) {
var sym = fn.argnames[i];
var arg = args[i];
var value = null;
if (sym instanceof AST_DefaultValue) {
value = sym.value;
sym = sym.name;
args[len + i] = value;
}
if (sym instanceof AST_Destructured) {
if (iife_in_try && arg_may_throw(function(node) {
return node.has_side_effects(compressor);
}, sym, arg)) {
2022-01-21 08:28:41 +00:00
candidates.length = 0;
break;
}
2022-08-05 07:44:52 +00:00
args[len + i] = fn.argnames[i];
continue;
}
if (names.has(sym.name)) continue;
names.set(sym.name, true);
if (value) arg = is_undefined(arg) ? value : null;
if (!arg && !value) {
arg = make_node(AST_Undefined, sym).transform(compressor);
} else if (arg instanceof AST_Lambda && arg.pinned()) {
arg = null;
} else if (arg) {
arg.walk(tw);
2022-01-21 08:28:41 +00:00
}
2022-08-05 07:44:52 +00:00
if (!arg) continue;
var candidate = make_node(AST_VarDef, sym, {
name: sym,
value: arg,
});
candidate.name_index = i;
candidate.arg_index = value ? len + i : i;
candidates.unshift([ candidate ]);
2022-01-21 08:28:41 +00:00
}
2022-08-05 07:44:52 +00:00
if (fn.rest) args.push(fn.rest);
2022-01-21 08:28:41 +00:00
}
function extract_candidates(expr, unused) {
hit_stack.push(expr);
if (expr instanceof AST_Array) {
expr.elements.forEach(function(node) {
extract_candidates(node, unused);
});
} else if (expr instanceof AST_Assign) {
var lhs = expr.left;
if (!(lhs instanceof AST_Destructured)) candidates.push(hit_stack.slice());
extract_candidates(lhs);
extract_candidates(expr.right);
if (lhs instanceof AST_SymbolRef && expr.operator == "=") {
assignments.set(lhs.name, (assignments.get(lhs.name) || 0) + 1);
}
} else if (expr instanceof AST_Await) {
extract_candidates(expr.expression, unused);
} else if (expr instanceof AST_Binary) {
var lazy = lazy_op[expr.operator];
if (unused
&& lazy
&& expr.operator != "??"
&& expr.right instanceof AST_Assign
&& expr.right.operator == "="
&& !(expr.right.left instanceof AST_Destructured)) {
candidates.push(hit_stack.slice());
}
extract_candidates(expr.left, !lazy && unused);
extract_candidates(expr.right, unused);
} else if (expr instanceof AST_Call) {
extract_candidates(expr.expression);
expr.args.forEach(extract_candidates);
} else if (expr instanceof AST_Case) {
extract_candidates(expr.expression);
} else if (expr instanceof AST_Conditional) {
extract_candidates(expr.condition);
extract_candidates(expr.consequent, unused);
extract_candidates(expr.alternative, unused);
} else if (expr instanceof AST_Definitions) {
expr.definitions.forEach(extract_candidates);
} else if (expr instanceof AST_Dot) {
extract_candidates(expr.expression);
} else if (expr instanceof AST_DWLoop) {
extract_candidates(expr.condition);
if (!(expr.body instanceof AST_Block)) {
extract_candidates(expr.body);
}
} else if (expr instanceof AST_Exit) {
if (expr.value) extract_candidates(expr.value);
} else if (expr instanceof AST_For) {
if (expr.init) extract_candidates(expr.init, true);
if (expr.condition) extract_candidates(expr.condition);
if (expr.step) extract_candidates(expr.step, true);
if (!(expr.body instanceof AST_Block)) {
extract_candidates(expr.body);
}
} else if (expr instanceof AST_ForEnumeration) {
extract_candidates(expr.object);
if (!(expr.body instanceof AST_Block)) {
extract_candidates(expr.body);
}
} else if (expr instanceof AST_If) {
extract_candidates(expr.condition);
if (!(expr.body instanceof AST_Block)) {
extract_candidates(expr.body);
}
if (expr.alternative && !(expr.alternative instanceof AST_Block)) {
extract_candidates(expr.alternative);
}
} else if (expr instanceof AST_Object) {
expr.properties.forEach(function(prop) {
hit_stack.push(prop);
if (prop.key instanceof AST_Node) extract_candidates(prop.key);
if (prop instanceof AST_ObjectKeyVal) extract_candidates(prop.value, unused);
hit_stack.pop();
});
} else if (expr instanceof AST_Sequence) {
var end = expr.expressions.length - (unused ? 0 : 1);
expr.expressions.forEach(function(node, index) {
extract_candidates(node, index < end);
});
} else if (expr instanceof AST_SimpleStatement) {
extract_candidates(expr.body, true);
} else if (expr instanceof AST_Spread) {
extract_candidates(expr.expression);
} else if (expr instanceof AST_Sub) {
extract_candidates(expr.expression);
extract_candidates(expr.property);
} else if (expr instanceof AST_Switch) {
extract_candidates(expr.expression);
expr.body.forEach(extract_candidates);
} else if (expr instanceof AST_Unary) {
if (UNARY_POSTFIX[expr.operator]) {
candidates.push(hit_stack.slice());
} else {
extract_candidates(expr.expression);
}
} else if (expr instanceof AST_VarDef) {
if (expr.name instanceof AST_SymbolVar) {
if (expr.value) {
var def = expr.name.definition();
if (def.references.length > def.replaced) {
candidates.push(hit_stack.slice());
}
} else {
declare_only.set(expr.name.name, (declare_only.get(expr.name.name) || 0) + 1);
}
}
if (expr.value) extract_candidates(expr.value);
} else if (expr instanceof AST_Yield) {
if (expr.expression) extract_candidates(expr.expression);
}
hit_stack.pop();
}
function find_stop(node, level) {
var parent = scanner.parent(level);
if (parent instanceof AST_Array) return node;
if (parent instanceof AST_Assign) return node;
if (parent instanceof AST_Await) return node;
if (parent instanceof AST_Binary) return node;
if (parent instanceof AST_Call) return node;
if (parent instanceof AST_Case) return node;
if (parent instanceof AST_Conditional) return node;
if (parent instanceof AST_Definitions) return find_stop_unused(parent, level + 1);
if (parent instanceof AST_Exit) return node;
if (parent instanceof AST_If) return node;
if (parent instanceof AST_IterationStatement) return node;
if (parent instanceof AST_ObjectProperty) return node;
if (parent instanceof AST_PropAccess) return node;
if (parent instanceof AST_Sequence) {
return (parent.tail_node() === node ? find_stop : find_stop_unused)(parent, level + 1);
}
if (parent instanceof AST_SimpleStatement) return find_stop_unused(parent, level + 1);
if (parent instanceof AST_Spread) return node;
if (parent instanceof AST_Switch) return node;
if (parent instanceof AST_Unary) return node;
if (parent instanceof AST_VarDef) return node;
if (parent instanceof AST_Yield) return node;
return null;
}
function find_stop_logical(parent, op, level) {
var node;
do {
node = parent;
parent = scanner.parent(++level);
} while (parent instanceof AST_Assign && parent.operator.slice(0, -1) == op
|| parent instanceof AST_Binary && parent.operator == op);
return node;
}
function find_stop_expr(expr, cont, node, parent, level) {
var replace = can_replace;
can_replace = false;
var after = stop_after;
var if_hit = stop_if_hit;
var stack = scanner.stack;
scanner.stack = [ parent ];
expr.transform(scanner);
scanner.stack = stack;
stop_if_hit = if_hit;
stop_after = after;
can_replace = replace;
if (abort) {
abort = false;
return node;
}
return cont(parent, level + 1);
}
function find_stop_value(node, level) {
var parent = scanner.parent(level);
if (parent instanceof AST_Array) return find_stop_value(parent, level + 1);
if (parent instanceof AST_Assign) {
if (may_throw(parent)) return node;
if (parent.left.match_symbol(function(ref) {
return ref instanceof AST_SymbolRef && (lhs.name == ref.name || value_def.name == ref.name);
})) return node;
var op;
if (parent.left === node || !lazy_op[op = parent.operator.slice(0, -1)]) {
return find_stop_value(parent, level + 1);
}
return find_stop_logical(parent, op, level);
}
2022-07-11 11:25:19 +00:00
if (parent instanceof AST_Await) return find_stop_value(parent, level + 1);
2022-01-21 08:28:41 +00:00
if (parent instanceof AST_Binary) {
var op;
if (parent.left === node || !lazy_op[op = parent.operator]) {
return find_stop_value(parent, level + 1);
}
return find_stop_logical(parent, op, level);
}
if (parent instanceof AST_Call) return parent;
if (parent instanceof AST_Case) {
if (parent.expression !== node) return node;
return find_stop_value(parent, level + 1);
}
if (parent instanceof AST_Conditional) {
if (parent.condition !== node) return node;
return find_stop_value(parent, level + 1);
}
if (parent instanceof AST_Definitions) return find_stop_unused(parent, level + 1);
if (parent instanceof AST_Do) return node;
if (parent instanceof AST_Exit) return find_stop_unused(parent, level + 1);
if (parent instanceof AST_For) {
if (parent.init !== node && parent.condition !== node) return node;
return find_stop_value(parent, level + 1);
}
if (parent instanceof AST_ForEnumeration) {
if (parent.init !== node) return node;
return find_stop_value(parent, level + 1);
}
if (parent instanceof AST_If) {
if (parent.condition !== node) return node;
return find_stop_value(parent, level + 1);
}
if (parent instanceof AST_ObjectProperty) {
var obj = scanner.parent(level + 1);
return all(obj.properties, function(prop) {
return prop instanceof AST_ObjectKeyVal;
}) ? find_stop_value(obj, level + 2) : obj;
}
if (parent instanceof AST_PropAccess) {
var exp = parent.expression;
return exp === node ? find_stop_value(parent, level + 1) : node;
}
if (parent instanceof AST_Sequence) {
return (parent.tail_node() === node ? find_stop_value : find_stop_unused)(parent, level + 1);
}
if (parent instanceof AST_SimpleStatement) return find_stop_unused(parent, level + 1);
if (parent instanceof AST_Spread) return find_stop_value(parent, level + 1);
if (parent instanceof AST_Switch) {
if (parent.expression !== node) return node;
return find_stop_value(parent, level + 1);
}
if (parent instanceof AST_Unary) {
if (parent.operator == "delete") return node;
return find_stop_value(parent, level + 1);
}
if (parent instanceof AST_VarDef) return parent.name.match_symbol(function(sym) {
return sym instanceof AST_SymbolDeclaration && (lhs.name == sym.name || value_def.name == sym.name);
}) ? node : find_stop_value(parent, level + 1);
if (parent instanceof AST_While) {
if (parent.condition !== node) return node;
return find_stop_value(parent, level + 1);
}
if (parent instanceof AST_Yield) return find_stop_value(parent, level + 1);
return null;
}
function find_stop_unused(node, level) {
var parent = scanner.parent(level);
if (is_last_node(node, parent)) return node;
if (in_conditional(node, parent)) return node;
if (parent instanceof AST_Array) return find_stop_unused(parent, level + 1);
if (parent instanceof AST_Assign) return check_assignment(parent.left);
if (parent instanceof AST_Await) return node;
if (parent instanceof AST_Binary) return find_stop_unused(parent, level + 1);
if (parent instanceof AST_Call) return find_stop_unused(parent, level + 1);
if (parent instanceof AST_Case) return find_stop_unused(parent, level + 1);
if (parent instanceof AST_Conditional) return find_stop_unused(parent, level + 1);
if (parent instanceof AST_Definitions) return find_stop_unused(parent, level + 1);
if (parent instanceof AST_Exit) return find_stop_unused(parent, level + 1);
if (parent instanceof AST_If) return find_stop_unused(parent, level + 1);
if (parent instanceof AST_IterationStatement) return node;
if (parent instanceof AST_ObjectProperty) {
var obj = scanner.parent(level + 1);
return all(obj.properties, function(prop) {
return prop instanceof AST_ObjectKeyVal;
}) ? find_stop_unused(obj, level + 2) : obj;
}
if (parent instanceof AST_PropAccess) {
var exp = parent.expression;
if (exp === node) return find_stop_unused(parent, level + 1);
return find_stop_expr(exp, find_stop_unused, node, parent, level);
}
if (parent instanceof AST_Sequence) return find_stop_unused(parent, level + 1);
if (parent instanceof AST_SimpleStatement) return find_stop_unused(parent, level + 1);
if (parent instanceof AST_Spread) return node;
if (parent instanceof AST_Switch) return find_stop_unused(parent, level + 1);
if (parent instanceof AST_Unary) return find_stop_unused(parent, level + 1);
if (parent instanceof AST_VarDef) return check_assignment(parent.name);
if (parent instanceof AST_Yield) return node;
return null;
function check_assignment(lhs) {
if (may_throw(parent)) return node;
if (lhs !== node && lhs instanceof AST_Destructured) {
return find_stop_expr(lhs, find_stop_unused, node, parent, level);
}
return find_stop_unused(parent, level + 1);
}
}
function mangleable_var(rhs) {
if (force_single) {
force_single = false;
return;
}
if (remaining < 1) return;
2022-02-07 14:48:46 +00:00
rhs = rhs.tail_node();
2022-01-21 08:28:41 +00:00
var value = rhs instanceof AST_Assign && rhs.operator == "=" ? rhs.left : rhs;
if (!(value instanceof AST_SymbolRef)) return;
var def = value.definition();
if (def.undeclared) return;
if (is_arguments(def)) return;
if (value !== rhs) {
if (is_lhs_read_only(value, compressor)) return;
var referenced = def.references.length - def.replaced;
if (referenced < 2) return;
var expr = candidate.clone();
expr[expr instanceof AST_Assign ? "right" : "value"] = value;
if (candidate.name_index >= 0) {
expr.name_index = candidate.name_index;
expr.arg_index = candidate.arg_index;
}
candidate = expr;
}
return value_def = def;
}
function remaining_refs(def) {
return def.references.length - def.replaced - (assignments.get(def.name) || 0);
}
function get_lhs(expr) {
if (expr instanceof AST_Assign) {
var lhs = expr.left;
if (!(lhs instanceof AST_SymbolRef)) return lhs;
var def = lhs.definition();
if (scope.uses_arguments && is_funarg(def)) return lhs;
if (compressor.exposed(def)) return lhs;
remaining = remaining_refs(def);
if (def.fixed && lhs.fixed) {
var matches = def.references.filter(function(ref) {
return ref.fixed === lhs.fixed;
}).length - 1;
if (matches < remaining) {
remaining = matches;
assign_pos = 0;
2022-04-11 08:07:00 +00:00
verify_ref = true;
2022-01-21 08:28:41 +00:00
}
}
2022-02-07 14:48:46 +00:00
if (expr.operator == "=") mangleable_var(expr.right);
2022-01-21 08:28:41 +00:00
return lhs;
}
if (expr instanceof AST_Binary) return expr.right.left;
if (expr instanceof AST_Unary) return expr.expression;
if (expr instanceof AST_VarDef) {
var lhs = expr.name;
var def = lhs.definition();
if (def.const_redefs) return;
if (!member(lhs, def.orig)) return;
if (scope.uses_arguments && is_funarg(def)) return;
var declared = def.orig.length - def.eliminated - (declare_only.get(def.name) || 0);
remaining = remaining_refs(def);
if (def.fixed) remaining = Math.min(remaining, def.references.filter(function(ref) {
if (!ref.fixed) return true;
if (!ref.fixed.assigns) return true;
var assign = ref.fixed.assigns[0];
return assign === lhs || get_rvalue(assign) === expr.value;
}).length);
if (declared > 1 && !(lhs instanceof AST_SymbolFunarg)) {
mangleable_var(expr.value);
2022-08-31 14:34:36 +00:00
return make_node(AST_SymbolRef, lhs);
2022-01-21 08:28:41 +00:00
}
if (mangleable_var(expr.value) || remaining == 1 && !compressor.exposed(def)) {
2022-08-31 14:34:36 +00:00
return make_node(AST_SymbolRef, lhs);
2022-01-21 08:28:41 +00:00
}
return;
}
}
function get_rvalue(expr) {
if (expr instanceof AST_Assign) return expr.right;
if (expr instanceof AST_Binary) {
var node = expr.clone();
node.right = expr.right.right;
return node;
}
if (expr instanceof AST_VarDef) return expr.value;
}
function invariant(expr) {
if (expr instanceof AST_Array) return false;
if (expr instanceof AST_Binary && lazy_op[expr.operator]) {
return invariant(expr.left) && invariant(expr.right);
}
if (expr instanceof AST_Call) return false;
if (expr instanceof AST_Conditional) {
return invariant(expr.consequent) && invariant(expr.alternative);
}
if (expr instanceof AST_Object) return false;
return !expr.has_side_effects(compressor);
}
function foldable(expr) {
if (expr instanceof AST_Assign && expr.right.single_use) return;
var lhs_ids = Object.create(null);
var marker = new TreeWalker(function(node) {
if (node instanceof AST_SymbolRef) lhs_ids[node.definition().id] = true;
});
while (expr instanceof AST_Assign && expr.operator == "=") {
expr.left.walk(marker);
expr = expr.right;
}
if (expr instanceof AST_ObjectIdentity) return rhs_exact_match;
if (expr instanceof AST_SymbolRef) {
var value = expr.evaluate(compressor);
if (value === expr) return rhs_exact_match;
return rhs_fuzzy_match(value, rhs_exact_match);
}
if (expr.is_truthy()) return rhs_fuzzy_match(true, return_false);
if (expr.is_constant()) {
var ev = expr.evaluate(compressor);
if (!(ev instanceof AST_Node)) return rhs_fuzzy_match(ev, rhs_exact_match);
}
if (!(lhs instanceof AST_SymbolRef)) return false;
if (!invariant(expr)) return false;
var circular;
expr.walk(new TreeWalker(function(node) {
if (circular) return true;
if (node instanceof AST_SymbolRef && lhs_ids[node.definition().id]) circular = true;
}));
return !circular && rhs_exact_match;
function rhs_exact_match(node) {
2022-08-05 07:44:52 +00:00
return expr.equals(node);
2022-01-21 08:28:41 +00:00
}
}
function rhs_fuzzy_match(value, fallback) {
return function(node, tw) {
if (tw.in_boolean_context()) {
if (value && node.is_truthy() && !node.has_side_effects(compressor)) {
return true;
}
if (node.is_constant()) {
var ev = node.evaluate(compressor);
if (!(ev instanceof AST_Node)) return !ev == !value;
}
}
return fallback(node);
};
}
2022-02-07 14:48:46 +00:00
function clear_write_only(assign) {
while (assign.write_only) {
assign.write_only = false;
if (!(assign instanceof AST_Assign)) break;
assign = assign.right;
}
}
function update_symbols(value, node) {
var scope = node.scope || find_scope(scanner) || block_scope;
value.walk(new TreeWalker(function(node) {
if (node instanceof AST_BlockScope) return true;
if (node instanceof AST_Symbol) node.scope = scope;
}));
}
2022-01-21 08:28:41 +00:00
function may_be_global(node) {
if (node instanceof AST_SymbolRef) {
node = node.fixed_value();
if (!node) return true;
}
if (node instanceof AST_Assign) return node.operator == "=" && may_be_global(node.right);
return node instanceof AST_PropAccess || node instanceof AST_ObjectIdentity;
}
function get_lvalues(expr) {
var lvalues = new Dictionary();
if (expr instanceof AST_VarDef) {
if (!expr.name.definition().fixed) well_defined = false;
lvalues.add(expr.name.name, lhs);
}
var find_arguments = scope.uses_arguments && !compressor.has_directive("use strict");
var scan_toplevel = scope instanceof AST_Toplevel;
var tw = new TreeWalker(function(node) {
var value;
if (node instanceof AST_SymbolRef) {
value = node.fixed_value();
if (!value) {
value = node;
var def = node.definition();
var escaped = node.fixed && node.fixed.escaped || def.escaped;
if (!def.undeclared
&& (def.assignments || !escaped || escaped.cross_scope)
&& (has_escaped(def, node.scope, node, tw.parent()) || !same_scope(def))) {
well_defined = false;
}
}
} else if (node instanceof AST_ObjectIdentity) {
value = node;
}
if (value) {
lvalues.add(node.name, is_modified(compressor, tw, node, value, 0));
} else if (node instanceof AST_Lambda) {
for (var level = 0, parent, child = node; parent = tw.parent(level++); child = parent) {
if (parent instanceof AST_Assign) {
if (parent.left === child) break;
if (parent.operator == "=") continue;
if (lazy_op[parent.operator.slice(0, -1)]) continue;
break;
}
if (parent instanceof AST_Binary) {
if (lazy_op[parent.operator]) continue;
break;
}
if (parent instanceof AST_Call) return;
if (parent instanceof AST_Scope) return;
if (parent instanceof AST_Sequence) {
if (parent.tail_node() === child) continue;
break;
}
if (parent instanceof AST_Template) {
if (parent.tag) return;
break;
}
}
2022-02-07 14:48:46 +00:00
node.enclosed.forEach(function(def) {
if (def.scope !== node) enclosed.set(def.name, true);
});
2022-01-21 08:28:41 +00:00
return true;
} else if (find_arguments && node instanceof AST_Sub) {
scope.each_argname(function(argname) {
if (!compressor.option("reduce_vars") || argname.definition().assignments) {
if (!argname.definition().fixed) well_defined = false;
lvalues.add(argname.name, true);
}
});
find_arguments = false;
}
if (!scan_toplevel) return;
if (node.TYPE == "Call") {
if (modify_toplevel) return;
var exp = node.expression;
if (exp instanceof AST_PropAccess) return;
if (exp instanceof AST_LambdaExpression && !exp.contains_this()) return;
modify_toplevel = true;
} else if (node instanceof AST_PropAccess && may_be_global(node.expression)) {
if (node === lhs && !(expr instanceof AST_Unary)) {
modify_toplevel = true;
} else {
read_toplevel = true;
}
}
});
expr.walk(tw);
return lvalues;
}
function remove_candidate(expr) {
2022-02-07 14:48:46 +00:00
var value = rvalue === rhs_value ? null : make_sequence(rhs_value, rhs_value.expressions.slice(0, -1));
2022-01-21 08:28:41 +00:00
var index = expr.name_index;
if (index >= 0) {
2022-02-07 14:48:46 +00:00
var args, argname = scope.argnames[index];
2022-01-21 08:28:41 +00:00
if (argname instanceof AST_DefaultValue) {
2022-02-07 14:48:46 +00:00
scope.argnames[index] = argname = argname.clone();
argname.value = value || make_node(AST_Number, argname, { value: 0 });
} else if ((args = compressor.parent().args)[index]) {
scope.argnames[index] = argname.clone();
args[index] = value || make_node(AST_Number, args[index], { value: 0 });
2022-01-21 08:28:41 +00:00
}
2022-02-07 14:48:46 +00:00
return;
2022-01-21 08:28:41 +00:00
}
var end = hit_stack.length - 1;
2022-04-11 08:07:00 +00:00
var last = hit_stack[end];
if (last instanceof AST_VarDef || hit_stack[end - 1].body === last) end--;
2022-01-21 08:28:41 +00:00
var tt = new TreeTransformer(function(node, descend, in_list) {
if (hit) return node;
if (node !== hit_stack[hit_index]) return node;
hit_index++;
if (hit_index <= end) return handle_custom_scan_order(node, tt);
hit = true;
2022-04-11 08:07:00 +00:00
if (node instanceof AST_Definitions) {
declare_only.set(last.name.name, (declare_only.get(last.name.name) || 0) + 1);
2022-01-21 08:28:41 +00:00
if (value_def) value_def.replaced++;
2022-04-11 08:07:00 +00:00
var defns = node.definitions;
var index = defns.indexOf(last);
var defn = last.clone();
defn.value = null;
if (!value) {
node.definitions[index] = defn;
return node;
}
var body = [ make_node(AST_SimpleStatement, value, { body: value }) ];
if (index > 0) {
var head = node.clone();
head.definitions = defns.slice(0, index);
body.unshift(head);
node = node.clone();
node.definitions = defns.slice(index);
}
body.push(node);
node.definitions[0] = defn;
return in_list ? List.splice(body) : make_node(AST_BlockStatement, node, { body: body });
2022-02-07 14:48:46 +00:00
}
if (!value) return in_list ? List.skip : null;
return is_statement(node) ? make_node(AST_SimpleStatement, value, { body: value }) : value;
}, function(node, in_list) {
if (node instanceof AST_For) return patch_for_init(node, in_list);
2022-04-11 08:07:00 +00:00
return patch_sequence(node, tt);
2022-02-07 14:48:46 +00:00
});
2022-01-21 08:28:41 +00:00
abort = false;
hit = false;
hit_index = 0;
2022-02-07 14:48:46 +00:00
if (!(statements[stat_index] = statements[stat_index].transform(tt))) statements.splice(stat_index, 1);
2022-01-21 08:28:41 +00:00
}
2022-02-07 14:48:46 +00:00
function patch_sequence(node, tt) {
2022-01-21 08:28:41 +00:00
if (node instanceof AST_Sequence) switch (node.expressions.length) {
case 0: return null;
2022-08-31 14:34:36 +00:00
case 1: return maintain_this_binding(tt.parent(), node, node.expressions[0]);
2022-01-21 08:28:41 +00:00
}
}
function is_lhs_local(lhs) {
var sym = root_expr(lhs);
2022-02-07 14:48:46 +00:00
if (!(sym instanceof AST_SymbolRef)) return false;
if (sym.definition().scope.resolve() !== scope) return false;
if (!in_loop) return true;
if (compound) return false;
if (candidate instanceof AST_Unary) return false;
var lvalue = lvalues.get(sym.name);
return !lvalue || lvalue[0] === lhs;
2022-01-21 08:28:41 +00:00
}
function value_has_side_effects() {
if (candidate instanceof AST_Unary) return false;
return rvalue.has_side_effects(compressor);
}
function replace_all_symbols(expr) {
if (expr instanceof AST_Unary) return false;
if (side_effects) return false;
if (value_def) return true;
if (!(lhs instanceof AST_SymbolRef)) return false;
var referenced;
if (expr instanceof AST_VarDef) {
referenced = 1;
} else if (expr.operator == "=") {
referenced = 2;
} else {
return false;
}
var def = lhs.definition();
if (def.references.length - def.replaced == referenced) return true;
2022-04-11 08:07:00 +00:00
if (!def.fixed) return false;
if (!lhs.fixed) return false;
2022-09-30 13:48:25 +00:00
var assigns = lhs.fixed.assigns;
var matched = 0;
if (!all(def.references, function(ref, index) {
var fixed = ref.fixed;
if (!fixed) return false;
if (fixed.to_binary || fixed.to_prefix) return false;
if (fixed === lhs.fixed) {
matched++;
return true;
}
return assigns && fixed.assigns && assigns[0] !== fixed.assigns[0];
})) return false;
if (matched != referenced) return false;
2022-04-11 08:07:00 +00:00
verify_ref = true;
return true;
2022-01-21 08:28:41 +00:00
}
function symbol_in_lvalues(sym, parent) {
var lvalue = lvalues.get(sym.name);
if (!lvalue || all(lvalue, function(lhs) {
return !lhs;
})) return;
if (lvalue[0] !== lhs) return true;
scan_rhs = false;
}
function may_modify(sym) {
var def = sym.definition();
if (def.orig.length == 1 && def.orig[0] instanceof AST_SymbolDefun) return false;
if (def.scope.resolve() !== scope) return true;
if (modify_toplevel && compressor.exposed(def)) return true;
return !all(def.references, function(ref) {
2022-04-11 08:07:00 +00:00
return ref.scope.resolve(true) === scope;
2022-01-21 08:28:41 +00:00
});
}
function side_effects_external(node, lhs) {
if (node instanceof AST_Assign) return side_effects_external(node.left, true);
if (node instanceof AST_Unary) return side_effects_external(node.expression, true);
if (node instanceof AST_VarDef) return node.value && side_effects_external(node.value);
if (lhs) {
if (node instanceof AST_Dot) return side_effects_external(node.expression, true);
if (node instanceof AST_Sub) return side_effects_external(node.expression, true);
if (node instanceof AST_SymbolRef) return node.definition().scope.resolve() !== scope;
}
return false;
}
}
function eliminate_spurious_blocks(statements) {
2022-02-07 14:48:46 +00:00
var changed = false, seen_dirs = [];
2022-01-21 08:28:41 +00:00
for (var i = 0; i < statements.length;) {
var stat = statements[i];
if (stat instanceof AST_BlockStatement) {
if (all(stat.body, safe_to_trim)) {
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
eliminate_spurious_blocks(stat.body);
[].splice.apply(statements, [i, 1].concat(stat.body));
i += stat.body.length;
continue;
}
}
if (stat instanceof AST_Directive) {
if (member(stat.value, seen_dirs)) {
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
statements.splice(i, 1);
continue;
}
seen_dirs.push(stat.value);
}
if (stat instanceof AST_EmptyStatement) {
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
statements.splice(i, 1);
continue;
}
i++;
}
2022-02-07 14:48:46 +00:00
return changed;
2022-01-21 08:28:41 +00:00
}
function handle_if_return(statements, compressor) {
2022-02-07 14:48:46 +00:00
var changed = false;
2022-01-21 08:28:41 +00:00
var parent = compressor.parent();
2022-02-07 14:48:46 +00:00
var self = compressor.self();
2022-08-31 14:34:36 +00:00
var declare_only, jump, merge_jump;
2022-02-07 14:48:46 +00:00
var in_iife = in_lambda && parent && parent.TYPE == "Call" && parent.expression === self;
var chain_if_returns = in_lambda && compressor.option("conditionals") && compressor.option("sequences");
2022-11-30 12:56:09 +00:00
var drop_return_void = !(in_try && in_try.bfinally && in_async_generator(scope));
2022-01-21 08:28:41 +00:00
var multiple_if_returns = has_multiple_if_returns(statements);
for (var i = statements.length; --i >= 0;) {
var stat = statements[i];
var j = next_index(i);
var next = statements[j];
2022-08-31 14:34:36 +00:00
if (in_lambda && declare_only && !next && stat instanceof AST_Return
2022-10-10 08:26:02 +00:00
&& drop_return_void && !(self instanceof AST_SwitchBranch)) {
2022-08-05 07:44:52 +00:00
var body = stat.value;
if (!body) {
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
statements.splice(i, 1);
continue;
}
2022-08-05 07:44:52 +00:00
var tail = body.tail_node();
if (is_undefined(tail)) {
2022-02-07 14:48:46 +00:00
changed = true;
2022-08-05 07:44:52 +00:00
if (body instanceof AST_UnaryPrefix) {
body = body.expression;
} else if (tail instanceof AST_UnaryPrefix) {
body = body.clone();
body.expressions[body.expressions.length - 1] = tail.expression;
2022-01-21 08:28:41 +00:00
}
2022-02-07 14:48:46 +00:00
statements[i] = make_node(AST_SimpleStatement, stat, { body: body });
2022-01-21 08:28:41 +00:00
continue;
}
}
if (stat instanceof AST_If) {
var ab = aborts(stat.body);
2022-08-31 14:34:36 +00:00
// if (foo()) { bar(); return; } else baz(); moo(); ---> if (foo()) bar(); else { baz(); moo(); }
2022-01-21 08:28:41 +00:00
if (can_merge_flow(ab)) {
if (ab.label) remove(ab.label.thedef.references, ab);
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
stat = stat.clone();
stat.body = make_node(AST_BlockStatement, stat, {
2022-03-14 15:40:45 +00:00
body: as_statement_array_with_return(stat.body, ab),
});
stat.alternative = make_node(AST_BlockStatement, stat, {
2022-08-31 14:34:36 +00:00
body: as_statement_array(stat.alternative).concat(extract_functions(merge_jump, jump)),
2022-01-21 08:28:41 +00:00
});
2022-09-30 13:48:25 +00:00
adjust_refs(ab.value, merge_jump);
2022-01-21 08:28:41 +00:00
statements[i] = stat;
statements[i] = stat.transform(compressor);
continue;
}
2022-08-31 14:34:36 +00:00
// if (foo()) { bar(); return x; } return y; ---> if (!foo()) return y; bar(); return x;
2022-03-14 15:40:45 +00:00
if (ab && !stat.alternative && next instanceof AST_Jump) {
var cond = stat.condition;
2022-08-31 14:34:36 +00:00
var preference = i + 1 == j && stat.body instanceof AST_BlockStatement;
cond = best_of_expression(cond, cond.negate(compressor), preference);
2022-03-14 15:40:45 +00:00
if (cond !== stat.condition) {
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
stat = stat.clone();
2022-03-14 15:40:45 +00:00
stat.condition = cond;
2022-08-31 14:34:36 +00:00
var body = stat.body;
stat.body = make_node(AST_BlockStatement, next, {
body: extract_functions(true, null, j + 1),
});
statements.splice(i, 1, stat, body);
// proceed further only if `TreeWalker.stack` is in a consistent state
// https://github.com/mishoo/UglifyJS/issues/5595
// https://github.com/mishoo/UglifyJS/issues/5597
if (!in_lambda || self instanceof AST_Block && self.body === statements) {
statements[i] = stat.transform(compressor);
}
2022-01-21 08:28:41 +00:00
continue;
}
}
var alt = aborts(stat.alternative);
2022-08-31 14:34:36 +00:00
// if (foo()) bar(); else { baz(); return; } moo(); ---> if (foo()) { bar(); moo(); } else baz();
2022-01-21 08:28:41 +00:00
if (can_merge_flow(alt)) {
if (alt.label) remove(alt.label.thedef.references, alt);
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
stat = stat.clone();
stat.body = make_node(AST_BlockStatement, stat.body, {
2022-08-31 14:34:36 +00:00
body: as_statement_array(stat.body).concat(extract_functions(merge_jump, jump)),
2022-01-21 08:28:41 +00:00
});
2022-03-14 15:40:45 +00:00
stat.alternative = make_node(AST_BlockStatement, stat.alternative, {
body: as_statement_array_with_return(stat.alternative, alt),
});
2022-09-30 13:48:25 +00:00
adjust_refs(alt.value, merge_jump);
2022-01-21 08:28:41 +00:00
statements[i] = stat;
statements[i] = stat.transform(compressor);
continue;
}
if (compressor.option("typeofs")) {
if (ab && !alt) {
2022-02-07 14:48:46 +00:00
var stats = make_node(AST_BlockStatement, self, { body: statements.slice(i + 1) });
mark_locally_defined(stat.condition, null, stats);
2022-01-21 08:28:41 +00:00
}
if (!ab && alt) {
2022-02-07 14:48:46 +00:00
var stats = make_node(AST_BlockStatement, self, { body: statements.slice(i + 1) });
mark_locally_defined(stat.condition, stats);
2022-01-21 08:28:41 +00:00
}
}
}
if (stat instanceof AST_If && stat.body instanceof AST_Return) {
var value = stat.body.value;
var in_bool = stat.body.in_bool || next instanceof AST_Return && next.in_bool;
// if (foo()) return x; return y; ---> return foo() ? x : y;
2022-10-10 08:26:02 +00:00
if (!stat.alternative && next instanceof AST_Return
&& (drop_return_void || !value == !next.value)) {
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
stat = stat.clone();
2022-08-31 14:34:36 +00:00
stat.alternative = make_node(AST_BlockStatement, next, {
body: extract_functions(true, null, j + 1),
});
statements[i] = stat;
statements[i] = stat.transform(compressor);
2022-01-21 08:28:41 +00:00
continue;
}
// if (foo()) return x; [ return ; ] ---> return foo() ? x : undefined;
2022-08-31 14:34:36 +00:00
// if (foo()) return bar() ? x : void 0; ---> return foo() && bar() ? x : void 0;
// if (foo()) return bar() ? void 0 : x; ---> return !foo() || bar() ? void 0 : x;
if (in_lambda && declare_only && !next && !stat.alternative && (in_bool
|| value && multiple_if_returns
|| value instanceof AST_Conditional && (is_undefined(value.consequent, compressor)
|| is_undefined(value.alternative, compressor)))) {
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
stat = stat.clone();
2022-02-07 14:48:46 +00:00
stat.alternative = make_node(AST_Return, stat, { value: null });
2022-08-31 14:34:36 +00:00
statements[i] = stat;
statements[i] = stat.transform(compressor);
2022-01-21 08:28:41 +00:00
continue;
}
// if (a) return b; if (c) return d; e; ---> return a ? b : c ? d : void e;
//
// if sequences is not enabled, this can lead to an endless loop (issue #866).
// however, with sequences on this helps producing slightly better output for
// the example code.
2022-02-07 14:48:46 +00:00
var prev, prev_stat;
if (chain_if_returns && !stat.alternative
&& (!(prev_stat = statements[prev = prev_index(i)]) && in_iife
|| prev_stat instanceof AST_If && prev_stat.body instanceof AST_Return)
2022-08-31 14:34:36 +00:00
&& (!next ? !declare_only
: next instanceof AST_SimpleStatement && next_index(j) == statements.length)) {
2022-02-07 14:48:46 +00:00
changed = true;
var exprs = [];
2022-01-21 08:28:41 +00:00
stat = stat.clone();
2022-02-07 14:48:46 +00:00
exprs.push(stat.condition);
stat.condition = make_sequence(stat, exprs);
2022-08-31 14:34:36 +00:00
stat.alternative = make_node(AST_BlockStatement, self, {
body: extract_functions().concat(make_node(AST_Return, self, { value: null })),
2022-01-21 08:28:41 +00:00
});
2022-08-31 14:34:36 +00:00
statements[i] = stat.transform(compressor);
2022-02-07 14:48:46 +00:00
i = prev + 1;
2022-01-21 08:28:41 +00:00
continue;
}
}
2022-07-11 11:25:19 +00:00
2022-08-31 14:34:36 +00:00
if (stat instanceof AST_Break || stat instanceof AST_Exit) {
jump = stat;
2022-08-05 07:44:52 +00:00
continue;
2022-07-11 11:25:19 +00:00
}
2022-08-05 07:44:52 +00:00
2022-09-30 13:48:25 +00:00
if (declare_only && jump && jump === next) eliminate_returns(stat);
2022-01-21 08:28:41 +00:00
}
2022-02-07 14:48:46 +00:00
return changed;
2022-01-21 08:28:41 +00:00
function has_multiple_if_returns(statements) {
var n = 0;
for (var i = statements.length; --i >= 0;) {
var stat = statements[i];
if (stat instanceof AST_If && stat.body instanceof AST_Return) {
if (++n > 1) return true;
}
}
return false;
}
function match_target(target) {
2022-02-07 14:48:46 +00:00
return last_of(compressor, function(node) {
2022-01-21 08:28:41 +00:00
return node === target;
});
}
2022-08-05 07:44:52 +00:00
function match_return(ab, exact) {
2022-08-31 14:34:36 +00:00
if (!jump) return false;
if (jump.TYPE != ab.TYPE) return false;
2022-08-05 07:44:52 +00:00
var value = ab.value;
if (!value) return false;
2022-08-31 14:34:36 +00:00
var equals = jump.equals(ab);
2022-08-05 07:44:52 +00:00
if (!equals && value instanceof AST_Sequence) {
value = value.tail_node();
2022-08-31 14:34:36 +00:00
if (jump.value && jump.value.equals(value)) equals = 2;
2022-08-05 07:44:52 +00:00
}
2022-08-31 14:34:36 +00:00
if (!equals && !exact && jump.value instanceof AST_Sequence) {
if (jump.value.tail_node().equals(value)) equals = 3;
2022-08-05 07:44:52 +00:00
}
return equals;
}
2022-01-21 08:28:41 +00:00
function can_drop_abort(ab) {
2022-07-11 11:25:19 +00:00
if (ab instanceof AST_Exit) {
2022-08-31 14:34:36 +00:00
if (merge_jump = match_return(ab)) return true;
2022-08-05 07:44:52 +00:00
if (!in_lambda) return false;
if (!(ab instanceof AST_Return)) return false;
2022-08-31 14:34:36 +00:00
var value = ab.value;
if (value && !is_undefined(value.tail_node())) return false;
if (!(self instanceof AST_SwitchBranch)) return true;
if (!jump) return false;
if (jump instanceof AST_Exit && jump.value) return false;
merge_jump = 4;
return true;
2022-07-11 11:25:19 +00:00
}
2022-01-21 08:28:41 +00:00
if (!(ab instanceof AST_LoopControl)) return false;
2022-10-10 08:26:02 +00:00
if (self instanceof AST_SwitchBranch) {
2022-08-31 14:34:36 +00:00
if (jump instanceof AST_Exit) {
if (!in_lambda) return false;
if (jump.value) return false;
2022-10-10 08:26:02 +00:00
merge_jump = true;
} else if (jump) {
if (compressor.loopcontrol_target(jump) !== parent) return false;
merge_jump = true;
} else if (jump === false) {
2022-08-31 14:34:36 +00:00
return false;
}
}
2022-01-21 08:28:41 +00:00
var lct = compressor.loopcontrol_target(ab);
if (ab instanceof AST_Continue) return match_target(loop_body(lct));
if (lct instanceof AST_IterationStatement) return false;
return match_target(lct);
}
function can_merge_flow(ab) {
2022-08-31 14:34:36 +00:00
merge_jump = false;
2022-01-21 08:28:41 +00:00
if (!can_drop_abort(ab)) return false;
for (var j = statements.length; --j > i;) {
var stat = statements[j];
if (stat instanceof AST_DefClass) {
if (stat.name.definition().preinit) return false;
} else if (stat instanceof AST_Const || stat instanceof AST_Let) {
if (!all(stat.definitions, function(defn) {
return !defn.name.match_symbol(function(node) {
return node instanceof AST_SymbolDeclaration && node.definition().preinit;
});
})) return false;
}
}
return true;
}
2022-08-31 14:34:36 +00:00
function extract_functions(mode, stop, end) {
2022-01-21 08:28:41 +00:00
var defuns = [];
var lexical = false;
2022-07-11 11:25:19 +00:00
var start = i + 1;
2022-08-31 14:34:36 +00:00
if (!mode) {
2022-07-11 11:25:19 +00:00
end = statements.length;
2022-08-31 14:34:36 +00:00
jump = null;
} else if (stop) {
end = statements.lastIndexOf(stop);
} else {
stop = statements[end];
2022-10-10 08:26:02 +00:00
if (stop !== jump) jump = false;
2022-07-11 11:25:19 +00:00
}
var tail = statements.splice(start, end - start).filter(function(stat) {
2022-01-21 08:28:41 +00:00
if (stat instanceof AST_LambdaDefinition) {
defuns.push(stat);
return false;
}
if (is_lexical_definition(stat)) lexical = true;
return true;
});
2022-08-31 14:34:36 +00:00
if (mode === 3) {
tail.push(make_node(AST_SimpleStatement, stop.value, {
body: make_sequence(stop.value, stop.value.expressions.slice(0, -1)),
2022-08-05 07:44:52 +00:00
}));
2022-08-31 14:34:36 +00:00
stop.value = stop.value.tail_node();
2022-08-05 07:44:52 +00:00
}
2022-01-21 08:28:41 +00:00
[].push.apply(lexical ? tail : statements, defuns);
return tail;
}
2022-08-05 07:44:52 +00:00
function trim_return(value, mode) {
if (value) switch (mode) {
2022-08-31 14:34:36 +00:00
case 4:
return value;
2022-08-05 07:44:52 +00:00
case 3:
if (!(value instanceof AST_Sequence)) break;
case 2:
return make_sequence(value, value.expressions.slice(0, -1));
}
}
2022-01-21 08:28:41 +00:00
function as_statement_array_with_return(node, ab) {
var body = as_statement_array(node);
var block = body, last;
while ((last = block[block.length - 1]) !== ab) {
block = last.body;
}
block.pop();
2022-08-05 07:44:52 +00:00
var value = ab.value;
2022-08-31 14:34:36 +00:00
if (merge_jump) value = trim_return(value, merge_jump);
2022-08-05 07:44:52 +00:00
if (value) block.push(make_node(AST_SimpleStatement, value, { body: value }));
2022-01-21 08:28:41 +00:00
return body;
}
2022-09-30 13:48:25 +00:00
function adjust_refs(value, mode) {
if (!mode) return;
if (!value) return;
switch (mode) {
case 4:
return;
case 3:
case 2:
value = value.tail_node();
}
merge_expression(value, jump.value);
}
2022-01-21 08:28:41 +00:00
function next_index(i) {
2022-08-31 14:34:36 +00:00
declare_only = true;
for (var j = i; ++j < statements.length;) {
var stat = statements[j];
if (is_declaration(stat)) continue;
if (stat instanceof AST_Var) {
declare_only = false;
continue;
}
break;
2022-01-21 08:28:41 +00:00
}
return j;
}
function prev_index(i) {
for (var j = i; --j >= 0;) {
2022-02-07 14:48:46 +00:00
var stat = statements[j];
2022-08-31 14:34:36 +00:00
if (stat instanceof AST_Var) continue;
if (is_declaration(stat)) continue;
break;
2022-02-07 14:48:46 +00:00
}
2022-08-31 14:34:36 +00:00
return j;
2022-02-07 14:48:46 +00:00
}
2022-08-05 07:44:52 +00:00
2022-09-30 13:48:25 +00:00
function eliminate_returns(stat, keep_throws, in_block) {
2022-08-05 07:44:52 +00:00
if (stat instanceof AST_Exit) {
2022-09-30 13:48:25 +00:00
var mode = !(keep_throws && stat instanceof AST_Throw) && match_return(stat, true);
2022-08-05 07:44:52 +00:00
if (mode) {
2022-09-30 13:48:25 +00:00
changed = true;
2022-08-05 07:44:52 +00:00
var value = trim_return(stat.value, mode);
if (value) return make_node(AST_SimpleStatement, value, { body: value });
return in_block ? null : make_node(AST_EmptyStatement, stat);
}
} else if (stat instanceof AST_If) {
2022-09-30 13:48:25 +00:00
stat.body = eliminate_returns(stat.body, keep_throws);
if (stat.alternative) stat.alternative = eliminate_returns(stat.alternative, keep_throws);
2022-08-05 07:44:52 +00:00
} else if (stat instanceof AST_LabeledStatement) {
2022-09-30 13:48:25 +00:00
stat.body = eliminate_returns(stat.body, keep_throws);
2022-08-05 07:44:52 +00:00
} else if (stat instanceof AST_Try) {
2022-08-31 14:34:36 +00:00
if (!stat.bfinally || !jump.value || jump.value.is_constant()) {
2022-09-30 13:48:25 +00:00
if (stat.bcatch) eliminate_returns(stat.bcatch, keep_throws);
var trimmed = eliminate_returns(stat.body.pop(), true, true);
2022-08-05 07:44:52 +00:00
if (trimmed) stat.body.push(trimmed);
}
} else if (stat instanceof AST_Block && !(stat instanceof AST_Scope || stat instanceof AST_Switch)) {
2022-09-30 13:48:25 +00:00
var trimmed = eliminate_returns(stat.body.pop(), keep_throws, true);
2022-08-05 07:44:52 +00:00
if (trimmed) stat.body.push(trimmed);
}
return stat;
}
2022-01-21 08:28:41 +00:00
}
function eliminate_dead_code(statements, compressor) {
var has_quit;
var self = compressor.self();
2022-07-11 11:25:19 +00:00
if (self instanceof AST_Catch) {
self = compressor.parent();
} else if (self instanceof AST_LabeledStatement) {
self = self.body;
}
2022-01-21 08:28:41 +00:00
for (var i = 0, n = 0, len = statements.length; i < len; i++) {
var stat = statements[i];
if (stat instanceof AST_LoopControl) {
var lct = compressor.loopcontrol_target(stat);
if (loop_body(lct) !== self
|| stat instanceof AST_Break && lct instanceof AST_IterationStatement) {
statements[n++] = stat;
} else if (stat.label) {
remove(stat.label.thedef.references, stat);
}
} else {
statements[n++] = stat;
}
if (aborts(stat)) {
has_quit = statements.slice(i + 1);
break;
}
}
statements.length = n;
if (has_quit) has_quit.forEach(function(stat) {
extract_declarations_from_unreachable_code(compressor, stat, statements);
});
2022-02-07 14:48:46 +00:00
return statements.length != len;
}
function trim_awaits(statements, compressor) {
if (!in_lambda || in_try && in_try.bfinally) return;
var changed = false;
for (var index = statements.length; --index >= 0;) {
var stat = statements[index];
if (!(stat instanceof AST_SimpleStatement)) break;
var node = stat.body;
if (!(node instanceof AST_Await)) break;
var exp = node.expression;
2022-09-30 13:48:25 +00:00
if (!needs_enqueuing(compressor, exp)) break;
2022-02-07 14:48:46 +00:00
changed = true;
exp = exp.drop_side_effect_free(compressor, true);
if (exp) {
stat.body = exp;
break;
}
}
statements.length = index + 1;
return changed;
}
function inline_iife(statements, compressor) {
var changed = false;
var index = statements.length - 1;
if (in_lambda && index >= 0) {
2022-08-31 14:34:36 +00:00
var no_return = in_try && in_try.bfinally && in_async_generator(scope);
var inlined = statements[index].try_inline(compressor, block_scope, no_return);
2022-02-07 14:48:46 +00:00
if (inlined) {
statements[index--] = inlined;
changed = true;
}
}
var loop = in_loop && in_try && in_try.bfinally ? "try" : in_loop;
for (; index >= 0; index--) {
var inlined = statements[index].try_inline(compressor, block_scope, true, loop);
if (!inlined) continue;
statements[index] = inlined;
changed = true;
}
return changed;
2022-01-21 08:28:41 +00:00
}
function sequencesize(statements, compressor) {
if (statements.length < 2) return;
var seq = [], n = 0;
function push_seq() {
if (!seq.length) return;
var body = make_sequence(seq[0], seq);
statements[n++] = make_node(AST_SimpleStatement, body, { body: body });
seq = [];
}
for (var i = 0, len = statements.length; i < len; i++) {
var stat = statements[i];
if (stat instanceof AST_SimpleStatement) {
if (seq.length >= compressor.sequences_limit) push_seq();
2022-03-14 15:40:45 +00:00
merge_sequence(seq, stat.body);
2022-01-21 08:28:41 +00:00
} else if (is_declaration(stat)) {
statements[n++] = stat;
} else {
push_seq();
statements[n++] = stat;
}
}
push_seq();
statements.length = n;
2022-02-07 14:48:46 +00:00
return n != len;
2022-01-21 08:28:41 +00:00
}
function to_simple_statement(block, decls) {
if (!(block instanceof AST_BlockStatement)) return block;
var stat = null;
for (var i = 0; i < block.body.length; i++) {
var line = block.body[i];
if (line instanceof AST_Var && declarations_only(line)) {
decls.push(line);
} else if (stat || is_lexical_definition(line)) {
return false;
} else {
stat = line;
}
}
return stat;
}
function sequencesize_2(statements, compressor) {
2022-02-07 14:48:46 +00:00
var changed = false, n = 0, prev;
2022-01-21 08:28:41 +00:00
for (var i = 0; i < statements.length; i++) {
var stat = statements[i];
if (prev) {
if (stat instanceof AST_Exit) {
if (stat.value || !in_async_generator(scope)) {
stat.value = cons_seq(stat.value || make_node(AST_Undefined, stat)).optimize(compressor);
}
} else if (stat instanceof AST_For) {
if (!(stat.init instanceof AST_Definitions)) {
var abort = false;
prev.body.walk(new TreeWalker(function(node) {
if (abort || node instanceof AST_Scope) return true;
if (node instanceof AST_Binary && node.operator == "in") {
abort = true;
return true;
}
}));
if (!abort) {
if (stat.init) stat.init = cons_seq(stat.init);
else {
stat.init = prev.body;
n--;
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
}
}
}
} else if (stat instanceof AST_ForIn) {
if (!is_lexical_definition(stat.init)) stat.object = cons_seq(stat.object);
} else if (stat instanceof AST_If) {
stat.condition = cons_seq(stat.condition);
} else if (stat instanceof AST_Switch) {
stat.expression = cons_seq(stat.expression);
} else if (stat instanceof AST_With) {
stat.expression = cons_seq(stat.expression);
}
}
if (compressor.option("conditionals") && stat instanceof AST_If) {
var decls = [];
var body = to_simple_statement(stat.body, decls);
var alt = to_simple_statement(stat.alternative, decls);
if (body !== false && alt !== false && decls.length > 0) {
var len = decls.length;
decls.push(make_node(AST_If, stat, {
condition: stat.condition,
body: body || make_node(AST_EmptyStatement, stat.body),
2022-08-31 14:34:36 +00:00
alternative: alt,
2022-01-21 08:28:41 +00:00
}));
decls.unshift(n, 1);
[].splice.apply(statements, decls);
i += len;
n += len + 1;
prev = null;
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
continue;
}
}
statements[n++] = stat;
prev = stat instanceof AST_SimpleStatement ? stat : null;
}
statements.length = n;
2022-02-07 14:48:46 +00:00
return changed;
function cons_seq(right) {
n--;
changed = true;
var left = prev.body;
return make_sequence(left, [ left, right ]);
}
2022-01-21 08:28:41 +00:00
}
function extract_exprs(body) {
if (body instanceof AST_Assign) return [ body ];
if (body instanceof AST_Sequence) return body.expressions.slice();
}
function join_assigns(defn, body, keep) {
var exprs = extract_exprs(body);
if (!exprs) return;
2022-03-14 15:40:45 +00:00
keep = keep || 0;
2022-01-21 08:28:41 +00:00
var trimmed = false;
2022-03-14 15:40:45 +00:00
for (var i = exprs.length - keep; --i >= 0;) {
2022-01-21 08:28:41 +00:00
var expr = exprs[i];
if (!can_trim(expr)) continue;
var tail;
if (expr.left instanceof AST_SymbolRef) {
tail = exprs.slice(i + 1);
} else if (expr.left instanceof AST_PropAccess && can_trim(expr.left.expression)) {
tail = exprs.slice(i + 1);
var flattened = expr.clone();
expr = expr.left.expression;
flattened.left = flattened.left.clone();
flattened.left.expression = expr.left.clone();
tail.unshift(flattened);
} else {
continue;
}
if (tail.length == 0) continue;
if (!trim_assigns(expr.left, expr.right, tail)) continue;
trimmed = true;
exprs = exprs.slice(0, i).concat(expr, tail);
}
if (defn instanceof AST_Definitions) {
for (var i = defn.definitions.length; --i >= 0;) {
var def = defn.definitions[i];
if (!def.value) continue;
if (trim_assigns(def.name, def.value, exprs)) trimmed = true;
if (merge_conditional_assignments(def, exprs, keep)) trimmed = true;
break;
}
if (defn instanceof AST_Var && join_var_assign(defn.definitions, exprs, keep)) trimmed = true;
}
return trimmed && exprs;
function can_trim(node) {
return node instanceof AST_Assign && node.operator == "=";
}
}
function merge_assigns(prev, defn) {
if (!(prev instanceof AST_SimpleStatement)) return;
if (declarations_only(defn)) return;
var exprs = extract_exprs(prev.body);
if (!exprs) return;
var definitions = [];
if (!join_var_assign(definitions, exprs.reverse(), 0)) return;
defn.definitions = definitions.reverse().concat(defn.definitions);
return exprs.reverse();
}
function merge_conditional_assignments(var_def, exprs, keep) {
if (!compressor.option("conditionals")) return;
if (var_def.name instanceof AST_Destructured) return;
var trimmed = false;
var def = var_def.name.definition();
while (exprs.length > keep) {
var cond = to_conditional_assignment(compressor, def, var_def.value, exprs[0]);
if (!cond) break;
var_def.value = cond;
exprs.shift();
trimmed = true;
}
return trimmed;
}
function join_var_assign(definitions, exprs, keep) {
var trimmed = false;
while (exprs.length > keep) {
var expr = exprs[0];
if (!(expr instanceof AST_Assign)) break;
if (expr.operator != "=") break;
var lhs = expr.left;
if (!(lhs instanceof AST_SymbolRef)) break;
if (is_undeclared_ref(lhs)) break;
if (lhs.scope.resolve() !== scope) break;
var def = lhs.definition();
if (def.scope !== scope) break;
if (def.orig.length > def.eliminated + 1) break;
if (def.orig[0].TYPE != "SymbolVar") break;
2022-08-31 14:34:36 +00:00
var name = make_node(AST_SymbolVar, lhs);
2022-01-21 08:28:41 +00:00
definitions.push(make_node(AST_VarDef, expr, {
name: name,
2022-08-31 14:34:36 +00:00
value: expr.right,
2022-01-21 08:28:41 +00:00
}));
def.orig.push(name);
def.replaced++;
exprs.shift();
trimmed = true;
}
return trimmed;
}
function trim_assigns(name, value, exprs) {
var names = new Dictionary();
names.set(name.name, true);
while (value instanceof AST_Assign && value.operator == "=") {
if (value.left instanceof AST_SymbolRef) names.set(value.left.name, true);
value = value.right;
}
if (!(value instanceof AST_Object)) return;
var trimmed = false;
do {
if (!try_join(exprs[0])) break;
exprs.shift();
trimmed = true;
} while (exprs.length);
return trimmed;
function try_join(node) {
if (!(node instanceof AST_Assign)) return;
if (node.operator != "=") return;
if (!(node.left instanceof AST_PropAccess)) return;
var sym = node.left.expression;
if (!(sym instanceof AST_SymbolRef)) return;
if (!names.has(sym.name)) return;
if (!node.right.is_constant_expression(scope)) return;
var prop = node.left.property;
if (prop instanceof AST_Node) {
if (try_join(prop)) prop = node.left.property = prop.right.clone();
prop = prop.evaluate(compressor);
}
if (prop instanceof AST_Node) return;
prop = "" + prop;
var diff = prop == "__proto__" || compressor.has_directive("use strict") ? function(node) {
var key = node.key;
return typeof key == "string" && key != prop && key != "__proto__";
} : function(node) {
var key = node.key;
if (node instanceof AST_ObjectGetter || node instanceof AST_ObjectSetter) {
return typeof key == "string" && key != prop;
}
return key !== "__proto__";
};
if (!all(value.properties, diff)) return;
value.properties.push(make_node(AST_ObjectKeyVal, node, {
key: prop,
value: node.right,
}));
return true;
}
}
function join_consecutive_vars(statements) {
2022-02-07 14:48:46 +00:00
var changed = false, defs;
2022-01-21 08:28:41 +00:00
for (var i = 0, j = -1; i < statements.length; i++) {
var stat = statements[i];
var prev = statements[j];
if (stat instanceof AST_Definitions) {
if (prev && prev.TYPE == stat.TYPE) {
prev.definitions = prev.definitions.concat(stat.definitions);
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
} else if (defs && defs.TYPE == stat.TYPE && declarations_only(stat)) {
defs.definitions = defs.definitions.concat(stat.definitions);
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
} else if (stat instanceof AST_Var) {
var exprs = merge_assigns(prev, stat);
if (exprs) {
if (exprs.length) {
prev.body = make_sequence(prev, exprs);
j++;
}
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
} else {
j++;
}
statements[j] = defs = stat;
} else {
statements[++j] = stat;
}
continue;
} else if (stat instanceof AST_Exit) {
stat.value = join_assigns_expr(stat.value);
} else if (stat instanceof AST_For) {
var exprs = join_assigns(prev, stat.init);
if (exprs) {
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
stat.init = exprs.length ? make_sequence(stat.init, exprs) : null;
} else if (prev instanceof AST_Var && (!stat.init || stat.init.TYPE == prev.TYPE)) {
if (stat.init) {
prev.definitions = prev.definitions.concat(stat.init.definitions);
}
2022-02-07 14:48:46 +00:00
stat = stat.clone();
2022-01-21 08:28:41 +00:00
defs = stat.init = prev;
statements[j] = merge_defns(stat);
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
continue;
} else if (defs && stat.init && defs.TYPE == stat.init.TYPE && declarations_only(stat.init)) {
defs.definitions = defs.definitions.concat(stat.init.definitions);
stat.init = null;
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
} else if (stat.init instanceof AST_Var) {
defs = stat.init;
exprs = merge_assigns(prev, stat.init);
if (exprs) {
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
if (exprs.length == 0) {
statements[j] = merge_defns(stat);
continue;
}
prev.body = make_sequence(prev, exprs);
}
}
} else if (stat instanceof AST_ForEnumeration) {
if (defs && defs.TYPE == stat.init.TYPE) {
var defns = defs.definitions.slice();
stat.init = stat.init.definitions[0].name.convert_symbol(AST_SymbolRef, function(ref, name) {
defns.push(make_node(AST_VarDef, name, {
name: name,
value: null,
}));
name.definition().references.push(ref);
});
defs.definitions = defns;
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
}
stat.object = join_assigns_expr(stat.object);
} else if (stat instanceof AST_If) {
stat.condition = join_assigns_expr(stat.condition);
} else if (stat instanceof AST_SimpleStatement) {
2022-02-07 14:48:46 +00:00
var exprs = join_assigns(prev, stat.body), next;
2022-01-21 08:28:41 +00:00
if (exprs) {
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
if (!exprs.length) continue;
stat.body = make_sequence(stat.body, exprs);
2022-02-07 14:48:46 +00:00
} else if (prev instanceof AST_Definitions
&& (next = statements[i + 1])
&& prev.TYPE == next.TYPE
&& (next = next.definitions[0]).value) {
changed = true;
next.value = make_sequence(stat, [ stat.body, next.value ]);
continue;
2022-01-21 08:28:41 +00:00
}
} else if (stat instanceof AST_Switch) {
stat.expression = join_assigns_expr(stat.expression);
} else if (stat instanceof AST_With) {
stat.expression = join_assigns_expr(stat.expression);
}
statements[++j] = defs ? merge_defns(stat) : stat;
}
statements.length = j + 1;
2022-02-07 14:48:46 +00:00
return changed;
2022-01-21 08:28:41 +00:00
function join_assigns_expr(value) {
var exprs = join_assigns(prev, value, 1);
if (!exprs) return value;
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
var tail = value.tail_node();
if (exprs[exprs.length - 1] !== tail) exprs.push(tail.left);
return make_sequence(value, exprs);
}
function merge_defns(stat) {
return stat.transform(new TreeTransformer(function(node, descend, in_list) {
if (node instanceof AST_Definitions) {
if (defs === node) return node;
if (defs.TYPE != node.TYPE) return node;
var parent = this.parent();
if (parent instanceof AST_ForEnumeration && parent.init === node) return node;
if (!declarations_only(node)) return node;
defs.definitions = defs.definitions.concat(node.definitions);
2022-02-07 14:48:46 +00:00
changed = true;
2022-01-21 08:28:41 +00:00
if (parent instanceof AST_For && parent.init === node) return null;
return in_list ? List.skip : make_node(AST_EmptyStatement, node);
}
if (node instanceof AST_ExportDeclaration) return node;
if (node instanceof AST_Scope) return node;
if (!is_statement(node)) return node;
}));
}
}
}
function extract_declarations_from_unreachable_code(compressor, stat, target) {
var block;
var dropped = false;
stat.walk(new TreeWalker(function(node, descend) {
if (node instanceof AST_DefClass) {
node.extends = null;
node.properties = [];
push(node);
return true;
}
if (node instanceof AST_Definitions) {
var defns = [];
if (node.remove_initializers(compressor, defns)) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Dropping initialization in unreachable code [{start}]", node);
2022-01-21 08:28:41 +00:00
}
if (defns.length > 0) {
node.definitions = defns;
push(node);
}
return true;
}
if (node instanceof AST_LambdaDefinition) {
push(node);
return true;
}
if (node instanceof AST_Scope) return true;
if (node instanceof AST_BlockScope) {
var save = block;
block = [];
descend();
if (block.required) {
target.push(make_node(AST_BlockStatement, stat, { body: block }));
} else if (block.length) {
[].push.apply(target, block);
}
block = save;
return true;
}
if (!(node instanceof AST_LoopControl)) dropped = true;
}));
2022-08-31 14:34:36 +00:00
if (dropped) AST_Node.warn("Dropping unreachable code [{start}]", stat);
2022-01-21 08:28:41 +00:00
function push(node) {
if (block) {
block.push(node);
if (!safe_to_trim(node)) block.required = true;
} else {
target.push(node);
}
}
}
function is_undefined(node, compressor) {
2022-02-07 14:48:46 +00:00
return node == null
|| node.is_undefined
2022-01-21 08:28:41 +00:00
|| node instanceof AST_Undefined
|| node instanceof AST_UnaryPrefix
&& node.operator == "void"
&& !(compressor && node.expression.has_side_effects(compressor));
}
2022-06-08 10:36:39 +00:00
// in_strict_mode()
// return true if scope executes in Strict Mode
(function(def) {
def(AST_Class, return_true);
def(AST_Scope, function(compressor) {
var body = this.body;
for (var i = 0; i < body.length; i++) {
var stat = body[i];
if (!(stat instanceof AST_Directive)) break;
if (stat.value == "use strict") return true;
}
var parent = this.parent_scope;
if (!parent) return compressor.option("module");
return parent.resolve(true).in_strict_mode(compressor);
});
})(function(node, func) {
node.DEFMETHOD("in_strict_mode", func);
});
2022-01-21 08:28:41 +00:00
// is_truthy()
// return true if `!!node === true`
(function(def) {
def(AST_Node, return_false);
def(AST_Array, return_true);
def(AST_Assign, function() {
return this.operator == "=" && this.right.is_truthy();
});
def(AST_Lambda, return_true);
def(AST_Object, return_true);
def(AST_RegExp, return_true);
def(AST_Sequence, function() {
return this.tail_node().is_truthy();
});
def(AST_SymbolRef, function() {
var fixed = this.fixed_value();
if (!fixed) return false;
this.is_truthy = return_false;
var result = fixed.is_truthy();
delete this.is_truthy;
return result;
});
})(function(node, func) {
node.DEFMETHOD("is_truthy", func);
});
// is_negative_zero()
// return true if the node may represent -0
(function(def) {
def(AST_Node, return_true);
def(AST_Array, return_false);
function binary(op, left, right) {
switch (op) {
case "-":
return left.is_negative_zero()
&& (!(right instanceof AST_Constant) || right.value == 0);
case "&&":
case "||":
return left.is_negative_zero() || right.is_negative_zero();
case "*":
case "/":
case "%":
case "**":
return true;
default:
return false;
}
}
def(AST_Assign, function() {
var op = this.operator;
if (op == "=") return this.right.is_negative_zero();
return binary(op.slice(0, -1), this.left, this.right);
});
def(AST_Binary, function() {
return binary(this.operator, this.left, this.right);
});
def(AST_Constant, function() {
return this.value == 0 && 1 / this.value < 0;
});
def(AST_Lambda, return_false);
def(AST_Object, return_false);
def(AST_RegExp, return_false);
def(AST_Sequence, function() {
return this.tail_node().is_negative_zero();
});
def(AST_SymbolRef, function() {
var fixed = this.fixed_value();
if (!fixed) return true;
this.is_negative_zero = return_true;
var result = fixed.is_negative_zero();
delete this.is_negative_zero;
return result;
});
def(AST_UnaryPrefix, function() {
return this.operator == "+" && this.expression.is_negative_zero()
|| this.operator == "-";
});
})(function(node, func) {
node.DEFMETHOD("is_negative_zero", func);
});
// may_throw_on_access()
// returns true if this node may be null, undefined or contain `AST_Accessor`
(function(def) {
AST_Node.DEFMETHOD("may_throw_on_access", function(compressor, force) {
return !compressor.option("pure_getters") || this._dot_throw(compressor, force);
});
function is_strict(compressor, force) {
return force || /strict/.test(compressor.option("pure_getters"));
}
def(AST_Node, is_strict);
def(AST_Array, return_false);
def(AST_Assign, function(compressor) {
var op = this.operator;
var sym = this.left;
var rhs = this.right;
if (op != "=") {
return lazy_op[op.slice(0, -1)] && (sym._dot_throw(compressor) || rhs._dot_throw(compressor));
}
if (!rhs._dot_throw(compressor)) return false;
if (!(sym instanceof AST_SymbolRef)) return true;
if (rhs instanceof AST_Binary && rhs.operator == "||" && sym.name == rhs.left.name) {
return rhs.right._dot_throw(compressor);
}
return true;
});
def(AST_Binary, function(compressor) {
return lazy_op[this.operator] && (this.left._dot_throw(compressor) || this.right._dot_throw(compressor));
});
2022-08-31 14:34:36 +00:00
def(AST_Class, function(compressor, force) {
return is_strict(compressor, force) && !all(this.properties, function(prop) {
if (prop.private) return true;
if (!prop.static) return true;
return !(prop instanceof AST_ClassGetter || prop instanceof AST_ClassSetter);
});
});
2022-01-21 08:28:41 +00:00
def(AST_Conditional, function(compressor) {
return this.consequent._dot_throw(compressor) || this.alternative._dot_throw(compressor);
});
def(AST_Constant, return_false);
def(AST_Dot, function(compressor, force) {
if (!is_strict(compressor, force)) return false;
var exp = this.expression;
if (exp instanceof AST_SymbolRef) exp = exp.fixed_value();
return !(this.property == "prototype" && is_lambda(exp));
});
def(AST_Lambda, return_false);
def(AST_Null, return_true);
def(AST_Object, function(compressor, force) {
return is_strict(compressor, force) && !all(this.properties, function(prop) {
2022-08-31 14:34:36 +00:00
if (prop instanceof AST_ObjectGetter || prop instanceof AST_ObjectSetter) return false;
2022-01-21 08:28:41 +00:00
return !(prop.key === "__proto__" && prop.value._dot_throw(compressor, force));
});
});
def(AST_ObjectIdentity, function(compressor, force) {
return is_strict(compressor, force) && !this.scope.resolve().new;
});
def(AST_Sequence, function(compressor) {
return this.tail_node()._dot_throw(compressor);
});
def(AST_SymbolRef, function(compressor, force) {
if (this.is_undefined) return true;
if (!is_strict(compressor, force)) return false;
if (is_undeclared_ref(this) && this.is_declared(compressor)) return false;
if (this.is_immutable()) return false;
var def = this.definition();
if (is_arguments(def) && !def.scope.rest && all(def.scope.argnames, function(argname) {
return argname instanceof AST_SymbolFunarg;
})) return def.scope.uses_arguments > 2;
2022-09-30 13:48:25 +00:00
var fixed = this.fixed_value(true);
2022-01-21 08:28:41 +00:00
if (!fixed) return true;
this._dot_throw = return_true;
if (fixed._dot_throw(compressor)) {
delete this._dot_throw;
return true;
}
this._dot_throw = return_false;
return false;
});
def(AST_UnaryPrefix, function() {
return this.operator == "void";
});
def(AST_UnaryPostfix, return_false);
def(AST_Undefined, return_true);
})(function(node, func) {
node.DEFMETHOD("_dot_throw", func);
});
(function(def) {
def(AST_Node, return_false);
def(AST_Array, return_true);
function is_binary_defined(compressor, op, node) {
switch (op) {
case "&&":
return node.left.is_defined(compressor) && node.right.is_defined(compressor);
case "||":
return node.left.is_truthy() || node.right.is_defined(compressor);
case "??":
return node.left.is_defined(compressor) || node.right.is_defined(compressor);
default:
return true;
}
}
def(AST_Assign, function(compressor) {
var op = this.operator;
if (op == "=") return this.right.is_defined(compressor);
return is_binary_defined(compressor, op.slice(0, -1), this);
});
def(AST_Binary, function(compressor) {
return is_binary_defined(compressor, this.operator, this);
});
def(AST_Conditional, function(compressor) {
return this.consequent.is_defined(compressor) && this.alternative.is_defined(compressor);
});
def(AST_Constant, return_true);
def(AST_Hole, return_false);
def(AST_Lambda, return_true);
def(AST_Object, return_true);
def(AST_Sequence, function(compressor) {
return this.tail_node().is_defined(compressor);
});
def(AST_SymbolRef, function(compressor) {
if (this.is_undefined) return false;
if (is_undeclared_ref(this) && this.is_declared(compressor)) return true;
if (this.is_immutable()) return true;
var fixed = this.fixed_value();
if (!fixed) return false;
this.is_defined = return_false;
var result = fixed.is_defined(compressor);
delete this.is_defined;
return result;
});
def(AST_UnaryPrefix, function() {
return this.operator != "void";
});
def(AST_UnaryPostfix, return_true);
def(AST_Undefined, return_false);
})(function(node, func) {
node.DEFMETHOD("is_defined", func);
});
/* -----[ boolean/negation helpers ]----- */
// methods to determine whether an expression has a boolean result type
(function(def) {
def(AST_Node, return_false);
def(AST_Assign, function(compressor) {
return this.operator == "=" && this.right.is_boolean(compressor);
});
var binary = makePredicate("in instanceof == != === !== < <= >= >");
def(AST_Binary, function(compressor) {
return binary[this.operator] || lazy_op[this.operator]
&& this.left.is_boolean(compressor)
&& this.right.is_boolean(compressor);
});
def(AST_Boolean, return_true);
var fn = makePredicate("every hasOwnProperty isPrototypeOf propertyIsEnumerable some");
def(AST_Call, function(compressor) {
if (!compressor.option("unsafe")) return false;
var exp = this.expression;
return exp instanceof AST_Dot && (fn[exp.property]
|| exp.property == "test" && exp.expression instanceof AST_RegExp);
});
def(AST_Conditional, function(compressor) {
return this.consequent.is_boolean(compressor) && this.alternative.is_boolean(compressor);
});
def(AST_New, return_false);
def(AST_Sequence, function(compressor) {
return this.tail_node().is_boolean(compressor);
});
def(AST_SymbolRef, function(compressor) {
var fixed = this.fixed_value();
if (!fixed) return false;
this.is_boolean = return_false;
var result = fixed.is_boolean(compressor);
delete this.is_boolean;
return result;
});
var unary = makePredicate("! delete");
def(AST_UnaryPrefix, function() {
return unary[this.operator];
});
})(function(node, func) {
node.DEFMETHOD("is_boolean", func);
});
// methods to determine if an expression has a numeric result type
(function(def) {
def(AST_Node, return_false);
var binary = makePredicate("- * / % ** & | ^ << >> >>>");
def(AST_Assign, function(compressor) {
return binary[this.operator.slice(0, -1)]
|| this.operator == "=" && this.right.is_number(compressor);
});
def(AST_Binary, function(compressor) {
if (binary[this.operator]) return true;
if (this.operator != "+") return false;
return (this.left.is_boolean(compressor) || this.left.is_number(compressor))
&& (this.right.is_boolean(compressor) || this.right.is_number(compressor));
});
var fn = makePredicate([
"charCodeAt",
"getDate",
"getDay",
"getFullYear",
"getHours",
"getMilliseconds",
"getMinutes",
"getMonth",
"getSeconds",
"getTime",
"getTimezoneOffset",
"getUTCDate",
"getUTCDay",
"getUTCFullYear",
"getUTCHours",
"getUTCMilliseconds",
"getUTCMinutes",
"getUTCMonth",
"getUTCSeconds",
"getYear",
"indexOf",
"lastIndexOf",
"localeCompare",
"push",
"search",
"setDate",
"setFullYear",
"setHours",
"setMilliseconds",
"setMinutes",
"setMonth",
"setSeconds",
"setTime",
"setUTCDate",
"setUTCFullYear",
"setUTCHours",
"setUTCMilliseconds",
"setUTCMinutes",
"setUTCMonth",
"setUTCSeconds",
"setYear",
]);
def(AST_Call, function(compressor) {
if (!compressor.option("unsafe")) return false;
var exp = this.expression;
return exp instanceof AST_Dot && (fn[exp.property]
|| is_undeclared_ref(exp.expression) && exp.expression.name == "Math");
});
def(AST_Conditional, function(compressor) {
return this.consequent.is_number(compressor) && this.alternative.is_number(compressor);
});
def(AST_New, return_false);
def(AST_Number, return_true);
def(AST_Sequence, function(compressor) {
return this.tail_node().is_number(compressor);
});
2022-03-14 15:40:45 +00:00
def(AST_SymbolRef, function(compressor, keep_unary) {
2022-01-21 08:28:41 +00:00
var fixed = this.fixed_value();
if (!fixed) return false;
2022-03-14 15:40:45 +00:00
if (keep_unary
&& fixed instanceof AST_UnaryPrefix
&& fixed.operator == "+"
2022-08-05 07:44:52 +00:00
&& fixed.expression.equals(this)) {
2022-03-14 15:40:45 +00:00
return false;
}
2022-01-21 08:28:41 +00:00
this.is_number = return_false;
var result = fixed.is_number(compressor);
delete this.is_number;
return result;
});
var unary = makePredicate("+ - ~ ++ --");
def(AST_Unary, function() {
return unary[this.operator];
});
})(function(node, func) {
node.DEFMETHOD("is_number", func);
});
// methods to determine if an expression has a string result type
(function(def) {
def(AST_Node, return_false);
def(AST_Assign, function(compressor) {
switch (this.operator) {
case "+=":
if (this.left.is_string(compressor)) return true;
case "=":
return this.right.is_string(compressor);
}
});
def(AST_Binary, function(compressor) {
return this.operator == "+" &&
(this.left.is_string(compressor) || this.right.is_string(compressor));
});
var fn = makePredicate([
"charAt",
"substr",
"substring",
2022-03-14 15:40:45 +00:00
"toExponential",
"toFixed",
2022-01-21 08:28:41 +00:00
"toLowerCase",
2022-03-14 15:40:45 +00:00
"toPrecision",
2022-01-21 08:28:41 +00:00
"toString",
"toUpperCase",
"trim",
]);
def(AST_Call, function(compressor) {
if (!compressor.option("unsafe")) return false;
var exp = this.expression;
return exp instanceof AST_Dot && fn[exp.property];
});
def(AST_Conditional, function(compressor) {
return this.consequent.is_string(compressor) && this.alternative.is_string(compressor);
});
def(AST_Sequence, function(compressor) {
return this.tail_node().is_string(compressor);
});
def(AST_String, return_true);
def(AST_SymbolRef, function(compressor) {
var fixed = this.fixed_value();
if (!fixed) return false;
this.is_string = return_false;
var result = fixed.is_string(compressor);
delete this.is_string;
return result;
});
def(AST_Template, function(compressor) {
return !this.tag || is_raw_tag(compressor, this.tag);
});
def(AST_UnaryPrefix, function() {
return this.operator == "typeof";
});
})(function(node, func) {
node.DEFMETHOD("is_string", func);
});
var lazy_op = makePredicate("&& || ??");
(function(def) {
function to_node(value, orig) {
if (value instanceof AST_Node) return value.clone(true);
if (Array.isArray(value)) return make_node(AST_Array, orig, {
elements: value.map(function(value) {
return to_node(value, orig);
})
});
if (value && typeof value == "object") {
var props = [];
for (var key in value) if (HOP(value, key)) {
props.push(make_node(AST_ObjectKeyVal, orig, {
key: key,
2022-08-31 14:34:36 +00:00
value: to_node(value[key], orig),
2022-01-21 08:28:41 +00:00
}));
}
2022-08-31 14:34:36 +00:00
return make_node(AST_Object, orig, { properties: props });
2022-01-21 08:28:41 +00:00
}
return make_node_from_constant(value, orig);
}
function warn(node) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("global_defs {this} redefined [{start}]", node);
2022-01-21 08:28:41 +00:00
}
AST_Toplevel.DEFMETHOD("resolve_defines", function(compressor) {
if (!compressor.option("global_defs")) return this;
this.figure_out_scope({ ie: compressor.option("ie") });
return this.transform(new TreeTransformer(function(node) {
var def = node._find_defs(compressor, "");
if (!def) return;
var level = 0, child = node, parent;
while (parent = this.parent(level++)) {
if (!(parent instanceof AST_PropAccess)) break;
if (parent.expression !== child) break;
child = parent;
}
if (is_lhs(child, parent)) {
warn(node);
return;
}
return def;
}));
});
def(AST_Node, noop);
def(AST_Dot, function(compressor, suffix) {
return this.expression._find_defs(compressor, "." + this.property + suffix);
});
def(AST_SymbolDeclaration, function(compressor) {
if (!this.definition().global) return;
if (HOP(compressor.option("global_defs"), this.name)) warn(this);
});
def(AST_SymbolRef, function(compressor, suffix) {
if (!this.definition().global) return;
var defines = compressor.option("global_defs");
var name = this.name + suffix;
if (HOP(defines, name)) return to_node(defines[name], this);
});
})(function(node, func) {
node.DEFMETHOD("_find_defs", func);
});
function best_of_expression(ast1, ast2, threshold) {
var delta = ast2.print_to_string().length - ast1.print_to_string().length;
return delta < (threshold || 0) ? ast2 : ast1;
}
function best_of_statement(ast1, ast2, threshold) {
return best_of_expression(make_node(AST_SimpleStatement, ast1, {
2022-08-05 07:44:52 +00:00
body: ast1,
2022-01-21 08:28:41 +00:00
}), make_node(AST_SimpleStatement, ast2, {
2022-08-05 07:44:52 +00:00
body: ast2,
2022-01-21 08:28:41 +00:00
}), threshold).body;
}
function best_of(compressor, ast1, ast2, threshold) {
return (first_in_statement(compressor) ? best_of_statement : best_of_expression)(ast1, ast2, threshold);
}
function convert_to_predicate(obj) {
var map = Object.create(null);
Object.keys(obj).forEach(function(key) {
map[key] = makePredicate(obj[key]);
});
return map;
}
function skip_directives(body) {
for (var i = 0; i < body.length; i++) {
var stat = body[i];
if (!(stat instanceof AST_Directive)) return stat;
}
}
function arrow_first_statement() {
2022-08-31 14:34:36 +00:00
if (this.value) return make_node(AST_Return, this.value, { value: this.value });
2022-01-21 08:28:41 +00:00
return skip_directives(this.body);
}
AST_Arrow.DEFMETHOD("first_statement", arrow_first_statement);
AST_AsyncArrow.DEFMETHOD("first_statement", arrow_first_statement);
AST_Lambda.DEFMETHOD("first_statement", function() {
return skip_directives(this.body);
});
AST_Lambda.DEFMETHOD("length", function() {
var argnames = this.argnames;
for (var i = 0; i < argnames.length; i++) {
if (argnames[i] instanceof AST_DefaultValue) break;
}
return i;
});
function try_evaluate(compressor, node) {
var ev = node.evaluate(compressor);
if (ev === node) return node;
ev = make_node_from_constant(ev, node).optimize(compressor);
return best_of(compressor, node, ev, compressor.eval_threshold);
}
var object_fns = [
"constructor",
"toString",
"valueOf",
];
var native_fns = convert_to_predicate({
Array: [
"indexOf",
"join",
"lastIndexOf",
"slice",
].concat(object_fns),
Boolean: object_fns,
Function: object_fns,
Number: [
"toExponential",
"toFixed",
"toPrecision",
].concat(object_fns),
Object: object_fns,
RegExp: [
"exec",
"test",
].concat(object_fns),
String: [
"charAt",
"charCodeAt",
"concat",
"indexOf",
"italics",
"lastIndexOf",
"match",
"replace",
"search",
"slice",
"split",
"substr",
"substring",
"toLowerCase",
"toUpperCase",
"trim",
].concat(object_fns),
});
var static_fns = convert_to_predicate({
Array: [
"isArray",
],
Math: [
"abs",
"acos",
"asin",
"atan",
"ceil",
"cos",
"exp",
"floor",
"log",
"round",
"sin",
"sqrt",
"tan",
"atan2",
"pow",
"max",
"min",
],
Number: [
"isFinite",
"isNaN",
],
Object: [
"create",
"getOwnPropertyDescriptor",
"getOwnPropertyNames",
"getPrototypeOf",
"isExtensible",
"isFrozen",
"isSealed",
"keys",
],
String: [
"fromCharCode",
"raw",
],
});
function is_static_fn(node) {
if (!(node instanceof AST_Dot)) return false;
var expr = node.expression;
if (!is_undeclared_ref(expr)) return false;
var static_fn = static_fns[expr.name];
return static_fn && (static_fn[node.property] || expr.name == "Math" && node.property == "random");
}
2022-10-10 08:26:02 +00:00
// Accommodate when compress option evaluate=false
2022-01-21 08:28:41 +00:00
// as well as the common constant expressions !0 and -1
(function(def) {
def(AST_Node, return_false);
def(AST_Constant, return_true);
def(AST_RegExp, return_false);
var unaryPrefix = makePredicate("! ~ - + void");
def(AST_UnaryPrefix, function() {
return unaryPrefix[this.operator] && this.expression instanceof AST_Constant;
});
})(function(node, func) {
node.DEFMETHOD("is_constant", func);
});
// methods to evaluate a constant expression
(function(def) {
// If the node has been successfully reduced to a constant,
// then its value is returned; otherwise the element itself
// is returned.
//
// They can be distinguished as constant value is never a
// descendant of AST_Node.
//
// When `ignore_side_effects` is `true`, inspect the constant value
// produced without worrying about any side effects caused by said
// expression.
AST_Node.DEFMETHOD("evaluate", function(compressor, ignore_side_effects) {
if (!compressor.option("evaluate")) return this;
var cached = [];
var val = this._eval(compressor, ignore_side_effects, cached, 1);
cached.forEach(function(node) {
delete node._eval;
});
if (ignore_side_effects) return val;
if (!val || val instanceof RegExp) return val;
if (typeof val == "function" || typeof val == "object") return this;
return val;
});
var scan_modified = new TreeWalker(function(node) {
if (node instanceof AST_Assign) modified(node.left);
2022-04-11 08:07:00 +00:00
if (node instanceof AST_ForEnumeration) modified(node.init);
2022-01-21 08:28:41 +00:00
if (node instanceof AST_Unary && UNARY_POSTFIX[node.operator]) modified(node.expression);
});
function modified(node) {
if (node instanceof AST_DestructuredArray) {
node.elements.forEach(modified);
} else if (node instanceof AST_DestructuredObject) {
node.properties.forEach(function(prop) {
modified(prop.value);
});
} else if (node instanceof AST_PropAccess) {
modified(node.expression);
} else if (node instanceof AST_SymbolRef) {
node.definition().references.forEach(function(ref) {
delete ref._eval;
});
}
}
def(AST_Statement, function() {
2022-08-31 14:34:36 +00:00
throw new Error(string_template("Cannot evaluate a statement [{start}]", this));
2022-01-21 08:28:41 +00:00
});
def(AST_Accessor, return_this);
def(AST_BigInt, return_this);
def(AST_Class, return_this);
def(AST_Node, return_this);
def(AST_Constant, function() {
return this.value;
});
def(AST_Assign, function(compressor, ignore_side_effects, cached, depth) {
var lhs = this.left;
if (!ignore_side_effects) {
if (!(lhs instanceof AST_SymbolRef)) return this;
if (!HOP(lhs, "_eval")) {
if (!lhs.fixed) return this;
var def = lhs.definition();
if (!def.fixed) return this;
if (def.undeclared) return this;
if (def.last_ref !== lhs) return this;
if (def.single_use == "m") return this;
2022-08-05 07:44:52 +00:00
if (this.right.has_side_effects(compressor)) return this;
2022-01-21 08:28:41 +00:00
}
}
var op = this.operator;
var node;
if (!HOP(lhs, "_eval") && lhs instanceof AST_SymbolRef && lhs.fixed && lhs.definition().fixed) {
node = lhs;
} else if (op == "=") {
node = this.right;
} else {
node = make_node(AST_Binary, this, {
operator: op.slice(0, -1),
left: lhs,
right: this.right,
});
}
lhs.walk(scan_modified);
var value = node._eval(compressor, ignore_side_effects, cached, depth);
if (typeof value == "object") return this;
modified(lhs);
return value;
});
def(AST_Sequence, function(compressor, ignore_side_effects, cached, depth) {
if (!ignore_side_effects) return this;
var exprs = this.expressions;
for (var i = 0, last = exprs.length - 1; i < last; i++) {
exprs[i].walk(scan_modified);
}
var tail = exprs[last];
var value = tail._eval(compressor, ignore_side_effects, cached, depth);
return value === tail ? this : value;
});
def(AST_Lambda, function(compressor) {
if (compressor.option("unsafe")) {
var fn = function() {};
fn.node = this;
fn.toString = function() {
return "function(){}";
};
return fn;
}
return this;
});
def(AST_Array, function(compressor, ignore_side_effects, cached, depth) {
if (compressor.option("unsafe")) {
var elements = [];
for (var i = 0; i < this.elements.length; i++) {
var element = this.elements[i];
if (element instanceof AST_Hole) return this;
var value = element._eval(compressor, ignore_side_effects, cached, depth);
if (element === value) return this;
elements.push(value);
}
return elements;
}
return this;
});
def(AST_Object, function(compressor, ignore_side_effects, cached, depth) {
if (compressor.option("unsafe")) {
var val = {};
for (var i = 0; i < this.properties.length; i++) {
var prop = this.properties[i];
if (!(prop instanceof AST_ObjectKeyVal)) return this;
var key = prop.key;
if (key instanceof AST_Node) {
key = key._eval(compressor, ignore_side_effects, cached, depth);
if (key === prop.key) return this;
}
switch (key) {
case "__proto__":
case "toString":
case "valueOf":
return this;
}
val[key] = prop.value._eval(compressor, ignore_side_effects, cached, depth);
if (val[key] === prop.value) return this;
}
return val;
}
return this;
});
var non_converting_unary = makePredicate("! typeof void");
def(AST_UnaryPrefix, function(compressor, ignore_side_effects, cached, depth) {
var e = this.expression;
var op = this.operator;
// Function would be evaluated to an array and so typeof would
// incorrectly return "object". Hence making is a special case.
if (compressor.option("typeofs")
&& op == "typeof"
&& (e instanceof AST_Lambda
|| e instanceof AST_SymbolRef
&& e.fixed_value() instanceof AST_Lambda)) {
return typeof function(){};
}
var def = e instanceof AST_SymbolRef && e.definition();
if (!non_converting_unary[op] && !(def && def.fixed)) depth++;
e.walk(scan_modified);
var v = e._eval(compressor, ignore_side_effects, cached, depth);
if (v === e) {
if (ignore_side_effects && op == "void") return;
return this;
}
switch (op) {
case "!": return !v;
case "typeof":
// typeof <RegExp> returns "object" or "function" on different platforms
// so cannot evaluate reliably
if (v instanceof RegExp) return this;
return typeof v;
case "void": return;
case "~": return ~v;
case "-": return -v;
case "+": return +v;
case "++":
case "--":
if (!def) return this;
if (!ignore_side_effects) {
if (def.undeclared) return this;
if (def.last_ref !== e) return this;
}
if (HOP(e, "_eval")) v = +(op[0] + 1) + +v;
modified(e);
return v;
}
return this;
});
def(AST_UnaryPostfix, function(compressor, ignore_side_effects, cached, depth) {
var e = this.expression;
if (!(e instanceof AST_SymbolRef)) {
if (!ignore_side_effects) return this;
} else if (!HOP(e, "_eval")) {
if (!e.fixed) return this;
if (!ignore_side_effects) {
var def = e.definition();
if (!def.fixed) return this;
if (def.undeclared) return this;
if (def.last_ref !== e) return this;
}
}
if (!(e instanceof AST_SymbolRef && e.definition().fixed)) depth++;
e.walk(scan_modified);
var v = e._eval(compressor, ignore_side_effects, cached, depth);
if (v === e) return this;
modified(e);
return +v;
});
var non_converting_binary = makePredicate("&& || === !==");
def(AST_Binary, function(compressor, ignore_side_effects, cached, depth) {
if (!non_converting_binary[this.operator]) depth++;
var left = this.left._eval(compressor, ignore_side_effects, cached, depth);
if (left === this.left) return this;
if (this.operator == (left ? "||" : "&&")) return left;
var rhs_ignore_side_effects = ignore_side_effects && !(left && typeof left == "object");
var right = this.right._eval(compressor, rhs_ignore_side_effects, cached, depth);
if (right === this.right) return this;
var result;
switch (this.operator) {
case "&&" : result = left && right; break;
case "||" : result = left || right; break;
case "??" :
result = left == null ? right : left;
break;
case "|" : result = left | right; break;
case "&" : result = left & right; break;
case "^" : result = left ^ right; break;
case "+" : result = left + right; break;
case "-" : result = left - right; break;
case "*" : result = left * right; break;
case "/" : result = left / right; break;
case "%" : result = left % right; break;
case "<<" : result = left << right; break;
case ">>" : result = left >> right; break;
case ">>>": result = left >>> right; break;
case "==" : result = left == right; break;
case "===": result = left === right; break;
case "!=" : result = left != right; break;
case "!==": result = left !== right; break;
case "<" : result = left < right; break;
case "<=" : result = left <= right; break;
case ">" : result = left > right; break;
case ">=" : result = left >= right; break;
case "**":
result = Math.pow(left, right);
break;
case "in":
if (right && typeof right == "object" && HOP(right, left)) {
result = true;
break;
}
default:
return this;
}
if (isNaN(result)) return compressor.find_parent(AST_With) ? this : result;
if (compressor.option("unsafe_math")
&& !ignore_side_effects
&& result
&& typeof result == "number"
&& (this.operator == "+" || this.operator == "-")) {
var digits = Math.max(0, decimals(left), decimals(right));
// 53-bit significand ---> 15.95 decimal places
if (digits < 16) return +result.toFixed(digits);
}
return result;
function decimals(operand) {
2022-02-07 14:48:46 +00:00
var match = /(\.[0-9]*)?(e[^e]+)?$/.exec(+operand);
2022-01-21 08:28:41 +00:00
return (match[1] || ".").length - 1 - (match[2] || "").slice(1);
}
});
def(AST_Conditional, function(compressor, ignore_side_effects, cached, depth) {
var condition = this.condition._eval(compressor, ignore_side_effects, cached, depth);
if (condition === this.condition) return this;
var node = condition ? this.consequent : this.alternative;
var value = node._eval(compressor, ignore_side_effects, cached, depth);
return value === node ? this : value;
});
function verify_escaped(ref, depth) {
var escaped = ref.definition().escaped;
switch (escaped.length) {
case 0:
return true;
case 1:
var found = false;
escaped[0].walk(new TreeWalker(function(node) {
if (found) return true;
if (node === ref) return found = true;
if (node instanceof AST_Scope) return true;
}));
return found;
default:
return depth <= escaped.depth;
}
}
def(AST_SymbolRef, function(compressor, ignore_side_effects, cached, depth) {
var fixed = this.fixed_value();
if (!fixed) return this;
var value;
if (HOP(fixed, "_eval")) {
value = fixed._eval();
} else {
this._eval = return_this;
value = fixed._eval(compressor, ignore_side_effects, cached, depth);
delete this._eval;
if (value === fixed) return this;
fixed._eval = function() {
return value;
};
cached.push(fixed);
}
return value && typeof value == "object" && !verify_escaped(this, depth) ? this : value;
});
var global_objs = {
Array: Array,
Math: Math,
Number: Number,
Object: Object,
String: String,
};
var static_values = convert_to_predicate({
Math: [
"E",
"LN10",
"LN2",
"LOG2E",
"LOG10E",
"PI",
"SQRT1_2",
"SQRT2",
],
Number: [
"MAX_VALUE",
"MIN_VALUE",
"NaN",
"NEGATIVE_INFINITY",
"POSITIVE_INFINITY",
],
});
var regexp_props = makePredicate("global ignoreCase multiline source");
def(AST_PropAccess, function(compressor, ignore_side_effects, cached, depth) {
if (compressor.option("unsafe")) {
var val;
var exp = this.expression;
if (!is_undeclared_ref(exp)) {
val = exp._eval(compressor, ignore_side_effects, cached, depth + 1);
if (val == null || val === exp) return this;
}
var key = this.property;
if (key instanceof AST_Node) {
key = key._eval(compressor, ignore_side_effects, cached, depth);
if (key === this.property) return this;
}
if (val === undefined) {
var static_value = static_values[exp.name];
if (!static_value || !static_value[key]) return this;
val = global_objs[exp.name];
} else if (val instanceof RegExp) {
if (!regexp_props[key]) return this;
} else if (typeof val == "object") {
if (!HOP(val, key)) return this;
} else if (typeof val == "function") switch (key) {
case "name":
return val.node.name ? val.node.name.name : "";
case "length":
return val.node.length();
default:
return this;
}
return val[key];
}
return this;
});
function eval_all(nodes, compressor, ignore_side_effects, cached, depth) {
var values = [];
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
var value = node._eval(compressor, ignore_side_effects, cached, depth);
if (node === value) return;
values.push(value);
}
return values;
}
def(AST_Call, function(compressor, ignore_side_effects, cached, depth) {
var exp = this.expression;
var fn = exp instanceof AST_SymbolRef ? exp.fixed_value() : exp;
if (fn instanceof AST_Arrow || fn instanceof AST_Defun || fn instanceof AST_Function) {
if (fn.evaluating) return this;
if (fn.name && fn.name.definition().recursive_refs > 0) return this;
if (this.is_expr_pure(compressor)) return this;
var args = eval_all(this.args, compressor, ignore_side_effects, cached, depth);
if (!all(fn.argnames, function(sym, index) {
if (sym instanceof AST_DefaultValue) {
if (!args) return false;
if (args[index] === undefined) {
var value = sym.value._eval(compressor, ignore_side_effects, cached, depth);
if (value === sym.value) return false;
args[index] = value;
}
sym = sym.name;
}
return !(sym instanceof AST_Destructured);
})) return this;
if (fn.rest instanceof AST_Destructured) return this;
if (!args && !ignore_side_effects) return this;
var stat = fn.first_statement();
if (!(stat instanceof AST_Return)) {
if (ignore_side_effects) {
fn.walk(scan_modified);
var found = false;
fn.evaluating = true;
walk_body(fn, new TreeWalker(function(node) {
if (found) return true;
if (node instanceof AST_Return) {
if (node.value && node.value._eval(compressor, true, cached, depth) !== undefined) {
found = true;
}
return true;
}
if (node instanceof AST_Scope && node !== fn) return true;
}));
fn.evaluating = false;
if (!found) return;
}
return this;
}
var val = stat.value;
if (!val) return;
var cached_args = [];
if (!args || all(fn.argnames, function(sym, i) {
return assign(sym, args[i]);
}) && !(fn.rest && !assign(fn.rest, args.slice(fn.argnames.length))) || ignore_side_effects) {
if (ignore_side_effects) fn.argnames.forEach(function(sym) {
if (sym instanceof AST_DefaultValue) sym.value.walk(scan_modified);
});
fn.evaluating = true;
val = val._eval(compressor, ignore_side_effects, cached, depth);
fn.evaluating = false;
}
cached_args.forEach(function(node) {
delete node._eval;
});
return val === stat.value ? this : val;
} else if (compressor.option("unsafe") && exp instanceof AST_PropAccess) {
var key = exp.property;
if (key instanceof AST_Node) {
key = key._eval(compressor, ignore_side_effects, cached, depth);
if (key === exp.property) return this;
}
var val;
var e = exp.expression;
if (is_undeclared_ref(e)) {
var static_fn = static_fns[e.name];
if (!static_fn || !static_fn[key]) return this;
val = global_objs[e.name];
} else {
val = e._eval(compressor, ignore_side_effects, cached, depth + 1);
if (val == null || val === e) return this;
var native_fn = native_fns[val.constructor.name];
if (!native_fn || !native_fn[key]) return this;
if (val instanceof RegExp && val.global && !(e instanceof AST_RegExp)) return this;
}
var args = eval_all(this.args, compressor, ignore_side_effects, cached, depth);
if (!args) return this;
if (key == "replace" && typeof args[1] == "function") return this;
try {
return val[key].apply(val, args);
} catch (ex) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Error evaluating {this} [{start}]", this);
2022-01-21 08:28:41 +00:00
} finally {
if (val instanceof RegExp) val.lastIndex = 0;
}
}
return this;
function assign(sym, arg) {
if (sym instanceof AST_DefaultValue) sym = sym.name;
var def = sym.definition();
if (def.orig[def.orig.length - 1] !== sym) return false;
var value = arg;
def.references.forEach(function(node) {
node._eval = function() {
return value;
};
cached_args.push(node);
});
return true;
}
});
def(AST_New, return_this);
def(AST_Template, function(compressor, ignore_side_effects, cached, depth) {
if (!compressor.option("templates")) return this;
if (this.tag) {
if (!is_raw_tag(compressor, this.tag)) return this;
decode = function(str) {
return str;
};
}
var exprs = eval_all(this.expressions, compressor, ignore_side_effects, cached, depth);
if (!exprs) return this;
var malformed = false;
var ret = decode(this.strings[0]);
for (var i = 0; i < exprs.length; i++) {
ret += exprs[i] + decode(this.strings[i + 1]);
}
if (!malformed) return ret;
this._eval = return_this;
return this;
function decode(str) {
str = decode_template(str);
if (typeof str != "string") malformed = true;
return str;
}
});
})(function(node, func) {
node.DEFMETHOD("_eval", func);
});
// method to negate an expression
(function(def) {
function basic_negation(exp) {
return make_node(AST_UnaryPrefix, exp, {
operator: "!",
2022-08-05 07:44:52 +00:00
expression: exp,
2022-01-21 08:28:41 +00:00
});
}
function best(orig, alt, first_in_statement) {
var negated = basic_negation(orig);
2022-08-05 07:44:52 +00:00
if (first_in_statement) return best_of_expression(negated, make_node(AST_SimpleStatement, alt, {
body: alt,
})) === negated ? negated : alt;
2022-01-21 08:28:41 +00:00
return best_of_expression(negated, alt);
}
def(AST_Node, function() {
return basic_negation(this);
});
def(AST_Statement, function() {
throw new Error("Cannot negate a statement");
});
def(AST_Binary, function(compressor, first_in_statement) {
var self = this.clone(), op = this.operator;
if (compressor.option("unsafe_comps")) {
switch (op) {
case "<=" : self.operator = ">" ; return self;
case "<" : self.operator = ">=" ; return self;
case ">=" : self.operator = "<" ; return self;
case ">" : self.operator = "<=" ; return self;
}
}
switch (op) {
case "==" : self.operator = "!="; return self;
case "!=" : self.operator = "=="; return self;
case "===": self.operator = "!=="; return self;
case "!==": self.operator = "==="; return self;
case "&&":
self.operator = "||";
self.left = self.left.negate(compressor, first_in_statement);
self.right = self.right.negate(compressor);
return best(this, self, first_in_statement);
case "||":
self.operator = "&&";
self.left = self.left.negate(compressor, first_in_statement);
self.right = self.right.negate(compressor);
return best(this, self, first_in_statement);
}
return basic_negation(this);
});
def(AST_ClassExpression, function() {
return basic_negation(this);
});
def(AST_Conditional, function(compressor, first_in_statement) {
var self = this.clone();
self.consequent = self.consequent.negate(compressor);
self.alternative = self.alternative.negate(compressor);
return best(this, self, first_in_statement);
});
def(AST_LambdaExpression, function() {
return basic_negation(this);
});
def(AST_Sequence, function(compressor) {
var expressions = this.expressions.slice();
expressions.push(expressions.pop().negate(compressor));
return make_sequence(this, expressions);
});
def(AST_UnaryPrefix, function() {
if (this.operator == "!")
return this.expression;
return basic_negation(this);
});
})(function(node, func) {
node.DEFMETHOD("negate", function(compressor, first_in_statement) {
return func.call(this, compressor, first_in_statement);
});
});
var global_pure_fns = makePredicate("Boolean decodeURI decodeURIComponent Date encodeURI encodeURIComponent Error escape EvalError isFinite isNaN Number Object parseFloat parseInt RangeError ReferenceError String SyntaxError TypeError unescape URIError");
var global_pure_constructors = makePredicate("Map Set WeakMap WeakSet");
AST_Call.DEFMETHOD("is_expr_pure", function(compressor) {
if (compressor.option("unsafe")) {
var expr = this.expression;
if (is_undeclared_ref(expr)) {
if (global_pure_fns[expr.name]) return true;
if (this instanceof AST_New && global_pure_constructors[expr.name]) return true;
}
if (is_static_fn(expr)) return true;
}
return compressor.option("annotations") && this.pure || !compressor.pure_funcs(this);
});
AST_Template.DEFMETHOD("is_expr_pure", function(compressor) {
var tag = this.tag;
if (!tag) return true;
if (compressor.option("unsafe")) {
if (is_undeclared_ref(tag) && global_pure_fns[tag.name]) return true;
if (tag instanceof AST_Dot && is_undeclared_ref(tag.expression)) {
var static_fn = static_fns[tag.expression.name];
return static_fn && (static_fn[tag.property]
|| tag.expression.name == "Math" && tag.property == "random");
}
}
return !compressor.pure_funcs(this);
});
AST_Node.DEFMETHOD("is_call_pure", return_false);
AST_Call.DEFMETHOD("is_call_pure", function(compressor) {
if (!compressor.option("unsafe")) return false;
var dot = this.expression;
if (!(dot instanceof AST_Dot)) return false;
var exp = dot.expression;
var map;
var prop = dot.property;
if (exp instanceof AST_Array) {
map = native_fns.Array;
} else if (exp.is_boolean(compressor)) {
map = native_fns.Boolean;
} else if (exp.is_number(compressor)) {
map = native_fns.Number;
} else if (exp instanceof AST_RegExp) {
map = native_fns.RegExp;
} else if (exp.is_string(compressor)) {
map = native_fns.String;
if (prop == "replace") {
var arg = this.args[1];
if (arg && !arg.is_string(compressor)) return false;
}
} else if (!dot.may_throw_on_access(compressor)) {
map = native_fns.Object;
}
return map && map[prop];
});
2022-02-07 14:48:46 +00:00
// determine if object spread syntax may cause runtime exception
(function(def) {
def(AST_Node, return_false);
def(AST_Array, return_true);
def(AST_Assign, function() {
switch (this.operator) {
case "=":
return this.right.safe_to_spread();
case "&&=":
case "||=":
case "??=":
return this.left.safe_to_spread() && this.right.safe_to_spread();
}
return true;
});
def(AST_Binary, function() {
return !lazy_op[this.operator] || this.left.safe_to_spread() && this.right.safe_to_spread();
});
def(AST_Constant, return_true);
def(AST_Lambda, return_true);
def(AST_Object, function() {
return all(this.properties, function(prop) {
2022-01-21 08:28:41 +00:00
return !(prop instanceof AST_ObjectGetter || prop instanceof AST_Spread);
2022-02-07 14:48:46 +00:00
});
});
def(AST_Sequence, function() {
return this.tail_node().safe_to_spread();
});
def(AST_SymbolRef, function() {
var fixed = this.fixed_value();
return fixed && fixed.safe_to_spread();
});
def(AST_Unary, return_true);
})(function(node, func) {
node.DEFMETHOD("safe_to_spread", func);
});
2022-01-21 08:28:41 +00:00
// determine if expression has side effects
(function(def) {
function any(list, compressor, spread) {
return !all(list, spread ? function(node) {
return node instanceof AST_Spread ? !spread(node, compressor) : !node.has_side_effects(compressor);
} : function(node) {
return !node.has_side_effects(compressor);
});
}
function array_spread(node, compressor) {
2022-02-07 14:48:46 +00:00
var exp = node.expression;
return !exp.is_string(compressor) || exp.has_side_effects(compressor);
2022-01-21 08:28:41 +00:00
}
def(AST_Node, return_true);
def(AST_Array, function(compressor) {
return any(this.elements, compressor, array_spread);
});
def(AST_Assign, function(compressor) {
var lhs = this.left;
if (!(lhs instanceof AST_PropAccess)) return true;
var node = lhs.expression;
return !(node instanceof AST_ObjectIdentity)
|| !node.scope.resolve().new
|| lhs instanceof AST_Sub && lhs.property.has_side_effects(compressor)
|| this.right.has_side_effects(compressor);
});
def(AST_Binary, function(compressor) {
return this.left.has_side_effects(compressor)
|| this.right.has_side_effects(compressor)
2022-07-11 11:25:19 +00:00
|| !can_drop_op(this.operator, this.right, compressor);
2022-01-21 08:28:41 +00:00
});
def(AST_Block, function(compressor) {
return any(this.body, compressor);
});
def(AST_Call, function(compressor) {
if (!this.is_expr_pure(compressor)
&& (!this.is_call_pure(compressor) || this.expression.has_side_effects(compressor))) {
return true;
}
return any(this.args, compressor, array_spread);
});
def(AST_Case, function(compressor) {
return this.expression.has_side_effects(compressor)
|| any(this.body, compressor);
});
def(AST_Class, function(compressor) {
var base = this.extends;
if (base) {
if (base instanceof AST_SymbolRef) base = base.fixed_value();
if (!safe_for_extends(base)) return true;
}
return any(this.properties, compressor);
});
def(AST_ClassProperty, function(compressor) {
return this.key instanceof AST_Node && this.key.has_side_effects(compressor)
|| this.static && this.value && this.value.has_side_effects(compressor);
});
def(AST_Conditional, function(compressor) {
return this.condition.has_side_effects(compressor)
|| this.consequent.has_side_effects(compressor)
|| this.alternative.has_side_effects(compressor);
});
def(AST_Constant, return_false);
def(AST_Definitions, function(compressor) {
return any(this.definitions, compressor);
});
def(AST_DestructuredArray, function(compressor) {
return any(this.elements, compressor);
});
def(AST_DestructuredKeyVal, function(compressor) {
return this.key instanceof AST_Node && this.key.has_side_effects(compressor)
|| this.value.has_side_effects(compressor);
});
def(AST_DestructuredObject, function(compressor) {
return any(this.properties, compressor);
});
def(AST_Dot, function(compressor) {
2022-02-07 14:48:46 +00:00
return this.expression.may_throw_on_access(compressor)
2022-01-21 08:28:41 +00:00
|| this.expression.has_side_effects(compressor);
});
def(AST_EmptyStatement, return_false);
def(AST_If, function(compressor) {
return this.condition.has_side_effects(compressor)
|| this.body && this.body.has_side_effects(compressor)
|| this.alternative && this.alternative.has_side_effects(compressor);
});
def(AST_LabeledStatement, function(compressor) {
return this.body.has_side_effects(compressor);
});
def(AST_Lambda, return_false);
def(AST_Object, function(compressor) {
return any(this.properties, compressor, function(node, compressor) {
var exp = node.expression;
2022-02-07 14:48:46 +00:00
return !exp.safe_to_spread() || exp.has_side_effects(compressor);
2022-01-21 08:28:41 +00:00
});
});
def(AST_ObjectIdentity, return_false);
def(AST_ObjectProperty, function(compressor) {
return this.key instanceof AST_Node && this.key.has_side_effects(compressor)
|| this.value.has_side_effects(compressor);
});
def(AST_Sequence, function(compressor) {
return any(this.expressions, compressor);
});
def(AST_SimpleStatement, function(compressor) {
return this.body.has_side_effects(compressor);
});
def(AST_Sub, function(compressor) {
2022-02-07 14:48:46 +00:00
return this.expression.may_throw_on_access(compressor)
2022-01-21 08:28:41 +00:00
|| this.expression.has_side_effects(compressor)
|| this.property.has_side_effects(compressor);
});
def(AST_Switch, function(compressor) {
return this.expression.has_side_effects(compressor)
|| any(this.body, compressor);
});
def(AST_SymbolDeclaration, return_false);
def(AST_SymbolRef, function(compressor) {
return !this.is_declared(compressor) || !can_drop_symbol(this, compressor);
});
def(AST_Template, function(compressor) {
return !this.is_expr_pure(compressor) || any(this.expressions, compressor);
});
def(AST_Try, function(compressor) {
return any(this.body, compressor)
|| this.bcatch && this.bcatch.has_side_effects(compressor)
|| this.bfinally && this.bfinally.has_side_effects(compressor);
});
def(AST_Unary, function(compressor) {
return unary_side_effects[this.operator]
|| this.expression.has_side_effects(compressor);
});
def(AST_VarDef, function() {
return this.value;
});
})(function(node, func) {
node.DEFMETHOD("has_side_effects", func);
});
// determine if expression may throw
(function(def) {
def(AST_Node, return_true);
def(AST_Constant, return_false);
def(AST_EmptyStatement, return_false);
def(AST_Lambda, return_false);
def(AST_ObjectIdentity, return_false);
def(AST_SymbolDeclaration, return_false);
function any(list, compressor) {
for (var i = list.length; --i >= 0;)
if (list[i].may_throw(compressor))
return true;
return false;
}
function call_may_throw(exp, compressor) {
if (exp.may_throw(compressor)) return true;
if (exp instanceof AST_SymbolRef) exp = exp.fixed_value();
if (!(exp instanceof AST_Lambda)) return true;
if (any(exp.argnames, compressor)) return true;
if (any(exp.body, compressor)) return true;
return is_arrow(exp) && exp.value && exp.value.may_throw(compressor);
}
def(AST_Array, function(compressor) {
return any(this.elements, compressor);
});
def(AST_Assign, function(compressor) {
if (this.right.may_throw(compressor)) return true;
if (!compressor.has_directive("use strict")
&& this.operator == "="
&& this.left instanceof AST_SymbolRef) {
return false;
}
return this.left.may_throw(compressor);
});
2022-02-07 14:48:46 +00:00
def(AST_Await, function(compressor) {
return this.expression.may_throw(compressor);
});
2022-01-21 08:28:41 +00:00
def(AST_Binary, function(compressor) {
return this.left.may_throw(compressor)
|| this.right.may_throw(compressor)
2022-07-11 11:25:19 +00:00
|| !can_drop_op(this.operator, this.right, compressor);
2022-01-21 08:28:41 +00:00
});
def(AST_Block, function(compressor) {
return any(this.body, compressor);
});
def(AST_Call, function(compressor) {
if (any(this.args, compressor)) return true;
if (this.is_expr_pure(compressor)) return false;
this.may_throw = return_true;
var ret = call_may_throw(this.expression, compressor);
delete this.may_throw;
return ret;
});
def(AST_Case, function(compressor) {
return this.expression.may_throw(compressor)
|| any(this.body, compressor);
});
def(AST_Conditional, function(compressor) {
return this.condition.may_throw(compressor)
|| this.consequent.may_throw(compressor)
|| this.alternative.may_throw(compressor);
});
def(AST_DefaultValue, function(compressor) {
return this.name.may_throw(compressor)
|| this.value && this.value.may_throw(compressor);
});
def(AST_Definitions, function(compressor) {
return any(this.definitions, compressor);
});
def(AST_Dot, function(compressor) {
return !this.optional && this.expression.may_throw_on_access(compressor)
|| this.expression.may_throw(compressor);
});
2022-02-07 14:48:46 +00:00
def(AST_ForEnumeration, function(compressor) {
if (this.init.may_throw(compressor)) return true;
var obj = this.object;
if (obj.may_throw(compressor)) return true;
obj = obj.tail_node();
if (!(obj instanceof AST_Array || obj.is_string(compressor))) return true;
return this.body.may_throw(compressor);
});
2022-01-21 08:28:41 +00:00
def(AST_If, function(compressor) {
return this.condition.may_throw(compressor)
|| this.body && this.body.may_throw(compressor)
|| this.alternative && this.alternative.may_throw(compressor);
});
def(AST_LabeledStatement, function(compressor) {
return this.body.may_throw(compressor);
});
def(AST_Object, function(compressor) {
return any(this.properties, compressor);
});
def(AST_ObjectProperty, function(compressor) {
return this.value.may_throw(compressor)
|| this.key instanceof AST_Node && this.key.may_throw(compressor);
});
def(AST_Return, function(compressor) {
return this.value && this.value.may_throw(compressor);
});
def(AST_Sequence, function(compressor) {
return any(this.expressions, compressor);
});
def(AST_SimpleStatement, function(compressor) {
return this.body.may_throw(compressor);
});
def(AST_Sub, function(compressor) {
return !this.optional && this.expression.may_throw_on_access(compressor)
|| this.expression.may_throw(compressor)
|| this.property.may_throw(compressor);
});
def(AST_Switch, function(compressor) {
return this.expression.may_throw(compressor)
|| any(this.body, compressor);
});
def(AST_SymbolRef, function(compressor) {
return !this.is_declared(compressor) || !can_drop_symbol(this, compressor);
});
def(AST_Template, function(compressor) {
if (any(this.expressions, compressor)) return true;
if (this.is_expr_pure(compressor)) return false;
if (!this.tag) return false;
this.may_throw = return_true;
var ret = call_may_throw(this.tag, compressor);
delete this.may_throw;
return ret;
});
def(AST_Try, function(compressor) {
return (this.bcatch ? this.bcatch.may_throw(compressor) : any(this.body, compressor))
|| this.bfinally && this.bfinally.may_throw(compressor);
});
def(AST_Unary, function(compressor) {
return this.expression.may_throw(compressor)
&& !(this.operator == "typeof" && this.expression instanceof AST_SymbolRef);
});
def(AST_VarDef, function(compressor) {
return this.name.may_throw(compressor)
|| this.value && this.value.may_throw(compressor);
});
})(function(node, func) {
node.DEFMETHOD("may_throw", func);
});
// determine if expression is constant
(function(def) {
function all_constant(list, scope) {
for (var i = list.length; --i >= 0;)
if (!list[i].is_constant_expression(scope))
return false;
return true;
}
def(AST_Node, return_false);
def(AST_Array, function(scope) {
return all_constant(this.elements, scope);
});
def(AST_Binary, function(scope) {
return this.left.is_constant_expression(scope)
&& this.right.is_constant_expression(scope)
2022-07-11 11:25:19 +00:00
&& can_drop_op(this.operator, this.right);
2022-01-21 08:28:41 +00:00
});
def(AST_Class, function(scope) {
var base = this.extends;
if (base && !safe_for_extends(base)) return false;
return all_constant(this.properties, scope);
});
def(AST_ClassProperty, function(scope) {
return typeof this.key == "string" && (!this.value || this.value.is_constant_expression(scope));
});
def(AST_Constant, return_true);
def(AST_Lambda, function(scope) {
var self = this;
var result = true;
var scopes = [];
self.walk(new TreeWalker(function(node, descend) {
if (!result) return true;
if (node instanceof AST_BlockScope) {
if (node === self) return;
scopes.push(node);
descend();
scopes.pop();
return true;
}
if (node instanceof AST_SymbolRef) {
2022-08-05 07:44:52 +00:00
if (self.inlined || node.redef || node.in_arg) {
2022-01-21 08:28:41 +00:00
result = false;
return true;
}
if (self.variables.has(node.name)) return true;
var def = node.definition();
if (member(def.scope, scopes)) return true;
if (scope && !def.redefined()) {
var scope_def = scope.find_variable(node.name);
if (scope_def ? scope_def === def : def.undeclared) {
result = "f";
return true;
}
}
result = false;
return true;
}
if (node instanceof AST_ObjectIdentity) {
if (is_arrow(self) && all(scopes, function(s) {
return !(s instanceof AST_Scope) || is_arrow(s);
})) result = false;
return true;
}
}));
return result;
});
def(AST_Object, function(scope) {
return all_constant(this.properties, scope);
});
def(AST_ObjectProperty, function(scope) {
return typeof this.key == "string" && this.value.is_constant_expression(scope);
});
def(AST_Unary, function(scope) {
return this.expression.is_constant_expression(scope);
});
})(function(node, func) {
node.DEFMETHOD("is_constant_expression", func);
});
// tell me if a statement aborts
function aborts(thing) {
return thing && thing.aborts();
}
(function(def) {
def(AST_Statement, return_null);
def(AST_Jump, return_this);
function block_aborts() {
var n = this.body.length;
return n > 0 && aborts(this.body[n - 1]);
}
def(AST_BlockStatement, block_aborts);
def(AST_SwitchBranch, block_aborts);
def(AST_If, function() {
return this.alternative && aborts(this.body) && aborts(this.alternative) && this;
});
})(function(node, func) {
node.DEFMETHOD("aborts", func);
});
/* -----[ optimizers ]----- */
var directives = makePredicate(["use asm", "use strict"]);
OPT(AST_Directive, function(self, compressor) {
if (compressor.option("directives")
&& (!directives[self.value] || compressor.has_directive(self.value) !== self)) {
return make_node(AST_EmptyStatement, self);
}
return self;
});
OPT(AST_Debugger, function(self, compressor) {
if (compressor.option("drop_debugger"))
return make_node(AST_EmptyStatement, self);
return self;
});
OPT(AST_LabeledStatement, function(self, compressor) {
2022-07-11 11:25:19 +00:00
if (self.body instanceof AST_If || self.body instanceof AST_Break) {
var body = tighten_body([ self.body ], compressor);
switch (body.length) {
case 0:
self.body = make_node(AST_EmptyStatement, self);
break;
case 1:
self.body = body[0];
break;
default:
self.body = make_node(AST_BlockStatement, self, { body: body });
break;
}
2022-01-21 08:28:41 +00:00
}
return compressor.option("unused") && self.label.references.length == 0 ? self.body : self;
});
OPT(AST_LoopControl, function(self, compressor) {
if (!compressor.option("dead_code")) return self;
var label = self.label;
if (label) {
var lct = compressor.loopcontrol_target(self);
self.label = null;
if (compressor.loopcontrol_target(self) === lct) {
remove(label.thedef.references, self);
} else {
self.label = label;
}
}
return self;
});
OPT(AST_Block, function(self, compressor) {
self.body = tighten_body(self.body, compressor);
return self;
});
function trim_block(node, parent, in_list) {
switch (node.body.length) {
case 0:
return in_list ? List.skip : make_node(AST_EmptyStatement, node);
case 1:
var stat = node.body[0];
if (!safe_to_trim(stat)) return node;
if (parent instanceof AST_IterationStatement && stat instanceof AST_LambdaDefinition) return node;
return stat;
}
return node;
}
OPT(AST_BlockStatement, function(self, compressor) {
self.body = tighten_body(self.body, compressor);
return trim_block(self, compressor.parent());
});
function drop_rest_farg(fn, compressor) {
if (!compressor.option("rests")) return;
if (fn.uses_arguments) return;
if (!(fn.rest instanceof AST_DestructuredArray)) return;
if (!compressor.drop_fargs(fn, compressor.parent())) return;
fn.argnames = fn.argnames.concat(fn.rest.elements);
fn.rest = fn.rest.rest;
}
OPT(AST_Lambda, function(self, compressor) {
drop_rest_farg(self, compressor);
self.body = tighten_body(self.body, compressor);
return self;
});
function opt_arrow(self, compressor) {
if (!compressor.option("arrows")) return self;
drop_rest_farg(self, compressor);
2022-08-31 14:34:36 +00:00
if (self.value) self.body = [ self.first_statement() ];
var body = tighten_body(self.body, compressor);
2022-01-21 08:28:41 +00:00
switch (body.length) {
case 1:
var stat = body[0];
if (stat instanceof AST_Return) {
self.body.length = 0;
self.value = stat.value;
break;
}
default:
self.body = body;
self.value = null;
break;
}
return self;
}
OPT(AST_Arrow, opt_arrow);
OPT(AST_AsyncArrow, opt_arrow);
OPT(AST_Function, function(self, compressor) {
drop_rest_farg(self, compressor);
self.body = tighten_body(self.body, compressor);
var parent = compressor.parent();
if (compressor.option("inline")) for (var i = 0; i < self.body.length; i++) {
var stat = self.body[i];
if (stat instanceof AST_Directive) continue;
if (stat instanceof AST_Return) {
if (i != self.body.length - 1) break;
var call = stat.value;
if (!call || call.TYPE != "Call") break;
if (call.is_expr_pure(compressor)) break;
2022-09-30 13:48:25 +00:00
var exp = call.expression, fn;
if (!(exp instanceof AST_SymbolRef)) {
fn = exp;
} else if (self.name && self.name.definition() === exp.definition()) {
break;
} else {
fn = exp.fixed_value();
2022-01-21 08:28:41 +00:00
}
if (!(fn instanceof AST_Defun || fn instanceof AST_Function)) break;
if (fn.rest) break;
if (fn.uses_arguments) break;
2022-09-30 13:48:25 +00:00
if (fn === exp) {
2022-01-21 08:28:41 +00:00
if (fn.parent_scope !== self) break;
if (!all(fn.enclosed, function(def) {
return def.scope !== self;
})) break;
}
2022-09-30 13:48:25 +00:00
if ((fn !== exp || fn.name)
2022-01-21 08:28:41 +00:00
&& (parent instanceof AST_ClassMethod || parent instanceof AST_ObjectMethod)
&& parent.value === compressor.self()) break;
if (fn.contains_this()) break;
var len = fn.argnames.length;
if (len > 0 && compressor.option("inline") < 2) break;
if (len > self.argnames.length) break;
if (!all(self.argnames, function(argname) {
return argname instanceof AST_SymbolFunarg;
})) break;
if (!all(call.args, function(arg) {
return !(arg instanceof AST_Spread);
})) break;
for (var j = 0; j < len; j++) {
var arg = call.args[j];
if (!(arg instanceof AST_SymbolRef)) break;
if (arg.definition() !== self.argnames[j].definition()) break;
}
if (j < len) break;
for (; j < call.args.length; j++) {
if (call.args[j].has_side_effects(compressor)) break;
}
if (j < call.args.length) break;
if (len < self.argnames.length && !compressor.drop_fargs(self, parent)) {
if (!compressor.drop_fargs(fn, call)) break;
do {
fn.argnames.push(fn.make_var(AST_SymbolFunarg, fn, "argument_" + len));
} while (++len < self.argnames.length);
}
2022-09-30 13:48:25 +00:00
return exp;
2022-01-21 08:28:41 +00:00
}
break;
}
return self;
});
var NO_MERGE = makePredicate("arguments await yield");
AST_Scope.DEFMETHOD("merge_variables", function(compressor) {
if (!compressor.option("merge_vars")) return;
2022-06-08 10:36:39 +00:00
var in_arg = [], in_try, root, segment = {}, self = this;
2022-01-21 08:28:41 +00:00
var first = [], last = [], index = 0;
var declarations = new Dictionary();
var references = Object.create(null);
var prev = Object.create(null);
var tw = new TreeWalker(function(node, descend) {
if (node instanceof AST_Assign) {
var lhs = node.left;
var rhs = node.right;
if (lhs instanceof AST_Destructured) {
rhs.walk(tw);
2022-06-08 10:36:39 +00:00
walk_destructured(AST_SymbolRef, mark, lhs);
2022-01-21 08:28:41 +00:00
return true;
}
if (lazy_op[node.operator.slice(0, -1)]) {
lhs.walk(tw);
push();
rhs.walk(tw);
if (lhs instanceof AST_SymbolRef) mark(lhs);
pop();
return true;
}
if (lhs instanceof AST_SymbolRef) {
if (node.operator != "=") mark(lhs, true);
rhs.walk(tw);
mark(lhs);
return true;
}
return;
}
if (node instanceof AST_Binary) {
if (!lazy_op[node.operator]) return;
2022-03-14 15:40:45 +00:00
walk_cond(node);
2022-01-21 08:28:41 +00:00
return true;
}
if (node instanceof AST_Break) {
var target = tw.loopcontrol_target(node);
if (!(target instanceof AST_IterationStatement)) insert(target);
return true;
}
if (node instanceof AST_Call) {
var exp = node.expression;
2022-05-29 09:24:36 +00:00
if (exp instanceof AST_LambdaExpression) {
node.args.forEach(function(arg) {
arg.walk(tw);
});
exp.walk(tw);
} else {
2022-01-21 08:28:41 +00:00
descend();
2022-05-29 09:24:36 +00:00
mark_expression(exp);
2022-01-21 08:28:41 +00:00
}
return true;
}
2022-03-14 15:40:45 +00:00
if (node instanceof AST_Class) {
if (node.name) node.name.walk(tw);
if (node.extends) node.extends.walk(tw);
node.properties.filter(function(prop) {
if (prop.key instanceof AST_Node) prop.key.walk(tw);
return prop.value;
}).forEach(function(prop) {
if (prop.static) {
prop.value.walk(tw);
} else {
2022-05-29 09:24:36 +00:00
push();
segment.block = node;
2022-03-14 15:40:45 +00:00
prop.value.walk(tw);
2022-05-29 09:24:36 +00:00
pop();
2022-03-14 15:40:45 +00:00
}
});
return true;
}
2022-01-21 08:28:41 +00:00
if (node instanceof AST_Conditional) {
2022-03-14 15:40:45 +00:00
walk_cond(node.condition, node.consequent, node.alternative);
2022-01-21 08:28:41 +00:00
return true;
}
if (node instanceof AST_Continue) {
var target = tw.loopcontrol_target(node);
if (target instanceof AST_Do) insert(target);
return true;
}
if (node instanceof AST_Do) {
push();
segment.block = node;
segment.loop = true;
var save = segment;
node.body.walk(tw);
if (segment.inserted === node) segment = save;
node.condition.walk(tw);
pop();
return true;
}
if (node instanceof AST_For) {
if (node.init) node.init.walk(tw);
push();
segment.block = node;
segment.loop = true;
if (node.condition) node.condition.walk(tw);
node.body.walk(tw);
if (node.step) node.step.walk(tw);
pop();
return true;
}
if (node instanceof AST_ForEnumeration) {
node.object.walk(tw);
push();
segment.block = node;
segment.loop = true;
node.init.walk(tw);
node.body.walk(tw);
pop();
return true;
}
if (node instanceof AST_If) {
2022-03-14 15:40:45 +00:00
walk_cond(node.condition, node.body, node.alternative);
2022-01-21 08:28:41 +00:00
return true;
}
if (node instanceof AST_LabeledStatement) {
push();
segment.block = node;
var save = segment;
node.body.walk(tw);
if (segment.inserted === node) segment = save;
pop();
return true;
}
if (node instanceof AST_Scope) {
push();
segment.block = node;
if (node === self) root = segment;
if (node instanceof AST_Lambda) {
if (node.name) references[node.name.definition().id] = false;
var marker = node.uses_arguments && !tw.has_directive("use strict") ? function(node) {
2022-06-08 10:36:39 +00:00
references[node.definition().id] = false;
2022-01-21 08:28:41 +00:00
} : function(node) {
2022-06-08 10:36:39 +00:00
mark(node);
2022-01-21 08:28:41 +00:00
};
2022-06-08 10:36:39 +00:00
in_arg.push(node);
2022-01-21 08:28:41 +00:00
node.argnames.forEach(function(argname) {
2022-06-08 10:36:39 +00:00
walk_destructured(AST_SymbolFunarg, marker, argname);
2022-01-21 08:28:41 +00:00
});
2022-06-08 10:36:39 +00:00
if (node.rest) walk_destructured(AST_SymbolFunarg, marker, node.rest);
in_arg.pop();
2022-01-21 08:28:41 +00:00
}
walk_lambda(node, tw);
pop();
return true;
}
if (node instanceof AST_Sub) {
var exp = node.expression;
if (node.optional) {
exp.walk(tw);
push();
node.property.walk(tw);
pop();
} else {
descend();
}
2022-05-29 09:24:36 +00:00
mark_expression(exp);
return true;
2022-01-21 08:28:41 +00:00
}
if (node instanceof AST_Switch) {
node.expression.walk(tw);
var save = segment;
node.body.forEach(function(branch) {
if (branch instanceof AST_Default) return;
branch.expression.walk(tw);
if (save === segment) push();
});
segment = save;
node.body.forEach(function(branch) {
push();
segment.block = node;
var save = segment;
walk_body(branch, tw);
if (segment.inserted === node) segment = save;
pop();
});
return true;
}
if (node instanceof AST_SymbolConst || node instanceof AST_SymbolLet) {
references[node.definition().id] = false;
return true;
}
if (node instanceof AST_SymbolRef) {
mark(node, true);
return true;
}
if (node instanceof AST_Try) {
var save_try = in_try;
in_try = node;
walk_body(node, tw);
if (node.bcatch) {
if (node.bcatch.argname) node.bcatch.argname.mark_symbol(function(node) {
if (node instanceof AST_SymbolCatch) {
var def = node.definition();
references[def.id] = false;
if (def = def.redefined()) references[def.id] = false;
}
}, tw);
if (node.bfinally || (in_try = save_try)) {
walk_body(node.bcatch, tw);
} else {
push();
walk_body(node.bcatch, tw);
pop();
}
}
in_try = save_try;
if (node.bfinally) node.bfinally.walk(tw);
return true;
}
if (node instanceof AST_Unary) {
if (!UNARY_POSTFIX[node.operator]) return;
var sym = node.expression;
if (!(sym instanceof AST_SymbolRef)) return;
mark(sym, true);
return true;
}
if (node instanceof AST_VarDef) {
var assigned = node.value;
if (assigned) {
assigned.walk(tw);
} else {
assigned = segment.block instanceof AST_ForEnumeration && segment.block.init === tw.parent();
}
2022-08-31 14:34:36 +00:00
walk_destructured(AST_SymbolDeclaration, assigned ? function(node) {
2022-01-21 08:28:41 +00:00
if (node instanceof AST_SymbolVar) {
mark(node);
} else {
2022-09-30 13:48:25 +00:00
node.walk(tw);
2022-01-21 08:28:41 +00:00
}
} : function(node) {
2022-09-30 13:48:25 +00:00
if (node instanceof AST_SymbolVar) {
var id = node.definition().id;
var refs = references[id];
if (refs) {
refs.push(node);
} else if (!(id in references)) {
declarations.add(id, node);
}
} else {
node.walk(tw);
2022-01-21 08:28:41 +00:00
}
2022-08-31 14:34:36 +00:00
}, node.name);
2022-01-21 08:28:41 +00:00
return true;
}
if (node instanceof AST_While) {
push();
segment.block = node;
segment.loop = true;
descend();
pop();
return true;
}
function mark_expression(exp) {
2022-05-29 09:24:36 +00:00
if (!compressor.option("ie")) return;
var sym = root_expr(exp);
if (sym instanceof AST_SymbolRef) sym.walk(tw);
2022-01-21 08:28:41 +00:00
}
2022-03-14 15:40:45 +00:00
function walk_cond(condition, consequent, alternative) {
var save = segment;
var segments = [ save, save ];
if (condition instanceof AST_Binary) switch (condition.operator) {
case "&&":
segments[0] = walk_cond(condition.left, condition.right)[0];
break;
case "||":
case "??":
segments[1] = walk_cond(condition.left, null, condition.right)[1];
break;
default:
condition.walk(tw);
break;
} else if (condition instanceof AST_Conditional) {
walk_cond(condition.condition, condition.consequent, condition.alternative);
} else {
condition.walk(tw);
}
segment = segments[0];
if (consequent) {
push();
consequent.walk(tw);
}
segments[0] = segment;
segment = segments[1];
if (alternative) {
push();
alternative.walk(tw);
}
segments[1] = segment;
segment = save;
return segments;
}
2022-01-21 08:28:41 +00:00
});
tw.directives = Object.create(compressor.directives);
self.walk(tw);
var changed = false;
var merged = Object.create(null);
while (first.length && last.length) {
2022-02-07 14:48:46 +00:00
var tail = last.shift();
if (!tail) continue;
var def = tail.definition;
var tail_refs = references[def.id];
if (!tail_refs) continue;
tail_refs = { end: tail_refs.end };
2022-01-21 08:28:41 +00:00
while (def.id in merged) def = merged[def.id];
2022-02-07 14:48:46 +00:00
tail_refs.start = references[def.id].start;
2022-01-21 08:28:41 +00:00
var skipped = [];
do {
2022-02-07 14:48:46 +00:00
var head = first.shift();
2022-01-21 08:28:41 +00:00
if (tail.index > head.index) continue;
2022-11-30 12:56:09 +00:00
var prev_def = head.definition;
if (!(prev_def.id in prev)) continue;
var head_refs = references[prev_def.id];
2022-02-07 14:48:46 +00:00
if (!head_refs) continue;
2022-01-21 08:28:41 +00:00
if (head_refs.start.block !== tail_refs.start.block
|| !mergeable(head_refs, tail_refs)
|| (head_refs.start.loop || !same_scope(def)) && !mergeable(tail_refs, head_refs)
2022-11-30 12:56:09 +00:00
|| compressor.option("webkit") && is_funarg(def) !== is_funarg(prev_def)
|| prev_def.const_redefs
2022-09-30 13:48:25 +00:00
|| !all(head_refs.scopes, function(scope) {
return scope.find_variable(def.name) === def;
2022-01-21 08:28:41 +00:00
})) {
2022-02-07 14:48:46 +00:00
skipped.push(head);
2022-01-21 08:28:41 +00:00
continue;
}
2022-02-07 14:48:46 +00:00
head_refs.forEach(function(sym) {
2022-01-21 08:28:41 +00:00
sym.thedef = def;
sym.name = def.name;
if (sym instanceof AST_SymbolRef) {
2022-02-07 14:48:46 +00:00
def.references.push(sym);
2022-11-30 12:56:09 +00:00
prev_def.replaced++;
2022-01-21 08:28:41 +00:00
} else {
2022-02-07 14:48:46 +00:00
def.orig.push(sym);
2022-11-30 12:56:09 +00:00
prev_def.eliminated++;
2022-01-21 08:28:41 +00:00
}
});
2022-11-30 12:56:09 +00:00
if (!prev_def.fixed) def.fixed = false;
merged[prev_def.id] = def;
2022-01-21 08:28:41 +00:00
changed = true;
break;
2022-02-07 14:48:46 +00:00
} while (first.length);
if (skipped.length) first = skipped.concat(first);
2022-01-21 08:28:41 +00:00
}
return changed;
function push() {
segment = Object.create(segment);
}
function pop() {
segment = Object.getPrototypeOf(segment);
}
2022-06-08 10:36:39 +00:00
function walk_destructured(symbol_type, mark, lhs) {
var marker = new TreeWalker(function(node) {
if (node instanceof AST_Destructured) return;
if (node instanceof AST_DefaultValue) {
push();
node.value.walk(tw);
pop();
node.name.walk(marker);
} else if (node instanceof AST_DestructuredKeyVal) {
2022-08-31 14:34:36 +00:00
if (!(node.key instanceof AST_Node)) {
node.value.walk(marker);
} else if (node.value instanceof AST_PropAccess) {
2022-06-08 10:36:39 +00:00
push();
segment.block = node;
node.key.walk(tw);
node.value.walk(marker);
pop();
} else {
2022-08-31 14:34:36 +00:00
node.key.walk(tw);
2022-06-08 10:36:39 +00:00
node.value.walk(marker);
}
} else if (node instanceof symbol_type) {
mark(node);
} else {
node.walk(tw);
}
return true;
});
lhs.walk(marker);
}
2022-01-21 08:28:41 +00:00
function mark(sym, read) {
2022-06-08 10:36:39 +00:00
var def = sym.definition(), ldef;
if (read && !all(in_arg, function(fn) {
ldef = fn.variables.get(sym.name);
if (!ldef) return true;
if (!is_funarg(ldef)) return true;
return ldef !== def
&& !def.undeclared
&& fn.parent_scope.find_variable(sym.name) !== def;
})) return references[def.id] = references[ldef.id] = false;
var seg = segment;
2022-01-21 08:28:41 +00:00
if (in_try) {
push();
seg = segment;
pop();
}
if (def.id in references) {
var refs = references[def.id];
if (!refs) return;
if (refs.start.block !== seg.block) return references[def.id] = false;
2022-09-30 13:48:25 +00:00
push_ref(sym);
2022-01-21 08:28:41 +00:00
refs.end = seg;
if (def.id in prev) {
last[prev[def.id]] = null;
} else if (!read) {
return;
}
} else if ((ldef = self.variables.get(def.name)) !== def) {
if (ldef && root === seg) references[ldef.id] = false;
return references[def.id] = false;
} else if (compressor.exposed(def) || NO_MERGE[sym.name]) {
return references[def.id] = false;
} else {
var refs = declarations.get(def.id) || [];
2022-09-30 13:48:25 +00:00
refs.scopes = [];
push_ref(sym);
2022-01-21 08:28:41 +00:00
references[def.id] = refs;
if (!read) {
refs.start = seg;
return first.push({
index: index++,
definition: def,
});
}
if (seg.block !== self) return references[def.id] = false;
refs.start = root;
}
prev[def.id] = last.length;
last.push({
index: index++,
definition: def,
});
2022-09-30 13:48:25 +00:00
function push_ref(sym) {
refs.push(sym);
push_uniq(refs.scopes, sym.scope);
var scope = find_scope(tw);
if (scope !== sym.scope) push_uniq(refs.scopes, scope);
}
2022-01-21 08:28:41 +00:00
}
function insert(target) {
var stack = [];
while (true) {
if (HOP(segment, "block")) {
var block = segment.block;
if (block instanceof AST_LabeledStatement) block = block.body;
if (block === target) break;
}
stack.push(segment);
pop();
}
segment.inserted = segment.block;
push();
while (stack.length) {
var seg = stack.pop();
push();
if (HOP(seg, "block")) segment.block = seg.block;
if (HOP(seg, "loop")) segment.loop = seg.loop;
}
}
function must_visit(base, segment) {
return base === segment || base.isPrototypeOf(segment);
}
function mergeable(head, tail) {
return must_visit(head.start, head.end) || must_visit(head.start, tail.start);
}
});
function fill_holes(orig, elements) {
for (var i = elements.length; --i >= 0;) {
if (!elements[i]) elements[i] = make_node(AST_Hole, orig);
}
}
function to_class_expr(defcl, drop_name) {
2022-08-31 14:34:36 +00:00
var cl = make_node(AST_ClassExpression, defcl);
if (cl.name) cl.name = drop_name ? null : make_node(AST_SymbolClass, cl.name);
2022-01-21 08:28:41 +00:00
return cl;
}
function to_func_expr(defun, drop_name) {
var ctor;
switch (defun.CTOR) {
case AST_AsyncDefun:
ctor = AST_AsyncFunction;
break;
case AST_AsyncGeneratorDefun:
ctor = AST_AsyncGeneratorFunction;
break;
case AST_Defun:
ctor = AST_Function;
break;
case AST_GeneratorDefun:
ctor = AST_GeneratorFunction;
break;
}
2022-08-31 14:34:36 +00:00
var fn = make_node(ctor, defun);
fn.name = drop_name ? null : make_node(AST_SymbolLambda, defun.name);
2022-01-21 08:28:41 +00:00
return fn;
}
AST_Scope.DEFMETHOD("drop_unused", function(compressor) {
if (!compressor.option("unused")) return;
var self = this;
var drop_funcs = !(self instanceof AST_Toplevel) || compressor.toplevel.funcs;
var drop_vars = !(self instanceof AST_Toplevel) || compressor.toplevel.vars;
var assign_as_unused = /keep_assign/.test(compressor.option("unused")) ? return_false : function(node, props) {
var sym, nested = false;
if (node instanceof AST_Assign) {
if (node.write_only || node.operator == "=") sym = extract_reference(node.left, props);
} else if (node instanceof AST_Unary) {
if (node.write_only) sym = extract_reference(node.expression, props);
}
if (!(sym instanceof AST_SymbolRef)) return;
var def = sym.definition();
if (export_defaults[def.id]) return;
if (compressor.exposed(def)) return;
if (!can_drop_symbol(sym, compressor, nested)) return;
return sym;
function extract_reference(node, props) {
if (node instanceof AST_PropAccess) {
var expr = node.expression;
if (!expr.may_throw_on_access(compressor, true)) {
nested = true;
if (props && node instanceof AST_Sub) props.unshift(node.property);
return extract_reference(expr, props);
}
} else if (node instanceof AST_Assign && node.operator == "=") {
node.write_only = "p";
var ref = extract_reference(node.right);
if (!props) return ref;
props.assign = node;
return ref instanceof AST_SymbolRef ? ref : node.left;
}
return node;
}
};
var assign_in_use = Object.create(null);
var export_defaults = Object.create(null);
var find_variable = function(name) {
find_variable = compose(self, 0, noop);
return find_variable(name);
function compose(child, level, find) {
var parent = compressor.parent(level);
if (!parent) return find;
var in_arg = parent instanceof AST_Lambda && member(child, parent.argnames);
return compose(parent, level + 1, in_arg ? function(name) {
var def = find(name);
if (def) return def;
def = parent.variables.get(name);
if (def) {
var sym = def.orig[0];
if (sym instanceof AST_SymbolFunarg || sym instanceof AST_SymbolLambda) return def;
}
} : parent.variables ? function(name) {
return find(name) || parent.variables.get(name);
} : find);
}
};
var for_ins = Object.create(null);
var in_use = [];
var in_use_ids = Object.create(null); // avoid expensive linear scans of in_use
2022-07-11 11:25:19 +00:00
var lambda_ids = Object.create(null);
2022-01-21 08:28:41 +00:00
var value_read = Object.create(null);
var value_modified = Object.create(null);
var var_defs = Object.create(null);
if (self instanceof AST_Toplevel && compressor.top_retain) {
self.variables.each(function(def) {
if (compressor.top_retain(def) && !(def.id in in_use_ids)) {
2022-09-30 13:48:25 +00:00
AST_Node.info("Retaining variable {name}", def);
2022-01-21 08:28:41 +00:00
in_use_ids[def.id] = true;
in_use.push(def);
}
});
}
var assignments = new Dictionary();
var initializations = new Dictionary();
// pass 1: find out which symbols are directly used in
// this scope (not in nested scopes).
var scope = this;
var tw = new TreeWalker(function(node, descend) {
if (node instanceof AST_Lambda && node.uses_arguments && !tw.has_directive("use strict")) {
node.each_argname(function(argname) {
var def = argname.definition();
if (!(def.id in in_use_ids)) {
in_use_ids[def.id] = true;
in_use.push(def);
}
});
}
if (node === self) return;
if (scope === self) {
if (node instanceof AST_DefClass) {
var def = node.name.definition();
2022-02-07 14:48:46 +00:00
var drop = drop_funcs && !def.exported;
if (!drop && !(def.id in in_use_ids)) {
2022-01-21 08:28:41 +00:00
in_use_ids[def.id] = true;
in_use.push(def);
}
2022-02-07 14:48:46 +00:00
var used = tw.parent() instanceof AST_ExportDefault;
2022-07-11 11:25:19 +00:00
if (used) {
export_defaults[def.id] = true;
} else if (drop && !(def.id in lambda_ids)) {
lambda_ids[def.id] = 1;
}
if (node.extends) node.extends.walk(tw);
2022-02-07 14:48:46 +00:00
var values = [];
2022-01-21 08:28:41 +00:00
node.properties.forEach(function(prop) {
if (prop.key instanceof AST_Node) prop.key.walk(tw);
2022-02-07 14:48:46 +00:00
var value = prop.value;
if (!value) return;
2022-07-11 11:25:19 +00:00
if (is_static_field_or_init(prop)) {
2022-02-07 14:48:46 +00:00
if (!used && value.contains_this()) used = true;
walk_class_prop(value);
2022-01-21 08:28:41 +00:00
} else {
2022-02-07 14:48:46 +00:00
values.push(value);
2022-01-21 08:28:41 +00:00
}
});
2022-02-07 14:48:46 +00:00
values.forEach(drop && used ? walk_class_prop : function(value) {
initializations.add(def.id, value);
});
2022-01-21 08:28:41 +00:00
return true;
}
if (node instanceof AST_LambdaDefinition) {
var def = node.name.definition();
2022-07-11 11:25:19 +00:00
var drop = drop_funcs && !def.exported;
if (!drop && !(def.id in in_use_ids)) {
2022-01-21 08:28:41 +00:00
in_use_ids[def.id] = true;
in_use.push(def);
}
initializations.add(def.id, node);
if (tw.parent() instanceof AST_ExportDefault) {
export_defaults[def.id] = true;
2022-09-30 13:48:25 +00:00
return scan_ref_scoped(node, descend, true);
2022-01-21 08:28:41 +00:00
}
2022-07-11 11:25:19 +00:00
if (drop && !(def.id in lambda_ids)) lambda_ids[def.id] = 1;
return true;
2022-01-21 08:28:41 +00:00
}
if (node instanceof AST_Definitions) {
node.definitions.forEach(function(defn) {
var value = defn.value;
var side_effects = value
&& (defn.name instanceof AST_Destructured || value.has_side_effects(compressor));
var shared = side_effects && value.tail_node().operator == "=";
defn.name.mark_symbol(function(name) {
if (!(name instanceof AST_SymbolDeclaration)) return;
var def = name.definition();
var_defs[def.id] = (var_defs[def.id] || 0) + 1;
if (node instanceof AST_Var && def.orig[0] instanceof AST_SymbolCatch) {
var redef = def.redefined();
if (redef) var_defs[redef.id] = (var_defs[redef.id] || 0) + 1;
}
if (!(def.id in in_use_ids) && (!drop_vars || def.exported
|| (node instanceof AST_Const ? def.redefined() : def.const_redefs)
|| !(node instanceof AST_Var || is_safe_lexical(def)))) {
in_use_ids[def.id] = true;
in_use.push(def);
}
if (value) {
if (!side_effects) {
initializations.add(def.id, value);
} else if (shared) {
verify_safe_usage(def, name, value_modified[def.id]);
}
assignments.add(def.id, defn);
}
2022-07-11 11:25:19 +00:00
unmark_lambda(def);
2022-01-21 08:28:41 +00:00
return true;
}, tw);
if (side_effects) value.walk(tw);
});
return true;
}
if (node instanceof AST_SymbolFunarg) {
var def = node.definition();
var_defs[def.id] = (var_defs[def.id] || 0) + 1;
assignments.add(def.id, node);
return true;
}
if (node instanceof AST_SymbolImport) {
var def = node.definition();
if (!(def.id in in_use_ids) && (!drop_vars || !is_safe_lexical(def))) {
in_use_ids[def.id] = true;
in_use.push(def);
}
return true;
}
}
return scan_ref_scoped(node, descend, true);
2022-02-07 14:48:46 +00:00
function walk_class_prop(value) {
var save_scope = scope;
scope = node;
value.walk(tw);
scope = save_scope;
}
2022-01-21 08:28:41 +00:00
});
tw.directives = Object.create(compressor.directives);
self.walk(tw);
var drop_fn_name = compressor.option("keep_fnames") ? return_false : compressor.option("ie") ? function(def) {
return !compressor.exposed(def) && def.references.length == def.replaced;
} : function(def) {
if (!(def.id in in_use_ids)) return true;
if (def.orig.length - def.eliminated < 2) return false;
// function argument will always overshadow its name
if (def.orig[1] instanceof AST_SymbolFunarg) return true;
// retain if referenced within destructured object of argument
return all(def.references, function(ref) {
return !ref.in_arg;
});
};
if (compressor.option("ie")) initializations.each(function(init, id) {
if (id in in_use_ids) return;
init.forEach(function(init) {
init.walk(new TreeWalker(function(node) {
if (node instanceof AST_Function && node.name && !drop_fn_name(node.name.definition())) {
node.walk(tw);
return true;
}
if (node instanceof AST_Scope) return true;
}));
});
});
// pass 2: for every used symbol we need to walk its
// initialization code to figure out if it uses other
// symbols (that may not be in_use).
tw = new TreeWalker(scan_ref_scoped);
for (var i = 0; i < in_use.length; i++) {
var init = initializations.get(in_use[i].id);
if (init) init.forEach(function(init) {
init.walk(tw);
});
}
Object.keys(assign_in_use).forEach(function(id) {
var assigns = assign_in_use[id];
if (!assigns) {
delete assign_in_use[id];
return;
}
assigns = assigns.reduce(function(in_use, assigns) {
assigns.forEach(function(assign) {
push_uniq(in_use, assign);
});
return in_use;
}, []);
var in_use = (assignments.get(id) || []).filter(function(node) {
return find_if(node instanceof AST_Unary ? function(assign) {
return assign === node;
} : function(assign) {
if (assign === node) return true;
if (assign instanceof AST_Unary) return false;
return get_rvalue(assign) === get_rvalue(node);
}, assigns);
});
if (assigns.length == in_use.length) {
assign_in_use[id] = in_use;
} else {
delete assign_in_use[id];
}
});
// pass 3: we should drop declarations not in_use
var calls_to_drop_args = [];
var fns_with_marked_args = [];
var trimmer = new TreeTransformer(function(node) {
if (node instanceof AST_DefaultValue) return trim_default(trimmer, node);
if (node instanceof AST_Destructured && node.rest) node.rest = node.rest.transform(trimmer);
if (node instanceof AST_DestructuredArray) {
var trim = !node.rest;
for (var i = node.elements.length; --i >= 0;) {
var element = node.elements[i].transform(trimmer);
if (element) {
node.elements[i] = element;
trim = false;
} else if (trim) {
node.elements.pop();
} else {
node.elements[i] = make_node(AST_Hole, node.elements[i]);
}
}
return node;
}
if (node instanceof AST_DestructuredObject) {
var properties = [];
node.properties.forEach(function(prop) {
var retain = false;
if (prop.key instanceof AST_Node) {
prop.key = prop.key.transform(tt);
retain = prop.key.has_side_effects(compressor);
}
if ((retain || node.rest) && is_decl(prop.value)) {
prop.value = prop.value.transform(tt);
properties.push(prop);
} else {
var value = prop.value.transform(trimmer);
if (!value && node.rest) {
if (prop.value instanceof AST_DestructuredArray) {
value = make_node(AST_DestructuredArray, prop.value, { elements: [] });
} else {
value = make_node(AST_DestructuredObject, prop.value, { properties: [] });
}
}
if (value) {
prop.value = value;
properties.push(prop);
}
}
});
node.properties = properties;
return node;
}
2022-07-11 11:25:19 +00:00
if (node instanceof AST_SymbolDeclaration) return trim_decl(node);
2022-01-21 08:28:41 +00:00
});
var tt = new TreeTransformer(function(node, descend, in_list) {
var parent = tt.parent();
if (drop_vars) {
var props = [], sym = assign_as_unused(node, props);
if (sym) {
var value;
if (can_drop_lhs(sym, node)) {
if (node instanceof AST_Assign) {
value = get_rhs(node);
if (node.write_only === true) value = value.drop_side_effect_free(compressor);
}
if (!value) value = make_node(AST_Number, node, { value: 0 });
}
if (value) {
if (props.assign) {
var assign = props.assign.drop_side_effect_free(compressor);
if (assign) {
assign.write_only = true;
props.unshift(assign);
}
}
if (!(parent instanceof AST_Sequence)
|| parent.tail_node() === node
|| value.has_side_effects(compressor)) {
props.push(value);
}
switch (props.length) {
case 0:
return List.skip;
case 1:
2022-08-31 14:34:36 +00:00
return maintain_this_binding(parent, node, props[0].transform(tt));
2022-01-21 08:28:41 +00:00
default:
return make_sequence(node, props.map(function(prop) {
return prop.transform(tt);
}));
}
}
} else if (node instanceof AST_UnaryPostfix
&& node.expression instanceof AST_SymbolRef
&& indexOf_assign(node.expression.definition(), node) < 0) {
return make_node(AST_UnaryPrefix, node, {
operator: "+",
2022-02-07 14:48:46 +00:00
expression: node.expression,
2022-01-21 08:28:41 +00:00
});
}
}
2022-07-11 11:25:19 +00:00
if (node instanceof AST_Binary && node.operator == "instanceof") {
var sym = node.right;
if (!(sym instanceof AST_SymbolRef)) return;
if (sym.definition().id in in_use_ids) return;
var lhs = node.left.drop_side_effect_free(compressor);
var value = make_node(AST_False, node).optimize(compressor);
return lhs ? make_sequence(node, [ lhs, value ]) : value;
}
2022-04-11 08:07:00 +00:00
if (node instanceof AST_Call) {
calls_to_drop_args.push(node);
node.args = node.args.map(function(arg) {
return arg.transform(tt);
});
node.expression = node.expression.transform(tt);
return node;
}
2022-01-21 08:28:41 +00:00
if (scope !== self) return;
if (drop_funcs && node !== self && node instanceof AST_DefClass) {
var def = node.name.definition();
if (!(def.id in in_use_ids)) {
log(node.name, "Dropping unused class {name}");
def.eliminated++;
descend(node, tt);
2022-02-07 14:48:46 +00:00
var trimmed = to_class_expr(node, true);
if (parent instanceof AST_ExportDefault) return trimmed;
trimmed = trimmed.drop_side_effect_free(compressor, true);
2022-01-21 08:28:41 +00:00
if (trimmed) return make_node(AST_SimpleStatement, node, { body: trimmed });
return in_list ? List.skip : make_node(AST_EmptyStatement, node);
}
}
if (node instanceof AST_ClassExpression && node.name && drop_fn_name(node.name.definition())) {
2022-06-08 10:36:39 +00:00
node.name = null;
2022-01-21 08:28:41 +00:00
}
if (node instanceof AST_Lambda) {
if (drop_funcs && node !== self && node instanceof AST_LambdaDefinition) {
var def = node.name.definition();
if (!(def.id in in_use_ids)) {
log(node.name, "Dropping unused function {name}");
def.eliminated++;
if (parent instanceof AST_ExportDefault) {
descend_scope();
return to_func_expr(node, true);
}
return in_list ? List.skip : make_node(AST_EmptyStatement, node);
}
}
2022-11-30 12:56:09 +00:00
descend_scope();
2022-01-21 08:28:41 +00:00
if (node instanceof AST_LambdaExpression && node.name && drop_fn_name(node.name.definition())) {
2022-06-08 10:36:39 +00:00
node.name = null;
2022-01-21 08:28:41 +00:00
}
if (!(node instanceof AST_Accessor)) {
2022-02-07 14:48:46 +00:00
var args, spread, trim = compressor.drop_fargs(node, parent);
if (trim && parent instanceof AST_Call && parent.expression === node) {
args = parent.args;
for (spread = 0; spread < args.length; spread++) {
if (args[spread] instanceof AST_Spread) break;
}
}
var argnames = node.argnames;
var rest = node.rest;
2022-06-08 10:36:39 +00:00
var after = false, before = false;
2022-02-07 14:48:46 +00:00
if (rest) {
2022-06-08 10:36:39 +00:00
before = true;
2022-02-07 14:48:46 +00:00
if (!args || spread < argnames.length || rest instanceof AST_SymbolFunarg) {
rest = rest.transform(trimmer);
} else {
var trimmed = trim_destructured(rest, make_node(AST_Array, parent, {
elements: args.slice(argnames.length),
2022-07-11 11:25:19 +00:00
}), trim_decl, !node.uses_arguments, rest);
2022-02-07 14:48:46 +00:00
rest = trimmed.name;
args.length = argnames.length;
if (trimmed.value.elements.length) [].push.apply(args, trimmed.value.elements);
}
2022-06-08 10:36:39 +00:00
if (rest instanceof AST_Destructured && !rest.rest) {
2022-01-21 08:28:41 +00:00
if (rest instanceof AST_DestructuredArray) {
if (rest.elements.length == 0) rest = null;
} else if (rest.properties.length == 0) {
rest = null;
}
}
node.rest = rest;
2022-06-08 10:36:39 +00:00
if (rest) {
trim = false;
after = true;
}
2022-01-21 08:28:41 +00:00
}
var default_length = trim ? -1 : node.length();
2022-06-08 10:36:39 +00:00
var trim_value = args && !node.uses_arguments && parent !== compressor.parent();
2022-01-21 08:28:41 +00:00
for (var i = argnames.length; --i >= 0;) {
var sym = argnames[i];
2022-02-07 14:48:46 +00:00
if (sym instanceof AST_SymbolFunarg) {
var def = sym.definition();
if (def.id in in_use_ids) {
trim = false;
if (indexOf_assign(def, sym) < 0) sym.unused = null;
} else if (trim) {
log(sym, "Dropping unused function argument {name}");
argnames.pop();
2022-07-11 11:25:19 +00:00
def.eliminated++;
sym.unused = true;
2022-02-07 14:48:46 +00:00
} else {
sym.unused = true;
}
} else {
2022-06-08 10:36:39 +00:00
before = true;
2022-02-07 14:48:46 +00:00
var funarg;
if (!args || spread < i) {
funarg = sym.transform(trimmer);
} else {
2022-07-11 11:25:19 +00:00
var trimmed = trim_destructured(sym, args[i], trim_decl, trim_value, sym);
2022-06-08 10:36:39 +00:00
funarg = trimmed.name;
if (trimmed.value) args[i] = trimmed.value;
2022-02-07 14:48:46 +00:00
}
if (funarg) {
2022-01-21 08:28:41 +00:00
trim = false;
2022-06-08 10:36:39 +00:00
argnames[i] = funarg;
if (!after) after = !(funarg instanceof AST_SymbolFunarg);
2022-01-21 08:28:41 +00:00
} else if (trim) {
2022-02-07 14:48:46 +00:00
log_default(sym, "Dropping unused default argument {name}");
2022-01-21 08:28:41 +00:00
argnames.pop();
} else if (i > default_length) {
2022-02-07 14:48:46 +00:00
log_default(sym, "Dropping unused default argument assignment {name}");
2022-06-08 10:36:39 +00:00
if (sym.name instanceof AST_SymbolFunarg) {
sym.name.unused = true;
} else {
after = true;
}
2022-01-21 08:28:41 +00:00
argnames[i] = sym.name;
} else {
2022-02-07 14:48:46 +00:00
log_default(sym, "Dropping unused default argument value {name}");
2022-06-08 10:36:39 +00:00
argnames[i] = sym = sym.clone();
2022-01-21 08:28:41 +00:00
sym.value = make_node(AST_Number, sym, { value: 0 });
2022-06-08 10:36:39 +00:00
after = true;
2022-01-21 08:28:41 +00:00
}
}
}
2022-06-08 10:36:39 +00:00
if (before && !after && node.uses_arguments && !tt.has_directive("use strict")) {
node.rest = make_node(AST_DestructuredArray, node, { elements: [] });
}
2022-01-21 08:28:41 +00:00
fns_with_marked_args.push(node);
}
2022-11-30 12:56:09 +00:00
return node;
2022-01-21 08:28:41 +00:00
}
if (node instanceof AST_Catch && node.argname instanceof AST_Destructured) {
node.argname.transform(trimmer);
}
if (node instanceof AST_Definitions && !(parent instanceof AST_ForEnumeration && parent.init === node)) {
// place uninitialized names at the start
var body = [], head = [], tail = [];
// for unused names whose initialization has
// side effects, we can cascade the init. code
// into the next one, or next statement.
var side_effects = [];
var duplicated = 0;
var is_var = node instanceof AST_Var;
node.definitions.forEach(function(def) {
if (def.value) def.value = def.value.transform(tt);
var value = def.value;
if (def.name instanceof AST_Destructured) {
var trimmed = trim_destructured(def.name, value, function(node) {
if (!drop_vars) return node;
if (node.definition().id in in_use_ids) return node;
if (is_catch(node)) return node;
if (is_var && !can_drop_symbol(node)) return node;
return null;
}, true);
if (trimmed.name) {
def = make_node(AST_VarDef, def, {
name: trimmed.name,
value: value = trimmed.value,
});
flush();
} else if (trimmed.value) {
side_effects.push(trimmed.value);
}
return;
}
var sym = def.name.definition();
var drop_sym = is_var ? can_drop_symbol(def.name) : is_safe_lexical(sym);
if (!drop_sym || !drop_vars || sym.id in in_use_ids) {
2022-02-07 14:48:46 +00:00
var index;
if (value && ((index = indexOf_assign(sym, def)) < 0 || self_assign(value.tail_node()))) {
def = def.clone();
2022-01-21 08:28:41 +00:00
value = value.drop_side_effect_free(compressor);
2022-08-31 14:34:36 +00:00
if (value) AST_Node.warn("Side effects in definition of variable {name} [{start}]", def.name);
2022-02-07 14:48:46 +00:00
if (node instanceof AST_Const) {
def.value = value || make_node(AST_Number, def, { value: 0 });
} else {
def.value = null;
if (value) side_effects.push(value);
2022-01-21 08:28:41 +00:00
}
value = null;
2022-02-07 14:48:46 +00:00
if (index >= 0) assign_in_use[sym.id][index] = def;
2022-01-21 08:28:41 +00:00
}
2022-02-07 14:48:46 +00:00
var old_def, fn;
2022-01-21 08:28:41 +00:00
if (!value && !(node instanceof AST_Let)) {
if (parent instanceof AST_ExportDeclaration) {
flush();
} else if (drop_sym && var_defs[sym.id] > 1) {
2022-08-31 14:34:36 +00:00
AST_Node.info("Dropping declaration of variable {name} [{start}]", def.name);
2022-01-21 08:28:41 +00:00
var_defs[sym.id]--;
sym.eliminated++;
} else {
head.push(def);
}
} else if (compressor.option("functions")
&& !compressor.option("ie")
&& drop_sym
2022-02-07 14:48:46 +00:00
&& value
2022-01-21 08:28:41 +00:00
&& var_defs[sym.id] == 1
&& sym.assignments == 0
2022-02-07 14:48:46 +00:00
&& (fn = value.tail_node()) instanceof AST_LambdaExpression
2022-01-21 08:28:41 +00:00
&& !is_arguments(sym)
2022-02-07 14:48:46 +00:00
&& !is_arrow(fn)
&& assigned_once(fn, sym.references)
&& can_declare_defun(fn)
&& (old_def = rename_def(fn, def.name.name)) !== false) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Declaring {name} as function [{start}]", def.name);
2022-01-21 08:28:41 +00:00
var ctor;
2022-02-07 14:48:46 +00:00
switch (fn.CTOR) {
2022-01-21 08:28:41 +00:00
case AST_AsyncFunction:
ctor = AST_AsyncDefun;
break;
case AST_AsyncGeneratorFunction:
ctor = AST_AsyncGeneratorDefun;
break;
case AST_Function:
ctor = AST_Defun;
break;
case AST_GeneratorFunction:
ctor = AST_GeneratorDefun;
break;
}
2022-08-31 14:34:36 +00:00
var defun = make_node(ctor, fn);
defun.name = make_node(AST_SymbolDefun, def.name);
2022-01-21 08:28:41 +00:00
var name_def = def.name.scope.resolve().def_function(defun.name);
if (old_def) old_def.forEach(function(node) {
node.name = name_def.name;
node.thedef = name_def;
node.reference();
});
body.push(defun);
2022-02-07 14:48:46 +00:00
if (value !== fn) [].push.apply(side_effects, value.expressions.slice(0, -1));
2022-01-21 08:28:41 +00:00
} else {
if (drop_sym
&& var_defs[sym.id] > 1
&& !(parent instanceof AST_ExportDeclaration)
&& sym.orig.indexOf(def.name) > sym.eliminated) {
var_defs[sym.id]--;
duplicated++;
}
flush();
}
} else if (is_catch(def.name)) {
value = value && value.drop_side_effect_free(compressor);
if (value) side_effects.push(value);
if (var_defs[sym.id] > 1) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Dropping duplicated declaration of variable {name} [{start}]", def.name);
2022-01-21 08:28:41 +00:00
var_defs[sym.id]--;
sym.eliminated++;
} else {
def.value = null;
head.push(def);
}
} else {
2022-02-07 14:48:46 +00:00
value = value && value.drop_side_effect_free(compressor);
2022-01-21 08:28:41 +00:00
if (value) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Side effects in initialization of unused variable {name} [{start}]", def.name);
2022-01-21 08:28:41 +00:00
side_effects.push(value);
} else {
log(def.name, "Dropping unused variable {name}");
}
sym.eliminated++;
}
2022-02-07 14:48:46 +00:00
function self_assign(ref) {
return ref instanceof AST_SymbolRef && ref.definition() === sym;
}
2022-01-21 08:28:41 +00:00
function assigned_once(fn, refs) {
if (refs.length == 0) return fn === def.name.fixed_value();
return all(refs, function(ref) {
return fn === ref.fixed_value();
});
}
function can_declare_defun(fn) {
if (!is_var || compressor.has_directive("use strict") || !(fn instanceof AST_Function)) {
return parent instanceof AST_Scope;
}
return parent instanceof AST_Block
|| parent instanceof AST_For && parent.init === node
|| parent instanceof AST_If;
}
function rename_def(fn, name) {
if (!fn.name) return null;
var def = fn.name.definition();
if (def.orig.length > 1) return null;
if (def.assignments > 0) return false;
if (def.name == name) return def;
2022-04-11 08:07:00 +00:00
if (compressor.option("keep_fnames")) return false;
2022-01-21 08:28:41 +00:00
var forbidden;
switch (name) {
case "await":
forbidden = is_async;
break;
case "yield":
forbidden = is_generator;
break;
}
return all(def.references, function(ref) {
var scope = ref.scope;
if (scope.find_variable(name) !== sym) return false;
if (forbidden) do {
scope = scope.resolve();
if (forbidden(scope)) return false;
} while (scope !== fn && (scope = scope.parent_scope));
return true;
}) && def;
}
function is_catch(node) {
var sym = node.definition();
return sym.orig[0] instanceof AST_SymbolCatch && sym.scope.resolve() === node.scope.resolve();
}
function flush() {
if (side_effects.length > 0) {
if (tail.length == 0) {
body.push(make_node(AST_SimpleStatement, node, {
body: make_sequence(node, side_effects),
}));
} else if (value) {
side_effects.push(value);
def.value = make_sequence(value, side_effects);
} else {
def.value = make_node(AST_UnaryPrefix, def, {
operator: "void",
expression: make_sequence(def, side_effects),
});
}
side_effects = [];
}
tail.push(def);
}
});
switch (head.length) {
case 0:
if (tail.length == 0) break;
if (tail.length == duplicated) {
[].unshift.apply(side_effects, tail.map(function(def) {
2022-08-31 14:34:36 +00:00
AST_Node.info("Dropping duplicated definition of variable {name} [{start}]", def.name);
2022-01-21 08:28:41 +00:00
var sym = def.name.definition();
2022-08-31 14:34:36 +00:00
var ref = make_node(AST_SymbolRef, def.name);
2022-01-21 08:28:41 +00:00
sym.references.push(ref);
var assign = make_node(AST_Assign, def, {
operator: "=",
left: ref,
right: def.value,
});
var index = indexOf_assign(sym, def);
if (index >= 0) assign_in_use[sym.id][index] = assign;
2022-06-08 10:36:39 +00:00
sym.assignments++;
2022-01-21 08:28:41 +00:00
sym.eliminated++;
return assign;
}));
break;
}
case 1:
if (tail.length == 0) {
var id = head[0].name.definition().id;
if (id in for_ins) {
node.definitions = head;
for_ins[id].init = node;
break;
}
}
default:
2022-02-07 14:48:46 +00:00
var seq;
if (tail.length > 0 && (seq = tail[0].value) instanceof AST_Sequence) {
tail[0].value = seq.tail_node();
body.push(make_node(AST_SimpleStatement, node, {
body: make_sequence(seq, seq.expressions.slice(0, -1)),
}));
}
2022-01-21 08:28:41 +00:00
node.definitions = head.concat(tail);
body.push(node);
}
if (side_effects.length > 0) {
2022-02-07 14:48:46 +00:00
body.push(make_node(AST_SimpleStatement, node, { body: make_sequence(node, side_effects) }));
2022-01-21 08:28:41 +00:00
}
return insert_statements(body, node, in_list);
}
if (node instanceof AST_Assign) {
descend(node, tt);
if (!(node.left instanceof AST_Destructured)) return node;
var trimmed = trim_destructured(node.left, node.right, function(node) {
return node;
}, node.write_only === true);
if (trimmed.name) return make_node(AST_Assign, node, {
operator: node.operator,
left: trimmed.name,
right: trimmed.value,
});
if (trimmed.value) return trimmed.value;
if (parent instanceof AST_Sequence && parent.tail_node() !== node) return List.skip;
return make_node(AST_Number, node, { value: 0 });
}
if (node instanceof AST_LabeledStatement && node.body instanceof AST_For) {
// Certain combination of unused name + side effect leads to invalid AST:
// https://github.com/mishoo/UglifyJS/issues/1830
// We fix it at this stage by moving the label inwards, back to the `for`.
descend(node, tt);
if (node.body instanceof AST_BlockStatement) {
var block = node.body;
node.body = block.body.pop();
block.body.push(node);
return in_list ? List.splice(block.body) : block;
}
return node;
}
if (node instanceof AST_Scope) {
descend_scope();
return node;
}
if (node instanceof AST_SymbolImport) {
if (!compressor.option("imports") || node.definition().id in in_use_ids) return node;
return in_list ? List.skip : null;
}
function descend_scope() {
var save_scope = scope;
scope = node;
descend(node, tt);
scope = save_scope;
}
}, function(node, in_list) {
if (node instanceof AST_BlockStatement) return trim_block(node, tt.parent(), in_list);
2022-06-08 10:36:39 +00:00
if (node instanceof AST_ExportDeclaration) {
var block = node.body;
if (!(block instanceof AST_BlockStatement)) return;
node.body = block.body.pop();
block.body.push(node);
return in_list ? List.splice(block.body) : block;
}
2022-02-07 14:48:46 +00:00
if (node instanceof AST_For) return patch_for_init(node, in_list);
2022-01-21 08:28:41 +00:00
if (node instanceof AST_ForIn) {
if (!drop_vars || !compressor.option("loops")) return;
if (!is_empty(node.body)) return;
var sym = get_init_symbol(node);
if (!sym) return;
var def = sym.definition();
if (def.id in in_use_ids) return;
log(sym, "Dropping unused loop variable {name}");
if (for_ins[def.id] === node) delete for_ins[def.id];
var body = [];
var value = node.object.drop_side_effect_free(compressor);
if (value) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Side effects in object of for-in loop [{start}]", value);
body.push(make_node(AST_SimpleStatement, node, { body: value }));
2022-01-21 08:28:41 +00:00
}
if (node.init instanceof AST_Definitions && def.orig[0] instanceof AST_SymbolCatch) {
body.push(node.init);
}
return insert_statements(body, node, in_list);
}
if (node instanceof AST_Import) {
if (node.properties && node.properties.length == 0) node.properties = null;
return node;
}
if (node instanceof AST_Sequence) {
if (node.expressions.length > 1) return;
2022-08-31 14:34:36 +00:00
return maintain_this_binding(tt.parent(), node, node.expressions[0]);
2022-01-21 08:28:41 +00:00
}
});
tt.push(compressor.parent());
2022-06-08 10:36:39 +00:00
tt.directives = Object.create(compressor.directives);
2022-01-21 08:28:41 +00:00
self.transform(tt);
if (self instanceof AST_Lambda
&& self.body.length == 1
&& self.body[0] instanceof AST_Directive
&& self.body[0].value == "use strict") {
self.body.length = 0;
}
calls_to_drop_args.forEach(function(call) {
drop_unused_call_args(call, compressor, fns_with_marked_args);
});
function log(sym, text) {
2022-08-31 14:34:36 +00:00
AST_Node[sym.definition().references.length > 0 ? "info" : "warn"](text + " [{start}]", sym);
2022-01-21 08:28:41 +00:00
}
2022-02-07 14:48:46 +00:00
function log_default(node, text) {
if (node.name instanceof AST_SymbolFunarg) {
log(node.name, text);
} else {
2022-08-31 14:34:36 +00:00
AST_Node.info(text + " [{start}]", node);
2022-02-07 14:48:46 +00:00
}
}
2022-01-21 08:28:41 +00:00
function get_rvalue(expr) {
return expr[expr instanceof AST_Assign ? "right" : "value"];
}
function insert_statements(body, orig, in_list) {
switch (body.length) {
case 0:
return in_list ? List.skip : make_node(AST_EmptyStatement, orig);
case 1:
return body[0];
default:
2022-08-31 14:34:36 +00:00
return in_list ? List.splice(body) : make_node(AST_BlockStatement, orig, { body: body });
2022-01-21 08:28:41 +00:00
}
}
function track_assigns(def, node) {
if (def.scope.resolve() !== self) return false;
if (!def.fixed || !node.fixed) assign_in_use[def.id] = false;
return assign_in_use[def.id] !== false;
}
function add_assigns(def, node) {
if (!assign_in_use[def.id]) assign_in_use[def.id] = [];
if (node.fixed.assigns) push_uniq(assign_in_use[def.id], node.fixed.assigns);
}
function indexOf_assign(def, node) {
var nodes = assign_in_use[def.id];
return nodes && nodes.indexOf(node);
}
2022-07-11 11:25:19 +00:00
function unmark_lambda(def) {
if (lambda_ids[def.id] > 1 && !(def.id in in_use_ids)) {
in_use_ids[def.id] = true;
in_use.push(def);
}
lambda_ids[def.id] = 0;
}
2022-01-21 08:28:41 +00:00
function verify_safe_usage(def, read, modified) {
if (def.id in in_use_ids) return;
if (read && modified) {
in_use_ids[def.id] = read;
in_use.push(def);
} else {
value_read[def.id] = read;
value_modified[def.id] = modified;
}
}
function can_drop_lhs(sym, node) {
var def = sym.definition();
var in_use = in_use_ids[def.id];
if (!in_use) return true;
if (node[node instanceof AST_Assign ? "left" : "expression"] !== sym) return false;
return in_use === sym && def.references.length - def.replaced == 1 || indexOf_assign(def, node) < 0;
}
function get_rhs(assign) {
var rhs = assign.right;
if (!assign.write_only) return rhs;
if (!(rhs instanceof AST_Binary && lazy_op[rhs.operator])) return rhs;
if (!(rhs.left instanceof AST_SymbolRef)) return rhs;
if (!(assign.left instanceof AST_SymbolRef)) return rhs;
var def = assign.left.definition();
if (rhs.left.definition() !== def) return rhs;
if (rhs.right.has_side_effects(compressor)) return rhs;
if (track_assigns(def, rhs.left)) add_assigns(def, rhs.left);
return rhs.right;
}
function get_init_symbol(for_in) {
var init = for_in.init;
if (init instanceof AST_Definitions) {
init = init.definitions[0].name;
return init instanceof AST_SymbolDeclaration && init;
}
while (init instanceof AST_PropAccess) init = init.expression.tail_node();
if (init instanceof AST_SymbolRef) return init;
}
function scan_ref_scoped(node, descend, init) {
if (node instanceof AST_Assign && node.left instanceof AST_SymbolRef) {
var def = node.left.definition();
if (def.scope.resolve() === self) assignments.add(def.id, node);
}
2022-08-05 07:44:52 +00:00
if (node instanceof AST_SymbolRef && node.in_arg) var_defs[node.definition().id] = 0;
2022-01-21 08:28:41 +00:00
if (node instanceof AST_Unary && node.expression instanceof AST_SymbolRef) {
var def = node.expression.definition();
if (def.scope.resolve() === self) assignments.add(def.id, node);
}
2022-07-11 11:25:19 +00:00
var props = [], sym = assign_as_unused(node, props);
if (sym) {
var node_def = sym.definition();
if (node_def.scope.resolve() !== self && self.variables.get(sym.name) !== node_def) return;
if (is_arguments(node_def) && !all(self.argnames, function(argname) {
2022-01-21 08:28:41 +00:00
return !argname.match_symbol(function(node) {
if (node instanceof AST_SymbolFunarg) {
var def = node.definition();
return def.references.length > def.replaced;
}
}, true);
2022-07-11 11:25:19 +00:00
})) return;
2022-01-21 08:28:41 +00:00
if (node.write_only === "p" && node.right.may_throw_on_access(compressor, true)) return;
var assign = props.assign;
if (assign) {
assign.write_only = true;
assign.walk(tw);
}
props.forEach(function(prop) {
prop.walk(tw);
});
if (node instanceof AST_Assign) {
var right = get_rhs(node), shared = false;
if (init && node.write_only === true && !right.has_side_effects(compressor)) {
initializations.add(node_def.id, right);
} else {
right.walk(tw);
shared = right.tail_node().operator == "=";
}
if (node.left === sym) {
if (!node.write_only || shared) {
verify_safe_usage(node_def, sym, value_modified[node_def.id]);
}
} else {
var fixed = sym.fixed_value();
if (!fixed || !fixed.is_constant()) {
verify_safe_usage(node_def, value_read[node_def.id], true);
}
}
}
if (track_assigns(node_def, sym) && is_lhs(sym, node) !== sym) add_assigns(node_def, sym);
2022-07-11 11:25:19 +00:00
unmark_lambda(node_def);
return true;
}
if (node instanceof AST_Binary) {
if (node.operator != "instanceof") return;
var sym = node.right;
if (!(sym instanceof AST_SymbolRef)) return;
var id = sym.definition().id;
if (!lambda_ids[id]) return;
node.left.walk(tw);
lambda_ids[id]++;
2022-01-21 08:28:41 +00:00
return true;
}
if (node instanceof AST_ForIn) {
if (node.init instanceof AST_SymbolRef && scope === self) {
var id = node.init.definition().id;
if (!(id in for_ins)) for_ins[id] = node;
}
if (!drop_vars || !compressor.option("loops")) return;
if (!is_empty(node.body)) return;
if (node.init.has_side_effects(compressor)) return;
var sym = get_init_symbol(node);
if (!sym) return;
var def = sym.definition();
if (def.scope.resolve() !== self) {
var d = find_variable(sym.name);
if (d === def || d && d.redefined() === def) return;
}
node.object.walk(tw);
return true;
}
if (node instanceof AST_SymbolRef) {
2022-07-11 11:25:19 +00:00
var node_def = node.definition();
2022-01-21 08:28:41 +00:00
if (!(node_def.id in in_use_ids)) {
in_use_ids[node_def.id] = true;
in_use.push(node_def);
}
if (cross_scope(node_def.scope, node.scope)) {
var redef = node_def.redefined();
if (redef && !(redef.id in in_use_ids)) {
in_use_ids[redef.id] = true;
in_use.push(redef);
}
}
if (track_assigns(node_def, node)) add_assigns(node_def, node);
return true;
}
if (node instanceof AST_Scope) {
var save_scope = scope;
scope = node;
descend();
scope = save_scope;
return true;
}
}
function is_decl(node) {
return (node instanceof AST_DefaultValue ? node.name : node) instanceof AST_SymbolDeclaration;
}
2022-07-11 11:25:19 +00:00
function trim_decl(node) {
if (node.definition().id in in_use_ids) return node;
if (node instanceof AST_SymbolFunarg) node.unused = true;
return null;
}
2022-01-21 08:28:41 +00:00
function trim_default(trimmer, node) {
node.value = node.value.transform(tt);
var name = node.name.transform(trimmer);
if (!name) {
if (node.name instanceof AST_Destructured) return null;
var value = node.value.drop_side_effect_free(compressor);
if (!value) return null;
log(node.name, "Side effects in default value of unused variable {name}");
2022-06-08 10:36:39 +00:00
node = node.clone();
2022-01-21 08:28:41 +00:00
node.name.unused = null;
node.value = value;
}
return node;
}
2022-02-07 14:48:46 +00:00
function trim_destructured(node, value, process, drop, root) {
2022-01-21 08:28:41 +00:00
var trimmer = new TreeTransformer(function(node) {
if (node instanceof AST_DefaultValue) {
2022-02-07 14:48:46 +00:00
if (!(compressor.option("default_values") && value && value.is_defined(compressor))) {
2022-01-21 08:28:41 +00:00
var save_drop = drop;
drop = false;
var trimmed = trim_default(trimmer, node);
drop = save_drop;
if (!trimmed && drop && value) value = value.drop_side_effect_free(compressor);
return trimmed;
2022-02-07 14:48:46 +00:00
} else if (node === root) {
root = node = node.name;
} else {
node = node.name;
2022-01-21 08:28:41 +00:00
}
}
if (node instanceof AST_DestructuredArray) {
var save_drop = drop;
var save_value = value;
if (value instanceof AST_SymbolRef) {
drop = false;
value = value.fixed_value();
}
2022-09-30 13:48:25 +00:00
var native, values;
if (value instanceof AST_Array) {
native = true;
values = value.elements;
} else {
native = value && value.is_string(compressor);
values = false;
}
2022-01-21 08:28:41 +00:00
var elements = [], newValues = drop && [], pos = 0;
node.elements.forEach(function(element, index) {
value = values && values[index];
if (value instanceof AST_Hole) {
value = null;
} else if (value instanceof AST_Spread) {
if (drop) {
newValues.length = pos;
fill_holes(save_value, newValues);
[].push.apply(newValues, values.slice(index));
save_value.elements = newValues;
}
value = values = false;
}
element = element.transform(trimmer);
if (element) elements[pos] = element;
if (drop && value) newValues[pos] = value;
if (element || value || !drop || !values) pos++;
});
value = values && make_node(AST_Array, save_value, {
elements: values.slice(node.elements.length),
});
if (node.rest) {
var was_drop = drop;
drop = false;
node.rest = node.rest.transform(compressor.option("rests") ? trimmer : tt);
drop = was_drop;
if (node.rest) elements.length = pos;
}
if (drop) {
if (value && !node.rest) value = value.drop_side_effect_free(compressor);
if (value instanceof AST_Array) {
value = value.elements;
} else if (value instanceof AST_Sequence) {
value = value.expressions;
} else if (value) {
value = [ value ];
}
if (value && value.length) {
newValues.length = pos;
[].push.apply(newValues, value);
}
}
value = save_value;
drop = save_drop;
if (values && newValues) {
fill_holes(value, newValues);
2022-06-08 10:36:39 +00:00
value = value.clone();
2022-01-21 08:28:41 +00:00
value.elements = newValues;
}
2022-09-30 13:48:25 +00:00
if (!native) {
elements.length = node.elements.length;
} else if (!node.rest) switch (elements.length) {
2022-01-21 08:28:41 +00:00
case 0:
2022-02-07 14:48:46 +00:00
if (node === root) break;
2022-01-21 08:28:41 +00:00
if (drop) value = value.drop_side_effect_free(compressor);
return null;
case 1:
if (!drop) break;
2022-02-07 14:48:46 +00:00
if (node === root) break;
2022-01-21 08:28:41 +00:00
var sym = elements[0];
if (sym.has_side_effects(compressor)) break;
if (value.has_side_effects(compressor) && sym.match_symbol(function(node) {
return node instanceof AST_PropAccess;
})) break;
value = make_node(AST_Sub, node, {
expression: value,
property: make_node(AST_Number, node, { value: 0 }),
});
return sym;
}
fill_holes(node, elements);
node.elements = elements;
return node;
}
if (node instanceof AST_DestructuredObject) {
var save_drop = drop;
var save_value = value;
if (value instanceof AST_SymbolRef) {
drop = false;
value = value.fixed_value();
}
2022-06-08 10:36:39 +00:00
var prop_keys, prop_map, values;
2022-01-21 08:28:41 +00:00
if (value instanceof AST_Object) {
prop_keys = [];
prop_map = new Dictionary();
2022-06-08 10:36:39 +00:00
values = value.properties.map(function(prop, index) {
prop = prop.clone();
if (prop instanceof AST_Spread) {
2022-01-21 08:28:41 +00:00
prop_map = false;
2022-06-08 10:36:39 +00:00
} else {
var key = prop.key;
if (key instanceof AST_Node) key = key.evaluate(compressor, true);
if (key instanceof AST_Node) {
prop_map = false;
} else if (prop_map && !(prop instanceof AST_ObjectSetter)) {
prop_map.set(key, prop);
}
prop_keys[index] = key;
2022-01-21 08:28:41 +00:00
}
2022-06-08 10:36:39 +00:00
return prop;
2022-01-21 08:28:41 +00:00
});
}
if (node.rest) {
value = false;
node.rest = node.rest.transform(compressor.option("rests") ? trimmer : tt);
}
var can_drop = new Dictionary();
var drop_keys = drop && new Dictionary();
var properties = [];
node.properties.map(function(prop) {
var key = prop.key;
if (key instanceof AST_Node) {
prop.key = key = key.transform(tt);
key = key.evaluate(compressor, true);
}
if (key instanceof AST_Node) {
drop_keys = false;
} else {
can_drop.set(key, !can_drop.has(key));
}
return key;
}).forEach(function(key, index) {
var prop = node.properties[index], trimmed;
if (key instanceof AST_Node) {
drop = false;
value = false;
trimmed = prop.value.transform(trimmer) || retain_lhs(prop.value);
} else {
drop = drop_keys && can_drop.get(key);
var mapped = prop_map && prop_map.get(key);
if (mapped) {
value = mapped.value;
if (value instanceof AST_Accessor) value = false;
} else {
value = false;
}
trimmed = prop.value.transform(trimmer);
if (!trimmed) {
if (node.rest || retain_key(prop)) trimmed = retain_lhs(prop.value);
if (drop_keys && !drop_keys.has(key)) {
if (mapped) {
drop_keys.set(key, mapped);
if (value === null) {
prop_map.set(key, retain_key(mapped) && make_node(AST_ObjectKeyVal, mapped, {
key: mapped.key,
value: make_node(AST_Number, mapped, { value: 0 }),
}));
}
} else {
drop_keys.set(key, true);
}
}
} else if (drop_keys) {
drop_keys.set(key, false);
}
if (value) mapped.value = value;
}
if (trimmed) {
prop.value = trimmed;
properties.push(prop);
}
});
value = save_value;
drop = save_drop;
2022-06-08 10:36:39 +00:00
if (drop_keys && prop_keys) {
value = value.clone();
value.properties = List(values, function(prop, index) {
if (prop instanceof AST_Spread) return prop;
var key = prop_keys[index];
if (key instanceof AST_Node) return prop;
if (drop_keys.has(key)) {
var mapped = drop_keys.get(key);
if (!mapped) return prop;
if (mapped === prop) return prop_map.get(key) || List.skip;
} else if (node.rest) {
return prop;
}
var trimmed = prop.value.drop_side_effect_free(compressor);
if (trimmed) {
prop.value = trimmed;
return prop;
}
return retain_key(prop) ? make_node(AST_ObjectKeyVal, prop, {
key: prop.key,
value: make_node(AST_Number, prop, { value: 0 }),
}) : List.skip;
});
}
2022-01-21 08:28:41 +00:00
if (value && !node.rest) switch (properties.length) {
case 0:
2022-02-07 14:48:46 +00:00
if (node === root) break;
2022-01-21 08:28:41 +00:00
if (value.may_throw_on_access(compressor, true)) break;
if (drop) value = value.drop_side_effect_free(compressor);
return null;
case 1:
if (!drop) break;
2022-02-07 14:48:46 +00:00
if (node === root) break;
2022-01-21 08:28:41 +00:00
var prop = properties[0];
if (prop.key instanceof AST_Node) break;
if (prop.value.has_side_effects(compressor)) break;
if (value.has_side_effects(compressor) && prop.value.match_symbol(function(node) {
return node instanceof AST_PropAccess;
})) break;
value = make_node(AST_Sub, node, {
expression: value,
property: make_node_from_constant(prop.key, prop),
});
return prop.value;
}
node.properties = properties;
return node;
}
if (node instanceof AST_Hole) {
node = null;
} else {
node = process(node);
}
if (!node && drop && value) value = value.drop_side_effect_free(compressor);
return node;
});
return {
name: node.transform(trimmer),
value: value,
};
function retain_key(prop) {
return prop.key instanceof AST_Node && prop.key.has_side_effects(compressor);
}
2022-03-14 15:40:45 +00:00
function clear_write_only(node) {
if (node instanceof AST_Assign) {
node.write_only = false;
clear_write_only(node.right);
} else if (node instanceof AST_Binary) {
if (!lazy_op[node.operator]) return;
clear_write_only(node.left);
clear_write_only(node.right);
} else if (node instanceof AST_Conditional) {
clear_write_only(node.consequent);
clear_write_only(node.alternative);
} else if (node instanceof AST_Sequence) {
clear_write_only(node.tail_node());
} else if (node instanceof AST_Unary) {
node.write_only = false;
}
}
2022-01-21 08:28:41 +00:00
function retain_lhs(node) {
if (node instanceof AST_DefaultValue) return retain_lhs(node.name);
if (node instanceof AST_Destructured) {
if (value === null) {
value = make_node(AST_Number, node, { value: 0 });
2022-03-14 15:40:45 +00:00
} else if (value) {
if (value.may_throw_on_access(compressor, true)) {
value = make_node(AST_Array, node, {
elements: value instanceof AST_Sequence ? value.expressions : [ value ],
});
} else {
clear_write_only(value);
}
2022-01-21 08:28:41 +00:00
}
return make_node(AST_DestructuredObject, node, { properties: [] });
}
node.unused = null;
return node;
}
}
});
AST_Scope.DEFMETHOD("hoist_declarations", function(compressor) {
if (compressor.has_directive("use asm")) return;
var hoist_funs = compressor.option("hoist_funs");
var hoist_vars = compressor.option("hoist_vars");
var self = this;
if (hoist_vars) {
// let's count var_decl first, we seem to waste a lot of
// space if we hoist `var` when there's only one.
var var_decl = 0;
self.walk(new TreeWalker(function(node) {
if (var_decl > 1) return true;
if (node instanceof AST_ExportDeclaration) return true;
if (node instanceof AST_Scope && node !== self) return true;
if (node instanceof AST_Var) {
var_decl++;
return true;
}
}));
if (var_decl <= 1) hoist_vars = false;
}
if (!hoist_funs && !hoist_vars) return;
var consts = new Dictionary();
var dirs = [];
var hoisted = [];
2022-04-11 08:07:00 +00:00
var vars = new Dictionary();
2022-01-21 08:28:41 +00:00
var tt = new TreeTransformer(function(node, descend, in_list) {
if (node === self) return;
if (node instanceof AST_Directive) {
dirs.push(node);
return in_list ? List.skip : make_node(AST_EmptyStatement, node);
}
if (node instanceof AST_LambdaDefinition) {
if (!hoist_funs) return node;
var p = tt.parent();
if (p instanceof AST_ExportDeclaration) return node;
if (p instanceof AST_ExportDefault) return node;
if (p !== self && compressor.has_directive("use strict")) return node;
hoisted.push(node);
return in_list ? List.skip : make_node(AST_EmptyStatement, node);
}
if (node instanceof AST_Var) {
if (!hoist_vars) return node;
var p = tt.parent();
if (p instanceof AST_ExportDeclaration) return node;
if (!all(node.definitions, function(defn) {
var sym = defn.name;
return sym instanceof AST_SymbolVar
&& !consts.has(sym.name)
&& self.find_variable(sym.name) === sym.definition();
})) return node;
2022-03-14 15:40:45 +00:00
node.definitions.forEach(function(defn) {
vars.set(defn.name.name, defn);
2022-01-21 08:28:41 +00:00
});
var seq = node.to_assignments();
if (p instanceof AST_ForEnumeration && p.init === node) {
if (seq) return seq;
2022-03-14 15:40:45 +00:00
var sym = node.definitions[0].name;
2022-08-31 14:34:36 +00:00
return make_node(AST_SymbolRef, sym);
2022-01-21 08:28:41 +00:00
}
if (p instanceof AST_For && p.init === node) return seq;
if (!seq) return in_list ? List.skip : make_node(AST_EmptyStatement, node);
return make_node(AST_SimpleStatement, node, { body: seq });
}
if (node instanceof AST_Scope) return node;
if (node instanceof AST_SymbolConst) {
consts.set(node.name, true);
return node;
}
});
self.transform(tt);
2022-04-11 08:07:00 +00:00
if (vars.size() > 0) {
2022-01-21 08:28:41 +00:00
// collect only vars which don't show up in self's arguments list
2022-03-14 15:40:45 +00:00
var defns = [];
2022-01-21 08:28:41 +00:00
if (self instanceof AST_Lambda) self.each_argname(function(argname) {
2022-08-05 07:44:52 +00:00
if (all(argname.definition().references, function(ref) {
return !ref.in_arg;
})) vars.del(argname.name);
2022-01-21 08:28:41 +00:00
});
2022-03-14 15:40:45 +00:00
vars.each(function(defn, name) {
defn = defn.clone();
defn.name = defn.name.clone();
defn.value = null;
defns.push(defn);
vars.set(name, defn);
defn.name.definition().orig.unshift(defn.name);
2022-01-21 08:28:41 +00:00
});
2022-09-30 13:48:25 +00:00
if (defns.length > 0) hoisted.push(make_node(AST_Var, self, { definitions: defns }));
2022-01-21 08:28:41 +00:00
}
self.body = dirs.concat(hoisted, self.body);
});
function scan_local_returns(fn, transform) {
fn.walk(new TreeWalker(function(node) {
if (node instanceof AST_Return) {
transform(node);
return true;
}
if (node instanceof AST_Scope && node !== fn) return true;
}));
}
2022-03-14 15:40:45 +00:00
function map_self_returns(fn) {
2022-01-21 08:28:41 +00:00
var map = Object.create(null);
scan_local_returns(fn, function(node) {
var value = node.value;
if (value) value = value.tail_node();
if (value instanceof AST_SymbolRef) {
var id = value.definition().id;
map[id] = (map[id] || 0) + 1;
}
});
return map;
}
2022-03-14 15:40:45 +00:00
function can_trim_returns(def, self_returns, compressor) {
if (compressor.exposed(def)) return false;
switch (def.references.length - def.replaced - (self_returns[def.id] || 0)) {
case def.drop_return:
return "d";
case def.bool_return:
return true;
}
2022-01-21 08:28:41 +00:00
}
function process_boolean_returns(fn, compressor) {
scan_local_returns(fn, function(node) {
node.in_bool = true;
var value = node.value;
if (value) {
var ev = fuzzy_eval(compressor, value);
if (!ev) {
value = value.drop_side_effect_free(compressor);
node.value = value ? make_sequence(node.value, [
value,
make_node(AST_Number, node.value, { value: 0 }),
]) : null;
} else if (!(ev instanceof AST_Node)) {
value = value.drop_side_effect_free(compressor);
node.value = value ? make_sequence(node.value, [
value,
make_node(AST_Number, node.value, { value: 1 }),
]) : make_node(AST_Number, node.value, { value: 1 });
}
}
});
}
2022-03-14 15:40:45 +00:00
AST_Scope.DEFMETHOD("process_returns", noop);
AST_Defun.DEFMETHOD("process_returns", function(compressor) {
2022-01-21 08:28:41 +00:00
if (!compressor.option("booleans")) return;
if (compressor.parent() instanceof AST_ExportDefault) return;
2022-03-14 15:40:45 +00:00
switch (can_trim_returns(this.name.definition(), map_self_returns(this), compressor)) {
case "d":
drop_returns(compressor, this, true);
break;
case true:
process_boolean_returns(this, compressor);
break;
}
2022-01-21 08:28:41 +00:00
});
2022-03-14 15:40:45 +00:00
AST_Function.DEFMETHOD("process_returns", function(compressor) {
2022-01-21 08:28:41 +00:00
if (!compressor.option("booleans")) return;
2022-03-14 15:40:45 +00:00
var drop = true;
var self_returns = map_self_returns(this);
if (this.name && !can_trim(this.name.definition())) return;
2022-01-21 08:28:41 +00:00
var parent = compressor.parent();
if (parent instanceof AST_Assign) {
if (parent.operator != "=") return;
var sym = parent.left;
if (!(sym instanceof AST_SymbolRef)) return;
2022-03-14 15:40:45 +00:00
if (!can_trim(sym.definition())) return;
2022-01-21 08:28:41 +00:00
} else if (parent instanceof AST_Call && parent.expression !== this) {
var exp = parent.expression;
if (exp instanceof AST_SymbolRef) exp = exp.fixed_value();
if (!(exp instanceof AST_Lambda)) return;
if (exp.uses_arguments || exp.pinned()) return;
2022-03-14 15:40:45 +00:00
var args = parent.args, sym;
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (arg === this) {
sym = exp.argnames[i];
if (!sym && exp.rest) return;
break;
}
if (arg instanceof AST_Spread) return;
}
2022-01-21 08:28:41 +00:00
if (sym instanceof AST_DefaultValue) sym = sym.name;
2022-03-14 15:40:45 +00:00
if (sym instanceof AST_SymbolFunarg && !can_trim(sym.definition())) return;
2022-01-21 08:28:41 +00:00
} else if (parent.TYPE == "Call") {
compressor.pop();
var in_bool = compressor.in_boolean_context();
compressor.push(this);
2022-03-14 15:40:45 +00:00
switch (in_bool) {
case true:
drop = false;
case "d":
break;
default:
return;
}
2022-01-21 08:28:41 +00:00
} else return;
2022-03-14 15:40:45 +00:00
if (drop) {
drop_returns(compressor, this, true);
} else {
process_boolean_returns(this, compressor);
}
function can_trim(def) {
switch (can_trim_returns(def, self_returns, compressor)) {
case true:
drop = false;
case "d":
return true;
}
}
2022-01-21 08:28:41 +00:00
});
AST_BlockScope.DEFMETHOD("var_names", function() {
var var_names = this._var_names;
if (!var_names) {
this._var_names = var_names = new Dictionary();
this.enclosed.forEach(function(def) {
var_names.set(def.name, true);
});
this.variables.each(function(def, name) {
var_names.set(name, true);
});
}
return var_names;
});
AST_Scope.DEFMETHOD("make_var", function(type, orig, prefix) {
var scopes = [ this ];
if (orig instanceof AST_SymbolDeclaration) orig.definition().references.forEach(function(ref) {
var s = ref.scope;
do {
2022-08-31 14:34:36 +00:00
if (!push_uniq(scopes, s)) return;
2022-01-21 08:28:41 +00:00
s = s.parent_scope;
} while (s && s !== this);
});
2022-02-07 14:48:46 +00:00
prefix = prefix.replace(/^[^a-z_$]|[^a-z0-9_$]/gi, "_");
2022-01-21 08:28:41 +00:00
var name = prefix;
for (var i = 0; !all(scopes, function(scope) {
return !scope.var_names().has(name);
}); i++) name = prefix + "$" + i;
var sym = make_node(type, orig, {
name: name,
scope: this,
});
var def = this.def_variable(sym);
scopes.forEach(function(scope) {
scope.enclosed.push(def);
scope.var_names().set(name, true);
});
return sym;
});
AST_Scope.DEFMETHOD("hoist_properties", function(compressor) {
if (!compressor.option("hoist_props") || compressor.has_directive("use asm")) return;
var self = this;
2022-09-30 13:48:25 +00:00
if (is_arrow(self) && self.value) return;
2022-01-21 08:28:41 +00:00
var top_retain = self instanceof AST_Toplevel && compressor.top_retain || return_false;
var defs_by_id = Object.create(null);
2022-06-08 10:36:39 +00:00
var tt = new TreeTransformer(function(node, descend) {
2022-01-21 08:28:41 +00:00
if (node instanceof AST_Assign) {
if (node.operator != "=") return;
if (!node.write_only) return;
if (!can_hoist(node.left, node.right, 1)) return;
2022-06-08 10:36:39 +00:00
descend(node, tt);
2022-01-21 08:28:41 +00:00
var defs = new Dictionary();
var assignments = [];
var decls = [];
node.right.properties.forEach(function(prop) {
var decl = make_sym(AST_SymbolVar, node.left, prop.key);
decls.push(make_node(AST_VarDef, node, {
name: decl,
value: null,
}));
var sym = make_node(AST_SymbolRef, node, {
name: decl.name,
scope: self,
thedef: decl.definition(),
});
sym.reference();
assignments.push(make_node(AST_Assign, node, {
operator: "=",
left: sym,
right: prop.value,
}));
});
defs.value = node.right;
defs_by_id[node.left.definition().id] = defs;
2022-06-08 10:36:39 +00:00
self.body.splice(self.body.indexOf(tt.stack[1]) + 1, 0, make_node(AST_Var, node, {
2022-01-21 08:28:41 +00:00
definitions: decls,
}));
return make_sequence(node, assignments);
}
2022-06-08 10:36:39 +00:00
if (node instanceof AST_Scope) {
if (node === self) return;
var parent = tt.parent();
if (parent.TYPE == "Call" && parent.expression === node) return;
return node;
}
2022-01-21 08:28:41 +00:00
if (node instanceof AST_VarDef) {
if (!can_hoist(node.name, node.value, 0)) return;
2022-06-08 10:36:39 +00:00
descend(node, tt);
2022-01-21 08:28:41 +00:00
var defs = new Dictionary();
var var_defs = [];
var decl = node.clone();
decl.value = node.name instanceof AST_SymbolConst ? make_node(AST_Number, node, { value: 0 }) : null;
var_defs.push(decl);
node.value.properties.forEach(function(prop) {
var_defs.push(make_node(AST_VarDef, node, {
name: make_sym(node.name.CTOR, node.name, prop.key),
value: prop.value,
}));
});
defs.value = node.value;
defs_by_id[node.name.definition().id] = defs;
return List.splice(var_defs);
}
function make_sym(type, sym, key) {
var new_var = self.make_var(type, sym, sym.name + "_" + key);
defs.set(key, new_var.definition());
return new_var;
}
2022-06-08 10:36:39 +00:00
});
self.transform(tt);
2022-01-21 08:28:41 +00:00
self.transform(new TreeTransformer(function(node, descend) {
if (node instanceof AST_PropAccess) {
if (!(node.expression instanceof AST_SymbolRef)) return;
var defs = defs_by_id[node.expression.definition().id];
if (!defs) return;
if (node.expression.fixed_value() !== defs.value) return;
var def = defs.get(node.get_property());
var sym = make_node(AST_SymbolRef, node, {
name: def.name,
scope: node.expression.scope,
thedef: def,
});
sym.reference();
return sym;
}
if (node instanceof AST_SymbolRef) {
var defs = defs_by_id[node.definition().id];
if (!defs) return;
if (node.fixed_value() !== defs.value) return;
return make_node(AST_Object, node, { properties: [] });
}
}));
function can_hoist(sym, right, count) {
if (!(sym instanceof AST_Symbol)) return;
var def = sym.definition();
if (def.assignments != count) return;
if (def.references.length - def.replaced == count) return;
if (def.single_use) return;
2022-06-08 10:36:39 +00:00
if (self.find_variable(sym.name) !== def) return;
2022-01-21 08:28:41 +00:00
if (top_retain(def)) return;
if (sym.fixed_value() !== right) return;
var fixed = sym.fixed || def.fixed;
if (fixed.direct_access) return;
if (fixed.escaped && fixed.escaped.depth == 1) return;
return right instanceof AST_Object
&& right.properties.length > 0
2022-07-11 11:25:19 +00:00
&& can_drop_symbol(sym, compressor)
&& all(right.properties, function(prop) {
return can_hoist_property(prop) && prop.key !== "__proto__";
});
2022-01-21 08:28:41 +00:00
}
});
function fn_name_unused(fn, compressor) {
if (!fn.name || !compressor.option("ie")) return true;
var def = fn.name.definition();
if (compressor.exposed(def)) return false;
return all(def.references, function(sym) {
return !(sym instanceof AST_SymbolRef);
});
}
2022-03-14 15:40:45 +00:00
function drop_returns(compressor, exp, ignore_name) {
if (!(exp instanceof AST_Lambda)) return;
var arrow = is_arrow(exp);
var async = is_async(exp);
var changed = false;
var drop_body = false;
if (arrow && compressor.option("arrows")) {
if (!exp.value) {
drop_body = true;
2022-09-30 13:48:25 +00:00
} else if (!async || needs_enqueuing(compressor, exp.value)) {
2022-03-14 15:40:45 +00:00
var dropped = exp.value.drop_side_effect_free(compressor);
if (dropped !== exp.value) {
changed = true;
exp.value = dropped;
}
}
} else if (!is_generator(exp)) {
if (!ignore_name && exp.name) {
var def = exp.name.definition();
drop_body = def.references.length == def.replaced;
} else {
drop_body = true;
}
}
if (drop_body) {
exp.process_expression(false, function(node) {
var value = node.value;
if (value) {
2022-09-30 13:48:25 +00:00
if (async && !needs_enqueuing(compressor, value)) return node;
2022-03-14 15:40:45 +00:00
value = value.drop_side_effect_free(compressor, true);
}
changed = true;
if (!value) return make_node(AST_EmptyStatement, node);
return make_node(AST_SimpleStatement, node, { body: value });
});
scan_local_returns(exp, function(node) {
var value = node.value;
if (value) {
2022-09-30 13:48:25 +00:00
if (async && !needs_enqueuing(compressor, value)) return;
2022-03-14 15:40:45 +00:00
var dropped = value.drop_side_effect_free(compressor);
if (dropped !== value) {
changed = true;
2022-09-30 13:48:25 +00:00
if (dropped && async && !needs_enqueuing(compressor, dropped)) {
2022-06-08 10:36:39 +00:00
dropped = dropped.negate(compressor);
}
2022-03-14 15:40:45 +00:00
node.value = dropped;
}
}
});
}
if (async && compressor.option("awaits")) {
if (drop_body) exp.process_expression("awaits", function(node) {
var body = node.body;
if (body instanceof AST_Await) {
2022-09-30 13:48:25 +00:00
if (needs_enqueuing(compressor, body.expression)) {
2022-03-14 15:40:45 +00:00
changed = true;
body = body.expression.drop_side_effect_free(compressor, true);
if (!body) return make_node(AST_EmptyStatement, node);
node.body = body;
}
} else if (body instanceof AST_Sequence) {
var exprs = body.expressions;
for (var i = exprs.length; --i >= 0;) {
var tail = exprs[i];
if (!(tail instanceof AST_Await)) break;
var value = tail.expression;
2022-09-30 13:48:25 +00:00
if (!needs_enqueuing(compressor, value)) break;
2022-03-14 15:40:45 +00:00
changed = true;
if (exprs[i] = value.drop_side_effect_free(compressor)) break;
}
switch (i) {
case -1:
return make_node(AST_EmptyStatement, node);
case 0:
node.body = exprs[0];
break;
default:
exprs.length = i + 1;
break;
}
}
return node;
});
2022-09-30 13:48:25 +00:00
var abort = !drop_body && exp.name || arrow && exp.value && !needs_enqueuing(compressor, exp.value);
2022-03-14 15:40:45 +00:00
var tw = new TreeWalker(function(node) {
if (abort) return true;
if (tw.parent() === exp && node.may_throw(compressor)) return abort = true;
if (node instanceof AST_Await) return abort = true;
if (node instanceof AST_ForAwaitOf) return abort = true;
if (node instanceof AST_Return) {
2022-09-30 13:48:25 +00:00
if (node.value && !needs_enqueuing(compressor, node.value)) return abort = true;
2022-03-14 15:40:45 +00:00
return;
}
if (node instanceof AST_Scope && node !== exp) return true;
});
exp.walk(tw);
if (!abort) {
var ctor;
switch (exp.CTOR) {
case AST_AsyncArrow:
ctor = AST_Arrow;
break;
case AST_AsyncFunction:
ctor = AST_Function;
break;
case AST_AsyncGeneratorFunction:
ctor = AST_GeneratorFunction;
break;
}
2022-08-31 14:34:36 +00:00
return make_node(ctor, exp);
2022-03-14 15:40:45 +00:00
}
}
return changed && exp.clone();
}
2022-01-21 08:28:41 +00:00
// drop_side_effect_free()
// remove side-effect-free parts which only affects return value
(function(def) {
// Drop side-effect-free elements from an array of expressions.
// Returns an array of expressions with side-effects or null
// if all elements were dropped. Note: original array may be
// returned if nothing changed.
function trim(nodes, compressor, first_in_statement, spread) {
var len = nodes.length;
var ret = [], changed = false;
for (var i = 0; i < len; i++) {
var node = nodes[i];
var trimmed;
if (spread && node instanceof AST_Spread) {
trimmed = spread(node, compressor, first_in_statement);
} else {
trimmed = node.drop_side_effect_free(compressor, first_in_statement);
}
if (trimmed !== node) changed = true;
if (trimmed) {
ret.push(trimmed);
first_in_statement = false;
}
}
return ret.length ? changed ? ret : nodes : null;
}
function array_spread(node, compressor, first_in_statement) {
var exp = node.expression;
if (!exp.is_string(compressor)) return node;
return exp.drop_side_effect_free(compressor, first_in_statement);
}
function convert_spread(node) {
2022-02-07 14:48:46 +00:00
return node instanceof AST_Spread ? make_node(AST_Array, node, { elements: [ node ] }) : node;
2022-01-21 08:28:41 +00:00
}
def(AST_Node, return_this);
def(AST_Accessor, return_null);
def(AST_Array, function(compressor, first_in_statement) {
var values = trim(this.elements, compressor, first_in_statement, array_spread);
if (!values) return null;
if (values === this.elements && all(values, function(node) {
return node instanceof AST_Spread;
})) return this;
return make_sequence(this, values.map(convert_spread));
});
def(AST_Assign, function(compressor) {
var left = this.left;
if (left instanceof AST_PropAccess) {
var expr = left.expression;
if (expr.may_throw_on_access(compressor, true)) return this;
if (compressor.has_directive("use strict") && expr.is_constant()) return this;
}
if (left.has_side_effects(compressor)) return this;
if (lazy_op[this.operator.slice(0, -1)]) return this;
this.write_only = true;
if (!root_expr(left).is_constant_expression(compressor.find_parent(AST_Scope))) return this;
return this.right.drop_side_effect_free(compressor);
});
def(AST_Await, function(compressor) {
if (!compressor.option("awaits")) return this;
var exp = this.expression;
2022-09-30 13:48:25 +00:00
if (!needs_enqueuing(compressor, exp)) return this;
2022-02-07 14:48:46 +00:00
if (exp instanceof AST_UnaryPrefix && exp.operator == "!") exp = exp.expression;
var dropped = exp.drop_side_effect_free(compressor);
if (dropped === exp) return this;
if (!dropped) {
dropped = make_node(AST_Number, exp, { value: 0 });
2022-09-30 13:48:25 +00:00
} else if (!needs_enqueuing(compressor, dropped)) {
2022-02-07 14:48:46 +00:00
dropped = dropped.negate(compressor);
}
2022-01-21 08:28:41 +00:00
var node = this.clone();
2022-02-07 14:48:46 +00:00
node.expression = dropped;
2022-01-21 08:28:41 +00:00
return node;
});
def(AST_Binary, function(compressor, first_in_statement) {
var left = this.left;
var right = this.right;
var op = this.operator;
2022-07-11 11:25:19 +00:00
if (!can_drop_op(op, right, compressor)) {
2022-01-21 08:28:41 +00:00
var lhs = left.drop_side_effect_free(compressor, first_in_statement);
if (lhs === left) return this;
var node = this.clone();
node.left = lhs || make_node(AST_Number, left, { value: 0 });
return node;
}
var rhs = right.drop_side_effect_free(compressor, first_in_statement);
if (!rhs) return left.drop_side_effect_free(compressor, first_in_statement);
if (lazy_op[op] && rhs.has_side_effects(compressor)) {
var node = this;
if (rhs !== right) {
node = node.clone();
node.right = rhs.drop_side_effect_free(compressor);
}
if (op == "??") return node;
2022-03-14 15:40:45 +00:00
var negated = node.clone();
negated.operator = op == "&&" ? "||" : "&&";
negated.left = left.negate(compressor, first_in_statement);
2022-11-30 12:56:09 +00:00
var negated_rhs = negated.right.tail_node();
if (negated_rhs instanceof AST_Binary && negated.operator == negated_rhs.operator) swap_chain(negated);
2022-03-14 15:40:45 +00:00
var best = first_in_statement ? best_of_statement : best_of_expression;
return op == "&&" ? best(node, negated) : best(negated, node);
2022-01-21 08:28:41 +00:00
}
var lhs = left.drop_side_effect_free(compressor, first_in_statement);
if (!lhs) return rhs;
rhs = rhs.drop_side_effect_free(compressor);
if (!rhs) return lhs;
return make_sequence(this, [ lhs, rhs ]);
});
2022-02-07 14:48:46 +00:00
function assign_this_only(fn, compressor) {
fn.new = true;
var result = all(fn.body, function(stat) {
return !stat.has_side_effects(compressor);
}) && all(fn.argnames, function(argname) {
return !argname.match_symbol(return_false);
}) && !(fn.rest && fn.rest.match_symbol(return_false));
fn.new = false;
return result;
}
def(AST_Call, function(compressor, first_in_statement) {
var self = this;
2022-01-21 08:28:41 +00:00
if (self.is_expr_pure(compressor)) {
2022-08-31 14:34:36 +00:00
if (self.pure) AST_Node.warn("Dropping __PURE__ call [{start}]", self);
2022-01-21 08:28:41 +00:00
var args = trim(self.args, compressor, first_in_statement, array_spread);
return args && make_sequence(self, args.map(convert_spread));
}
var exp = self.expression;
if (self.is_call_pure(compressor)) {
var exprs = self.args.slice();
exprs.unshift(exp.expression);
exprs = trim(exprs, compressor, first_in_statement, array_spread);
return exprs && make_sequence(self, exprs.map(convert_spread));
}
if (compressor.option("yields") && is_generator(exp)) {
var call = self.clone();
2022-08-31 14:34:36 +00:00
call.expression = make_node(AST_Function, exp);
2022-01-21 08:28:41 +00:00
call.expression.body = [];
var opt = call.transform(compressor);
if (opt !== call) return opt.drop_side_effect_free(compressor, first_in_statement);
}
var dropped = drop_returns(compressor, exp);
if (dropped) {
// always shallow clone to ensure stripping of negated IIFEs
self = self.clone();
self.expression = dropped;
// avoid extraneous traversal
if (exp._squeezed) self.expression._squeezed = true;
}
if (self instanceof AST_New) {
var fn = exp;
if (fn instanceof AST_SymbolRef) fn = fn.fixed_value();
if (fn instanceof AST_Lambda) {
if (assign_this_only(fn, compressor)) {
var exprs = self.args.slice();
exprs.unshift(exp);
exprs = trim(exprs, compressor, first_in_statement, array_spread);
return exprs && make_sequence(self, exprs.map(convert_spread));
}
2022-02-07 14:48:46 +00:00
if (!fn.contains_this()) {
2022-08-31 14:34:36 +00:00
self = make_node(AST_Call, self);
2022-02-07 14:48:46 +00:00
self.expression = self.expression.clone();
self.args = self.args.slice();
}
2022-01-21 08:28:41 +00:00
}
}
self.call_only = true;
return self;
});
2022-02-07 14:48:46 +00:00
def(AST_ClassExpression, function(compressor, first_in_statement) {
var self = this;
2022-07-11 11:25:19 +00:00
var exprs = [], values = [], init = 0;
2022-01-21 08:28:41 +00:00
var props = self.properties;
for (var i = 0; i < props.length; i++) {
var prop = props[i];
if (prop.key instanceof AST_Node) exprs.push(prop.key);
2022-07-11 11:25:19 +00:00
if (!is_static_field_or_init(prop)) continue;
var value = prop.value;
if (!value.has_side_effects(compressor)) continue;
if (value.contains_this()) return self;
if (prop instanceof AST_ClassInit) {
init++;
values.push(prop);
} else {
values.push(value);
2022-01-21 08:28:41 +00:00
}
}
var base = self.extends;
if (base) {
if (base instanceof AST_SymbolRef) base = base.fixed_value();
base = !safe_for_extends(base);
if (!base) exprs.unshift(self.extends);
}
exprs = trim(exprs, compressor, first_in_statement);
if (exprs) first_in_statement = false;
values = trim(values, compressor, first_in_statement);
if (!exprs) {
2022-02-07 14:48:46 +00:00
if (!base && !values && !self.name) return null;
2022-01-21 08:28:41 +00:00
exprs = [];
}
2022-02-07 14:48:46 +00:00
if (base || self.name || !compressor.has_directive("use strict")) {
var node = to_class_expr(self);
if (!base) node.extends = null;
2022-01-21 08:28:41 +00:00
node.properties = [];
2022-02-07 14:48:46 +00:00
if (values) {
2022-07-11 11:25:19 +00:00
if (values.length == init) {
if (exprs.length) values.unshift(make_node(AST_ClassField, self, {
key: make_sequence(self, exprs),
value: null,
}));
node.properties = values;
} else node.properties.push(make_node(AST_ClassField, self, {
2022-02-07 14:48:46 +00:00
static: true,
key: exprs.length ? make_sequence(self, exprs) : "c",
2022-07-11 11:25:19 +00:00
value: make_value(),
2022-02-07 14:48:46 +00:00
}));
2022-07-11 11:25:19 +00:00
} else if (exprs.length) node.properties.push(make_node(AST_ClassMethod, self, {
key: make_sequence(self, exprs),
value: make_node(AST_Function, self, {
argnames: [],
body: [],
}).init_vars(node),
}));
2022-02-07 14:48:46 +00:00
return node;
2022-01-21 08:28:41 +00:00
}
if (values) exprs.push(make_node(AST_Call, self, {
expression: make_node(AST_Arrow, self, {
argnames: [],
body: [],
2022-07-11 11:25:19 +00:00
value: make_value(),
2022-01-21 08:28:41 +00:00
}).init_vars(self.parent_scope),
args: [],
}));
return make_sequence(self, exprs);
2022-07-11 11:25:19 +00:00
function make_value() {
return make_sequence(self, values.map(function(node) {
if (!(node instanceof AST_ClassInit)) return node;
2022-08-31 14:34:36 +00:00
var fn = make_node(AST_Arrow, node.value);
2022-07-11 11:25:19 +00:00
fn.argnames = [];
return make_node(AST_Call, node, {
expression: fn,
args: [],
});
}));
}
2022-01-21 08:28:41 +00:00
});
def(AST_Conditional, function(compressor) {
var consequent = this.consequent.drop_side_effect_free(compressor);
var alternative = this.alternative.drop_side_effect_free(compressor);
if (consequent === this.consequent && alternative === this.alternative) return this;
var exprs;
if (compressor.option("ie")) {
exprs = [];
if (consequent instanceof AST_Function) {
exprs.push(consequent);
consequent = null;
}
if (alternative instanceof AST_Function) {
exprs.push(alternative);
alternative = null;
}
}
var node;
if (!consequent) {
node = alternative ? make_node(AST_Binary, this, {
operator: "||",
left: this.condition,
2022-02-07 14:48:46 +00:00
right: alternative,
2022-01-21 08:28:41 +00:00
}) : this.condition.drop_side_effect_free(compressor);
} else if (!alternative) {
node = make_node(AST_Binary, this, {
operator: "&&",
left: this.condition,
2022-02-07 14:48:46 +00:00
right: consequent,
2022-01-21 08:28:41 +00:00
});
} else {
node = this.clone();
node.consequent = consequent;
node.alternative = alternative;
}
2022-02-07 14:48:46 +00:00
if (!exprs) return node;
2022-01-21 08:28:41 +00:00
if (node) exprs.push(node);
return exprs.length == 0 ? null : make_sequence(this, exprs);
});
def(AST_Constant, return_null);
def(AST_Dot, function(compressor, first_in_statement) {
var expr = this.expression;
2022-02-07 14:48:46 +00:00
if (expr.may_throw_on_access(compressor)) return this;
2022-01-21 08:28:41 +00:00
return expr.drop_side_effect_free(compressor, first_in_statement);
});
def(AST_Function, function(compressor) {
return fn_name_unused(this, compressor) ? null : this;
});
def(AST_LambdaExpression, return_null);
def(AST_Object, function(compressor, first_in_statement) {
var exprs = [];
this.properties.forEach(function(prop) {
if (prop instanceof AST_Spread) {
exprs.push(prop);
} else {
if (prop.key instanceof AST_Node) exprs.push(prop.key);
exprs.push(prop.value);
}
});
var values = trim(exprs, compressor, first_in_statement, function(node, compressor, first_in_statement) {
var exp = node.expression;
2022-02-07 14:48:46 +00:00
return exp.safe_to_spread() ? exp.drop_side_effect_free(compressor, first_in_statement) : node;
2022-01-21 08:28:41 +00:00
});
if (!values) return null;
if (values === exprs && !all(values, function(node) {
return !(node instanceof AST_Spread);
})) return this;
return make_sequence(this, values.map(function(node) {
2022-02-07 14:48:46 +00:00
return node instanceof AST_Spread ? make_node(AST_Object, node, { properties: [ node ] }) : node;
2022-01-21 08:28:41 +00:00
}));
});
def(AST_ObjectIdentity, return_null);
def(AST_Sequence, function(compressor, first_in_statement) {
var expressions = trim(this.expressions, compressor, first_in_statement);
if (!expressions) return null;
var end = expressions.length - 1;
var last = expressions[end];
if (compressor.option("awaits") && end > 0 && last instanceof AST_Await && last.expression.is_constant()) {
expressions = expressions.slice(0, -1);
end--;
2022-02-07 14:48:46 +00:00
var expr = expressions[end];
2022-09-30 13:48:25 +00:00
last.expression = needs_enqueuing(compressor, expr) ? expr : expr.negate(compressor);
2022-01-21 08:28:41 +00:00
expressions[end] = last;
}
var assign, cond, lhs;
if (compressor.option("conditionals")
&& end > 0
&& (assign = expressions[end - 1]) instanceof AST_Assign
&& assign.operator == "="
&& (lhs = assign.left) instanceof AST_SymbolRef
&& (cond = to_conditional_assignment(compressor, lhs.definition(), assign.right, last))) {
assign = assign.clone();
assign.right = cond;
expressions = expressions.slice(0, -2);
expressions.push(assign.drop_side_effect_free(compressor, first_in_statement));
}
return expressions === this.expressions ? this : make_sequence(this, expressions);
});
def(AST_Sub, function(compressor, first_in_statement) {
var expr = this.expression;
2022-02-07 14:48:46 +00:00
if (expr.may_throw_on_access(compressor)) return this;
2022-01-21 08:28:41 +00:00
var prop = this.property;
expr = expr.drop_side_effect_free(compressor, first_in_statement);
if (!expr) return prop.drop_side_effect_free(compressor, first_in_statement);
prop = prop.drop_side_effect_free(compressor);
if (!prop) return expr;
return make_sequence(this, [ expr, prop ]);
});
def(AST_SymbolRef, function(compressor) {
return this.is_declared(compressor) && can_drop_symbol(this, compressor) ? null : this;
});
def(AST_Template, function(compressor, first_in_statement) {
var self = this;
if (self.is_expr_pure(compressor)) {
var expressions = self.expressions;
if (expressions.length == 0) return null;
return make_sequence(self, expressions).drop_side_effect_free(compressor, first_in_statement);
}
var tag = self.tag;
var dropped = drop_returns(compressor, tag);
if (dropped) {
// always shallow clone to signal internal changes
self = self.clone();
self.tag = dropped;
// avoid extraneous traversal
if (tag._squeezed) self.tag._squeezed = true;
}
return self;
});
def(AST_Unary, function(compressor, first_in_statement) {
var exp = this.expression;
if (unary_side_effects[this.operator]) {
this.write_only = !exp.has_side_effects(compressor);
return this;
}
if (this.operator == "typeof" && exp instanceof AST_SymbolRef && can_drop_symbol(exp, compressor)) {
return null;
}
var node = exp.drop_side_effect_free(compressor, first_in_statement);
if (first_in_statement && node && is_iife_call(node)) {
if (node === exp && this.operator == "!") return this;
return node.negate(compressor, first_in_statement);
}
return node;
});
})(function(node, func) {
node.DEFMETHOD("drop_side_effect_free", func);
});
OPT(AST_SimpleStatement, function(self, compressor) {
if (compressor.option("side_effects")) {
var body = self.body;
var node = body.drop_side_effect_free(compressor, true);
if (!node) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Dropping side-effect-free statement [{start}]", self);
2022-01-21 08:28:41 +00:00
return make_node(AST_EmptyStatement, self);
}
if (node !== body) {
return make_node(AST_SimpleStatement, self, { body: node });
}
}
return self;
});
OPT(AST_While, function(self, compressor) {
2022-08-31 14:34:36 +00:00
return compressor.option("loops") ? make_node(AST_For, self).optimize(compressor) : self;
2022-01-21 08:28:41 +00:00
});
function has_loop_control(loop, parent, type) {
if (!type) type = AST_LoopControl;
var found = false;
var tw = new TreeWalker(function(node) {
if (found || node instanceof AST_Scope) return true;
if (node instanceof type && tw.loopcontrol_target(node) === loop) {
return found = true;
}
});
if (parent instanceof AST_LabeledStatement) tw.push(parent);
tw.push(loop);
loop.body.walk(tw);
return found;
}
OPT(AST_Do, function(self, compressor) {
if (!compressor.option("loops")) return self;
var cond = fuzzy_eval(compressor, self.condition);
if (!(cond instanceof AST_Node)) {
if (cond && !has_loop_control(self, compressor.parent(), AST_Continue)) return make_node(AST_For, self, {
body: make_node(AST_BlockStatement, self.body, {
body: [
self.body,
2022-08-31 14:34:36 +00:00
make_node(AST_SimpleStatement, self.condition, { body: self.condition }),
],
}),
2022-01-21 08:28:41 +00:00
}).optimize(compressor);
if (!has_loop_control(self, compressor.parent())) return make_node(AST_BlockStatement, self.body, {
body: [
self.body,
2022-08-31 14:34:36 +00:00
make_node(AST_SimpleStatement, self.condition, { body: self.condition }),
],
2022-01-21 08:28:41 +00:00
}).optimize(compressor);
}
if (self.body instanceof AST_BlockStatement && !has_loop_control(self, compressor.parent(), AST_Continue)) {
var body = self.body.body;
for (var i = body.length; --i >= 0;) {
var stat = body[i];
if (stat instanceof AST_If
&& !stat.alternative
&& stat.body instanceof AST_Break
&& compressor.loopcontrol_target(stat.body) === self) {
if (has_block_scope_refs(stat.condition)) break;
self.condition = make_node(AST_Binary, self, {
operator: "&&",
left: stat.condition.negate(compressor),
right: self.condition,
});
body.splice(i, 1);
} else if (stat instanceof AST_SimpleStatement) {
if (has_block_scope_refs(stat.body)) break;
self.condition = make_sequence(self, [
stat.body,
self.condition,
]);
body.splice(i, 1);
} else if (!is_declaration(stat, true)) {
break;
}
}
self.body = trim_block(self.body, compressor.parent());
}
2022-08-31 14:34:36 +00:00
if (self.body instanceof AST_EmptyStatement) return make_node(AST_For, self).optimize(compressor);
2022-01-21 08:28:41 +00:00
if (self.body instanceof AST_SimpleStatement) return make_node(AST_For, self, {
condition: make_sequence(self.condition, [
self.body.body,
2022-08-31 14:34:36 +00:00
self.condition,
2022-01-21 08:28:41 +00:00
]),
2022-08-31 14:34:36 +00:00
body: make_node(AST_EmptyStatement, self),
2022-01-21 08:28:41 +00:00
}).optimize(compressor);
return self;
function has_block_scope_refs(node) {
var found = false;
node.walk(new TreeWalker(function(node) {
if (found) return true;
if (node instanceof AST_SymbolRef) {
if (!member(node.definition(), self.enclosed)) found = true;
return true;
}
}));
return found;
}
});
function if_break_in_loop(self, compressor) {
var first = first_statement(self.body);
if (compressor.option("dead_code")
&& (first instanceof AST_Break
|| first instanceof AST_Continue && external_target(first)
|| first instanceof AST_Exit)) {
var body = [];
if (is_statement(self.init)) {
body.push(self.init);
} else if (self.init) {
2022-08-31 14:34:36 +00:00
body.push(make_node(AST_SimpleStatement, self.init, { body: self.init }));
2022-01-21 08:28:41 +00:00
}
var retain = external_target(first) || first instanceof AST_Exit;
if (self.condition && retain) {
body.push(make_node(AST_If, self, {
condition: self.condition,
body: first,
2022-08-31 14:34:36 +00:00
alternative: null,
2022-01-21 08:28:41 +00:00
}));
} else if (self.condition) {
2022-08-31 14:34:36 +00:00
body.push(make_node(AST_SimpleStatement, self.condition, { body: self.condition }));
2022-01-21 08:28:41 +00:00
} else if (retain) {
body.push(first);
}
extract_declarations_from_unreachable_code(compressor, self.body, body);
2022-08-31 14:34:36 +00:00
return make_node(AST_BlockStatement, self, { body: body });
2022-01-21 08:28:41 +00:00
}
if (first instanceof AST_If) {
var ab = first_statement(first.body);
if (ab instanceof AST_Break && !external_target(ab)) {
if (self.condition) {
self.condition = make_node(AST_Binary, self.condition, {
left: self.condition,
operator: "&&",
right: first.condition.negate(compressor),
});
} else {
self.condition = first.condition.negate(compressor);
}
var body = as_statement_array(first.alternative);
extract_declarations_from_unreachable_code(compressor, first.body, body);
return drop_it(body);
}
ab = first_statement(first.alternative);
if (ab instanceof AST_Break && !external_target(ab)) {
if (self.condition) {
self.condition = make_node(AST_Binary, self.condition, {
left: self.condition,
operator: "&&",
right: first.condition,
});
} else {
self.condition = first.condition;
}
var body = as_statement_array(first.body);
extract_declarations_from_unreachable_code(compressor, first.alternative, body);
return drop_it(body);
}
}
return self;
function first_statement(body) {
return body instanceof AST_BlockStatement ? body.body[0] : body;
}
function external_target(node) {
return compressor.loopcontrol_target(node) !== compressor.self();
}
function drop_it(rest) {
if (self.body instanceof AST_BlockStatement) {
self.body = self.body.clone();
self.body.body = rest.concat(self.body.body.slice(1));
self.body = self.body.transform(compressor);
} else {
2022-08-31 14:34:36 +00:00
self.body = make_node(AST_BlockStatement, self.body, { body: rest }).transform(compressor);
2022-01-21 08:28:41 +00:00
}
return if_break_in_loop(self, compressor);
}
}
OPT(AST_For, function(self, compressor) {
if (!compressor.option("loops")) return self;
if (compressor.option("side_effects")) {
if (self.init) self.init = self.init.drop_side_effect_free(compressor);
if (self.step) self.step = self.step.drop_side_effect_free(compressor);
}
if (self.condition) {
var cond = fuzzy_eval(compressor, self.condition);
if (!cond) {
if (compressor.option("dead_code")) {
var body = [];
if (is_statement(self.init)) {
body.push(self.init);
} else if (self.init) {
body.push(make_node(AST_SimpleStatement, self.init, { body: self.init }));
}
body.push(make_node(AST_SimpleStatement, self.condition, { body: self.condition }));
extract_declarations_from_unreachable_code(compressor, self.body, body);
return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor);
}
} else if (!(cond instanceof AST_Node)) {
self.body = make_node(AST_BlockStatement, self.body, {
body: [
make_node(AST_SimpleStatement, self.condition, { body: self.condition }),
self.body,
],
});
self.condition = null;
}
}
return if_break_in_loop(self, compressor);
});
OPT(AST_ForEnumeration, function(self, compressor) {
if (compressor.option("varify") && is_lexical_definition(self.init)) {
var name = self.init.definitions[0].name;
if ((name instanceof AST_Destructured || name instanceof AST_SymbolLet)
&& !name.match_symbol(function(node) {
if (node instanceof AST_SymbolDeclaration) {
var def = node.definition();
return !same_scope(def) || may_overlap(compressor, def);
}
}, true)) {
2022-10-10 08:26:02 +00:00
self.init = to_var(self.init, self.resolve());
2022-01-21 08:28:41 +00:00
}
}
return self;
});
function mark_locally_defined(condition, consequent, alternative) {
2022-02-07 14:48:46 +00:00
if (condition instanceof AST_Sequence) condition = condition.tail_node();
2022-01-21 08:28:41 +00:00
if (!(condition instanceof AST_Binary)) return;
if (!(condition.left instanceof AST_String)) {
switch (condition.operator) {
case "&&":
mark_locally_defined(condition.left, consequent);
mark_locally_defined(condition.right, consequent);
break;
case "||":
mark_locally_defined(negate(condition.left), alternative);
mark_locally_defined(negate(condition.right), alternative);
break;
}
return;
}
if (!(condition.right instanceof AST_UnaryPrefix)) return;
if (condition.right.operator != "typeof") return;
var sym = condition.right.expression;
if (!is_undeclared_ref(sym)) return;
var body;
var undef = condition.left.value == "undefined";
switch (condition.operator) {
case "==":
body = undef ? alternative : consequent;
break;
case "!=":
body = undef ? consequent : alternative;
break;
default:
return;
}
if (!body) return;
2022-02-07 14:48:46 +00:00
var abort = false;
2022-01-21 08:28:41 +00:00
var def = sym.definition();
2022-02-07 14:48:46 +00:00
var fn;
var refs = [];
var scanned = [];
var tw = new TreeWalker(function(node, descend) {
if (abort) return true;
if (node instanceof AST_Assign) {
var ref = node.left;
if (!(ref instanceof AST_SymbolRef && ref.definition() === def)) return;
node.right.walk(tw);
switch (node.operator) {
case "=":
case "&&=":
abort = true;
}
return true;
}
if (node instanceof AST_Call) {
descend();
fn = node.expression.tail_node();
var save;
if (fn instanceof AST_SymbolRef) {
fn = fn.fixed_value();
save = refs.length;
}
if (!(fn instanceof AST_Lambda)) {
abort = true;
} else if (push_uniq(scanned, fn)) {
fn.walk(tw);
}
if (save >= 0) refs.length = save;
return true;
}
if (node instanceof AST_DWLoop) {
var save = refs.length;
descend();
if (abort) refs.length = save;
return true;
}
if (node instanceof AST_For) {
if (node.init) node.init.walk(tw);
var save = refs.length;
if (node.condition) node.condition.walk(tw);
node.body.walk(tw);
if (node.step) node.step.walk(tw);
if (abort) refs.length = save;
return true;
}
if (node instanceof AST_ForEnumeration) {
node.object.walk(tw);
var save = refs.length;
node.init.walk(tw);
node.body.walk(tw);
if (abort) refs.length = save;
return true;
}
2022-01-21 08:28:41 +00:00
if (node instanceof AST_Scope) {
2022-02-07 14:48:46 +00:00
if (node === fn) return;
return true;
}
if (node instanceof AST_SymbolRef) {
if (node.definition() === def) refs.push(node);
2022-01-21 08:28:41 +00:00
return true;
}
});
body.walk(tw);
2022-02-07 14:48:46 +00:00
refs.forEach(function(ref) {
ref.defined = true;
});
2022-01-21 08:28:41 +00:00
function negate(node) {
if (!(node instanceof AST_Binary)) return;
switch (node.operator) {
case "==":
node = node.clone();
node.operator = "!=";
return node;
case "!=":
node = node.clone();
node.operator = "==";
return node;
}
}
}
function fuzzy_eval(compressor, node, nullish) {
if (node.truthy) return true;
2022-06-08 10:36:39 +00:00
if (is_undefined(node)) return undefined;
2022-01-21 08:28:41 +00:00
if (node.falsy && !nullish) return false;
if (node.is_truthy()) return true;
return node.evaluate(compressor, true);
}
function mark_duplicate_condition(compressor, node) {
var child;
var level = 0;
var negated = false;
var parent = compressor.self();
if (!is_statement(parent)) while (true) {
child = parent;
parent = compressor.parent(level++);
if (parent instanceof AST_Binary) {
2022-06-08 10:36:39 +00:00
switch (child) {
case parent.left:
if (lazy_op[parent.operator]) continue;
2022-01-21 08:28:41 +00:00
break;
2022-06-08 10:36:39 +00:00
case parent.right:
if (match(parent.left)) switch (parent.operator) {
case "&&":
node[negated ? "falsy" : "truthy"] = true;
break;
case "||":
case "??":
node[negated ? "truthy" : "falsy"] = true;
break;
}
2022-01-21 08:28:41 +00:00
break;
}
} else if (parent instanceof AST_Conditional) {
var cond = parent.condition;
if (cond === child) continue;
if (match(cond)) switch (child) {
case parent.consequent:
node[negated ? "falsy" : "truthy"] = true;
break;
case parent.alternative:
node[negated ? "truthy" : "falsy"] = true;
break;
}
} else if (parent instanceof AST_Exit) {
break;
} else if (parent instanceof AST_If) {
break;
} else if (parent instanceof AST_Sequence) {
if (parent.expressions[0] === child) continue;
} else if (parent instanceof AST_SimpleStatement) {
break;
}
return;
}
while (true) {
child = parent;
parent = compressor.parent(level++);
if (parent instanceof AST_BlockStatement) {
if (parent.body[0] === child) continue;
} else if (parent instanceof AST_If) {
if (match(parent.condition)) switch (child) {
case parent.body:
node[negated ? "falsy" : "truthy"] = true;
break;
case parent.alternative:
node[negated ? "truthy" : "falsy"] = true;
break;
}
}
return;
}
function match(cond) {
2022-08-05 07:44:52 +00:00
if (node.equals(cond)) return true;
2022-01-21 08:28:41 +00:00
if (!(cond instanceof AST_UnaryPrefix)) return false;
if (cond.operator != "!") return false;
2022-08-05 07:44:52 +00:00
if (!node.equals(cond.expression)) return false;
2022-01-21 08:28:41 +00:00
negated = true;
return true;
}
}
OPT(AST_If, function(self, compressor) {
if (is_empty(self.alternative)) self.alternative = null;
if (!compressor.option("conditionals")) return self;
if (compressor.option("booleans") && !self.condition.has_side_effects(compressor)) {
mark_duplicate_condition(compressor, self.condition);
}
// if condition can be statically determined, warn and drop
// one of the blocks. note, statically determined implies
// “has no side effects”; also it doesn't work for cases like
// `x && true`, though it probably should.
if (compressor.option("dead_code")) {
var cond = fuzzy_eval(compressor, self.condition);
if (!cond) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Condition always false [{start}]", self.condition);
2022-03-14 15:40:45 +00:00
var body = [
make_node(AST_SimpleStatement, self.condition, { body: self.condition }).transform(compressor),
];
2022-01-21 08:28:41 +00:00
extract_declarations_from_unreachable_code(compressor, self.body, body);
if (self.alternative) body.push(self.alternative);
return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor);
} else if (!(cond instanceof AST_Node)) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Condition always true [{start}]", self.condition);
2022-01-21 08:28:41 +00:00
var body = [
2022-03-14 15:40:45 +00:00
make_node(AST_SimpleStatement, self.condition, { body: self.condition }).transform(compressor),
2022-01-21 08:28:41 +00:00
self.body,
];
if (self.alternative) extract_declarations_from_unreachable_code(compressor, self.alternative, body);
return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor);
}
}
var negated = self.condition.negate(compressor);
var self_condition_length = self.condition.print_to_string().length;
var negated_length = negated.print_to_string().length;
var negated_is_best = negated_length < self_condition_length;
if (self.alternative && negated_is_best) {
negated_is_best = false; // because we already do the switch here.
// no need to swap values of self_condition_length and negated_length
// here because they are only used in an equality comparison later on.
self.condition = negated;
var tmp = self.body;
2022-03-14 15:40:45 +00:00
self.body = self.alternative;
self.alternative = is_empty(tmp) ? null : tmp;
2022-01-21 08:28:41 +00:00
}
2022-02-07 14:48:46 +00:00
var body_defuns = [];
var body_var_defs = [];
var body_refs = [];
var body_exprs = sequencesize(self.body, body_defuns, body_var_defs, body_refs);
var alt_defuns = [];
var alt_var_defs = [];
var alt_refs = [];
var alt_exprs = sequencesize(self.alternative, alt_defuns, alt_var_defs, alt_refs);
if (body_exprs instanceof AST_BlockStatement || alt_exprs instanceof AST_BlockStatement) {
var body = [], var_defs = [];
if (body_exprs) {
[].push.apply(body, body_defuns);
[].push.apply(var_defs, body_var_defs);
if (body_exprs instanceof AST_BlockStatement) {
self.body = body_exprs;
} else if (body_exprs.length == 0) {
self.body = make_node(AST_EmptyStatement, self.body);
} else {
self.body = make_node(AST_SimpleStatement, self.body, {
body: make_sequence(self.body, body_exprs),
});
}
body_refs.forEach(process_to_assign);
}
if (alt_exprs) {
[].push.apply(body, alt_defuns);
[].push.apply(var_defs, alt_var_defs);
if (alt_exprs instanceof AST_BlockStatement) {
self.alternative = alt_exprs;
} else if (alt_exprs.length == 0) {
self.alternative = null;
} else {
self.alternative = make_node(AST_SimpleStatement, self.alternative, {
body: make_sequence(self.alternative, alt_exprs),
});
}
alt_refs.forEach(process_to_assign);
}
2022-01-21 08:28:41 +00:00
if (var_defs.length > 0) body.push(make_node(AST_Var, self, { definitions: var_defs }));
2022-02-07 14:48:46 +00:00
if (body.length > 0) {
2022-08-31 14:34:36 +00:00
body.push(self.transform(compressor));
2022-02-07 14:48:46 +00:00
return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor);
}
} else if (body_exprs && alt_exprs) {
var body = body_defuns.concat(alt_defuns);
if (body_var_defs.length > 0 || alt_var_defs.length > 0) body.push(make_node(AST_Var, self, {
definitions: body_var_defs.concat(alt_var_defs),
}));
2022-01-21 08:28:41 +00:00
if (body_exprs.length == 0) {
body.push(make_node(AST_SimpleStatement, self.condition, {
body: alt_exprs.length > 0 ? make_node(AST_Binary, self, {
2022-02-07 14:48:46 +00:00
operator: "||",
left: self.condition,
right: make_sequence(self.alternative, alt_exprs),
}).transform(compressor) : self.condition.clone(),
2022-01-21 08:28:41 +00:00
}).optimize(compressor));
} else if (alt_exprs.length == 0) {
if (self_condition_length === negated_length && !negated_is_best
&& self.condition instanceof AST_Binary && self.condition.operator == "||") {
// although the code length of self.condition and negated are the same,
// negated does not require additional surrounding parentheses.
// see https://github.com/mishoo/UglifyJS/issues/979
negated_is_best = true;
}
body.push(make_node(AST_SimpleStatement, self, {
body: make_node(AST_Binary, self, {
2022-02-07 14:48:46 +00:00
operator: negated_is_best ? "||" : "&&",
left: negated_is_best ? negated : self.condition,
right: make_sequence(self.body, body_exprs),
}).transform(compressor),
2022-01-21 08:28:41 +00:00
}).optimize(compressor));
} else {
body.push(make_node(AST_SimpleStatement, self, {
body: make_node(AST_Conditional, self, {
2022-02-07 14:48:46 +00:00
condition: self.condition,
consequent: make_sequence(self.body, body_exprs),
alternative: make_sequence(self.alternative, alt_exprs),
}),
2022-01-21 08:28:41 +00:00
}).optimize(compressor));
}
2022-02-07 14:48:46 +00:00
body_refs.forEach(process_to_assign);
alt_refs.forEach(process_to_assign);
return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor);
2022-01-21 08:28:41 +00:00
}
2022-02-07 14:48:46 +00:00
if (is_empty(self.body)) self = make_node(AST_If, self, {
condition: negated,
body: self.alternative,
alternative: null,
});
if (self.alternative instanceof AST_Exit && self.body.TYPE == self.alternative.TYPE) {
2022-10-10 08:26:02 +00:00
var cons_value = self.body.value;
var alt_value = self.alternative.value;
if (!cons_value && !alt_value) return make_node(AST_BlockStatement, self, {
body: [
make_node(AST_SimpleStatement, self, { body: self.condition }),
self.body,
],
}).optimize(compressor);
if (cons_value && alt_value || !keep_return_void()) {
var exit = make_node(self.body.CTOR, self, {
value: make_node(AST_Conditional, self, {
condition: self.condition,
consequent: cons_value || make_node(AST_Undefined, self.body).transform(compressor),
alternative: alt_value || make_node(AST_Undefined, self.alternative).transform(compressor),
}),
});
if (exit instanceof AST_Return) exit.in_bool = self.body.in_bool || self.alternative.in_bool;
return exit;
}
2022-01-21 08:28:41 +00:00
}
2022-02-07 14:48:46 +00:00
if (self.body instanceof AST_If && !self.body.alternative && !self.alternative) {
2022-01-21 08:28:41 +00:00
self = make_node(AST_If, self, {
condition: make_node(AST_Binary, self.condition, {
operator: "&&",
left: self.condition,
2022-02-07 14:48:46 +00:00
right: self.body.condition,
2022-01-21 08:28:41 +00:00
}),
body: self.body.body,
2022-02-07 14:48:46 +00:00
alternative: null,
2022-01-21 08:28:41 +00:00
});
}
2022-02-07 14:48:46 +00:00
if (aborts(self.body) && self.alternative) {
var alt = self.alternative;
self.alternative = null;
return make_node(AST_BlockStatement, self, { body: [ self, alt ] }).optimize(compressor);
2022-01-21 08:28:41 +00:00
}
if (aborts(self.alternative)) {
var body = self.body;
self.body = self.alternative;
self.condition = negated_is_best ? negated : self.condition.negate(compressor);
self.alternative = null;
2022-02-07 14:48:46 +00:00
return make_node(AST_BlockStatement, self, { body: [ self, body ] }).optimize(compressor);
2022-01-21 08:28:41 +00:00
}
2022-08-05 07:44:52 +00:00
if (self.alternative) {
var body_stats = as_array(self.body);
var body_index = last_index(body_stats);
var alt_stats = as_array(self.alternative);
var alt_index = last_index(alt_stats);
for (var stats = []; body_index >= 0 && alt_index >= 0;) {
var stat = body_stats[body_index];
2022-08-31 14:34:36 +00:00
var alt_stat = alt_stats[alt_index];
if (stat.equals(alt_stat)) {
body_stats.splice(body_index--, 1);
alt_stats.splice(alt_index--, 1);
2022-09-30 13:48:25 +00:00
stats.unshift(merge_expression(stat, alt_stat));
2022-08-31 14:34:36 +00:00
} else {
if (!(stat instanceof AST_SimpleStatement)) break;
if (!(alt_stat instanceof AST_SimpleStatement)) break;
2022-09-30 13:48:25 +00:00
var expr1 = stat.body.tail_node();
var expr2 = alt_stat.body.tail_node();
if (!expr1.equals(expr2)) break;
2022-08-31 14:34:36 +00:00
body_index = pop_expr(body_stats, stat.body, body_index);
alt_index = pop_expr(alt_stats, alt_stat.body, alt_index);
2022-09-30 13:48:25 +00:00
stats.unshift(make_node(AST_SimpleStatement, expr1, { body: merge_expression(expr1, expr2) }));
2022-08-31 14:34:36 +00:00
}
2022-08-05 07:44:52 +00:00
}
if (stats.length > 0) {
self.body = body_stats.length > 0 ? make_node(AST_BlockStatement, self, {
body: body_stats,
}) : make_node(AST_EmptyStatement, self);
self.alternative = alt_stats.length > 0 ? make_node(AST_BlockStatement, self, {
body: alt_stats,
}) : null;
stats.unshift(self);
return make_node(AST_BlockStatement, self, { body: stats }).optimize(compressor);
}
}
2022-01-21 08:28:41 +00:00
if (compressor.option("typeofs")) mark_locally_defined(self.condition, self.body, self.alternative);
return self;
2022-08-05 07:44:52 +00:00
function as_array(node) {
return node instanceof AST_BlockStatement ? node.body : [ node ];
}
2022-10-10 08:26:02 +00:00
function keep_return_void() {
var has_finally = false, level = 0, node = compressor.self();
do {
if (node instanceof AST_Catch) {
if (compressor.parent(level).bfinally) has_finally = true;
level++;
} else if (node instanceof AST_Finally) {
level++;
} else if (node instanceof AST_Scope) {
return has_finally && in_async_generator(node);
} else if (node instanceof AST_Try) {
if (node.bfinally) has_finally = true;
}
} while (node = compressor.parent(level++));
}
2022-08-05 07:44:52 +00:00
function last_index(stats) {
for (var index = stats.length; --index >= 0;) {
if (!is_declaration(stats[index], true)) break;
}
return index;
}
2022-08-31 14:34:36 +00:00
function pop_expr(stats, body, index) {
if (body instanceof AST_Sequence) {
stats[index] = make_node(AST_SimpleStatement, body, {
body: make_sequence(body, body.expressions.slice(0, -1)),
});
} else {
stats.splice(index--, 1);
}
return index;
}
2022-01-21 08:28:41 +00:00
function sequencesize(stat, defuns, var_defs, refs) {
if (stat == null) return [];
if (stat instanceof AST_BlockStatement) {
var exprs = [];
for (var i = 0; i < stat.body.length; i++) {
var line = stat.body[i];
2022-02-07 14:48:46 +00:00
if (line instanceof AST_EmptyStatement) continue;
if (line instanceof AST_Exit) {
2022-03-14 15:40:45 +00:00
if (i == 0) return;
if (exprs.length > 0) {
line = line.clone();
exprs.push(line.value || make_node(AST_Undefined, line).transform(compressor));
line.value = make_sequence(stat, exprs);
}
2022-02-07 14:48:46 +00:00
var block = stat.clone();
block.body = block.body.slice(i + 1);
block.body.unshift(line);
return block;
}
2022-01-21 08:28:41 +00:00
if (line instanceof AST_LambdaDefinition) {
defuns.push(line);
} else if (line instanceof AST_SimpleStatement) {
if (!compressor.option("sequences") && exprs.length > 0) return;
exprs.push(line.body);
} else if (line instanceof AST_Var) {
if (!compressor.option("sequences") && exprs.length > 0) return;
line.remove_initializers(compressor, var_defs);
line.definitions.forEach(process_var_def);
} else {
return;
}
}
return exprs;
}
if (stat instanceof AST_LambdaDefinition) {
defuns.push(stat);
return [];
}
if (stat instanceof AST_EmptyStatement) return [];
if (stat instanceof AST_SimpleStatement) return [ stat.body ];
if (stat instanceof AST_Var) {
var exprs = [];
stat.remove_initializers(compressor, var_defs);
stat.definitions.forEach(process_var_def);
return exprs;
}
function process_var_def(var_def) {
if (!var_def.value) return;
exprs.push(make_node(AST_Assign, var_def, {
operator: "=",
left: var_def.name.convert_symbol(AST_SymbolRef, function(ref) {
refs.push(ref);
}),
2022-02-07 14:48:46 +00:00
right: var_def.value,
2022-01-21 08:28:41 +00:00
}));
}
}
});
OPT(AST_Switch, function(self, compressor) {
if (!compressor.option("switches")) return self;
if (!compressor.option("dead_code")) return self;
var body = [];
var branch;
var decl = [];
var default_branch;
var exact_match;
var side_effects = [];
for (var i = 0, len = self.body.length; i < len; i++) {
branch = self.body[i];
if (branch instanceof AST_Default) {
var prev = body[body.length - 1];
if (default_branch || is_break(branch.body[0], compressor) && (!prev || aborts(prev))) {
eliminate_branch(branch, prev);
continue;
} else {
default_branch = branch;
}
} else {
var exp = branch.expression;
var equals = make_node(AST_Binary, self, {
operator: "===",
left: self.expression,
right: exp,
}).evaluate(compressor, true);
if (!equals) {
if (exp.has_side_effects(compressor)) side_effects.push(exp);
eliminate_branch(branch, body[body.length - 1]);
continue;
}
if (!(equals instanceof AST_Node)) {
if (default_branch) {
var default_index = body.indexOf(default_branch);
body.splice(default_index, 1);
eliminate_branch(default_branch, body[default_index - 1]);
default_branch = null;
}
if (exp.has_side_effects(compressor)) {
exact_match = branch;
} else {
2022-08-31 14:34:36 +00:00
default_branch = branch = make_node(AST_Default, branch);
2022-01-21 08:28:41 +00:00
}
while (++i < len) eliminate_branch(self.body[i], branch);
}
}
if (i + 1 >= len || aborts(branch)) {
var prev = body[body.length - 1];
var statements = branch.body;
if (aborts(prev)) switch (prev.body.length - statements.length) {
case 1:
var stat = prev.body[prev.body.length - 1];
if (!is_break(stat, compressor)) break;
statements = statements.concat(stat);
case 0:
2022-08-31 14:34:36 +00:00
var prev_block = make_node(AST_BlockStatement, prev);
2022-01-21 08:28:41 +00:00
var next_block = make_node(AST_BlockStatement, branch, { body: statements });
2022-08-05 07:44:52 +00:00
if (prev_block.equals(next_block)) prev.body = [];
2022-01-21 08:28:41 +00:00
}
}
if (side_effects.length) {
if (branch instanceof AST_Default) {
body.push(make_node(AST_Case, self, { expression: make_sequence(self, side_effects), body: [] }));
} else {
side_effects.push(branch.expression);
branch.expression = make_sequence(self, side_effects);
}
side_effects = [];
}
body.push(branch);
}
if (side_effects.length && !exact_match) {
body.push(make_node(AST_Case, self, { expression: make_sequence(self, side_effects), body: [] }));
}
while (branch = body[body.length - 1]) {
var stat = branch.body[branch.body.length - 1];
if (is_break(stat, compressor)) branch.body.pop();
if (branch === default_branch) {
if (!has_declarations_only(branch)) break;
} else if (branch.expression.has_side_effects(compressor)) {
break;
} else if (default_branch) {
if (!has_declarations_only(default_branch)) break;
if (body[body.length - 2] !== default_branch) break;
default_branch.body = default_branch.body.concat(branch.body);
branch.body = [];
} else if (!has_declarations_only(branch)) break;
eliminate_branch(branch);
if (body.pop() === default_branch) default_branch = null;
}
if (!branch) {
decl.push(make_node(AST_SimpleStatement, self.expression, { body: self.expression }));
if (side_effects.length) decl.push(make_node(AST_SimpleStatement, self, {
body: make_sequence(self, side_effects),
}));
return make_node(AST_BlockStatement, self, { body: decl }).optimize(compressor);
}
if (branch === default_branch) while (branch = body[body.length - 2]) {
if (branch instanceof AST_Default) break;
if (!has_declarations_only(branch)) break;
var exp = branch.expression;
if (exp.has_side_effects(compressor)) {
var prev = body[body.length - 3];
if (prev && !aborts(prev)) break;
default_branch.body.unshift(make_node(AST_SimpleStatement, self, { body: exp }));
}
eliminate_branch(branch);
body.splice(-2, 1);
}
body[0].body = decl.concat(body[0].body);
self.body = body;
if (compressor.option("conditionals")) switch (body.length) {
case 1:
if (!no_break(body[0])) break;
var exp = body[0].expression;
var statements = body[0].body.slice();
if (body[0] !== default_branch && body[0] !== exact_match) return make_node(AST_If, self, {
condition: make_node(AST_Binary, self, {
operator: "===",
left: self.expression,
right: exp,
}),
2022-03-14 15:40:45 +00:00
body: make_node(AST_BlockStatement, self, { body: statements }),
2022-01-21 08:28:41 +00:00
alternative: null,
}).optimize(compressor);
2022-03-14 15:40:45 +00:00
if (exp) statements.unshift(make_node(AST_SimpleStatement, exp, { body: exp }));
statements.unshift(make_node(AST_SimpleStatement, self.expression, { body: self.expression }));
return make_node(AST_BlockStatement, self, { body: statements }).optimize(compressor);
2022-01-21 08:28:41 +00:00
case 2:
if (!member(default_branch, body) || !no_break(body[1])) break;
var statements = body[0].body.slice();
var exclusive = statements.length && is_break(statements[statements.length - 1], compressor);
if (exclusive) statements.pop();
if (!all(statements, no_break)) break;
2022-08-31 14:34:36 +00:00
var alternative = body[1].body.length && make_node(AST_BlockStatement, body[1]);
2022-01-21 08:28:41 +00:00
var node = make_node(AST_If, self, {
condition: make_node(AST_Binary, self, body[0] === default_branch ? {
operator: "!==",
left: self.expression,
right: body[1].expression,
} : {
operator: "===",
left: self.expression,
right: body[0].expression,
}),
2022-03-14 15:40:45 +00:00
body: make_node(AST_BlockStatement, body[0], { body: statements }),
2022-01-21 08:28:41 +00:00
alternative: exclusive && alternative || null,
});
2022-03-14 15:40:45 +00:00
if (!exclusive && alternative) node = make_node(AST_BlockStatement, self, { body: [ node, alternative ] });
2022-01-21 08:28:41 +00:00
return node.optimize(compressor);
}
return self;
function is_break(node, tw) {
return node instanceof AST_Break && tw.loopcontrol_target(node) === self;
}
function no_break(node) {
var found = false;
var tw = new TreeWalker(function(node) {
if (found
|| node instanceof AST_Lambda
|| node instanceof AST_SimpleStatement) return true;
if (is_break(node, tw)) found = true;
});
tw.push(self);
node.walk(tw);
return !found;
}
function eliminate_branch(branch, prev) {
if (prev && !aborts(prev)) {
prev.body = prev.body.concat(branch.body);
} else {
extract_declarations_from_unreachable_code(compressor, branch, decl);
}
}
});
OPT(AST_Try, function(self, compressor) {
self.body = tighten_body(self.body, compressor);
if (compressor.option("dead_code")) {
if (has_declarations_only(self)
&& !(self.bcatch && self.bcatch.argname && self.bcatch.argname.match_symbol(function(node) {
return node instanceof AST_SymbolCatch && !can_drop_symbol(node);
}, true))) {
var body = [];
if (self.bcatch) {
extract_declarations_from_unreachable_code(compressor, self.bcatch, body);
body.forEach(function(stat) {
if (!(stat instanceof AST_Var)) return;
stat.definitions.forEach(function(var_def) {
var def = var_def.name.definition().redefined();
if (!def) return;
var_def.name = var_def.name.clone();
var_def.name.thedef = def;
});
});
}
2022-08-31 14:34:36 +00:00
body.unshift(make_node(AST_BlockStatement, self).optimize(compressor));
2022-01-21 08:28:41 +00:00
if (self.bfinally) {
2022-08-31 14:34:36 +00:00
body.push(make_node(AST_BlockStatement, self.bfinally).optimize(compressor));
2022-01-21 08:28:41 +00:00
}
2022-02-07 14:48:46 +00:00
return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor);
2022-01-21 08:28:41 +00:00
}
if (self.bfinally && has_declarations_only(self.bfinally)) {
2022-08-31 14:34:36 +00:00
var body = make_node(AST_BlockStatement, self.bfinally).optimize(compressor);
2022-01-21 08:28:41 +00:00
body = self.body.concat(body);
2022-02-07 14:48:46 +00:00
if (!self.bcatch) return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor);
2022-01-21 08:28:41 +00:00
self.body = body;
self.bfinally = null;
}
}
return self;
});
function remove_initializers(make_value) {
return function(compressor, defns) {
var dropped = false;
this.definitions.forEach(function(defn) {
if (defn.value) dropped = true;
defn.name.match_symbol(function(node) {
if (node instanceof AST_SymbolDeclaration) defns.push(make_node(AST_VarDef, node, {
name: node,
2022-08-31 14:34:36 +00:00
value: make_value(compressor, node),
2022-01-21 08:28:41 +00:00
}));
}, true);
});
return dropped;
};
}
AST_Const.DEFMETHOD("remove_initializers", remove_initializers(function(compressor, node) {
return make_node(AST_Undefined, node).optimize(compressor);
}));
AST_Let.DEFMETHOD("remove_initializers", remove_initializers(return_null));
AST_Var.DEFMETHOD("remove_initializers", remove_initializers(return_null));
AST_Definitions.DEFMETHOD("to_assignments", function() {
var assignments = this.definitions.reduce(function(a, defn) {
var def = defn.name.definition();
var value = defn.value;
if (value) {
if (value instanceof AST_Sequence) value = value.clone();
2022-08-31 14:34:36 +00:00
var name = make_node(AST_SymbolRef, defn.name);
2022-01-21 08:28:41 +00:00
var assign = make_node(AST_Assign, defn, {
operator: "=",
left: name,
right: value,
});
a.push(assign);
var fixed = function() {
return assign.right;
};
fixed.assigns = [ assign ];
fixed.direct_access = def.direct_access;
fixed.escaped = def.escaped;
name.fixed = fixed;
def.references.forEach(function(ref) {
2022-04-11 08:07:00 +00:00
if (!ref.fixed) return;
var assigns = ref.fixed.assigns;
if (!assigns) return;
if (assigns[0] !== defn) return;
if (assigns.length > 1 || ref.fixed.to_binary || ref.fixed.to_prefix) {
assigns[0] = assign;
} else {
ref.fixed = fixed;
if (def.fixed === ref.fixed) def.fixed = fixed;
}
2022-01-21 08:28:41 +00:00
});
def.references.push(name);
}
def.assignments++;
def.eliminated++;
def.single_use = false;
return a;
}, []);
if (assignments.length == 0) return null;
return make_sequence(this, assignments);
});
function is_safe_lexical(def) {
return def.name != "arguments" && def.orig.length < (def.orig[0] instanceof AST_SymbolLambda ? 3 : 2);
}
function may_overlap(compressor, def) {
if (compressor.exposed(def)) return true;
var scope = def.scope.resolve();
for (var s = def.scope; s !== scope;) {
s = s.parent_scope;
if (s.var_names().has(def.name)) return true;
}
}
2022-10-10 08:26:02 +00:00
function to_var(stat, scope) {
2022-01-21 08:28:41 +00:00
return make_node(AST_Var, stat, {
definitions: stat.definitions.map(function(defn) {
return make_node(AST_VarDef, defn, {
name: defn.name.convert_symbol(AST_SymbolVar, function(name, node) {
var def = name.definition();
def.orig[def.orig.indexOf(node)] = name;
if (def.scope === scope) return;
def.scope = scope;
scope.variables.set(def.name, def);
scope.enclosed.push(def);
scope.var_names().set(def.name, true);
}),
value: defn.value,
});
2022-08-31 14:34:36 +00:00
}),
2022-01-21 08:28:41 +00:00
});
}
function can_varify(compressor, sym) {
var def = sym.definition();
2022-09-30 13:48:25 +00:00
return (def.fixed || def.fixed === 0)
&& is_safe_lexical(def)
&& same_scope(def)
&& !may_overlap(compressor, def);
2022-01-21 08:28:41 +00:00
}
function varify(self, compressor) {
return compressor.option("varify") && all(self.definitions, function(defn) {
return !defn.name.match_symbol(function(node) {
if (node instanceof AST_SymbolDeclaration) return !can_varify(compressor, node);
}, true);
2022-10-10 08:26:02 +00:00
}) ? to_var(self, compressor.find_parent(AST_Scope)) : self;
2022-01-21 08:28:41 +00:00
}
OPT(AST_Const, varify);
OPT(AST_Let, varify);
function trim_optional_chain(node, compressor) {
if (!compressor.option("optional_chains")) return;
if (node.terminal) do {
var expr = node.expression;
if (node.optional) {
var ev = fuzzy_eval(compressor, expr, true);
if (ev == null) return make_node(AST_UnaryPrefix, node, {
operator: "void",
expression: expr,
}).optimize(compressor);
if (!(ev instanceof AST_Node)) node.optional = false;
}
node = expr;
} while ((node.TYPE == "Call" || node instanceof AST_PropAccess) && !node.terminal);
}
function lift_sequence_in_expression(node, compressor) {
var exp = node.expression;
if (!(exp instanceof AST_Sequence)) return node;
var x = exp.expressions.slice();
var e = node.clone();
e.expression = x.pop();
x.push(e);
return make_sequence(node, x);
}
function drop_unused_call_args(call, compressor, fns_with_marked_args) {
var exp = call.expression;
var fn = exp instanceof AST_SymbolRef ? exp.fixed_value() : exp;
if (!(fn instanceof AST_Lambda)) return;
if (fn.uses_arguments) return;
if (fn.pinned()) return;
if (fns_with_marked_args && fns_with_marked_args.indexOf(fn) < 0) return;
var args = call.args;
if (!all(args, function(arg) {
return !(arg instanceof AST_Spread);
})) return;
var argnames = fn.argnames;
var is_iife = fn === exp && !fn.name;
if (fn.rest) {
if (!(is_iife && compressor.option("rests"))) return;
var insert = argnames.length;
args = args.slice(0, insert);
while (args.length < insert) args.push(make_node(AST_Undefined, call).optimize(compressor));
args.push(make_node(AST_Array, call, { elements: call.args.slice(insert) }));
argnames = argnames.concat(fn.rest);
fn.rest = null;
} else {
args = args.slice();
argnames = argnames.slice();
}
var pos = 0, last = 0;
var drop_defaults = is_iife && compressor.option("default_values");
var drop_fargs = is_iife && compressor.drop_fargs(fn, call) ? function(argname, arg) {
if (!argname) return true;
if (argname instanceof AST_DestructuredArray) {
return argname.elements.length == 0 && !argname.rest && arg instanceof AST_Array;
}
if (argname instanceof AST_DestructuredObject) {
return argname.properties.length == 0 && !argname.rest && arg && !arg.may_throw_on_access(compressor);
}
return argname.unused;
} : return_false;
var side_effects = [];
for (var i = 0; i < args.length; i++) {
var argname = argnames[i];
if (drop_defaults && argname instanceof AST_DefaultValue && args[i].is_defined(compressor)) {
argnames[i] = argname = argname.name;
}
if (!argname || argname.unused !== undefined) {
var node = args[i].drop_side_effect_free(compressor);
if (drop_fargs(argname)) {
if (argname) argnames.splice(i, 1);
args.splice(i, 1);
if (node) side_effects.push(node);
i--;
continue;
} else if (node) {
side_effects.push(node);
args[pos++] = make_sequence(call, side_effects);
side_effects = [];
} else if (argname) {
if (side_effects.length) {
args[pos++] = make_sequence(call, side_effects);
side_effects = [];
} else {
2022-02-07 14:48:46 +00:00
args[pos++] = make_node(AST_Number, args[i], { value: 0 });
2022-01-21 08:28:41 +00:00
continue;
}
}
} else if (drop_fargs(argname, args[i])) {
var node = args[i].drop_side_effect_free(compressor);
argnames.splice(i, 1);
args.splice(i, 1);
if (node) side_effects.push(node);
i--;
continue;
} else {
side_effects.push(args[i]);
args[pos++] = make_sequence(call, side_effects);
side_effects = [];
}
last = pos;
}
for (; i < argnames.length; i++) {
if (drop_fargs(argnames[i])) argnames.splice(i--, 1);
}
fn.argnames = argnames;
args.length = last;
call.args = args;
if (!side_effects.length) return;
var arg = make_sequence(call, side_effects);
args.push(args.length < argnames.length ? make_node(AST_UnaryPrefix, call, {
operator: "void",
expression: arg,
}) : arg);
}
2022-07-11 11:25:19 +00:00
function avoid_await_yield(compressor, parent_scope) {
if (!parent_scope) parent_scope = compressor.find_parent(AST_Scope);
2022-01-21 08:28:41 +00:00
var avoid = [];
2022-07-11 11:25:19 +00:00
if (is_async(parent_scope) || parent_scope instanceof AST_Toplevel && compressor.option("module")) {
avoid.push("await");
}
2022-01-21 08:28:41 +00:00
if (is_generator(parent_scope)) avoid.push("yield");
return avoid.length && makePredicate(avoid);
}
2022-02-07 14:48:46 +00:00
function safe_from_await_yield(fn, avoid) {
if (!avoid) return true;
var safe = true;
var tw = new TreeWalker(function(node) {
if (!safe) return true;
if (node instanceof AST_Scope) {
if (node === fn) return;
if (is_arrow(node)) {
for (var i = 0; safe && i < node.argnames.length; i++) node.argnames[i].walk(tw);
} else if (node instanceof AST_LambdaDefinition && avoid[node.name.name]) {
safe = false;
}
return true;
}
if (node instanceof AST_Symbol && avoid[node.name] && node !== fn.name) safe = false;
});
fn.walk(tw);
return safe;
}
2022-06-08 10:36:39 +00:00
function safe_from_strict_mode(fn, compressor) {
return fn.in_strict_mode(compressor) || !compressor.has_directive("use strict");
}
2022-01-21 08:28:41 +00:00
OPT(AST_Call, function(self, compressor) {
var exp = self.expression;
var terminated = trim_optional_chain(self, compressor);
if (terminated) return terminated;
if (compressor.option("sequences")) {
if (exp instanceof AST_PropAccess) {
var seq = lift_sequence_in_expression(exp, compressor);
if (seq !== exp) {
var call = self.clone();
call.expression = seq.expressions.pop();
seq.expressions.push(call);
return seq.optimize(compressor);
}
2022-08-31 14:34:36 +00:00
} else if (!needs_unbinding(exp.tail_node())) {
2022-01-21 08:28:41 +00:00
var seq = lift_sequence_in_expression(self, compressor);
if (seq !== self) return seq.optimize(compressor);
}
}
if (compressor.option("unused")) drop_unused_call_args(self, compressor);
if (compressor.option("unsafe")) {
if (is_undeclared_ref(exp)) switch (exp.name) {
case "Array":
// Array(n) ---> [ , , ... , ]
if (self.args.length == 1) {
var first = self.args[0];
if (first instanceof AST_Number) try {
var length = first.value;
if (length > 6) break;
var elements = Array(length);
for (var i = 0; i < length; i++) elements[i] = make_node(AST_Hole, self);
return make_node(AST_Array, self, { elements: elements });
} catch (ex) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Invalid array length: {length} [{start}]", {
2022-01-21 08:28:41 +00:00
length: length,
2022-08-31 14:34:36 +00:00
start: self.start,
2022-01-21 08:28:41 +00:00
});
break;
}
if (!first.is_boolean(compressor) && !first.is_string(compressor)) break;
}
// Array(...) ---> [ ... ]
return make_node(AST_Array, self, { elements: self.args });
case "Object":
// Object() ---> {}
if (self.args.length == 0) return make_node(AST_Object, self, { properties: [] });
break;
case "String":
// String() ---> ""
if (self.args.length == 0) return make_node(AST_String, self, { value: "" });
// String(x) ---> "" + x
if (self.args.length == 1) return make_node(AST_Binary, self, {
operator: "+",
left: make_node(AST_String, self, { value: "" }),
right: self.args[0],
}).optimize(compressor);
break;
case "Number":
// Number() ---> 0
if (self.args.length == 0) return make_node(AST_Number, self, { value: 0 });
// Number(x) ---> +("" + x)
if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
operator: "+",
expression: make_node(AST_Binary, self, {
operator: "+",
left: make_node(AST_String, self, { value: "" }),
right: self.args[0],
}),
}).optimize(compressor);
break;
case "Boolean":
// Boolean() ---> false
if (self.args.length == 0) return make_node(AST_False, self).optimize(compressor);
// Boolean(x) ---> !!x
if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
operator: "!",
expression: make_node(AST_UnaryPrefix, self, {
operator: "!",
expression: self.args[0],
}),
}).optimize(compressor);
break;
case "RegExp":
// attempt to convert RegExp(...) to literal
var params = [];
if (all(self.args, function(arg) {
var value = arg.evaluate(compressor);
params.unshift(value);
return arg !== value;
})) try {
return best_of(compressor, self, make_node(AST_RegExp, self, {
value: RegExp.apply(RegExp, params),
}));
} catch (ex) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Error converting {this} [{start}]", self);
2022-01-21 08:28:41 +00:00
}
break;
} else if (exp instanceof AST_Dot) switch (exp.property) {
case "toString":
// x.toString() ---> "" + x
var expr = exp.expression;
if (self.args.length == 0 && !(expr.may_throw_on_access(compressor) || expr instanceof AST_Super)) {
return make_node(AST_Binary, self, {
operator: "+",
left: make_node(AST_String, self, { value: "" }),
right: expr,
}).optimize(compressor);
}
break;
case "join":
if (exp.expression instanceof AST_Array && self.args.length < 2) EXIT: {
var separator = self.args[0];
// [].join() ---> ""
// [].join(x) ---> (x, "")
if (exp.expression.elements.length == 0 && !(separator instanceof AST_Spread)) {
return separator ? make_sequence(self, [
separator,
make_node(AST_String, self, { value: "" }),
]).optimize(compressor) : make_node(AST_String, self, { value: "" });
}
if (separator) {
separator = separator.evaluate(compressor);
if (separator instanceof AST_Node) break EXIT; // not a constant
}
var elements = [];
var consts = [];
for (var i = 0; i < exp.expression.elements.length; i++) {
var el = exp.expression.elements[i];
var value = el.evaluate(compressor);
if (value !== el) {
consts.push(value);
} else if (el instanceof AST_Spread) {
break EXIT;
} else {
if (consts.length > 0) {
2022-08-31 14:34:36 +00:00
elements.push(make_node(AST_String, self, { value: consts.join(separator) }));
2022-01-21 08:28:41 +00:00
consts.length = 0;
}
elements.push(el);
}
}
if (consts.length > 0) elements.push(make_node(AST_String, self, {
value: consts.join(separator),
}));
// [ x ].join() ---> "" + x
// [ x ].join(".") ---> "" + x
// [ 1, 2, 3 ].join() ---> "1,2,3"
// [ 1, 2, 3 ].join(".") ---> "1.2.3"
if (elements.length == 1) {
if (elements[0].is_string(compressor)) return elements[0];
return make_node(AST_Binary, elements[0], {
operator: "+",
left: make_node(AST_String, self, { value: "" }),
right: elements[0],
});
}
// [ 1, 2, a, 3 ].join("") ---> "12" + a + "3"
if (separator == "") {
var first;
if (elements[0].is_string(compressor) || elements[1].is_string(compressor)) {
first = elements.shift();
} else {
first = make_node(AST_String, self, { value: "" });
}
return elements.reduce(function(prev, el) {
return make_node(AST_Binary, el, {
operator: "+",
left: prev,
right: el,
});
}, first).optimize(compressor);
}
// [ x, "foo", "bar", y ].join() ---> [ x, "foo,bar", y ].join()
// [ x, "foo", "bar", y ].join("-") ---> [ x, "foo-bar", y ].join("-")
// need this awkward cloning to not affect original element
// best_of will decide which one to get through.
var node = self.clone();
node.expression = node.expression.clone();
node.expression.expression = node.expression.expression.clone();
node.expression.expression.elements = elements;
return best_of(compressor, self, node);
}
break;
case "charAt":
if (self.args.length < 2) {
var node = make_node(AST_Binary, self, {
operator: "||",
left: make_node(AST_Sub, self, {
expression: exp.expression,
property: self.args.length ? make_node(AST_Binary, self.args[0], {
operator: "|",
left: make_node(AST_Number, self, { value: 0 }),
right: self.args[0],
}) : make_node(AST_Number, self, { value: 0 }),
}).optimize(compressor),
right: make_node(AST_String, self, { value: "" }),
});
node.is_string = return_true;
return node.optimize(compressor);
}
break;
case "apply":
if (self.args.length == 2 && self.args[1] instanceof AST_Array) {
var args = self.args[1].elements.slice();
args.unshift(self.args[0]);
return make_node(AST_Call, self, {
expression: make_node(AST_Dot, exp, {
expression: exp.expression,
property: "call",
}),
2022-02-07 14:48:46 +00:00
args: args,
2022-01-21 08:28:41 +00:00
}).optimize(compressor);
}
break;
case "call":
var func = exp.expression;
if (func instanceof AST_SymbolRef) {
func = func.fixed_value();
}
if (func instanceof AST_Lambda && !func.contains_this()) {
2022-08-31 14:34:36 +00:00
return (self.args.length ? make_sequence(self, [
2022-01-21 08:28:41 +00:00
self.args[0],
make_node(AST_Call, self, {
expression: exp.expression,
2022-02-07 14:48:46 +00:00
args: self.args.slice(1),
}),
2022-01-21 08:28:41 +00:00
]) : make_node(AST_Call, self, {
expression: exp.expression,
2022-02-07 14:48:46 +00:00
args: [],
2022-01-21 08:28:41 +00:00
})).optimize(compressor);
}
break;
2022-08-31 14:34:36 +00:00
} else if (compressor.option("side_effects")
&& exp instanceof AST_Call
&& exp.args.length == 1
&& is_undeclared_ref(exp.expression)
&& exp.expression.name == "Object") {
var call = self.clone();
call.expression = maintain_this_binding(self, exp, exp.args[0]);
return call.optimize(compressor);
2022-01-21 08:28:41 +00:00
}
}
if (compressor.option("unsafe_Function")
&& is_undeclared_ref(exp)
&& exp.name == "Function") {
// new Function() ---> function(){}
if (self.args.length == 0) return make_node(AST_Function, self, {
argnames: [],
2022-08-31 14:34:36 +00:00
body: [],
2022-01-21 08:28:41 +00:00
}).init_vars(exp.scope);
if (all(self.args, function(x) {
return x instanceof AST_String;
})) {
// quite a corner-case, but we can handle it:
// https://github.com/mishoo/UglifyJS/issues/203
// if the code argument is a constant, then we can minify it.
try {
var code = "n(function(" + self.args.slice(0, -1).map(function(arg) {
return arg.value;
}).join() + "){" + self.args[self.args.length - 1].value + "})";
var ast = parse(code);
var mangle = { ie: compressor.option("ie") };
ast.figure_out_scope(mangle);
var comp = new Compressor(compressor.options);
ast = ast.transform(comp);
ast.figure_out_scope(mangle);
ast.compute_char_frequency(mangle);
ast.mangle_names(mangle);
var fun;
ast.walk(new TreeWalker(function(node) {
if (fun) return true;
if (node instanceof AST_Lambda) {
fun = node;
return true;
}
}));
var code = OutputStream();
AST_BlockStatement.prototype._codegen.call(fun, code);
self.args = [
make_node(AST_String, self, {
value: fun.argnames.map(function(arg) {
return arg.print_to_string();
}).join(),
}),
make_node(AST_String, self.args[self.args.length - 1], {
value: code.get().replace(/^\{|\}$/g, "")
2022-08-31 14:34:36 +00:00
}),
2022-01-21 08:28:41 +00:00
];
return self;
} catch (ex) {
if (ex instanceof JS_Parse_Error) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Error parsing code passed to new Function [{start}]", self.args[self.args.length - 1]);
2022-01-21 08:28:41 +00:00
AST_Node.warn(ex.toString());
} else {
throw ex;
}
}
}
}
var fn = exp instanceof AST_SymbolRef ? exp.fixed_value() : exp;
var parent = compressor.parent(), current = compressor.self();
var is_func = fn instanceof AST_Lambda
&& (!is_async(fn) || compressor.option("awaits") && parent instanceof AST_Await)
&& (!is_generator(fn) || compressor.option("yields") && current instanceof AST_Yield && current.nested);
var stat = is_func && fn.first_statement();
var has_default = 0, has_destructured = false;
var has_spread = !all(self.args, function(arg) {
return !(arg instanceof AST_Spread);
});
var can_drop = is_func && all(fn.argnames, function(argname, index) {
if (has_default == 1 && self.args[index] instanceof AST_Spread) has_default = 2;
if (argname instanceof AST_DefaultValue) {
if (!has_default) has_default = 1;
var arg = has_default == 1 && self.args[index];
2022-02-07 14:48:46 +00:00
if (!is_undefined(arg)) has_default = 2;
if (has_arg_refs(fn, argname.value)) return false;
2022-01-21 08:28:41 +00:00
argname = argname.name;
}
if (argname instanceof AST_Destructured) {
has_destructured = true;
2022-02-07 14:48:46 +00:00
if (has_arg_refs(fn, argname)) return false;
2022-01-21 08:28:41 +00:00
}
return true;
2022-02-07 14:48:46 +00:00
}) && !(fn.rest instanceof AST_Destructured && has_arg_refs(fn, fn.rest));
2022-06-08 10:36:39 +00:00
var can_inline = can_drop
&& compressor.option("inline")
&& !self.is_expr_pure(compressor)
&& (exp === fn || safe_from_strict_mode(fn, compressor));
2022-01-21 08:28:41 +00:00
if (can_inline && stat instanceof AST_Return) {
var value = stat.value;
if (exp === fn
&& !fn.name
&& (!value || value.is_constant_expression())
2022-07-11 11:25:19 +00:00
&& safe_from_await_yield(fn, avoid_await_yield(compressor))) {
2022-01-21 08:28:41 +00:00
return make_sequence(self, convert_args(value)).optimize(compressor);
}
}
2022-02-07 14:48:46 +00:00
if (is_func && !fn.contains_this()) {
2022-01-21 08:28:41 +00:00
var def, value, var_assigned = false;
if (can_inline
&& !fn.uses_arguments
&& !fn.pinned()
&& !(fn.name && fn instanceof AST_LambdaExpression)
&& (exp === fn || !recursive_ref(compressor, def = exp.definition(), fn)
&& fn.is_constant_expression(find_scope(compressor)))
2022-02-07 14:48:46 +00:00
&& (value = can_flatten_body(stat))) {
2022-01-21 08:28:41 +00:00
var replacing = exp === fn || def.single_use && def.references.length - def.replaced == 1;
if (can_substitute_directly()) {
var args = self.args.slice();
var refs = [];
var retValue = value.clone(true).transform(new TreeTransformer(function(node) {
if (node instanceof AST_SymbolRef) {
var def = node.definition();
if (fn.variables.get(node.name) !== def) {
refs.push(node);
return node;
}
var index = resolve_index(def);
var arg = args[index];
if (!arg) return make_node(AST_Undefined, self);
args[index] = null;
var parent = this.parent();
2022-08-31 14:34:36 +00:00
return parent ? maintain_this_binding(parent, node, arg) : arg;
2022-01-21 08:28:41 +00:00
}
}));
var save_inlined = fn.inlined;
if (exp !== fn) fn.inlined = true;
var exprs = [];
args.forEach(function(arg) {
if (!arg) return;
arg = arg.clone(true);
arg.walk(new TreeWalker(function(node) {
if (node instanceof AST_SymbolRef) refs.push(node);
}));
exprs.push(arg);
}, []);
exprs.push(retValue);
var node = make_sequence(self, exprs).optimize(compressor);
fn.inlined = save_inlined;
2022-08-31 14:34:36 +00:00
node = maintain_this_binding(parent, current, node);
2022-01-21 08:28:41 +00:00
if (replacing || best_of_expression(node, self) === node) {
refs.forEach(function(ref) {
ref.scope = exp === fn ? fn.parent_scope : exp.scope;
ref.reference();
var def = ref.definition();
if (replacing) def.replaced++;
def.single_use = false;
});
return node;
} else if (!node.has_side_effects(compressor)) {
self.drop_side_effect_free = function(compressor, first_in_statement) {
var self = this;
var exprs = self.args.slice();
exprs.unshift(self.expression);
return make_sequence(self, exprs).drop_side_effect_free(compressor, first_in_statement);
};
}
}
var arg_used, insert, in_loop, scope;
if (replacing && can_inject_symbols()) {
fn._squeezed = true;
if (exp !== fn) fn.parent_scope = exp.scope;
var node = make_sequence(self, flatten_fn()).optimize(compressor);
2022-08-31 14:34:36 +00:00
return maintain_this_binding(parent, current, node);
2022-01-21 08:28:41 +00:00
}
}
if (compressor.option("side_effects")
&& can_drop
&& all(fn.body, is_empty)
&& (fn === exp ? fn_name_unused(fn, compressor) : !has_default && !has_destructured && !fn.rest)
&& !(is_arrow(fn) && fn.value)
2022-07-11 11:25:19 +00:00
&& safe_from_await_yield(fn, avoid_await_yield(compressor))) {
2022-01-21 08:28:41 +00:00
return make_sequence(self, convert_args()).optimize(compressor);
}
}
if (compressor.option("drop_console")) {
if (exp instanceof AST_PropAccess) {
var name = exp.expression;
while (name.expression) {
name = name.expression;
}
if (is_undeclared_ref(name) && name.name == "console") {
return make_node(AST_Undefined, self).optimize(compressor);
}
}
}
if (compressor.option("negate_iife") && parent instanceof AST_SimpleStatement && is_iife_call(current)) {
return self.negate(compressor, true);
}
return try_evaluate(compressor, self);
function make_void_lhs(orig) {
2022-07-11 11:25:19 +00:00
return make_node(AST_Sub, orig, {
2022-01-21 08:28:41 +00:00
expression: make_node(AST_Array, orig, { elements: [] }),
2022-07-11 11:25:19 +00:00
property: make_node(AST_Number, orig, { value: 0 }),
2022-01-21 08:28:41 +00:00
});
}
function convert_args(value) {
var args = self.args.slice();
var destructured = has_default > 1 || has_destructured || fn.rest;
if (destructured || has_spread) args = [ make_node(AST_Array, self, { elements: args }) ];
if (destructured) {
var tt = new TreeTransformer(function(node, descend) {
if (node instanceof AST_DefaultValue) return make_node(AST_DefaultValue, node, {
name: node.name.transform(tt) || make_void_lhs(node),
value: node.value,
});
if (node instanceof AST_DestructuredArray) {
var elements = [];
node.elements.forEach(function(node, index) {
node = node.transform(tt);
if (node) elements[index] = node;
});
fill_holes(node, elements);
return make_node(AST_DestructuredArray, node, { elements: elements });
}
if (node instanceof AST_DestructuredObject) {
var properties = [], side_effects = [];
node.properties.forEach(function(prop) {
var key = prop.key;
var value = prop.value.transform(tt);
if (value) {
if (side_effects.length) {
if (!(key instanceof AST_Node)) key = make_node_from_constant(key, prop);
side_effects.push(key);
key = make_sequence(node, side_effects);
side_effects = [];
}
properties.push(make_node(AST_DestructuredKeyVal, prop, {
key: key,
value: value,
}));
} else if (key instanceof AST_Node) {
side_effects.push(key);
}
});
if (side_effects.length) properties.push(make_node(AST_DestructuredKeyVal, node, {
key: make_sequence(node, side_effects),
value: make_void_lhs(node),
}));
return make_node(AST_DestructuredObject, node, { properties: properties });
}
if (node instanceof AST_SymbolFunarg) return null;
});
var lhs = [];
fn.argnames.forEach(function(argname, index) {
argname = argname.transform(tt);
if (argname) lhs[index] = argname;
});
var rest = fn.rest && fn.rest.transform(tt);
if (rest) lhs.length = fn.argnames.length;
fill_holes(fn, lhs);
args[0] = make_node(AST_Assign, self, {
operator: "=",
left: make_node(AST_DestructuredArray, fn, {
elements: lhs,
rest: rest,
}),
right: args[0],
});
} else fn.argnames.forEach(function(argname) {
if (argname instanceof AST_DefaultValue) args.push(argname.value);
});
args.push(value || make_node(AST_Undefined, self));
return args;
}
function noop_value() {
return self.call_only ? make_node(AST_Number, self, { value: 0 }) : make_node(AST_Undefined, self);
}
function return_value(stat) {
if (!stat) return noop_value();
if (stat instanceof AST_Return) return stat.value || noop_value();
if (stat instanceof AST_SimpleStatement) {
return self.call_only ? stat.body : make_node(AST_UnaryPrefix, stat, {
operator: "void",
expression: stat.body,
});
}
}
function can_flatten_body(stat) {
var len = fn.body.length;
if (len < 2) {
stat = return_value(stat);
if (stat) return stat;
}
if (compressor.option("inline") < 3) return false;
stat = null;
for (var i = 0; i < len; i++) {
var line = fn.body[i];
if (line instanceof AST_Var) {
2022-02-07 14:48:46 +00:00
if (var_assigned) {
if (!stat) continue;
if (!(stat instanceof AST_SimpleStatement)) return false;
if (!declarations_only(line)) stat = null;
} else if (!declarations_only(line)) {
if (stat && !(stat instanceof AST_SimpleStatement)) return false;
stat = null;
2022-01-21 08:28:41 +00:00
var_assigned = true;
}
} else if (line instanceof AST_AsyncDefun
|| line instanceof AST_Defun
|| line instanceof AST_EmptyStatement) {
continue;
} else if (stat) {
return false;
} else {
stat = line;
}
}
return return_value(stat);
}
function resolve_index(def) {
for (var i = fn.argnames.length; --i >= 0;) {
if (fn.argnames[i].definition() === def) return i;
}
}
function can_substitute_directly() {
2022-02-07 14:48:46 +00:00
if (has_default || has_destructured || has_spread || var_assigned || fn.rest) return;
2022-01-21 08:28:41 +00:00
if (compressor.option("inline") < 2 && fn.argnames.length) return;
if (!fn.variables.all(function(def) {
return def.references.length - def.replaced < 2 && def.orig[0] instanceof AST_SymbolFunarg;
})) return;
var scope = compressor.find_parent(AST_Scope);
var abort = false;
2022-07-11 11:25:19 +00:00
var avoid = avoid_await_yield(compressor, scope);
2022-01-21 08:28:41 +00:00
var begin;
var in_order = [];
var side_effects = false;
2022-08-31 14:34:36 +00:00
var tw = new TreeWalker(function(node, descend) {
2022-01-21 08:28:41 +00:00
if (abort) return true;
if (node instanceof AST_Binary && lazy_op[node.operator]
|| node instanceof AST_Conditional) {
in_order = null;
return;
}
if (node instanceof AST_Scope) return abort = true;
if (avoid && node instanceof AST_Symbol && avoid[node.name]) return abort = true;
if (node instanceof AST_SymbolRef) {
var def = node.definition();
if (fn.variables.get(node.name) !== def) {
in_order = null;
return;
}
if (def.init instanceof AST_LambdaDefinition) return abort = true;
2022-08-31 14:34:36 +00:00
if (is_lhs(node, tw.parent())) return abort = true;
2022-01-21 08:28:41 +00:00
var index = resolve_index(def);
if (!(begin < index)) begin = index;
if (!in_order) return;
if (side_effects) {
in_order = null;
} else {
in_order.push(fn.argnames[index]);
}
return;
}
2022-08-31 14:34:36 +00:00
if (side_effects) return;
if (node instanceof AST_Assign && node.left instanceof AST_PropAccess) {
node.left.expression.walk(tw);
if (node.left instanceof AST_Sub) node.left.property.walk(tw);
node.right.walk(tw);
side_effects = true;
return true;
}
2022-01-21 08:28:41 +00:00
if (node.has_side_effects(compressor)) {
descend();
side_effects = true;
return true;
}
2022-08-31 14:34:36 +00:00
});
value.walk(tw);
2022-01-21 08:28:41 +00:00
if (abort) return;
var end = self.args.length;
if (in_order && fn.argnames.length >= end) {
end = fn.argnames.length;
while (end-- > begin && fn.argnames[end] === in_order.pop());
end++;
}
return end <= begin || all(self.args.slice(begin, end), side_effects && !in_order ? function(funarg) {
return funarg.is_constant_expression(scope);
} : function(funarg) {
return !funarg.has_side_effects(compressor);
});
}
function var_exists(defined, name) {
return defined.has(name) || identifier_atom[name] || scope.var_names().has(name);
}
function can_inject_args(defined, safe_to_inject) {
var abort = false;
fn.each_argname(function(arg) {
if (abort) return;
if (arg.unused) return;
if (!safe_to_inject || var_exists(defined, arg.name)) return abort = true;
arg_used.set(arg.name, true);
if (in_loop) in_loop.push(arg.definition());
});
return !abort;
}
function can_inject_vars(defined, safe_to_inject) {
for (var i = 0; i < fn.body.length; i++) {
var stat = fn.body[i];
if (stat instanceof AST_LambdaDefinition) {
var name = stat.name;
if (!safe_to_inject) return false;
if (arg_used.has(name.name)) return false;
if (var_exists(defined, name.name)) return false;
if (!all(stat.enclosed, function(def) {
2022-02-07 14:48:46 +00:00
return def.scope === scope || def.scope === stat || !defined.has(def.name);
2022-01-21 08:28:41 +00:00
})) return false;
if (in_loop) in_loop.push(name.definition());
continue;
}
if (!(stat instanceof AST_Var)) continue;
if (!safe_to_inject) return false;
for (var j = stat.definitions.length; --j >= 0;) {
var name = stat.definitions[j].name;
if (var_exists(defined, name.name)) return false;
if (in_loop) in_loop.push(name.definition());
}
}
return true;
}
function can_inject_symbols() {
var defined = new Dictionary();
var level = 0, child;
scope = current;
do {
if (scope.variables) scope.variables.each(function(def) {
defined.set(def.name, true);
});
child = scope;
scope = compressor.parent(level++);
2022-07-11 11:25:19 +00:00
if (scope instanceof AST_ClassField) {
if (!scope.static) return false;
} else if (scope instanceof AST_DWLoop) {
2022-01-21 08:28:41 +00:00
in_loop = [];
} else if (scope instanceof AST_For) {
if (scope.init === child) continue;
in_loop = [];
} else if (scope instanceof AST_ForEnumeration) {
if (scope.init === child) continue;
if (scope.object === child) continue;
in_loop = [];
}
} while (!(scope instanceof AST_Scope));
insert = scope.body.indexOf(child) + 1;
if (!insert) return false;
2022-07-11 11:25:19 +00:00
if (!safe_from_await_yield(fn, avoid_await_yield(compressor, scope))) return false;
2022-03-14 15:40:45 +00:00
var safe_to_inject = (exp !== fn || fn.parent_scope.resolve() === scope) && !scope.pinned();
2022-01-21 08:28:41 +00:00
if (scope instanceof AST_Toplevel) {
if (compressor.toplevel.vars) {
defined.set("arguments", true);
} else {
safe_to_inject = false;
}
}
arg_used = new Dictionary();
var inline = compressor.option("inline");
if (!can_inject_args(defined, inline >= 2 && safe_to_inject)) return false;
if (!can_inject_vars(defined, inline >= 3 && safe_to_inject)) return false;
return !in_loop || in_loop.length == 0 || !is_reachable(fn, in_loop);
}
function append_var(decls, expressions, name, value) {
var def = name.definition();
if (!scope.var_names().has(name.name)) {
scope.var_names().set(name.name, true);
decls.push(make_node(AST_VarDef, name, {
name: name,
value: null,
}));
}
scope.variables.set(name.name, def);
scope.enclosed.push(def);
if (!value) return;
2022-08-31 14:34:36 +00:00
var sym = make_node(AST_SymbolRef, name);
2022-02-07 14:48:46 +00:00
def.assignments++;
2022-01-21 08:28:41 +00:00
def.references.push(sym);
expressions.push(make_node(AST_Assign, self, {
operator: "=",
left: sym,
right: value,
}));
}
function flatten_args(decls, expressions) {
var len = fn.argnames.length;
for (var i = self.args.length; --i >= len;) {
expressions.push(self.args[i]);
}
var default_args = [];
for (i = len; --i >= 0;) {
var argname = fn.argnames[i];
var name;
if (argname instanceof AST_DefaultValue) {
default_args.push(argname);
name = argname.name;
} else {
name = argname;
}
var value = self.args[i];
if (name.unused || scope.var_names().has(name.name)) {
if (value) expressions.push(value);
} else {
2022-08-31 14:34:36 +00:00
var symbol = make_node(AST_SymbolVar, name);
2022-02-07 14:48:46 +00:00
var def = name.definition();
def.orig.push(symbol);
def.eliminated++;
2022-01-21 08:28:41 +00:00
if (name.unused !== undefined) {
append_var(decls, expressions, symbol);
if (value) expressions.push(value);
} else {
2022-08-05 07:44:52 +00:00
if (!value && argname === name && (in_loop
|| name.name == "arguments" && !is_arrow(fn) && is_arrow(scope))) {
value = make_node(AST_Undefined, self);
}
2022-01-21 08:28:41 +00:00
append_var(decls, expressions, symbol, value);
}
}
}
decls.reverse();
expressions.reverse();
for (i = default_args.length; --i >= 0;) {
var node = default_args[i];
if (node.name.unused !== undefined) {
expressions.push(node.value);
} else {
2022-08-31 14:34:36 +00:00
var sym = make_node(AST_SymbolRef, node.name);
2022-01-21 08:28:41 +00:00
node.name.definition().references.push(sym);
expressions.push(make_node(AST_Assign, node, {
operator: "=",
left: sym,
right: node.value,
}));
}
}
}
function flatten_destructured(decls, expressions) {
expressions.push(make_node(AST_Assign, self, {
operator: "=",
left: make_node(AST_DestructuredArray, self, {
elements: fn.argnames.map(function(argname) {
if (argname.unused) return make_node(AST_Hole, argname);
return argname.convert_symbol(AST_SymbolRef, process);
}),
rest: fn.rest && fn.rest.convert_symbol(AST_SymbolRef, process),
}),
right: make_node(AST_Array, self, { elements: self.args.slice() }),
}));
function process(ref, name) {
2022-07-11 11:25:19 +00:00
if (name.unused) return make_void_lhs(name);
2022-01-21 08:28:41 +00:00
var def = name.definition();
2022-02-07 14:48:46 +00:00
def.assignments++;
2022-01-21 08:28:41 +00:00
def.references.push(ref);
2022-08-31 14:34:36 +00:00
var symbol = make_node(AST_SymbolVar, name);
2022-01-21 08:28:41 +00:00
def.orig.push(symbol);
2022-02-07 14:48:46 +00:00
def.eliminated++;
2022-01-21 08:28:41 +00:00
append_var(decls, expressions, symbol);
}
}
function flatten_vars(decls, expressions) {
var args = [ insert, 0 ];
2022-02-07 14:48:46 +00:00
var decl_var = [], expr_fn = [], expr_var = [], expr_loop = [], exprs = [];
fn.body.filter(in_loop ? function(stat) {
if (!(stat instanceof AST_LambdaDefinition)) return true;
2022-08-31 14:34:36 +00:00
var name = make_node(AST_SymbolVar, flatten_var(stat.name));
2022-02-07 14:48:46 +00:00
var def = name.definition();
def.fixed = false;
def.orig.push(name);
def.eliminated++;
append_var(decls, expr_fn, name, to_func_expr(stat, true));
return false;
} : function(stat) {
if (!(stat instanceof AST_LambdaDefinition)) return true;
var def = stat.name.definition();
scope.functions.set(def.name, def);
scope.variables.set(def.name, def);
scope.enclosed.push(def);
scope.var_names().set(def.name, true);
args.push(stat);
return false;
}).forEach(function(stat) {
if (!(stat instanceof AST_Var)) {
if (stat instanceof AST_SimpleStatement) exprs.push(stat.body);
return;
2022-01-21 08:28:41 +00:00
}
for (var j = 0; j < stat.definitions.length; j++) {
var var_def = stat.definitions[j];
var name = flatten_var(var_def.name);
2022-02-07 14:48:46 +00:00
var value = var_def.value;
if (value && exprs.length > 0) {
exprs.push(value);
value = make_sequence(var_def, exprs);
exprs = [];
}
append_var(decl_var, expr_var, name, value);
if (!in_loop) continue;
if (arg_used.has(name.name)) continue;
if (name.definition().orig.length == 1 && fn.functions.has(name.name)) continue;
expr_loop.push(init_ref(compressor, name));
2022-01-21 08:28:41 +00:00
}
2022-02-07 14:48:46 +00:00
});
2022-01-21 08:28:41 +00:00
[].push.apply(decls, decl_var);
[].push.apply(expressions, expr_loop);
2022-02-07 14:48:46 +00:00
[].push.apply(expressions, expr_fn);
2022-01-21 08:28:41 +00:00
[].push.apply(expressions, expr_var);
return args;
}
function flatten_fn() {
var decls = [];
var expressions = [];
2022-02-07 14:48:46 +00:00
if (has_default > 1 || has_destructured || has_spread || fn.rest) {
2022-01-21 08:28:41 +00:00
flatten_destructured(decls, expressions);
} else {
flatten_args(decls, expressions);
}
var args = flatten_vars(decls, expressions);
expressions.push(value);
2022-02-07 14:48:46 +00:00
if (decls.length) args.push(make_node(AST_Var, fn, { definitions: decls }));
2022-01-21 08:28:41 +00:00
[].splice.apply(scope.body, args);
fn.enclosed.forEach(function(def) {
if (scope.var_names().has(def.name)) return;
scope.enclosed.push(def);
scope.var_names().set(def.name, true);
});
return expressions;
}
});
OPT(AST_New, function(self, compressor) {
2022-08-31 14:34:36 +00:00
if (compressor.option("unsafe")) {
var exp = self.expression;
if (is_undeclared_ref(exp)) switch (exp.name) {
case "Array":
case "Error":
case "Function":
case "Object":
case "RegExp":
return make_node(AST_Call, self).transform(compressor);
}
}
2022-01-21 08:28:41 +00:00
if (compressor.option("sequences")) {
var seq = lift_sequence_in_expression(self, compressor);
if (seq !== self) return seq.optimize(compressor);
}
if (compressor.option("unused")) drop_unused_call_args(self, compressor);
return self;
});
// (a = b, x && a = c) ---> a = x ? c : b
// (a = b, x || a = c) ---> a = x ? b : c
function to_conditional_assignment(compressor, def, value, node) {
if (!(node instanceof AST_Binary)) return;
if (!(node.operator == "&&" || node.operator == "||")) return;
if (!(node.right instanceof AST_Assign)) return;
if (node.right.operator != "=") return;
if (!(node.right.left instanceof AST_SymbolRef)) return;
if (node.right.left.definition() !== def) return;
if (value.has_side_effects(compressor)) return;
if (!safe_from_assignment(node.left)) return;
if (!safe_from_assignment(node.right.right)) return;
def.replaced++;
return node.operator == "&&" ? make_node(AST_Conditional, node, {
condition: node.left,
consequent: node.right.right,
2022-08-31 14:34:36 +00:00
alternative: value,
2022-01-21 08:28:41 +00:00
}) : make_node(AST_Conditional, node, {
condition: node.left,
consequent: value,
2022-08-31 14:34:36 +00:00
alternative: node.right.right,
2022-01-21 08:28:41 +00:00
});
function safe_from_assignment(node) {
if (node.has_side_effects(compressor)) return;
var hit = false;
node.walk(new TreeWalker(function(node) {
if (hit) return true;
if (node instanceof AST_SymbolRef && node.definition() === def) return hit = true;
}));
return !hit;
}
}
OPT(AST_Sequence, function(self, compressor) {
var expressions = filter_for_side_effects();
var end = expressions.length - 1;
merge_assignments();
trim_right_for_undefined();
if (end == 0) {
2022-08-31 14:34:36 +00:00
self = maintain_this_binding(compressor.parent(), compressor.self(), expressions[0]);
2022-01-21 08:28:41 +00:00
if (!(self instanceof AST_Sequence)) self = self.optimize(compressor);
return self;
}
self.expressions = expressions;
return self;
function filter_for_side_effects() {
if (!compressor.option("side_effects")) return self.expressions;
var expressions = [];
var first = first_in_statement(compressor);
var last = self.expressions.length - 1;
self.expressions.forEach(function(expr, index) {
if (index < last) expr = expr.drop_side_effect_free(compressor, first);
if (expr) {
merge_sequence(expressions, expr);
first = false;
}
});
return expressions;
}
function trim_right_for_undefined() {
if (!compressor.option("side_effects")) return;
while (end > 0 && is_undefined(expressions[end], compressor)) end--;
if (end < expressions.length - 1) {
expressions[end] = make_node(AST_UnaryPrefix, self, {
2022-08-31 14:34:36 +00:00
operator: "void",
expression: expressions[end],
2022-01-21 08:28:41 +00:00
});
expressions.length = end + 1;
}
}
function is_simple_assign(node) {
return node instanceof AST_Assign
&& node.operator == "="
&& node.left instanceof AST_SymbolRef
&& node.left.definition();
}
function merge_assignments() {
for (var i = 1; i < end; i++) {
var prev = expressions[i - 1];
var def = is_simple_assign(prev);
if (!def) continue;
var expr = expressions[i];
if (compressor.option("conditionals")) {
var cond = to_conditional_assignment(compressor, def, prev.right, expr);
if (cond) {
prev.right = cond;
expressions.splice(i--, 1);
end--;
continue;
}
}
if (compressor.option("dead_code")
&& is_simple_assign(expr) === def
&& expr.right.is_constant_expression(def.scope.resolve())) {
expressions[--i] = prev.right;
}
}
}
});
OPT(AST_UnaryPostfix, function(self, compressor) {
if (compressor.option("sequences")) {
var seq = lift_sequence_in_expression(self, compressor);
if (seq !== self) return seq.optimize(compressor);
}
return try_evaluate(compressor, self);
});
var SIGN_OPS = makePredicate("+ -");
var MULTIPLICATIVE_OPS = makePredicate("* / %");
OPT(AST_UnaryPrefix, function(self, compressor) {
var op = self.operator;
var exp = self.expression;
if (compressor.option("sequences") && can_lift()) {
var seq = lift_sequence_in_expression(self, compressor);
if (seq !== self) return seq.optimize(compressor);
}
2022-02-07 14:48:46 +00:00
switch (op) {
2022-03-14 15:40:45 +00:00
case "+":
if (!compressor.option("evaluate")) break;
if (!exp.is_number(compressor, true)) break;
var parent = compressor.parent();
if (parent instanceof AST_UnaryPrefix && parent.operator == "delete") break;
return exp;
2022-02-07 14:48:46 +00:00
case "-":
if (exp instanceof AST_Infinity) exp = exp.transform(compressor);
// avoids infinite recursion of numerals
if (exp instanceof AST_Number || exp instanceof AST_Infinity) return self;
break;
case "!":
if (!compressor.option("booleans")) break;
if (exp.is_truthy()) return make_sequence(self, [ exp, make_node(AST_False, self) ]).optimize(compressor);
if (compressor.in_boolean_context()) {
// !!foo ---> foo, if we're in boolean context
if (exp instanceof AST_UnaryPrefix && exp.operator == "!") return exp.expression;
2022-01-21 08:28:41 +00:00
if (exp instanceof AST_Binary) {
2022-08-05 07:44:52 +00:00
var first = first_in_statement(compressor);
self = (first ? best_of_statement : best_of_expression)(self, exp.negate(compressor, first));
2022-01-21 08:28:41 +00:00
}
}
2022-02-07 14:48:46 +00:00
break;
case "delete":
if (!compressor.option("evaluate")) break;
if (may_not_delete(exp)) break;
return make_sequence(self, [ exp, make_node(AST_True, self) ]).optimize(compressor);
case "typeof":
if (!compressor.option("booleans")) break;
if (!compressor.in_boolean_context()) break;
// typeof always returns a non-empty string, thus always truthy
2022-08-31 14:34:36 +00:00
AST_Node.warn("Boolean expression always true [{start}]", self);
2022-02-07 14:48:46 +00:00
var exprs = [ make_node(AST_True, self) ];
if (!(exp instanceof AST_SymbolRef && can_drop_symbol(exp, compressor))) exprs.unshift(exp);
return make_sequence(self, exprs).optimize(compressor);
case "void":
if (!compressor.option("side_effects")) break;
exp = exp.drop_side_effect_free(compressor);
if (!exp) return make_node(AST_Undefined, self).optimize(compressor);
self.expression = exp;
return self;
2022-01-21 08:28:41 +00:00
}
if (compressor.option("evaluate")
&& exp instanceof AST_Binary
&& SIGN_OPS[op]
&& MULTIPLICATIVE_OPS[exp.operator]
&& (exp.left.is_constant() || !exp.right.has_side_effects(compressor))) {
return make_node(AST_Binary, self, {
operator: exp.operator,
left: make_node(AST_UnaryPrefix, exp.left, {
operator: op,
2022-02-07 14:48:46 +00:00
expression: exp.left,
2022-01-21 08:28:41 +00:00
}),
2022-02-07 14:48:46 +00:00
right: exp.right,
2022-01-21 08:28:41 +00:00
});
}
2022-02-07 14:48:46 +00:00
return try_evaluate(compressor, self);
2022-01-21 08:28:41 +00:00
function may_not_delete(node) {
return node instanceof AST_Infinity
|| node instanceof AST_NaN
|| node instanceof AST_NewTarget
|| node instanceof AST_PropAccess
|| node instanceof AST_SymbolRef
|| node instanceof AST_Undefined;
}
function can_lift() {
switch (op) {
case "delete":
return !may_not_delete(exp.tail_node());
case "typeof":
return !is_undeclared_ref(exp.tail_node());
default:
return true;
}
}
});
OPT(AST_Await, function(self, compressor) {
if (!compressor.option("awaits")) return self;
if (compressor.option("sequences")) {
var seq = lift_sequence_in_expression(self, compressor);
if (seq !== self) return seq.optimize(compressor);
}
if (compressor.option("side_effects")) {
var exp = self.expression;
if (exp instanceof AST_Await) return exp.optimize(compressor);
2022-02-07 14:48:46 +00:00
if (exp instanceof AST_UnaryPrefix && exp.expression instanceof AST_Await) return exp.optimize(compressor);
2022-01-21 08:28:41 +00:00
for (var level = 0, node = self, parent; parent = compressor.parent(level++); node = parent) {
if (is_arrow(parent)) {
if (parent.value === node) return exp.optimize(compressor);
} else if (parent instanceof AST_Return) {
var drop = true;
do {
node = parent;
parent = compressor.parent(level++);
if (parent instanceof AST_Try && (parent.bfinally || parent.bcatch) !== node) {
drop = false;
break;
}
} while (parent && !(parent instanceof AST_Scope));
if (drop) return exp.optimize(compressor);
} else if (parent instanceof AST_Sequence) {
if (parent.tail_node() === node) continue;
}
break;
}
}
return self;
});
OPT(AST_Yield, function(self, compressor) {
if (!compressor.option("yields")) return self;
if (compressor.option("sequences")) {
var seq = lift_sequence_in_expression(self, compressor);
if (seq !== self) return seq.optimize(compressor);
}
var exp = self.expression;
if (self.nested && exp.TYPE == "Call") {
var inlined = exp.clone().optimize(compressor);
if (inlined.TYPE != "Call") return inlined;
}
return self;
});
AST_Binary.DEFMETHOD("lift_sequences", function(compressor) {
if (this.left instanceof AST_PropAccess) {
if (!(this.left.expression instanceof AST_Sequence)) return this;
var x = this.left.expression.expressions.slice();
var e = this.clone();
e.left = e.left.clone();
e.left.expression = x.pop();
x.push(e);
return make_sequence(this, x);
}
if (this.left instanceof AST_Sequence) {
var x = this.left.expressions.slice();
var e = this.clone();
e.left = x.pop();
x.push(e);
return make_sequence(this, x);
}
if (this.right instanceof AST_Sequence) {
if (this.left.has_side_effects(compressor)) return this;
var assign = this.operator == "=" && this.left instanceof AST_SymbolRef;
var x = this.right.expressions;
var last = x.length - 1;
for (var i = 0; i < last; i++) {
if (!assign && x[i].has_side_effects(compressor)) break;
}
if (i == last) {
x = x.slice();
var e = this.clone();
e.right = x.pop();
x.push(e);
return make_sequence(this, x);
}
if (i > 0) {
var e = this.clone();
e.right = make_sequence(this.right, x.slice(i));
x = x.slice(0, i);
x.push(e);
return make_sequence(this, x);
}
}
return this;
});
var indexFns = makePredicate("indexOf lastIndexOf");
var commutativeOperators = makePredicate("== === != !== * & | ^");
2022-09-30 13:48:25 +00:00
function is_object(node, plain) {
if (node instanceof AST_Assign) return !plain && node.operator == "=" && is_object(node.right);
if (node instanceof AST_New) return !plain;
if (node instanceof AST_Sequence) return is_object(node.tail_node(), plain);
if (node instanceof AST_SymbolRef) return !plain && is_object(node.fixed_value());
2022-01-21 08:28:41 +00:00
return node instanceof AST_Array
|| node instanceof AST_Class
|| node instanceof AST_Lambda
|| node instanceof AST_Object;
}
2022-07-11 11:25:19 +00:00
function can_drop_op(op, rhs, compressor) {
switch (op) {
case "in":
return is_object(rhs) || compressor && compressor.option("unsafe_comps");
case "instanceof":
if (rhs instanceof AST_SymbolRef) rhs = rhs.fixed_value();
return is_lambda(rhs) || compressor && compressor.option("unsafe_comps");
default:
return true;
}
}
2022-09-30 13:48:25 +00:00
function needs_enqueuing(compressor, node) {
2022-01-21 08:28:41 +00:00
if (node.is_constant()) return true;
2022-09-30 13:48:25 +00:00
if (node instanceof AST_Assign) return node.operator != "=" || needs_enqueuing(compressor, node.right);
2022-01-21 08:28:41 +00:00
if (node instanceof AST_Binary) {
return !lazy_op[node.operator]
2022-09-30 13:48:25 +00:00
|| needs_enqueuing(compressor, node.left) && needs_enqueuing(compressor, node.right);
2022-01-21 08:28:41 +00:00
}
2022-09-30 13:48:25 +00:00
if (node instanceof AST_Call) return is_async(node.expression);
2022-01-21 08:28:41 +00:00
if (node instanceof AST_Conditional) {
2022-09-30 13:48:25 +00:00
return needs_enqueuing(compressor, node.consequent) && needs_enqueuing(compressor, node.alternative);
2022-01-21 08:28:41 +00:00
}
2022-09-30 13:48:25 +00:00
if (node instanceof AST_Sequence) return needs_enqueuing(compressor, node.tail_node());
2022-01-21 08:28:41 +00:00
if (node instanceof AST_SymbolRef) {
var fixed = node.fixed_value();
2022-09-30 13:48:25 +00:00
return fixed && needs_enqueuing(compressor, fixed);
2022-01-21 08:28:41 +00:00
}
if (node instanceof AST_Template) return !node.tag || is_raw_tag(compressor, node.tag);
if (node instanceof AST_Unary) return true;
}
2022-10-10 08:26:02 +00:00
function extract_lhs(node, compressor) {
if (node instanceof AST_Assign) return is_lhs_read_only(node.left, compressor) ? node : node.left;
if (node instanceof AST_Sequence) return extract_lhs(node.tail_node(), compressor);
if (node instanceof AST_UnaryPrefix && UNARY_POSTFIX[node.operator]) {
return is_lhs_read_only(node.expression, compressor) ? node : node.expression;
}
return node;
}
2022-01-21 08:28:41 +00:00
function repeatable(compressor, node) {
if (node instanceof AST_Dot) return repeatable(compressor, node.expression);
if (node instanceof AST_Sub) {
return repeatable(compressor, node.expression) && repeatable(compressor, node.property);
}
if (node instanceof AST_Symbol) return true;
return !node.has_side_effects(compressor);
}
2022-03-14 15:40:45 +00:00
function swap_chain(self, compressor) {
2022-11-30 12:56:09 +00:00
var rhs = self.right.tail_node();
if (rhs !== self.right) {
var exprs = self.right.expressions.slice(0, -1);
exprs.push(rhs.left);
rhs = rhs.clone();
rhs.left = make_sequence(self.right, exprs);
self.right = rhs;
}
2022-03-14 15:40:45 +00:00
self.left = make_node(AST_Binary, self, {
operator: self.operator,
left: self.left,
right: rhs.left,
start: self.left.start,
2022-08-31 14:34:36 +00:00
end: rhs.left.end,
2022-03-14 15:40:45 +00:00
});
self.right = rhs.right;
if (compressor) {
self.left = self.left.transform(compressor);
} else if (self.operator == rhs.left.operator) {
swap_chain(self.left);
}
}
2022-01-21 08:28:41 +00:00
OPT(AST_Binary, function(self, compressor) {
if (commutativeOperators[self.operator]
&& self.right.is_constant()
&& !self.left.is_constant()
&& !(self.left instanceof AST_Binary
&& PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) {
// if right is a constant, whatever side effects the
// left side might have could not influence the
// result. hence, force switch.
reverse();
}
if (compressor.option("sequences")) {
var seq = self.lift_sequences(compressor);
if (seq !== self) return seq.optimize(compressor);
}
if (compressor.option("assignments") && lazy_op[self.operator]) {
2022-10-10 08:26:02 +00:00
var lhs = extract_lhs(self.left, compressor);
2022-09-30 13:48:25 +00:00
var right = self.right;
2022-01-21 08:28:41 +00:00
// a || (a = x) ---> a = a || x
2022-10-10 08:26:02 +00:00
// (a = x) && (a = y) ---> a = (a = x) && y
if (lhs instanceof AST_SymbolRef
2022-09-30 13:48:25 +00:00
&& right instanceof AST_Assign
&& right.operator == "="
2022-10-10 08:26:02 +00:00
&& lhs.equals(right.left)) {
lhs = lhs.clone();
2022-09-30 13:48:25 +00:00
var assign = make_node(AST_Assign, self, {
2022-05-29 09:24:36 +00:00
operator: "=",
2022-10-10 08:26:02 +00:00
left: lhs,
2022-05-29 09:24:36 +00:00
right: make_node(AST_Binary, self, {
operator: self.operator,
left: self.left,
2022-09-30 13:48:25 +00:00
right: right.right,
2022-05-29 09:24:36 +00:00
}),
2022-09-30 13:48:25 +00:00
});
2022-10-10 08:26:02 +00:00
if (lhs.fixed) {
lhs.fixed = function() {
2022-09-30 13:48:25 +00:00
return assign.right;
};
2022-10-10 08:26:02 +00:00
lhs.fixed.assigns = [ assign ];
2022-09-30 13:48:25 +00:00
}
2022-10-10 08:26:02 +00:00
var def = lhs.definition();
def.references.push(lhs);
2022-09-30 13:48:25 +00:00
def.replaced++;
return assign.optimize(compressor);
2022-01-21 08:28:41 +00:00
}
}
if (compressor.option("comparisons")) switch (self.operator) {
case "===":
case "!==":
if (is_undefined(self.left, compressor) && self.right.is_defined(compressor)) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Expression always defined [{start}]", self);
2022-01-21 08:28:41 +00:00
return make_sequence(self, [
self.right,
2022-08-31 14:34:36 +00:00
make_node(self.operator == "===" ? AST_False : AST_True, self),
2022-01-21 08:28:41 +00:00
]).optimize(compressor);
}
var is_strict_comparison = true;
if ((self.left.is_string(compressor) && self.right.is_string(compressor)) ||
(self.left.is_number(compressor) && self.right.is_number(compressor)) ||
(self.left.is_boolean(compressor) && self.right.is_boolean(compressor)) ||
2022-08-05 07:44:52 +00:00
repeatable(compressor, self.left) && self.left.equals(self.right)) {
2022-01-21 08:28:41 +00:00
self.operator = self.operator.slice(0, 2);
}
// XXX: intentionally falling down to the next case
case "==":
case "!=":
// void 0 == x ---> null == x
if (!is_strict_comparison && is_undefined(self.left, compressor)) {
self.left = make_node(AST_Null, self.left);
}
// "undefined" == typeof x ---> undefined === x
else if (compressor.option("typeofs")
&& self.left instanceof AST_String
&& self.left.value == "undefined"
&& self.right instanceof AST_UnaryPrefix
&& self.right.operator == "typeof") {
var expr = self.right.expression;
if (expr instanceof AST_SymbolRef ? expr.is_declared(compressor)
: !(expr instanceof AST_PropAccess && compressor.option("ie"))) {
self.right = expr;
self.left = make_node(AST_Undefined, self.left).optimize(compressor);
if (self.operator.length == 2) self.operator += "=";
}
}
// obj !== obj ---> false
else if (self.left instanceof AST_SymbolRef
&& self.right instanceof AST_SymbolRef
&& self.left.definition() === self.right.definition()
&& is_object(self.left)) {
return make_node(self.operator[0] == "=" ? AST_True : AST_False, self).optimize(compressor);
}
break;
case "&&":
case "||":
// void 0 !== x && null !== x ---> null != x
// void 0 === x || null === x ---> null == x
2022-10-10 08:26:02 +00:00
var left = self.left;
if (!(left instanceof AST_Binary)) break;
if (left.operator != (self.operator == "&&" ? "!==" : "===")) break;
if (!(self.right instanceof AST_Binary)) break;
if (left.operator != self.right.operator) break;
if (is_undefined(left.left, compressor) && self.right.left instanceof AST_Null
|| left.left instanceof AST_Null && is_undefined(self.right.left, compressor)) {
var expr = left.right;
if (expr instanceof AST_Assign && expr.operator == "=") expr = expr.left;
if (expr.has_side_effects(compressor)) break;
if (!expr.equals(self.right.right)) break;
left.operator = left.operator.slice(0, -1);
left.left = make_node(AST_Null, self);
return left;
2022-01-21 08:28:41 +00:00
}
break;
}
var in_bool = false;
var parent = compressor.parent();
if (compressor.option("booleans")) {
2022-10-10 08:26:02 +00:00
var lhs = extract_lhs(self.left, compressor);
2022-01-21 08:28:41 +00:00
if (lazy_op[self.operator] && !lhs.has_side_effects(compressor)) {
2022-10-10 08:26:02 +00:00
// a || a ---> a
// (a = x) && a --> a = x
2022-08-05 07:44:52 +00:00
if (lhs.equals(self.right)) {
2022-10-10 08:26:02 +00:00
return maintain_this_binding(parent, compressor.self(), self.left).optimize(compressor);
2022-01-21 08:28:41 +00:00
}
mark_duplicate_condition(compressor, lhs);
}
in_bool = compressor.in_boolean_context();
}
if (in_bool) switch (self.operator) {
case "+":
2022-03-14 15:40:45 +00:00
var ev = self.left.evaluate(compressor, true);
if (ev && typeof ev == "string" || (ev = self.right.evaluate(compressor, true)) && typeof ev == "string") {
2022-08-31 14:34:36 +00:00
AST_Node.warn("+ in boolean context always true [{start}]", self);
2022-03-14 15:40:45 +00:00
var exprs = [];
if (self.left.evaluate(compressor) instanceof AST_Node) exprs.push(self.left);
if (self.right.evaluate(compressor) instanceof AST_Node) exprs.push(self.right);
if (exprs.length < 2) {
exprs.push(make_node(AST_True, self));
return make_sequence(self, exprs).optimize(compressor);
}
self.truthy = true;
2022-01-21 08:28:41 +00:00
}
break;
case "==":
if (self.left instanceof AST_String && self.left.value == "" && self.right.is_string(compressor)) {
return make_node(AST_UnaryPrefix, self, {
operator: "!",
2022-08-31 14:34:36 +00:00
expression: self.right,
2022-01-21 08:28:41 +00:00
}).optimize(compressor);
}
break;
case "!=":
if (self.left instanceof AST_String && self.left.value == "" && self.right.is_string(compressor)) {
return self.right.optimize(compressor);
}
break;
}
if (compressor.option("comparisons") && self.is_boolean(compressor)) {
2022-08-05 07:44:52 +00:00
if (parent.TYPE != "Binary") {
var negated = make_node(AST_UnaryPrefix, self, {
2022-01-21 08:28:41 +00:00
operator: "!",
2022-08-05 07:44:52 +00:00
expression: self.negate(compressor),
});
if (best_of(compressor, self, negated) === negated) return negated;
2022-01-21 08:28:41 +00:00
}
switch (self.operator) {
case ">": reverse("<"); break;
case ">=": reverse("<="); break;
}
}
2022-10-10 08:26:02 +00:00
if (compressor.option("conditionals") && lazy_op[self.operator]) {
if (self.left instanceof AST_Binary && self.operator == self.left.operator) {
var before = make_node(AST_Binary, self, {
operator: self.operator,
left: self.left.right,
right: self.right,
});
2022-11-30 12:56:09 +00:00
var after = before.transform(compressor);
2022-10-10 08:26:02 +00:00
if (before !== after) {
self.left = self.left.left;
self.right = after;
}
}
// x && (y && z) ---> x && y && z
2022-11-30 12:56:09 +00:00
// w || (x, y || z) ---> w || (x, y) || z
var rhs = self.right.tail_node();
if (rhs instanceof AST_Binary && self.operator == rhs.operator) swap_chain(self, compressor);
2022-01-21 08:28:41 +00:00
}
if (compressor.option("strings") && self.operator == "+") {
// "foo" + 42 + "" ---> "foo" + 42
if (self.right instanceof AST_String
&& self.right.value == ""
&& self.left.is_string(compressor)) {
return self.left.optimize(compressor);
}
// "" + ("foo" + 42) ---> "foo" + 42
if (self.left instanceof AST_String
&& self.left.value == ""
&& self.right.is_string(compressor)) {
return self.right.optimize(compressor);
}
// "" + 42 + "foo" ---> 42 + "foo"
if (self.left instanceof AST_Binary
&& self.left.operator == "+"
&& self.left.left instanceof AST_String
&& self.left.left.value == ""
&& self.right.is_string(compressor)
&& (self.left.right.is_constant() || !self.right.has_side_effects(compressor))) {
self.left = self.left.right;
return self.optimize(compressor);
}
// "x" + (y + "z") ---> "x" + y + "z"
2022-11-30 12:56:09 +00:00
// w + (x, "y" + z) ---> w + (x, "y") + z
var rhs = self.right.tail_node();
if (rhs instanceof AST_Binary
&& self.operator == rhs.operator
&& (self.left.is_string(compressor) && rhs.is_string(compressor)
|| rhs.left.is_string(compressor)
&& (self.left.is_constant() || !rhs.right.has_side_effects(compressor)))) {
2022-03-14 15:40:45 +00:00
swap_chain(self, compressor);
2022-01-21 08:28:41 +00:00
}
}
if (compressor.option("evaluate")) {
var associative = true;
switch (self.operator) {
case "&&":
var ll = fuzzy_eval(compressor, self.left);
if (!ll) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Condition left of && always false [{start}]", self);
return maintain_this_binding(parent, compressor.self(), self.left).optimize(compressor);
2022-01-21 08:28:41 +00:00
} else if (!(ll instanceof AST_Node)) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Condition left of && always true [{start}]", self);
2022-01-21 08:28:41 +00:00
return make_sequence(self, [ self.left, self.right ]).optimize(compressor);
}
2022-03-14 15:40:45 +00:00
if (!self.right.evaluate(compressor, true)) {
if (in_bool && !(self.right.evaluate(compressor) instanceof AST_Node)) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Boolean && always false [{start}]", self);
2022-03-14 15:40:45 +00:00
return make_sequence(self, [ self.left, make_node(AST_False, self) ]).optimize(compressor);
2022-01-21 08:28:41 +00:00
} else self.falsy = true;
2022-03-14 15:40:45 +00:00
} else if ((in_bool || parent.operator == "&&" && parent.left === compressor.self())
&& !(self.right.evaluate(compressor) instanceof AST_Node)) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Dropping side-effect-free && [{start}]", self);
2022-03-14 15:40:45 +00:00
return self.left.optimize(compressor);
2022-01-21 08:28:41 +00:00
}
// (x || false) && y ---> x ? y : false
if (self.left.operator == "||") {
var lr = fuzzy_eval(compressor, self.left.right);
if (!lr) return make_node(AST_Conditional, self, {
condition: self.left.left,
consequent: self.right,
2022-08-31 14:34:36 +00:00
alternative: self.left.right,
2022-01-21 08:28:41 +00:00
}).optimize(compressor);
}
break;
case "??":
var nullish = true;
case "||":
var ll = fuzzy_eval(compressor, self.left, nullish);
if (nullish ? ll == null : !ll) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Condition left of {operator} always {value} [{start}]", {
2022-01-21 08:28:41 +00:00
operator: self.operator,
2022-10-10 08:26:02 +00:00
value: nullish ? "nullish" : "false",
2022-08-31 14:34:36 +00:00
start: self.start,
2022-01-21 08:28:41 +00:00
});
return make_sequence(self, [ self.left, self.right ]).optimize(compressor);
} else if (!(ll instanceof AST_Node)) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Condition left of {operator} always {value} [{start}]", {
2022-01-21 08:28:41 +00:00
operator: self.operator,
value: nullish ? "defined" : "true",
2022-08-31 14:34:36 +00:00
start: self.start,
2022-01-21 08:28:41 +00:00
});
2022-08-31 14:34:36 +00:00
return maintain_this_binding(parent, compressor.self(), self.left).optimize(compressor);
2022-01-21 08:28:41 +00:00
}
2022-03-14 15:40:45 +00:00
var rr;
if (!nullish && (rr = self.right.evaluate(compressor, true)) && !(rr instanceof AST_Node)) {
if (in_bool && !(self.right.evaluate(compressor) instanceof AST_Node)) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Boolean || always true [{start}]", self);
2022-03-14 15:40:45 +00:00
return make_sequence(self, [ self.left, make_node(AST_True, self) ]).optimize(compressor);
2022-01-21 08:28:41 +00:00
} else self.truthy = true;
2022-03-14 15:40:45 +00:00
} else if ((in_bool || parent.operator == "||" && parent.left === compressor.self())
&& !self.right.evaluate(compressor)) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Dropping side-effect-free {operator} [{start}]", self);
2022-03-14 15:40:45 +00:00
return self.left.optimize(compressor);
2022-01-21 08:28:41 +00:00
}
// x && true || y ---> x ? true : y
if (!nullish && self.left.operator == "&&") {
var lr = fuzzy_eval(compressor, self.left.right);
if (lr && !(lr instanceof AST_Node)) return make_node(AST_Conditional, self, {
condition: self.left.left,
consequent: self.left.right,
2022-08-31 14:34:36 +00:00
alternative: self.right,
2022-01-21 08:28:41 +00:00
}).optimize(compressor);
}
break;
case "+":
// "foo" + ("bar" + x) ---> "foobar" + x
if (self.left instanceof AST_Constant
&& self.right instanceof AST_Binary
&& self.right.operator == "+"
&& self.right.left instanceof AST_Constant
&& self.right.is_string(compressor)) {
self = make_node(AST_Binary, self, {
operator: "+",
left: make_node(AST_String, self.left, {
value: "" + self.left.value + self.right.left.value,
start: self.left.start,
2022-08-31 14:34:36 +00:00
end: self.right.left.end,
2022-01-21 08:28:41 +00:00
}),
2022-08-31 14:34:36 +00:00
right: self.right.right,
2022-01-21 08:28:41 +00:00
});
}
// (x + "foo") + "bar" ---> x + "foobar"
if (self.right instanceof AST_Constant
&& self.left instanceof AST_Binary
&& self.left.operator == "+"
&& self.left.right instanceof AST_Constant
&& self.left.is_string(compressor)) {
self = make_node(AST_Binary, self, {
operator: "+",
left: self.left.left,
right: make_node(AST_String, self.right, {
value: "" + self.left.right.value + self.right.value,
start: self.left.right.start,
2022-08-31 14:34:36 +00:00
end: self.right.end,
}),
2022-01-21 08:28:41 +00:00
});
}
// a + -b ---> a - b
if (self.right instanceof AST_UnaryPrefix
&& self.right.operator == "-"
&& self.left.is_number(compressor)) {
self = make_node(AST_Binary, self, {
operator: "-",
left: self.left,
2022-08-31 14:34:36 +00:00
right: self.right.expression,
2022-01-21 08:28:41 +00:00
});
break;
}
// -a + b ---> b - a
if (self.left instanceof AST_UnaryPrefix
&& self.left.operator == "-"
&& reversible()
&& self.right.is_number(compressor)) {
self = make_node(AST_Binary, self, {
operator: "-",
left: self.right,
2022-08-31 14:34:36 +00:00
right: self.left.expression,
2022-01-21 08:28:41 +00:00
});
break;
}
// (a + b) + 3 ---> 3 + (a + b)
if (compressor.option("unsafe_math")
&& self.left instanceof AST_Binary
&& PRECEDENCE[self.left.operator] == PRECEDENCE[self.operator]
&& self.right.is_constant()
&& (self.right.is_boolean(compressor) || self.right.is_number(compressor))
&& self.left.is_number(compressor)
&& !self.left.right.is_constant()
&& (self.left.left.is_boolean(compressor) || self.left.left.is_number(compressor))) {
self = make_node(AST_Binary, self, {
operator: self.left.operator,
left: make_node(AST_Binary, self, {
operator: self.operator,
left: self.right,
2022-08-31 14:34:36 +00:00
right: self.left.left,
2022-01-21 08:28:41 +00:00
}),
2022-08-31 14:34:36 +00:00
right: self.left.right,
2022-01-21 08:28:41 +00:00
});
break;
}
case "-":
// a - -b ---> a + b
if (self.right instanceof AST_UnaryPrefix
&& self.right.operator == "-"
&& self.left.is_number(compressor)
&& self.right.expression.is_number(compressor)) {
self = make_node(AST_Binary, self, {
operator: "+",
left: self.left,
2022-08-31 14:34:36 +00:00
right: self.right.expression,
2022-01-21 08:28:41 +00:00
});
break;
}
case "*":
case "/":
associative = compressor.option("unsafe_math");
// +a - b ---> a - b
// a - +b ---> a - b
if (self.operator != "+") [ "left", "right" ].forEach(function(operand) {
var node = self[operand];
if (node instanceof AST_UnaryPrefix && node.operator == "+") {
var exp = node.expression;
if (exp.is_boolean(compressor) || exp.is_number(compressor) || exp.is_string(compressor)) {
self[operand] = exp;
}
}
});
case "&":
case "|":
case "^":
// a + +b ---> +b + a
if (self.operator != "-"
&& self.operator != "/"
&& (self.left.is_boolean(compressor) || self.left.is_number(compressor))
&& (self.right.is_boolean(compressor) || self.right.is_number(compressor))
&& reversible()
&& !(self.left instanceof AST_Binary
&& self.left.operator != self.operator
&& PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) {
2022-08-05 07:44:52 +00:00
self = best_of(compressor, self, make_node(AST_Binary, self, {
2022-01-21 08:28:41 +00:00
operator: self.operator,
left: self.right,
2022-08-05 07:44:52 +00:00
right: self.left,
}), self.right instanceof AST_Constant && !(self.left instanceof AST_Constant));
2022-01-21 08:28:41 +00:00
}
if (!associative || !self.is_number(compressor)) break;
// a + (b + c) ---> (a + b) + c
if (self.right instanceof AST_Binary
&& self.right.operator != "%"
&& PRECEDENCE[self.right.operator] == PRECEDENCE[self.operator]
&& self.right.is_number(compressor)
&& (self.operator != "+"
|| self.right.left.is_boolean(compressor)
|| self.right.left.is_number(compressor))
&& (self.operator != "-" || !self.left.is_negative_zero())
&& (self.right.left.is_constant_expression()
|| !self.right.right.has_side_effects(compressor))
&& !is_modify_array(self.right.right)) {
self = make_node(AST_Binary, self, {
operator: align(self.operator, self.right.operator),
left: make_node(AST_Binary, self.left, {
operator: self.operator,
left: self.left,
right: self.right.left,
start: self.left.start,
2022-08-31 14:34:36 +00:00
end: self.right.left.end,
2022-01-21 08:28:41 +00:00
}),
2022-08-31 14:34:36 +00:00
right: self.right.right,
2022-01-21 08:28:41 +00:00
});
if (self.operator == "+"
&& !self.right.is_boolean(compressor)
&& !self.right.is_number(compressor)) {
self.right = make_node(AST_UnaryPrefix, self.right, {
operator: "+",
2022-08-31 14:34:36 +00:00
expression: self.right,
2022-01-21 08:28:41 +00:00
});
}
}
// (2 * n) * 3 ---> 6 * n
// (n + 2) + 3 ---> n + 5
if (self.right instanceof AST_Constant
&& self.left instanceof AST_Binary
&& self.left.operator != "%"
&& PRECEDENCE[self.left.operator] == PRECEDENCE[self.operator]
&& self.left.is_number(compressor)) {
if (self.left.left instanceof AST_Constant) {
2022-08-31 14:34:36 +00:00
var lhs = make_binary(self.operator, self.left.left, self.right, {
start: self.left.left.start,
end: self.right.end,
});
self = make_binary(self.left.operator, try_evaluate(compressor, lhs), self.left.right, self);
2022-01-21 08:28:41 +00:00
} else if (self.left.right instanceof AST_Constant) {
var op = align(self.left.operator, self.operator);
2022-08-31 14:34:36 +00:00
var rhs = try_evaluate(compressor, make_binary(op, self.left.right, self.right, self.left));
2022-01-21 08:28:41 +00:00
if (rhs.is_constant()
&& !(self.left.operator == "-"
&& self.right.value != 0
&& +rhs.value == 0
&& self.left.left.is_negative_zero())) {
2022-08-31 14:34:36 +00:00
self = make_binary(self.left.operator, self.left.left, rhs, self);
2022-01-21 08:28:41 +00:00
}
}
}
break;
2022-07-11 11:25:19 +00:00
case "instanceof":
if (is_lambda(self.right)) return make_sequence(self, [
self,
make_node(AST_False, self),
]).optimize(compressor);
break;
2022-01-21 08:28:41 +00:00
}
if (!(parent instanceof AST_UnaryPrefix && parent.operator == "delete")) {
if (self.left instanceof AST_Number && !self.right.is_constant()) switch (self.operator) {
// 0 + n ---> n
case "+":
if (self.left.value == 0) {
if (self.right.is_boolean(compressor)) return make_node(AST_UnaryPrefix, self, {
operator: "+",
2022-03-14 15:40:45 +00:00
expression: self.right,
2022-01-21 08:28:41 +00:00
}).optimize(compressor);
if (self.right.is_number(compressor) && !self.right.is_negative_zero()) return self.right;
}
break;
// 1 * n ---> n
case "*":
2022-03-14 15:40:45 +00:00
if (self.left.value == 1) return make_node(AST_UnaryPrefix, self, {
operator: "+",
expression: self.right,
}).optimize(compressor);
2022-01-21 08:28:41 +00:00
break;
}
if (self.right instanceof AST_Number && !self.left.is_constant()) switch (self.operator) {
// n + 0 ---> n
case "+":
if (self.right.value == 0) {
if (self.left.is_boolean(compressor)) return make_node(AST_UnaryPrefix, self, {
operator: "+",
2022-03-14 15:40:45 +00:00
expression: self.left,
2022-01-21 08:28:41 +00:00
}).optimize(compressor);
if (self.left.is_number(compressor) && !self.left.is_negative_zero()) return self.left;
}
break;
// n - 0 ---> n
case "-":
2022-03-14 15:40:45 +00:00
if (self.right.value == 0) return make_node(AST_UnaryPrefix, self, {
operator: "+",
expression: self.left,
}).optimize(compressor);
2022-01-21 08:28:41 +00:00
break;
// n / 1 ---> n
case "/":
2022-03-14 15:40:45 +00:00
if (self.right.value == 1) return make_node(AST_UnaryPrefix, self, {
operator: "+",
expression: self.left,
}).optimize(compressor);
2022-01-21 08:28:41 +00:00
break;
}
}
}
if (compressor.option("typeofs")) switch (self.operator) {
case "&&":
mark_locally_defined(self.left, self.right, null);
break;
case "||":
mark_locally_defined(self.left, null, self.right);
break;
}
if (compressor.option("unsafe")) {
var indexRight = is_indexFn(self.right);
if (in_bool
&& indexRight
&& (self.operator == "==" || self.operator == "!=")
&& self.left instanceof AST_Number
&& self.left.value == 0) {
return (self.operator == "==" ? make_node(AST_UnaryPrefix, self, {
operator: "!",
2022-08-31 14:34:36 +00:00
expression: self.right,
2022-01-21 08:28:41 +00:00
}) : self.right).optimize(compressor);
}
var indexLeft = is_indexFn(self.left);
if (compressor.option("comparisons") && is_indexOf_match_pattern()) {
var node = make_node(AST_UnaryPrefix, self, {
operator: "!",
expression: make_node(AST_UnaryPrefix, self, {
operator: "~",
2022-08-31 14:34:36 +00:00
expression: indexLeft ? self.left : self.right,
}),
2022-01-21 08:28:41 +00:00
});
switch (self.operator) {
case "<":
if (indexLeft) break;
case "<=":
case "!=":
node = make_node(AST_UnaryPrefix, self, {
operator: "!",
2022-08-31 14:34:36 +00:00
expression: node,
2022-01-21 08:28:41 +00:00
});
break;
}
return node.optimize(compressor);
}
}
return try_evaluate(compressor, self);
function is_modify_array(node) {
var found = false;
node.walk(new TreeWalker(function(node) {
if (found) return true;
if (node instanceof AST_Assign) {
if (node.left instanceof AST_PropAccess) return found = true;
} else if (node instanceof AST_Unary) {
if (unary_side_effects[node.operator] && node.expression instanceof AST_PropAccess) {
return found = true;
}
}
}));
return found;
}
function align(ref, op) {
switch (ref) {
case "-":
return op == "+" ? "-" : "+";
case "/":
return op == "*" ? "/" : "*";
default:
return op;
}
}
2022-08-31 14:34:36 +00:00
function make_binary(op, left, right, orig) {
2022-01-21 08:28:41 +00:00
if (op == "+") {
if (!left.is_boolean(compressor) && !left.is_number(compressor)) {
left = make_node(AST_UnaryPrefix, left, {
operator: "+",
2022-08-31 14:34:36 +00:00
expression: left,
2022-01-21 08:28:41 +00:00
});
}
if (!right.is_boolean(compressor) && !right.is_number(compressor)) {
right = make_node(AST_UnaryPrefix, right, {
operator: "+",
2022-08-31 14:34:36 +00:00
expression: right,
2022-01-21 08:28:41 +00:00
});
}
}
return make_node(AST_Binary, orig, {
operator: op,
left: left,
right: right,
});
}
function is_indexFn(node) {
return node.TYPE == "Call"
&& node.expression instanceof AST_Dot
&& indexFns[node.expression.property];
}
function is_indexOf_match_pattern() {
switch (self.operator) {
case "<=":
// 0 <= array.indexOf(string) ---> !!~array.indexOf(string)
return indexRight && self.left instanceof AST_Number && self.left.value == 0;
case "<":
// array.indexOf(string) < 0 ---> !~array.indexOf(string)
if (indexLeft && self.right instanceof AST_Number && self.right.value == 0) return true;
// -1 < array.indexOf(string) ---> !!~array.indexOf(string)
case "==":
case "!=":
// -1 == array.indexOf(string) ---> !~array.indexOf(string)
// -1 != array.indexOf(string) ---> !!~array.indexOf(string)
if (!indexRight) return false;
return self.left instanceof AST_Number && self.left.value == -1
|| self.left instanceof AST_UnaryPrefix && self.left.operator == "-"
&& self.left.expression instanceof AST_Number && self.left.expression.value == 1;
}
}
2022-02-07 14:48:46 +00:00
function reversible() {
return self.left.is_constant()
|| self.right.is_constant()
|| !self.left.has_side_effects(compressor)
&& !self.right.has_side_effects(compressor);
}
function reverse(op) {
if (reversible()) {
if (op) self.operator = op;
var tmp = self.left;
self.left = self.right;
self.right = tmp;
}
}
2022-01-21 08:28:41 +00:00
});
OPT(AST_SymbolExport, function(self) {
return self;
});
function recursive_ref(compressor, def, fn) {
var level = 0, node = compressor.self();
do {
if (node === fn) return node;
if (is_lambda(node) && node.name && node.name.definition() === def) return node;
} while (node = compressor.parent(level++));
}
function same_scope(def) {
var scope = def.scope.resolve();
return all(def.references, function(ref) {
return scope === ref.scope.resolve();
});
}
OPT(AST_SymbolRef, function(self, compressor) {
if (!compressor.option("ie")
&& is_undeclared_ref(self)
// testing against `self.scope.uses_with` is an optimization
&& !(self.scope.resolve().uses_with && compressor.find_parent(AST_With))) {
switch (self.name) {
case "undefined":
return make_node(AST_Undefined, self).optimize(compressor);
case "NaN":
return make_node(AST_NaN, self).optimize(compressor);
case "Infinity":
return make_node(AST_Infinity, self).optimize(compressor);
}
}
var parent = compressor.parent();
if (compressor.option("reduce_vars") && is_lhs(compressor.self(), parent) !== compressor.self()) {
var def = self.definition();
var fixed = self.fixed_value();
var single_use = def.single_use && !(parent instanceof AST_Call && parent.is_expr_pure(compressor));
if (single_use) {
if (is_lambda(fixed)) {
2022-10-10 08:26:02 +00:00
if ((def.scope !== self.scope.resolve(true) || def.in_loop)
2022-01-21 08:28:41 +00:00
&& (!compressor.option("reduce_funcs") || def.escaped.depth == 1 || fixed.inlined)) {
single_use = false;
2022-07-11 11:25:19 +00:00
} else if (def.redefined()) {
single_use = false;
2022-01-21 08:28:41 +00:00
} else if (recursive_ref(compressor, def, fixed)) {
single_use = false;
} else if (fixed.name && fixed.name.definition() !== def) {
single_use = false;
} else if (fixed.parent_scope !== self.scope || is_funarg(def)) {
2022-06-08 10:36:39 +00:00
if (!safe_from_strict_mode(fixed, compressor)) {
single_use = false;
} else if ((single_use = fixed.is_constant_expression(self.scope)) == "f") {
2022-01-21 08:28:41 +00:00
var scope = self.scope;
do {
if (scope instanceof AST_LambdaDefinition || scope instanceof AST_LambdaExpression) {
scope.inlined = true;
}
} while (scope = scope.parent_scope);
}
} else if (fixed.name && (fixed.name.name == "await" && is_async(fixed)
|| fixed.name.name == "yield" && is_generator(fixed))) {
single_use = false;
} else if (fixed.has_side_effects(compressor)) {
single_use = false;
} else if (compressor.option("ie") && fixed instanceof AST_Class) {
single_use = false;
}
if (single_use) fixed.parent_scope = self.scope;
} else if (!fixed
|| def.recursive_refs > 0
|| !fixed.is_constant_expression()
|| fixed.drop_side_effect_free(compressor)) {
single_use = false;
}
}
if (single_use) {
def.single_use = false;
fixed._squeezed = true;
fixed.single_use = true;
if (fixed instanceof AST_DefClass) fixed = to_class_expr(fixed);
if (fixed instanceof AST_LambdaDefinition) fixed = to_func_expr(fixed);
if (is_lambda(fixed)) {
2022-08-31 14:34:36 +00:00
var scopes = [];
var scope = self.scope;
do {
scopes.push(scope);
if (scope === def.scope) break;
} while (scope = scope.parent_scope);
2022-01-21 08:28:41 +00:00
fixed.enclosed.forEach(function(def) {
if (fixed.variables.has(def.name)) return;
2022-08-31 14:34:36 +00:00
for (var i = 0; i < scopes.length; i++) {
var scope = scopes[i];
if (!push_uniq(scope.enclosed, def)) return;
scope.var_names().set(def.name, true);
}
2022-01-21 08:28:41 +00:00
});
}
var value;
if (def.recursive_refs > 0) {
value = fixed.clone(true);
var defun_def = value.name.definition();
var lambda_def = value.variables.get(value.name.name);
var name = lambda_def && lambda_def.orig[0];
var def_fn_name, symbol_type;
if (value instanceof AST_Class) {
def_fn_name = "def_function";
symbol_type = AST_SymbolClass;
} else {
def_fn_name = "def_variable";
symbol_type = AST_SymbolLambda;
}
if (!(name instanceof symbol_type)) {
2022-08-31 14:34:36 +00:00
name = make_node(symbol_type, value.name);
2022-01-21 08:28:41 +00:00
name.scope = value;
value.name = name;
lambda_def = value[def_fn_name](name);
lambda_def.recursive_refs = def.recursive_refs;
}
value.walk(new TreeWalker(function(node) {
if (node instanceof AST_SymbolDeclaration) {
if (node !== name) {
var def = node.definition();
def.orig.push(node);
def.eliminated++;
}
return;
}
if (!(node instanceof AST_SymbolRef)) return;
var def = node.definition();
if (def === defun_def) {
node.thedef = def = lambda_def;
} else {
def.single_use = false;
var fn = node.fixed_value();
if (is_lambda(fn)
&& fn.name
&& fn.name.definition() === def
&& def.scope === fn.name.scope
&& fixed.variables.get(fn.name.name) === def) {
fn.name = fn.name.clone();
node.thedef = def = value.variables.get(fn.name.name) || value[def_fn_name](fn.name);
}
}
def.references.push(node);
}));
} else {
if (fixed instanceof AST_Scope) {
compressor.push(fixed);
value = fixed.optimize(compressor);
compressor.pop();
} else {
value = fixed.optimize(compressor);
}
value = value.transform(new TreeTransformer(function(node, descend) {
if (node instanceof AST_Scope) return node;
node = node.clone();
descend(node, this);
return node;
}));
}
def.replaced++;
return value;
}
2022-02-07 14:48:46 +00:00
var state;
if (fixed && (state = self.fixed || def.fixed).should_replace !== false) {
2022-01-21 08:28:41 +00:00
var ev, init;
if (fixed instanceof AST_This) {
2022-02-07 14:48:46 +00:00
if (!is_funarg(def) && same_scope(def) && !cross_class(def)) init = fixed;
2022-01-21 08:28:41 +00:00
} else if ((ev = fixed.evaluate(compressor, true)) !== fixed
&& typeof ev != "function"
&& (ev === null
|| typeof ev != "object"
|| compressor.option("unsafe_regexp")
&& ev instanceof RegExp && !def.cross_loop && same_scope(def))) {
init = make_node_from_constant(ev, fixed);
}
if (init) {
2022-02-07 14:48:46 +00:00
if (state.should_replace === undefined) {
2022-01-21 08:28:41 +00:00
var value_length = init.optimize(compressor).print_to_string().length;
if (!has_symbol_ref(fixed)) {
value_length = Math.min(value_length, fixed.print_to_string().length);
}
var name_length = def.name.length;
if (compressor.option("unused") && !compressor.exposed(def)) {
2022-02-07 14:48:46 +00:00
var refs = def.references.length - def.replaced - def.assignments;
refs = Math.min(refs, def.references.filter(function(ref) {
return ref.fixed === state;
}).length);
name_length += (name_length + 2 + value_length) / Math.max(1, refs);
2022-01-21 08:28:41 +00:00
}
2022-02-07 14:48:46 +00:00
state.should_replace = value_length - Math.floor(name_length) < compressor.eval_threshold;
2022-01-21 08:28:41 +00:00
}
2022-02-07 14:48:46 +00:00
if (state.should_replace) {
2022-01-21 08:28:41 +00:00
var value;
if (has_symbol_ref(fixed)) {
value = init.optimize(compressor);
if (value === init) value = value.clone(true);
} else {
value = best_of_expression(init.optimize(compressor), fixed);
if (value === init || value === fixed) value = value.clone(true);
}
def.replaced++;
return value;
}
}
}
}
return self;
2022-02-07 14:48:46 +00:00
function cross_class(def) {
var scope = self.scope;
while (scope !== def.scope) {
if (scope instanceof AST_Class) return true;
scope = scope.parent_scope;
}
}
2022-01-21 08:28:41 +00:00
function has_symbol_ref(value) {
var found;
value.walk(new TreeWalker(function(node) {
if (node instanceof AST_SymbolRef) found = true;
if (found) return true;
}));
return found;
}
});
function is_raw_tag(compressor, tag) {
return compressor.option("unsafe")
&& tag instanceof AST_Dot
&& tag.property == "raw"
&& is_undeclared_ref(tag.expression)
&& tag.expression.name == "String";
}
function decode_template(str) {
var malformed = false;
str = str.replace(/\\(u\{[^{}]*\}?|u[\s\S]{0,4}|x[\s\S]{0,2}|[0-9]+|[\s\S])/g, function(match, seq) {
var ch = decode_escape_sequence(seq);
if (typeof ch == "string") return ch;
malformed = true;
});
if (!malformed) return str;
}
OPT(AST_Template, function(self, compressor) {
if (!compressor.option("templates")) return self;
var tag = self.tag;
if (!tag || is_raw_tag(compressor, tag)) {
var exprs = [];
var strs = [];
for (var i = 0, status; i < self.strings.length; i++) {
var str = self.strings[i];
if (!tag) {
var trimmed = decode_template(str);
if (trimmed) str = escape_literal(trimmed);
}
if (i > 0) {
var node = self.expressions[i - 1];
var value = should_join(node);
if (value) {
var prev = strs[strs.length - 1];
var joined = prev + value + str;
var decoded;
if (tag || typeof (decoded = decode_template(joined)) == status) {
strs[strs.length - 1] = decoded ? escape_literal(decoded) : joined;
continue;
}
}
exprs.push(node);
}
strs.push(str);
if (!tag) status = typeof trimmed;
}
if (!tag && strs.length > 1) {
if (strs[strs.length - 1] == "") return make_node(AST_Binary, self, {
operator: "+",
left: make_node(AST_Template, self, {
expressions: exprs.slice(0, -1),
strings: strs.slice(0, -1),
}).transform(compressor),
right: exprs[exprs.length - 1],
}).optimize(compressor);
if (strs[0] == "") {
var left = make_node(AST_Binary, self, {
operator: "+",
left: make_node(AST_String, self, { value: "" }),
right: exprs[0],
});
for (var i = 1; strs[i] == "" && i < exprs.length; i++) {
left = make_node(AST_Binary, self, {
operator: "+",
left: left,
right: exprs[i],
});
}
return best_of(compressor, self, make_node(AST_Binary, self, {
operator: "+",
left: left.transform(compressor),
right: make_node(AST_Template, self, {
expressions: exprs.slice(i),
strings: strs.slice(i),
}).transform(compressor),
}).optimize(compressor));
}
}
self.expressions = exprs;
self.strings = strs;
}
return try_evaluate(compressor, self);
function escape_literal(str) {
return str.replace(/\r|\\|`|\${/g, function(s) {
return "\\" + (s == "\r" ? "r" : s);
});
}
function should_join(node) {
var ev = node.evaluate(compressor);
if (ev === node) return;
if (tag && /\r|\\|`/.test(ev)) return;
ev = escape_literal("" + ev);
if (ev.length > node.print_to_string().length + "${}".length) return;
return ev;
}
});
function is_atomic(lhs, self) {
return lhs instanceof AST_SymbolRef || lhs.TYPE === self.TYPE;
}
OPT(AST_Undefined, function(self, compressor) {
if (compressor.option("unsafe_undefined")) {
var undef = find_scope(compressor).find_variable("undefined");
if (undef) {
var ref = make_node(AST_SymbolRef, self, {
2022-08-31 14:34:36 +00:00
name: "undefined",
scope: undef.scope,
thedef: undef,
2022-01-21 08:28:41 +00:00
});
ref.is_undefined = true;
return ref;
}
}
var lhs = is_lhs(compressor.self(), compressor.parent());
if (lhs && is_atomic(lhs, self)) return self;
return make_node(AST_UnaryPrefix, self, {
operator: "void",
2022-02-07 14:48:46 +00:00
expression: make_node(AST_Number, self, { value: 0 }),
2022-01-21 08:28:41 +00:00
});
});
OPT(AST_Infinity, function(self, compressor) {
var lhs = is_lhs(compressor.self(), compressor.parent());
if (lhs && is_atomic(lhs, self)) return self;
if (compressor.option("keep_infinity") && !lhs && !find_scope(compressor).find_variable("Infinity")) {
return self;
}
return make_node(AST_Binary, self, {
operator: "/",
2022-02-07 14:48:46 +00:00
left: make_node(AST_Number, self, { value: 1 }),
right: make_node(AST_Number, self, { value: 0 }),
2022-01-21 08:28:41 +00:00
});
});
OPT(AST_NaN, function(self, compressor) {
var lhs = is_lhs(compressor.self(), compressor.parent());
if (lhs && is_atomic(lhs, self)) return self;
if (!lhs && !find_scope(compressor).find_variable("NaN")) return self;
return make_node(AST_Binary, self, {
operator: "/",
2022-02-07 14:48:46 +00:00
left: make_node(AST_Number, self, { value: 0 }),
right: make_node(AST_Number, self, { value: 0 }),
2022-01-21 08:28:41 +00:00
});
});
function is_reachable(self, defs) {
var reachable = false;
var find_ref = new TreeWalker(function(node) {
if (reachable) return true;
2022-02-07 14:48:46 +00:00
if (node instanceof AST_SymbolRef && member(node.definition(), defs)) return reachable = true;
2022-01-21 08:28:41 +00:00
});
var scan_scope = new TreeWalker(function(node) {
if (reachable) return true;
if (node instanceof AST_Lambda && node !== self) {
if (!(node.name || is_async(node) || is_generator(node))) {
var parent = scan_scope.parent();
if (parent instanceof AST_Call && parent.expression === node) return;
}
node.walk(find_ref);
return true;
}
});
self.walk(scan_scope);
return reachable;
}
var ASSIGN_OPS = makePredicate("+ - * / % >> << >>> | ^ &");
var ASSIGN_OPS_COMMUTATIVE = makePredicate("* | ^ &");
OPT(AST_Assign, function(self, compressor) {
if (compressor.option("dead_code")) {
if (self.left instanceof AST_PropAccess) {
if (self.operator == "=") {
if (self.redundant) {
var exprs = [ self.left.expression ];
if (self.left instanceof AST_Sub) exprs.push(self.left.property);
exprs.push(self.right);
return make_sequence(self, exprs).optimize(compressor);
}
2022-08-05 07:44:52 +00:00
if (self.left.equals(self.right) && !self.left.has_side_effects(compressor)) {
2022-01-21 08:28:41 +00:00
return self.right;
}
var exp = self.left.expression;
if (exp instanceof AST_Lambda
|| !compressor.has_directive("use strict")
&& exp instanceof AST_Constant
&& !exp.may_throw_on_access(compressor)) {
return self.left instanceof AST_Dot ? self.right : make_sequence(self, [
self.left.property,
self.right
]).optimize(compressor);
}
}
} else if (self.left instanceof AST_SymbolRef && can_drop_symbol(self.left, compressor)) {
var parent;
2022-08-05 07:44:52 +00:00
if (self.operator == "=" && self.left.equals(self.right)
2022-01-21 08:28:41 +00:00
&& !((parent = compressor.parent()) instanceof AST_UnaryPrefix && parent.operator == "delete")) {
return self.right;
}
if (self.left.is_immutable()) return strip_assignment();
var def = self.left.definition();
var scope = def.scope.resolve();
var local = scope === compressor.find_parent(AST_Lambda);
var level = 0, node;
parent = compressor.self();
if (!(scope.uses_arguments && is_funarg(def)) || compressor.has_directive("use strict")) do {
node = parent;
parent = compressor.parent(level++);
if (parent instanceof AST_Assign) {
if (parent.left instanceof AST_SymbolRef && parent.left.definition() === def) {
2022-07-11 11:25:19 +00:00
if (in_try(level, parent, !local)) break;
2022-01-21 08:28:41 +00:00
return strip_assignment(def);
}
if (parent.left.match_symbol(function(node) {
if (node instanceof AST_PropAccess) return true;
})) break;
continue;
}
if (parent instanceof AST_Exit) {
if (!local) break;
if (in_try(level, parent)) break;
if (is_reachable(scope, [ def ])) break;
return strip_assignment(def);
}
if (parent instanceof AST_SimpleStatement) {
if (!local) break;
if (is_reachable(scope, [ def ])) break;
var stat;
do {
stat = parent;
parent = compressor.parent(level++);
if (parent === scope && is_last_statement(parent.body, stat)) return strip_assignment(def);
} while (is_tail_block(stat, parent));
break;
}
if (parent instanceof AST_VarDef) {
if (!(parent.name instanceof AST_SymbolDeclaration)) continue;
if (parent.name.definition() !== def) continue;
if (in_try(level, parent)) break;
return strip_assignment(def);
}
} while (is_tail(node, parent));
}
}
if (compressor.option("sequences")) {
var seq = self.lift_sequences(compressor);
if (seq !== self) return seq.optimize(compressor);
}
if (compressor.option("assignments")) {
if (self.operator == "=" && self.left instanceof AST_SymbolRef && self.right instanceof AST_Binary) {
// x = expr1 OP expr2
2022-11-30 12:56:09 +00:00
if (self.right.left instanceof AST_SymbolRef
&& self.right.left.name == self.left.name
2022-01-21 08:28:41 +00:00
&& ASSIGN_OPS[self.right.operator]) {
// x = x - 2 ---> x -= 2
2022-11-30 12:56:09 +00:00
return make_compound(self.right.right);
2022-01-21 08:28:41 +00:00
}
2022-11-30 12:56:09 +00:00
if (self.right.right instanceof AST_SymbolRef
&& self.right.right.name == self.left.name
2022-01-21 08:28:41 +00:00
&& ASSIGN_OPS_COMMUTATIVE[self.right.operator]
&& !self.right.left.has_side_effects(compressor)) {
// x = 2 & x ---> x &= 2
2022-11-30 12:56:09 +00:00
return make_compound(self.right.left);
2022-01-21 08:28:41 +00:00
}
}
if ((self.operator == "-=" || self.operator == "+="
&& (self.left.is_boolean(compressor) || self.left.is_number(compressor)))
&& self.right instanceof AST_Number
&& self.right.value == 1) {
var op = self.operator.slice(0, -1);
return make_node(AST_UnaryPrefix, self, {
operator: op + op,
2022-08-31 14:34:36 +00:00
expression: self.left,
2022-01-21 08:28:41 +00:00
});
}
}
return try_evaluate(compressor, self);
function is_tail(node, parent) {
2022-09-30 13:48:25 +00:00
if (parent instanceof AST_Binary) switch (node) {
case parent.left:
return parent.right.is_constant_expression(scope);
case parent.right:
return true;
default:
return false;
2022-01-21 08:28:41 +00:00
}
2022-09-30 13:48:25 +00:00
if (parent instanceof AST_Conditional) switch (node) {
case parent.condition:
return parent.consequent.is_constant_expression(scope)
&& parent.alternative.is_constant_expression(scope);
case parent.consequent:
case parent.alternative:
return true;
default:
return false;
2022-01-21 08:28:41 +00:00
}
if (parent instanceof AST_Sequence) {
var exprs = parent.expressions;
var stop = exprs.indexOf(node);
if (stop < 0) return false;
for (var i = exprs.length; --i > stop;) {
if (!exprs[i].is_constant_expression(scope)) return false;
}
return true;
}
2022-09-30 13:48:25 +00:00
return parent instanceof AST_UnaryPrefix;
2022-01-21 08:28:41 +00:00
}
function is_tail_block(stat, parent) {
if (parent instanceof AST_BlockStatement) return is_last_statement(parent.body, stat);
if (parent instanceof AST_Catch) return is_last_statement(parent.body, stat);
if (parent instanceof AST_Finally) return is_last_statement(parent.body, stat);
if (parent instanceof AST_If) return parent.body === stat || parent.alternative === stat;
if (parent instanceof AST_Try) return parent.bfinally ? parent.bfinally === stat : parent.bcatch === stat;
}
2022-07-11 11:25:19 +00:00
function in_try(level, node, sync) {
2022-01-21 08:28:41 +00:00
var right = self.right;
self.right = make_node(AST_Null, right);
var may_throw = node.may_throw(compressor);
self.right = right;
2022-08-05 07:44:52 +00:00
return find_try(compressor, level, node, scope, may_throw, sync);
2022-01-21 08:28:41 +00:00
}
2022-11-30 12:56:09 +00:00
function make_compound(rhs) {
var fixed = self.left.fixed;
if (fixed) fixed.to_binary = replace_ref(function(node) {
return node.left;
}, fixed);
return make_node(AST_Assign, self, {
operator: self.right.operator + "=",
left: self.left,
right: rhs,
});
}
2022-01-21 08:28:41 +00:00
function strip_assignment(def) {
if (def) def.fixed = false;
return (self.operator != "=" ? make_node(AST_Binary, self, {
operator: self.operator.slice(0, -1),
left: self.left,
right: self.right,
2022-08-31 14:34:36 +00:00
}) : maintain_this_binding(compressor.parent(), self, self.right)).optimize(compressor);
2022-01-21 08:28:41 +00:00
}
});
OPT(AST_Conditional, function(self, compressor) {
if (compressor.option("sequences") && self.condition instanceof AST_Sequence) {
var expressions = self.condition.expressions.slice();
2022-08-31 14:34:36 +00:00
var node = self.clone();
node.condition = expressions.pop();
expressions.push(node);
return make_sequence(self, expressions).optimize(compressor);
2022-01-21 08:28:41 +00:00
}
if (!compressor.option("conditionals")) return self;
var condition = self.condition;
if (compressor.option("booleans") && !condition.has_side_effects(compressor)) {
mark_duplicate_condition(compressor, condition);
}
condition = fuzzy_eval(compressor, condition);
if (!condition) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Condition always false [{start}]", self);
2022-01-21 08:28:41 +00:00
return make_sequence(self, [ self.condition, self.alternative ]).optimize(compressor);
} else if (!(condition instanceof AST_Node)) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Condition always true [{start}]", self);
2022-01-21 08:28:41 +00:00
return make_sequence(self, [ self.condition, self.consequent ]).optimize(compressor);
}
2022-08-05 07:44:52 +00:00
var first = first_in_statement(compressor);
var negated = condition.negate(compressor, first);
if ((first ? best_of_statement : best_of_expression)(condition, negated) === negated) {
2022-01-21 08:28:41 +00:00
self = make_node(AST_Conditional, self, {
condition: negated,
consequent: self.alternative,
2022-08-05 07:44:52 +00:00
alternative: self.consequent,
2022-01-21 08:28:41 +00:00
});
negated = condition;
condition = self.condition;
}
var consequent = self.consequent;
var alternative = self.alternative;
2022-10-10 08:26:02 +00:00
var cond_lhs = extract_lhs(condition, compressor);
if (repeatable(compressor, cond_lhs)) {
2022-01-21 08:28:41 +00:00
// x ? x : y ---> x || y
2022-10-10 08:26:02 +00:00
if (cond_lhs.equals(consequent)) return make_node(AST_Binary, self, {
2022-01-21 08:28:41 +00:00
operator: "||",
left: condition,
right: alternative,
}).optimize(compressor);
// x ? y : x ---> x && y
2022-10-10 08:26:02 +00:00
if (cond_lhs.equals(alternative)) return make_node(AST_Binary, self, {
2022-01-21 08:28:41 +00:00
operator: "&&",
left: condition,
right: consequent,
}).optimize(compressor);
}
// if (foo) exp = something; else exp = something_else;
// |
// v
// exp = foo ? something : something_else;
var seq_tail = consequent.tail_node();
if (seq_tail instanceof AST_Assign) {
var is_eq = seq_tail.operator == "=";
var alt_tail = is_eq ? alternative.tail_node() : alternative;
if ((is_eq || consequent === seq_tail)
&& alt_tail instanceof AST_Assign
&& seq_tail.operator == alt_tail.operator
2022-08-05 07:44:52 +00:00
&& seq_tail.left.equals(alt_tail.left)
2022-01-21 08:28:41 +00:00
&& (is_eq && seq_tail.left instanceof AST_SymbolRef
|| !condition.has_side_effects(compressor)
&& can_shift_lhs_of_tail(consequent)
&& can_shift_lhs_of_tail(alternative))) {
return make_node(AST_Assign, self, {
operator: seq_tail.operator,
left: seq_tail.left,
right: make_node(AST_Conditional, self, {
condition: condition,
consequent: pop_lhs(consequent),
2022-08-31 14:34:36 +00:00
alternative: pop_lhs(alternative),
}),
2022-01-21 08:28:41 +00:00
});
}
}
2022-08-31 14:34:36 +00:00
var alt_tail = alternative.tail_node();
2022-01-21 08:28:41 +00:00
// x ? y : y ---> x, y
2022-08-31 14:34:36 +00:00
// x ? (a, c) : (b, c) ---> x ? a : b, c
2022-09-30 13:48:25 +00:00
if (seq_tail.equals(alt_tail)) return make_sequence(self, consequent.equals(alternative) ? [
condition,
consequent,
] : [
make_node(AST_Conditional, self, {
condition: condition,
consequent: pop_seq(consequent),
alternative: pop_seq(alternative),
}),
alt_tail,
]).optimize(compressor);
2022-01-21 08:28:41 +00:00
// x ? y.p : z.p ---> (x ? y : z).p
// x ? y(a) : z(a) ---> (x ? y : z)(a)
// x ? y.f(a) : z.f(a) ---> (x ? y : z).f(a)
var combined = combine_tail(consequent, alternative, true);
if (combined) return combined;
// x ? y(a) : y(b) ---> y(x ? a : b)
var arg_index;
if (consequent instanceof AST_Call
&& alternative.TYPE == consequent.TYPE
&& (arg_index = arg_diff(consequent, alternative)) >= 0
2022-08-05 07:44:52 +00:00
&& consequent.expression.equals(alternative.expression)
2022-01-21 08:28:41 +00:00
&& !condition.has_side_effects(compressor)
&& !consequent.expression.has_side_effects(compressor)) {
var node = consequent.clone();
var arg = consequent.args[arg_index];
node.args[arg_index] = arg instanceof AST_Spread ? make_node(AST_Spread, self, {
expression: make_node(AST_Conditional, self, {
condition: condition,
consequent: arg.expression,
alternative: alternative.args[arg_index].expression,
}),
}) : make_node(AST_Conditional, self, {
condition: condition,
consequent: arg,
alternative: alternative.args[arg_index],
});
return node;
}
// x ? (y ? a : b) : b ---> x && y ? a : b
2022-08-31 14:34:36 +00:00
if (seq_tail instanceof AST_Conditional
&& seq_tail.alternative.equals(alternative)) {
2022-01-21 08:28:41 +00:00
return make_node(AST_Conditional, self, {
condition: make_node(AST_Binary, self, {
left: condition,
operator: "&&",
2022-08-31 14:34:36 +00:00
right: fuse(consequent, seq_tail, "condition"),
2022-01-21 08:28:41 +00:00
}),
2022-08-31 14:34:36 +00:00
consequent: seq_tail.consequent,
2022-09-30 13:48:25 +00:00
alternative: merge_expression(seq_tail.alternative, alternative),
2022-01-21 08:28:41 +00:00
});
}
// x ? (y ? a : b) : a ---> !x || y ? a : b
2022-08-31 14:34:36 +00:00
if (seq_tail instanceof AST_Conditional
&& seq_tail.consequent.equals(alternative)) {
2022-01-21 08:28:41 +00:00
return make_node(AST_Conditional, self, {
condition: make_node(AST_Binary, self, {
left: negated,
operator: "||",
2022-08-31 14:34:36 +00:00
right: fuse(consequent, seq_tail, "condition"),
2022-01-21 08:28:41 +00:00
}),
2022-09-30 13:48:25 +00:00
consequent: merge_expression(seq_tail.consequent, alternative),
2022-08-31 14:34:36 +00:00
alternative: seq_tail.alternative,
2022-01-21 08:28:41 +00:00
});
}
// x ? a : (y ? a : b) ---> x || y ? a : b
2022-08-31 14:34:36 +00:00
if (alt_tail instanceof AST_Conditional
&& consequent.equals(alt_tail.consequent)) {
2022-01-21 08:28:41 +00:00
return make_node(AST_Conditional, self, {
condition: make_node(AST_Binary, self, {
left: condition,
operator: "||",
2022-08-31 14:34:36 +00:00
right: fuse(alternative, alt_tail, "condition"),
2022-01-21 08:28:41 +00:00
}),
2022-09-30 13:48:25 +00:00
consequent: merge_expression(consequent, alt_tail.consequent),
2022-08-31 14:34:36 +00:00
alternative: alt_tail.alternative,
2022-01-21 08:28:41 +00:00
});
}
// x ? b : (y ? a : b) ---> !x && y ? a : b
2022-08-31 14:34:36 +00:00
if (alt_tail instanceof AST_Conditional
&& consequent.equals(alt_tail.alternative)) {
2022-01-21 08:28:41 +00:00
return make_node(AST_Conditional, self, {
condition: make_node(AST_Binary, self, {
left: negated,
operator: "&&",
2022-08-31 14:34:36 +00:00
right: fuse(alternative, alt_tail, "condition"),
2022-01-21 08:28:41 +00:00
}),
2022-08-31 14:34:36 +00:00
consequent: alt_tail.consequent,
2022-09-30 13:48:25 +00:00
alternative: merge_expression(consequent, alt_tail.alternative),
2022-01-21 08:28:41 +00:00
});
}
// x ? y && a : a ---> (!x || y) && a
2022-08-31 14:34:36 +00:00
if (seq_tail instanceof AST_Binary
&& seq_tail.operator == "&&"
&& seq_tail.right.equals(alternative)) {
2022-01-21 08:28:41 +00:00
return make_node(AST_Binary, self, {
operator: "&&",
left: make_node(AST_Binary, self, {
operator: "||",
left: negated,
2022-08-31 14:34:36 +00:00
right: fuse(consequent, seq_tail, "left"),
2022-01-21 08:28:41 +00:00
}),
2022-09-30 13:48:25 +00:00
right: merge_expression(seq_tail.right, alternative),
2022-01-21 08:28:41 +00:00
}).optimize(compressor);
}
// x ? y || a : a ---> x && y || a
2022-08-31 14:34:36 +00:00
if (seq_tail instanceof AST_Binary
&& seq_tail.operator == "||"
&& seq_tail.right.equals(alternative)) {
2022-01-21 08:28:41 +00:00
return make_node(AST_Binary, self, {
operator: "||",
left: make_node(AST_Binary, self, {
operator: "&&",
left: condition,
2022-08-31 14:34:36 +00:00
right: fuse(consequent, seq_tail, "left"),
2022-01-21 08:28:41 +00:00
}),
2022-09-30 13:48:25 +00:00
right: merge_expression(seq_tail.right, alternative),
2022-01-21 08:28:41 +00:00
}).optimize(compressor);
}
// x ? a : y && a ---> (x || y) && a
2022-08-31 14:34:36 +00:00
if (alt_tail instanceof AST_Binary
&& alt_tail.operator == "&&"
&& alt_tail.right.equals(consequent)) {
2022-01-21 08:28:41 +00:00
return make_node(AST_Binary, self, {
operator: "&&",
left: make_node(AST_Binary, self, {
operator: "||",
left: condition,
2022-08-31 14:34:36 +00:00
right: fuse(alternative, alt_tail, "left"),
2022-01-21 08:28:41 +00:00
}),
2022-09-30 13:48:25 +00:00
right: merge_expression(consequent, alt_tail.right),
2022-01-21 08:28:41 +00:00
}).optimize(compressor);
}
// x ? a : y || a ---> !x && y || a
2022-08-31 14:34:36 +00:00
if (alt_tail instanceof AST_Binary
&& alt_tail.operator == "||"
&& alt_tail.right.equals(consequent)) {
2022-01-21 08:28:41 +00:00
return make_node(AST_Binary, self, {
operator: "||",
left: make_node(AST_Binary, self, {
operator: "&&",
left: negated,
2022-08-31 14:34:36 +00:00
right: fuse(alternative, alt_tail, "left"),
2022-01-21 08:28:41 +00:00
}),
2022-09-30 13:48:25 +00:00
right: merge_expression(consequent, alt_tail.right),
2022-01-21 08:28:41 +00:00
}).optimize(compressor);
}
var in_bool = compressor.option("booleans") && compressor.in_boolean_context();
if (is_true(consequent)) {
2022-08-31 14:34:36 +00:00
// c ? true : false ---> !!c
if (is_false(alternative)) return booleanize(condition);
2022-01-21 08:28:41 +00:00
// c ? true : x ---> !!c || x
return make_node(AST_Binary, self, {
operator: "||",
left: booleanize(condition),
2022-08-31 14:34:36 +00:00
right: alternative,
2022-11-30 12:56:09 +00:00
}).optimize(compressor);
2022-01-21 08:28:41 +00:00
}
if (is_false(consequent)) {
2022-08-31 14:34:36 +00:00
// c ? false : true ---> !c
if (is_true(alternative)) return booleanize(condition.negate(compressor));
2022-01-21 08:28:41 +00:00
// c ? false : x ---> !c && x
return make_node(AST_Binary, self, {
operator: "&&",
left: booleanize(condition.negate(compressor)),
2022-08-31 14:34:36 +00:00
right: alternative,
2022-11-30 12:56:09 +00:00
}).optimize(compressor);
2022-01-21 08:28:41 +00:00
}
2022-08-31 14:34:36 +00:00
// c ? x : true ---> !c || x
if (is_true(alternative)) return make_node(AST_Binary, self, {
operator: "||",
left: booleanize(condition.negate(compressor)),
right: consequent,
2022-11-30 12:56:09 +00:00
}).optimize(compressor);
2022-08-31 14:34:36 +00:00
// c ? x : false ---> !!c && x
if (is_false(alternative)) return make_node(AST_Binary, self, {
operator: "&&",
left: booleanize(condition),
right: consequent,
2022-11-30 12:56:09 +00:00
}).optimize(compressor);
2022-01-21 08:28:41 +00:00
if (compressor.option("typeofs")) mark_locally_defined(condition, consequent, alternative);
return self;
function booleanize(node) {
if (node.is_boolean(compressor)) return node;
// !!expression
return make_node(AST_UnaryPrefix, node, {
operator: "!",
2022-08-31 14:34:36 +00:00
expression: node.negate(compressor),
2022-01-21 08:28:41 +00:00
});
}
// AST_True or !0
function is_true(node) {
return node instanceof AST_True
|| in_bool
&& node instanceof AST_Constant
&& node.value
|| (node instanceof AST_UnaryPrefix
&& node.operator == "!"
&& node.expression instanceof AST_Constant
&& !node.expression.value);
}
// AST_False or !1 or void 0
function is_false(node) {
return node instanceof AST_False
|| in_bool
&& (node instanceof AST_Constant
&& !node.value
|| node instanceof AST_UnaryPrefix
&& node.operator == "void"
&& !node.expression.has_side_effects(compressor))
|| (node instanceof AST_UnaryPrefix
&& node.operator == "!"
&& node.expression instanceof AST_Constant
&& node.expression.value);
}
function arg_diff(consequent, alternative) {
var a = consequent.args;
var b = alternative.args;
var len = a.length;
if (len != b.length) return -2;
for (var i = 0; i < len; i++) {
2022-08-05 07:44:52 +00:00
if (!a[i].equals(b[i])) {
2022-01-21 08:28:41 +00:00
if (a[i] instanceof AST_Spread !== b[i] instanceof AST_Spread) return -3;
for (var j = i + 1; j < len; j++) {
2022-08-05 07:44:52 +00:00
if (!a[j].equals(b[j])) return -2;
2022-01-21 08:28:41 +00:00
}
return i;
}
}
return -1;
}
2022-08-31 14:34:36 +00:00
function fuse(node, tail, prop) {
if (node === tail) return tail[prop];
var exprs = node.expressions.slice(0, -1);
exprs.push(tail[prop]);
return make_sequence(node, exprs);
}
2022-01-21 08:28:41 +00:00
function is_tail_equivalent(consequent, alternative) {
if (consequent.TYPE != alternative.TYPE) return;
if (consequent.optional != alternative.optional) return;
if (consequent instanceof AST_Call) {
if (arg_diff(consequent, alternative) != -1) return;
return consequent.TYPE != "Call"
|| !(consequent.expression instanceof AST_PropAccess
|| alternative.expression instanceof AST_PropAccess)
|| is_tail_equivalent(consequent.expression, alternative.expression);
}
if (!(consequent instanceof AST_PropAccess)) return;
var p = consequent.property;
var q = alternative.property;
2022-08-05 07:44:52 +00:00
return (p instanceof AST_Node ? p.equals(q) : p == q)
2022-01-21 08:28:41 +00:00
&& !(consequent.expression instanceof AST_Super || alternative.expression instanceof AST_Super);
}
function combine_tail(consequent, alternative, top) {
2022-08-31 14:34:36 +00:00
var seq_tail = consequent.tail_node();
var alt_tail = alternative.tail_node();
if (!is_tail_equivalent(seq_tail, alt_tail)) return !top && make_node(AST_Conditional, self, {
2022-01-21 08:28:41 +00:00
condition: condition,
consequent: consequent,
alternative: alternative,
});
2022-08-31 14:34:36 +00:00
var node = seq_tail.clone();
var seq_expr = fuse(consequent, seq_tail, "expression");
var alt_expr = fuse(alternative, alt_tail, "expression");
var combined = combine_tail(seq_expr, alt_expr);
if (seq_tail.expression instanceof AST_Sequence) {
combined = maintain_this_binding(seq_tail, seq_tail.expression, combined);
}
node.expression = combined;
2022-01-21 08:28:41 +00:00
return node;
}
function can_shift_lhs_of_tail(node) {
return node === node.tail_node() || all(node.expressions.slice(0, -1), function(expr) {
return !expr.has_side_effects(compressor);
});
}
function pop_lhs(node) {
if (!(node instanceof AST_Sequence)) return node.right;
var exprs = node.expressions.slice();
exprs.push(exprs.pop().right);
return make_sequence(node, exprs);
}
function pop_seq(node) {
2022-02-07 14:48:46 +00:00
if (!(node instanceof AST_Sequence)) return make_node(AST_Number, node, { value: 0 });
2022-01-21 08:28:41 +00:00
return make_sequence(node, node.expressions.slice(0, -1));
}
});
OPT(AST_Boolean, function(self, compressor) {
if (!compressor.option("booleans")) return self;
2022-02-07 14:48:46 +00:00
if (compressor.in_boolean_context()) return make_node(AST_Number, self, { value: +self.value });
2022-01-21 08:28:41 +00:00
var p = compressor.parent();
if (p instanceof AST_Binary && (p.operator == "==" || p.operator == "!=")) {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Non-strict equality against boolean: {operator} {value} [{start}]", {
operator: p.operator,
value: self.value,
start: p.start,
2022-01-21 08:28:41 +00:00
});
2022-02-07 14:48:46 +00:00
return make_node(AST_Number, self, { value: +self.value });
2022-01-21 08:28:41 +00:00
}
return make_node(AST_UnaryPrefix, self, {
operator: "!",
2022-02-07 14:48:46 +00:00
expression: make_node(AST_Number, self, { value: 1 - self.value }),
2022-01-21 08:28:41 +00:00
});
});
OPT(AST_Spread, function(self, compressor) {
var exp = self.expression;
if (compressor.option("spreads") && exp instanceof AST_Array && !(compressor.parent() instanceof AST_Object)) {
return List.splice(exp.elements.map(function(node) {
return node instanceof AST_Hole ? make_node(AST_Undefined, node).optimize(compressor) : node;
}));
}
return self;
});
function safe_to_flatten(value, compressor) {
if (!value) return false;
var parent = compressor.parent();
if (parent.TYPE != "Call") return true;
if (parent.expression !== compressor.self()) return true;
if (value instanceof AST_SymbolRef) {
value = value.fixed_value();
if (!value) return false;
}
return value instanceof AST_Lambda && !value.contains_this();
}
OPT(AST_Sub, function(self, compressor) {
var expr = self.expression;
var prop = self.property;
var terminated = trim_optional_chain(self, compressor);
if (terminated) return terminated;
if (compressor.option("properties")) {
var key = prop.evaluate(compressor);
if (key !== prop) {
if (typeof key == "string") {
if (key == "undefined") {
key = undefined;
} else {
var value = parseFloat(key);
if (value.toString() == key) {
key = value;
}
}
}
prop = self.property = best_of_expression(prop, make_node_from_constant(key, prop).transform(compressor));
var property = "" + key;
if (is_identifier_string(property)
&& property.length <= prop.print_to_string().length + 1) {
return make_node(AST_Dot, self, {
optional: self.optional,
expression: expr,
property: property,
2022-09-30 13:48:25 +00:00
quoted: true,
2022-01-21 08:28:41 +00:00
}).optimize(compressor);
}
}
}
var parent = compressor.parent();
var assigned = is_lhs(compressor.self(), parent);
var def, fn, fn_parent, index;
if (compressor.option("arguments")
&& expr instanceof AST_SymbolRef
&& is_arguments(def = expr.definition())
&& !expr.in_arg
&& prop instanceof AST_Number
&& Math.floor(index = prop.value) == index
&& (fn = def.scope) === find_lambda()
&& fn.uses_arguments < (assigned ? 2 : 3)) {
if (parent instanceof AST_UnaryPrefix && parent.operator == "delete") {
if (!def.deleted) def.deleted = [];
def.deleted[index] = true;
}
var argname = fn.argnames[index];
if (def.deleted && def.deleted[index]) {
argname = null;
} else if (argname) {
var arg_def;
if (!(argname instanceof AST_SymbolFunarg)
|| argname.name == "await"
|| expr.scope.find_variable(argname.name) !== (arg_def = argname.definition())) {
argname = null;
} else if (compressor.has_directive("use strict")
|| fn.name
|| fn.rest
|| !(fn_parent instanceof AST_Call
&& index < fn_parent.args.length
&& all(fn_parent.args.slice(0, index + 1), function(arg) {
return !(arg instanceof AST_Spread);
}))
|| !all(fn.argnames, function(argname) {
return argname instanceof AST_SymbolFunarg;
})) {
if (has_reassigned() || arg_def.assignments || arg_def.orig.length > 1) argname = null;
}
} else if ((assigned || !has_reassigned())
&& index < fn.argnames.length + 5
&& compressor.drop_fargs(fn, fn_parent)
&& !fn.rest) {
while (index >= fn.argnames.length) {
argname = fn.make_var(AST_SymbolFunarg, fn, "argument_" + fn.argnames.length);
fn.argnames.push(argname);
}
}
if (argname && find_if(function(node) {
return node.name === argname.name;
}, fn.argnames) === argname) {
if (assigned) def.reassigned--;
2022-08-31 14:34:36 +00:00
var sym = make_node(AST_SymbolRef, argname);
2022-01-21 08:28:41 +00:00
sym.reference();
argname.unused = undefined;
return sym;
}
}
if (assigned) return self;
if (compressor.option("sequences")
&& parent.TYPE != "Call"
&& !(parent instanceof AST_ForEnumeration && parent.init === self)) {
var seq = lift_sequence_in_expression(self, compressor);
if (seq !== self) return seq.optimize(compressor);
}
if (key !== prop) {
var sub = self.flatten_object(property, compressor);
if (sub) {
expr = self.expression = sub.expression;
prop = self.property = sub.property;
}
}
var elements;
if (compressor.option("properties")
&& compressor.option("side_effects")
&& prop instanceof AST_Number
&& expr instanceof AST_Array
&& all(elements = expr.elements, function(value) {
return !(value instanceof AST_Spread);
})) {
var index = prop.value;
var retValue = elements[index];
if (safe_to_flatten(retValue, compressor)) {
var is_hole = retValue instanceof AST_Hole;
var flatten = !is_hole;
var values = [];
for (var i = elements.length; --i > index;) {
var value = elements[i].drop_side_effect_free(compressor);
if (value) {
values.unshift(value);
if (flatten && value.has_side_effects(compressor)) flatten = false;
}
}
if (!flatten) values.unshift(retValue);
while (--i >= 0) {
var value = elements[i].drop_side_effect_free(compressor);
if (value) {
values.unshift(value);
} else if (is_hole) {
values.unshift(make_node(AST_Hole, elements[i]));
} else {
index--;
}
}
if (flatten) {
values.push(retValue);
return make_sequence(self, values).optimize(compressor);
2022-03-14 15:40:45 +00:00
}
return make_node(AST_Sub, self, {
2022-01-21 08:28:41 +00:00
expression: make_node(AST_Array, expr, { elements: values }),
property: make_node(AST_Number, prop, { value: index }),
});
}
}
return try_evaluate(compressor, self);
function find_lambda() {
var i = 0, p;
while (p = compressor.parent(i++)) {
if (p instanceof AST_Lambda) {
if (p instanceof AST_Accessor) return;
if (is_arrow(p)) continue;
fn_parent = compressor.parent(i);
return p;
}
}
}
function has_reassigned() {
return !compressor.option("reduce_vars") || def.reassigned;
}
});
AST_LambdaExpression.DEFMETHOD("contains_super", function() {
var result = false;
var self = this;
self.walk(new TreeWalker(function(node) {
if (result) return true;
if (node instanceof AST_Super) return result = true;
if (node !== self && node instanceof AST_Scope && !is_arrow(node)) return true;
}));
return result;
});
// contains_this()
// returns false only if context bound by the specified scope (or scope
// containing the specified expression) is not referenced by `this`
(function(def) {
// scope of arrow function cannot bind to any context
def(AST_Arrow, return_false);
def(AST_AsyncArrow, return_false);
def(AST_Node, function() {
var result = false;
var self = this;
self.walk(new TreeWalker(function(node) {
if (result) return true;
if (node instanceof AST_This) return result = true;
if (node !== self && node instanceof AST_Scope && !is_arrow(node)) return true;
}));
return result;
});
})(function(node, func) {
node.DEFMETHOD("contains_this", func);
});
function can_hoist_property(prop) {
return prop instanceof AST_ObjectKeyVal
&& typeof prop.key == "string"
&& !(prop instanceof AST_ObjectMethod && prop.value.contains_super());
}
AST_PropAccess.DEFMETHOD("flatten_object", function(key, compressor) {
if (!compressor.option("properties")) return;
if (key === "__proto__") return;
2022-04-11 08:07:00 +00:00
var self = this;
var expr = self.expression;
if (!(expr instanceof AST_Object)) return;
var props = expr.properties;
for (var i = props.length; --i >= 0;) {
var prop = props[i];
if (prop.key !== key) continue;
if (!all(props, can_hoist_property)) return;
if (!safe_to_flatten(prop.value, compressor)) return;
var call, scope, values = [];
for (var j = 0; j < props.length; j++) {
var value = props[j].value;
if (props[j] instanceof AST_ObjectMethod) {
var arrow = !(value.uses_arguments || is_generator(value) || value.contains_this());
if (arrow) {
if (!scope) scope = compressor.find_parent(AST_Scope);
2022-07-11 11:25:19 +00:00
var avoid = avoid_await_yield(compressor, scope);
2022-04-11 08:07:00 +00:00
value.each_argname(function(argname) {
if (avoid[argname.name]) arrow = false;
});
2022-01-21 08:28:41 +00:00
}
2022-04-11 08:07:00 +00:00
var ctor;
if (arrow) {
ctor = is_async(value) ? AST_AsyncArrow : AST_Arrow;
} else if (i != j
|| (call = compressor.parent()) instanceof AST_Call && call.expression === self) {
ctor = value.CTOR;
} else {
return;
}
2022-08-31 14:34:36 +00:00
value = make_node(ctor, value);
2022-01-21 08:28:41 +00:00
}
2022-04-11 08:07:00 +00:00
values.push(value);
2022-01-21 08:28:41 +00:00
}
2022-04-11 08:07:00 +00:00
return make_node(AST_Sub, self, {
expression: make_node(AST_Array, expr, { elements: values }),
property: make_node(AST_Number, self, { value: i }),
});
2022-01-21 08:28:41 +00:00
}
});
OPT(AST_Dot, function(self, compressor) {
if (self.property == "arguments" || self.property == "caller") {
2022-08-31 14:34:36 +00:00
AST_Node.warn("Function.prototype.{property} not supported [{start}]", self);
2022-01-21 08:28:41 +00:00
}
var parent = compressor.parent();
if (is_lhs(compressor.self(), parent)) return self;
var terminated = trim_optional_chain(self, compressor);
if (terminated) return terminated;
if (compressor.option("sequences")
&& parent.TYPE != "Call"
&& !(parent instanceof AST_ForEnumeration && parent.init === self)) {
var seq = lift_sequence_in_expression(self, compressor);
if (seq !== self) return seq.optimize(compressor);
}
if (compressor.option("unsafe_proto")
&& self.expression instanceof AST_Dot
&& self.expression.property == "prototype") {
var exp = self.expression.expression;
if (is_undeclared_ref(exp)) switch (exp.name) {
case "Array":
2022-02-07 14:48:46 +00:00
self.expression = make_node(AST_Array, self.expression, { elements: [] });
2022-01-21 08:28:41 +00:00
break;
case "Function":
self.expression = make_node(AST_Function, self.expression, {
argnames: [],
2022-02-07 14:48:46 +00:00
body: [],
2022-01-21 08:28:41 +00:00
}).init_vars(exp.scope);
break;
case "Number":
2022-02-07 14:48:46 +00:00
self.expression = make_node(AST_Number, self.expression, { value: 0 });
2022-01-21 08:28:41 +00:00
break;
case "Object":
2022-02-07 14:48:46 +00:00
self.expression = make_node(AST_Object, self.expression, { properties: [] });
2022-01-21 08:28:41 +00:00
break;
case "RegExp":
2022-02-07 14:48:46 +00:00
self.expression = make_node(AST_RegExp, self.expression, { value: /t/ });
2022-01-21 08:28:41 +00:00
break;
case "String":
2022-02-07 14:48:46 +00:00
self.expression = make_node(AST_String, self.expression, { value: "" });
2022-01-21 08:28:41 +00:00
break;
}
}
var sub = self.flatten_object(self.property, compressor);
if (sub) return sub.optimize(compressor);
return try_evaluate(compressor, self);
});
OPT(AST_DestructuredArray, function(self, compressor) {
if (compressor.option("rests") && self.rest instanceof AST_DestructuredArray) {
return make_node(AST_DestructuredArray, self, {
elements: self.elements.concat(self.rest.elements),
rest: self.rest.rest,
});
}
return self;
});
OPT(AST_DestructuredKeyVal, function(self, compressor) {
if (compressor.option("objects")) {
var key = self.key;
if (key instanceof AST_Node) {
key = key.evaluate(compressor);
if (key !== self.key) self.key = "" + key;
}
}
return self;
});
OPT(AST_Object, function(self, compressor) {
if (!compressor.option("objects")) return self;
var changed = false;
var found = false;
var generated = false;
var keep_duplicate = compressor.has_directive("use strict");
var keys = [];
var map = new Dictionary();
var values = [];
self.properties.forEach(function(prop) {
if (!(prop instanceof AST_Spread)) return process(prop);
found = true;
var exp = prop.expression;
if (compressor.option("spreads") && exp instanceof AST_Object && all(exp.properties, function(prop) {
if (prop instanceof AST_ObjectGetter) return false;
if (prop instanceof AST_Spread) return false;
if (prop.key !== "__proto__") return true;
if (prop instanceof AST_ObjectSetter) return true;
return !prop.value.has_side_effects(compressor);
})) {
changed = true;
exp.properties.forEach(function(prop) {
var key = prop.key;
var setter = prop instanceof AST_ObjectSetter;
if (key === "__proto__") {
if (!setter) return;
key = make_node_from_constant(key, prop);
}
process(setter ? make_node(AST_ObjectKeyVal, prop, {
key: key,
value: make_node(AST_Undefined, prop).optimize(compressor),
}) : prop);
});
} else {
generated = true;
flush();
values.push(prop);
}
});
flush();
if (!changed) return self;
if (found && generated && values.length == 1) {
var value = values[0];
if (value instanceof AST_ObjectProperty && value.key instanceof AST_Number) {
value.key = "" + value.key.value;
}
}
return make_node(AST_Object, self, { properties: values });
function flush() {
keys.forEach(function(key) {
var props = map.get(key);
switch (props.length) {
case 0:
return;
case 1:
return values.push(props[0]);
}
changed = true;
var tail = keep_duplicate && !generated && props.pop();
values.push(props.length == 1 ? props[0] : make_node(AST_ObjectKeyVal, self, {
key: props[0].key,
value: make_sequence(self, props.map(function(prop) {
return prop.value;
})),
}));
if (tail) values.push(tail);
props.length = 0;
});
keys = [];
map = new Dictionary();
}
function process(prop) {
var key = prop.key;
if (key instanceof AST_Node) {
found = true;
key = key.evaluate(compressor);
if (key === prop.key || key === "__proto__") {
generated = true;
} else {
key = prop.key = "" + key;
}
}
if (can_hoist_property(prop)) {
if (prop.value.has_side_effects(compressor)) flush();
keys.push(key);
map.add(key, prop);
} else {
flush();
values.push(prop);
}
if (found && !generated && typeof key == "string" && RE_POSITIVE_INTEGER.test(key)) {
generated = true;
if (map.has(key)) prop = map.get(key)[0];
prop.key = make_node(AST_Number, prop, { value: +key });
}
}
});
2022-02-07 14:48:46 +00:00
function flatten_var(name) {
var redef = name.definition().redefined();
if (redef) {
name = name.clone();
name.thedef = redef;
}
return name;
}
function has_arg_refs(fn, node) {
var found = false;
node.walk(new TreeWalker(function(node) {
if (found) return true;
if (node instanceof AST_SymbolRef && fn.variables.get(node.name) === node.definition()) {
return found = true;
}
}));
return found;
}
2022-04-11 08:07:00 +00:00
function insert_assign(def, assign) {
var visited = [];
def.references.forEach(function(ref) {
var fixed = ref.fixed;
if (!fixed || !push_uniq(visited, fixed)) return;
if (fixed.assigns) {
fixed.assigns.unshift(assign);
} else {
fixed.assigns = [ assign ];
}
});
}
2022-02-07 14:48:46 +00:00
function init_ref(compressor, name) {
2022-08-31 14:34:36 +00:00
var sym = make_node(AST_SymbolRef, name);
2022-02-07 14:48:46 +00:00
var assign = make_node(AST_Assign, name, {
operator: "=",
left: sym,
right: make_node(AST_Undefined, name).transform(compressor),
});
var def = name.definition();
if (def.fixed) {
sym.fixed = function() {
return assign.right;
};
sym.fixed.assigns = [ assign ];
2022-04-11 08:07:00 +00:00
insert_assign(def, assign);
2022-02-07 14:48:46 +00:00
}
def.assignments++;
def.references.push(sym);
return assign;
}
(function(def) {
def(AST_Node, noop);
def(AST_Assign, noop);
def(AST_Await, function(compressor, scope, no_return, in_loop) {
2022-09-30 13:48:25 +00:00
if (!compressor.option("awaits")) return;
2022-02-07 14:48:46 +00:00
var self = this;
2022-07-11 11:25:19 +00:00
var inlined = self.expression.try_inline(compressor, scope, no_return, in_loop, true);
2022-02-07 14:48:46 +00:00
if (!inlined) return;
if (!no_return) scan_local_returns(inlined, function(node) {
node.in_bool = false;
var value = node.value;
if (value instanceof AST_Await) return;
node.value = make_node(AST_Await, self, {
expression: value || make_node(AST_Undefined, node).transform(compressor),
});
});
return aborts(inlined) ? inlined : make_node(AST_BlockStatement, self, {
body: [ inlined, make_node(AST_SimpleStatement, self, {
body: make_node(AST_Await, self, { expression: make_node(AST_Number, self, { value: 0 })}),
}) ],
});
});
2022-07-11 11:25:19 +00:00
def(AST_Binary, function(compressor, scope, no_return, in_loop, in_await) {
2022-02-07 14:48:46 +00:00
if (no_return === undefined) return;
var self = this;
var op = self.operator;
if (!lazy_op[op]) return;
2022-07-11 11:25:19 +00:00
var inlined = self.right.try_inline(compressor, scope, no_return, in_loop, in_await);
2022-02-07 14:48:46 +00:00
if (!inlined) return;
return make_node(AST_If, self, {
condition: make_condition(self.left),
body: inlined,
2022-07-11 11:25:19 +00:00
alternative: no_return ? null : make_node(AST_Return, self, {
value: make_node(AST_Undefined, self).transform(compressor),
}),
2022-02-07 14:48:46 +00:00
});
function make_condition(cond) {
switch (op) {
case "&&":
return cond;
case "||":
return cond.negate(compressor);
case "??":
return make_node(AST_Binary, self, {
operator: "==",
left: make_node(AST_Null, self),
right: cond,
});
}
}
});
def(AST_BlockStatement, function(compressor, scope, no_return, in_loop) {
if (no_return) return;
if (!this.variables) return;
var body = this.body;
var last = body.length - 1;
if (last < 0) return;
var inlined = body[last].try_inline(compressor, this, no_return, in_loop);
if (!inlined) return;
body[last] = inlined;
return this;
});
2022-07-11 11:25:19 +00:00
def(AST_Call, function(compressor, scope, no_return, in_loop, in_await) {
2022-02-07 14:48:46 +00:00
if (compressor.option("inline") < 4) return;
var call = this;
if (call.is_expr_pure(compressor)) return;
var fn = call.expression;
if (!(fn instanceof AST_LambdaExpression)) return;
if (fn.name) return;
if (fn.uses_arguments) return;
2022-03-14 15:40:45 +00:00
if (fn.pinned()) return;
2022-02-07 14:48:46 +00:00
if (is_generator(fn)) return;
var arrow = is_arrow(fn);
if (arrow && fn.value) return;
if (fn.body[0] instanceof AST_Directive) return;
if (fn.contains_this()) return;
if (!scope) scope = find_scope(compressor);
var defined = new Dictionary();
defined.set("NaN", true);
while (!(scope instanceof AST_Scope)) {
scope.variables.each(function(def) {
defined.set(def.name, true);
});
scope = scope.parent_scope;
}
if (!member(scope, compressor.stack)) return;
2022-03-14 15:40:45 +00:00
if (scope.pinned() && fn.variables.size() > (arrow ? 0 : 1)) return;
2022-02-07 14:48:46 +00:00
if (scope instanceof AST_Toplevel) {
if (fn.variables.size() > (arrow ? 0 : 1)) {
if (!compressor.toplevel.vars) return;
if (fn.functions.size() > 0 && !compressor.toplevel.funcs) return;
}
defined.set("arguments", true);
}
2022-07-11 11:25:19 +00:00
var async = !in_await && is_async(fn);
2022-02-07 14:48:46 +00:00
if (async) {
if (!compressor.option("awaits")) return;
if (!is_async(scope)) return;
if (call.may_throw(compressor)) return;
}
var names = scope.var_names();
if (in_loop) in_loop = [];
if (!fn.variables.all(function(def, name) {
if (in_loop) in_loop.push(def);
if (!defined.has(name) && !names.has(name)) return true;
return !arrow && name == "arguments" && def.orig.length == 1;
})) return;
if (in_loop && in_loop.length > 0 && is_reachable(fn, in_loop)) return;
var simple_argnames = true;
if (!all(fn.argnames, function(argname) {
var abort = false;
var tw = new TreeWalker(function(node) {
if (abort) return true;
if (node instanceof AST_DefaultValue) {
if (has_arg_refs(fn, node.value)) return abort = true;
node.name.walk(tw);
return true;
}
if (node instanceof AST_DestructuredKeyVal) {
if (node.key instanceof AST_Node && has_arg_refs(fn, node.key)) return abort = true;
node.value.walk(tw);
return true;
}
if (node instanceof AST_SymbolFunarg && !all(node.definition().orig, function(sym) {
return !(sym instanceof AST_SymbolDefun);
})) return abort = true;
});
argname.walk(tw);
if (abort) return false;
if (!(argname instanceof AST_SymbolFunarg)) simple_argnames = false;
return true;
})) return;
if (fn.rest) {
if (has_arg_refs(fn, fn.rest)) return;
simple_argnames = false;
}
2022-07-11 11:25:19 +00:00
var verify_body;
if (no_return) {
verify_body = function(stat) {
var abort = false;
stat.walk(new TreeWalker(function(node) {
if (abort) return true;
2022-10-10 08:26:02 +00:00
if (async && (node instanceof AST_Await || node instanceof AST_ForAwaitOf)
|| node instanceof AST_Return) {
return abort = true;
}
2022-07-11 11:25:19 +00:00
if (node instanceof AST_Scope) return true;
}));
return !abort;
};
2022-09-30 13:48:25 +00:00
} else if (in_await || is_async(fn) || in_async_generator(scope)) {
2022-07-11 11:25:19 +00:00
verify_body = function(stat) {
var abort = false;
var find_return = new TreeWalker(function(node) {
if (abort) return true;
if (node instanceof AST_Return) return abort = true;
if (node instanceof AST_Scope) return true;
});
stat.walk(new TreeWalker(function(node) {
if (abort) return true;
if (node instanceof AST_Try) {
if (node.bfinally && all(node.body, function(stat) {
stat.walk(find_return);
return !abort;
}) && node.bcatch) node.bcatch.walk(find_return);
return true;
}
if (node instanceof AST_Scope) return true;
}));
return !abort;
};
}
if (verify_body && !all(fn.body, verify_body)) return;
if (!safe_from_await_yield(fn, avoid_await_yield(compressor, scope))) return;
2022-02-07 14:48:46 +00:00
fn.functions.each(function(def, name) {
scope.functions.set(name, def);
});
var body = [];
fn.variables.each(function(def, name) {
2022-05-29 09:24:36 +00:00
if (!arrow && name == "arguments" && def.orig.length == 1) return;
2022-02-07 14:48:46 +00:00
names.set(name, true);
scope.enclosed.push(def);
scope.variables.set(name, def);
def.single_use = false;
if (!in_loop) return;
if (def.references.length == def.replaced) return;
2022-03-14 15:40:45 +00:00
if (def.orig.length == def.eliminated) return;
2022-02-07 14:48:46 +00:00
if (def.orig.length == 1 && fn.functions.has(name)) return;
if (!all(def.orig, function(sym) {
if (sym instanceof AST_SymbolConst) return false;
2022-07-11 11:25:19 +00:00
if (sym instanceof AST_SymbolFunarg) return !sym.unused && def.scope.resolve() !== fn;
2022-02-07 14:48:46 +00:00
if (sym instanceof AST_SymbolLet) return false;
return true;
})) return;
var sym = def.orig[0];
if (sym instanceof AST_SymbolCatch) return;
body.push(make_node(AST_SimpleStatement, sym, { body: init_ref(compressor, flatten_var(sym)) }));
});
var defs = Object.create(null), syms = new Dictionary();
if (simple_argnames && all(call.args, function(arg) {
return !(arg instanceof AST_Spread);
})) {
var values = call.args.slice();
fn.argnames.forEach(function(argname) {
var value = values.shift();
if (argname.unused) {
if (value) body.push(make_node(AST_SimpleStatement, call, { body: value }));
return;
}
2022-04-11 08:07:00 +00:00
var defn = make_node(AST_VarDef, call, {
name: argname.convert_symbol(AST_SymbolVar, process),
value: value || make_node(AST_Undefined, call).transform(compressor),
});
if (argname instanceof AST_SymbolFunarg) insert_assign(argname.definition(), defn);
body.push(make_node(AST_Var, call, { definitions: [ defn ] }));
2022-02-07 14:48:46 +00:00
});
if (values.length) body.push(make_node(AST_SimpleStatement, call, {
body: make_sequence(call, values),
}));
} else {
body.push(make_node(AST_Var, call, {
definitions: [ make_node(AST_VarDef, call, {
name: make_node(AST_DestructuredArray, call, {
elements: fn.argnames.map(function(argname) {
if (argname.unused) return make_node(AST_Hole, argname);
return argname.convert_symbol(AST_SymbolVar, process);
}),
rest: fn.rest && fn.rest.convert_symbol(AST_SymbolVar, process),
}),
value: make_node(AST_Array, call, { elements: call.args.slice() }),
}) ],
}));
}
syms.each(function(orig, id) {
var def = defs[id];
[].unshift.apply(def.orig, orig);
def.eliminated += orig.length;
});
[].push.apply(body, in_loop ? fn.body.filter(function(stat) {
if (!(stat instanceof AST_LambdaDefinition)) return true;
2022-08-31 14:34:36 +00:00
var name = make_node(AST_SymbolVar, flatten_var(stat.name));
2022-02-07 14:48:46 +00:00
var def = name.definition();
def.fixed = false;
def.orig.push(name);
def.eliminated++;
body.push(make_node(AST_Var, stat, {
definitions: [ make_node(AST_VarDef, stat, {
name: name,
value: to_func_expr(stat, true),
}) ],
}));
return false;
}) : fn.body);
var inlined = make_node(AST_BlockStatement, call, { body: body });
if (!no_return) {
if (async) scan_local_returns(inlined, function(node) {
var value = node.value;
if (is_undefined(value)) return;
node.value = make_node(AST_Await, call, { expression: value });
});
2022-07-11 11:25:19 +00:00
body.push(make_node(AST_Return, call, {
value: in_async_generator(scope) ? make_node(AST_Undefined, call).transform(compressor) : null,
}));
2022-02-07 14:48:46 +00:00
}
return inlined;
function process(sym, argname) {
var def = argname.definition();
defs[def.id] = def;
syms.add(def.id, sym);
}
});
2022-07-11 11:25:19 +00:00
def(AST_Conditional, function(compressor, scope, no_return, in_loop, in_await) {
2022-02-07 14:48:46 +00:00
var self = this;
2022-07-11 11:25:19 +00:00
var body = self.consequent.try_inline(compressor, scope, no_return, in_loop, in_await);
var alt = self.alternative.try_inline(compressor, scope, no_return, in_loop, in_await);
2022-02-07 14:48:46 +00:00
if (!body && !alt) return;
return make_node(AST_If, self, {
condition: self.condition,
body: body || make_body(self.consequent),
alternative: alt || make_body(self.alternative),
});
function make_body(value) {
if (no_return) return make_node(AST_SimpleStatement, value, { body: value });
return make_node(AST_Return, value, { value: value });
}
});
def(AST_For, function(compressor, scope, no_return, in_loop) {
var body = this.body.try_inline(compressor, scope, true, true);
if (body) this.body = body;
var inlined = this.init;
if (inlined) {
inlined = inlined.try_inline(compressor, scope, true, in_loop);
if (inlined) {
this.init = null;
2022-03-14 15:40:45 +00:00
if (inlined instanceof AST_BlockStatement) {
inlined.body.push(this);
return inlined;
}
return make_node(AST_BlockStatement, inlined, { body: [ inlined, this ] });
2022-02-07 14:48:46 +00:00
}
}
return body && this;
});
def(AST_ForEnumeration, function(compressor, scope, no_return, in_loop) {
var body = this.body.try_inline(compressor, scope, true, true);
if (body) this.body = body;
var obj = this.object;
if (obj instanceof AST_Sequence) {
2022-07-11 11:25:19 +00:00
var inlined = inline_sequence(compressor, scope, true, in_loop, false, obj, 1);
2022-02-07 14:48:46 +00:00
if (inlined) {
this.object = obj.tail_node();
inlined.body.push(this);
return inlined;
}
}
return body && this;
});
def(AST_If, function(compressor, scope, no_return, in_loop) {
var body = this.body.try_inline(compressor, scope, no_return, in_loop);
if (body) this.body = body;
var alt = this.alternative;
if (alt) {
alt = alt.try_inline(compressor, scope, no_return, in_loop);
if (alt) this.alternative = alt;
}
var cond = this.condition;
if (cond instanceof AST_Sequence) {
2022-07-11 11:25:19 +00:00
var inlined = inline_sequence(compressor, scope, true, in_loop, false, cond, 1);
2022-02-07 14:48:46 +00:00
if (inlined) {
this.condition = cond.tail_node();
inlined.body.push(this);
return inlined;
}
}
return (body || alt) && this;
});
def(AST_IterationStatement, function(compressor, scope, no_return, in_loop) {
var body = this.body.try_inline(compressor, scope, true, true);
if (!body) return;
this.body = body;
return this;
});
def(AST_LabeledStatement, function(compressor, scope, no_return, in_loop) {
var body = this.body.try_inline(compressor, scope, no_return, in_loop);
if (!body) return;
2022-04-11 08:07:00 +00:00
if (this.body instanceof AST_IterationStatement && body instanceof AST_BlockStatement) {
var loop = body.body.pop();
this.body = loop;
body.body.push(this);
return body;
}
2022-02-07 14:48:46 +00:00
this.body = body;
return this;
});
def(AST_New, noop);
def(AST_Return, function(compressor, scope, no_return, in_loop) {
var value = this.value;
return value && value.try_inline(compressor, scope, undefined, in_loop === "try");
});
2022-07-11 11:25:19 +00:00
function inline_sequence(compressor, scope, no_return, in_loop, in_await, node, skip) {
2022-02-07 14:48:46 +00:00
var body = [], exprs = node.expressions, no_ret = no_return;
2022-07-11 11:25:19 +00:00
for (var i = exprs.length - (skip || 0), j = i; --i >= 0; no_ret = true, in_await = false) {
var inlined = exprs[i].try_inline(compressor, scope, no_ret, in_loop, in_await);
2022-02-07 14:48:46 +00:00
if (!inlined) continue;
flush();
body.push(inlined);
}
if (body.length == 0) return;
flush();
if (!no_return && body[0] instanceof AST_SimpleStatement) {
body[0] = make_node(AST_Return, node, { value: body[0].body });
}
return make_node(AST_BlockStatement, node, { body: body.reverse() });
function flush() {
if (j > i + 1) body.push(make_node(AST_SimpleStatement, node, {
body: make_sequence(node, exprs.slice(i + 1, j)),
}));
j = i;
}
}
2022-07-11 11:25:19 +00:00
def(AST_Sequence, function(compressor, scope, no_return, in_loop, in_await) {
return inline_sequence(compressor, scope, no_return, in_loop, in_await, this);
2022-02-07 14:48:46 +00:00
});
def(AST_SimpleStatement, function(compressor, scope, no_return, in_loop) {
var body = this.body;
while (body instanceof AST_UnaryPrefix) {
var op = body.operator;
if (unary_side_effects[op]) break;
if (op == "void") break;
body = body.expression;
}
if (!no_return && !is_undefined(body)) body = make_node(AST_UnaryPrefix, this, {
operator: "void",
expression: body,
});
return body.try_inline(compressor, scope, no_return || false, in_loop);
});
2022-07-11 11:25:19 +00:00
def(AST_UnaryPrefix, function(compressor, scope, no_return, in_loop, in_await) {
2022-02-07 14:48:46 +00:00
var self = this;
var op = self.operator;
if (unary_side_effects[op]) return;
if (!no_return && op == "void") no_return = false;
2022-07-11 11:25:19 +00:00
var inlined = self.expression.try_inline(compressor, scope, no_return, in_loop, in_await);
2022-02-07 14:48:46 +00:00
if (!inlined) return;
if (!no_return) scan_local_returns(inlined, function(node) {
node.in_bool = false;
var value = node.value;
if (op == "void" && is_undefined(value)) return;
node.value = make_node(AST_UnaryPrefix, self, {
operator: op,
expression: value || make_node(AST_Undefined, node).transform(compressor),
});
});
return inlined;
});
def(AST_With, function(compressor, scope, no_return, in_loop) {
var body = this.body.try_inline(compressor, scope, no_return, in_loop);
if (body) this.body = body;
var exp = this.expression;
if (exp instanceof AST_Sequence) {
2022-07-11 11:25:19 +00:00
var inlined = inline_sequence(compressor, scope, true, in_loop, false, exp, 1);
2022-02-07 14:48:46 +00:00
if (inlined) {
this.expression = exp.tail_node();
inlined.body.push(this);
return inlined;
}
}
return body && this;
});
def(AST_Yield, function(compressor, scope, no_return, in_loop) {
if (!compressor.option("yields")) return;
if (!this.nested) return;
var call = this.expression;
if (call.TYPE != "Call") return;
var fn = call.expression;
switch (fn.CTOR) {
case AST_AsyncGeneratorFunction:
2022-08-31 14:34:36 +00:00
fn = make_node(AST_AsyncFunction, fn);
2022-02-07 14:48:46 +00:00
break;
case AST_GeneratorFunction:
2022-08-31 14:34:36 +00:00
fn = make_node(AST_Function, fn);
2022-02-07 14:48:46 +00:00
break;
default:
return;
}
call = call.clone();
call.expression = fn;
return call.try_inline(compressor, scope, no_return, in_loop);
});
})(function(node, func) {
node.DEFMETHOD("try_inline", func);
});
2022-01-21 08:28:41 +00:00
OPT(AST_Return, function(self, compressor) {
2022-02-07 14:48:46 +00:00
var value = self.value;
if (value && compressor.option("side_effects")
&& is_undefined(value, compressor)
2022-01-21 08:28:41 +00:00
&& !in_async_generator(compressor.find_parent(AST_Scope))) {
self.value = null;
}
return self;
});
})(function(node, optimizer) {
node.DEFMETHOD("optimize", function(compressor) {
var self = this;
if (self._optimized) return self;
if (compressor.has_directive("use asm")) return self;
var opt = optimizer(self, compressor);
opt._optimized = true;
return opt;
});
});