Compare commits

..

24 Commits

Author SHA1 Message Date
Alex Lam S.L
90585e29c2 v3.3.15 2018-03-14 16:45:38 +00:00
Alex Lam S.L
d8fc281915 update dependencies (#3002)
acorn 5.5.3
commander 2.15.0

Miscellaneous
- drop unmaintained package from README
2018-03-14 15:54:41 +08:00
Alex Lam S.L
188c39e8d5 retain comments within brackets (#2999)
fixes #2998
2018-03-13 18:44:21 +08:00
Alex Lam S.L
5429234138 preserve non-constant value assignments with modifications (#2997)
fixes #2995
2018-03-13 17:35:34 +08:00
Alex Lam S.L
b9f72a4a81 handle case correctly under reduce_vars (#2993)
fixes #2992
2018-03-11 15:54:43 +08:00
Alex Lam S.L
fc6ebd04a5 preserve case when inline_script (#2991)
fixes #2989
2018-03-11 05:11:12 +08:00
Alex Lam S.L
7e00a12741 v3.3.14 2018-03-10 13:20:14 +00:00
Alex Lam S.L
10b3752b1e fix mangle of AST_SymbolLambda under ie8 (#2978)
fixes #2976
2018-03-07 17:20:38 +08:00
Alex Lam S.L
fe51a91395 handle negated constants correctly in collapse_vars (#2975)
fixes #2974
2018-03-06 00:45:58 +08:00
Alex Lam S.L
951d87ca94 v3.3.13 2018-03-04 07:38:49 +00:00
Alex Lam S.L
798fc21530 improve test/run-test.js performance (#2971)
- allow reuse of contextified sandbox
- minimise bottleneck from `vm.createContext()`
2018-03-04 04:50:00 +08:00
Alex Lam S.L
a75a046abb compress arguments[index] (#2967)
- always replace with existing parameter
- only introduce new parameter if `keep_fargs` is disabled
2018-03-02 11:22:09 +08:00
Alex Lam S.L
38f2b4579f fix value reference caching in evaluate (#2969)
fixes #2968
2018-03-02 04:04:29 +08:00
Alex Lam S.L
56e2a369d0 enhance conditionals (#2966)
- `x ? (y, w) : (z, w)` => `x ? y : z, w`
2018-02-28 23:34:48 +08:00
Alex Lam S.L
0daa199fa8 migrate safe transformations out of unsafe_comps (#2962)
fixes #2959
2018-02-28 22:02:24 +08:00
Alex Lam S.L
73e98dcda4 drop side_effects-free return values (#2965) 2018-02-28 19:59:19 +08:00
Alex Lam S.L
36bca6934d enhance collapse_vars (#2952)
- `a = b, b` => `a = b`
- `a.b = c, c()` => `(a.b = c)()`
2018-02-28 15:19:32 +08:00
Alex Lam S.L
ace5811691 drop lone "use strict" in function body (#2963)
fixes #2961
2018-02-26 15:22:52 +08:00
Dan
ba7bad0dbd show benchmark subtotal (#2960)
At the end of the benchmark, sums of the input, output and
gzip values are shown, such as:

    Subtotal

    Original: 7785102 bytes
    Uglified: 2283862 bytes
    GZipped:  662354 bytes
2018-02-26 11:46:26 +08:00
Alex Lam S.L
b8b2ac5230 improve fix for #2954 (#2958) 2018-02-26 03:14:22 +08:00
Alex Lam S.L
ea2359381b fix collapse_vars on nested exception (#2955)
fixes #2954
2018-02-25 15:39:00 +08:00
Alex Lam S.L
52de64cf16 deduplicate parenthesis around object and function literals (#2953) 2018-02-25 02:14:33 +08:00
Alex Lam S.L
455790202a minor clean-ups (#2951) 2018-02-24 02:24:47 +08:00
Alex Lam S.L
f40f5eb228 improve mangle (#2948) 2018-02-23 23:51:49 +08:00
29 changed files with 1839 additions and 288 deletions

View File

@@ -6,9 +6,8 @@ UglifyJS is a JavaScript parser, minifier, compressor and beautifier toolkit.
#### Note: #### Note:
- **`uglify-js@3` has a simplified [API](#api-reference) and [CLI](#command-line-usage) that is not backwards compatible with [`uglify-js@2`](https://github.com/mishoo/UglifyJS2/tree/v2.x)**. - **`uglify-js@3` has a simplified [API](#api-reference) and [CLI](#command-line-usage) that is not backwards compatible with [`uglify-js@2`](https://github.com/mishoo/UglifyJS2/tree/v2.x)**.
- **Documentation for UglifyJS `2.x` releases can be found [here](https://github.com/mishoo/UglifyJS2/tree/v2.x)**. - **Documentation for UglifyJS `2.x` releases can be found [here](https://github.com/mishoo/UglifyJS2/tree/v2.x)**.
- `uglify-js` only supports ECMAScript 5 (ES5). - `uglify-js` only supports JavaScript (ECMAScript 5).
- Those wishing to minify - To minify ECMAScript 2015 or above, transpile using tools like [Babel](https://babeljs.io/).
ES2015+ (ES6+) should use the `npm` package [**uglify-es**](https://github.com/mishoo/UglifyJS2/tree/harmony).
Install Install
------- -------
@@ -598,6 +597,9 @@ If you're using the `X-SourceMap` header instead, you can just omit `sourceMap.u
## Compress options ## Compress options
- `arguments` (default: `true`) -- replace `arguments[index]` with function
parameter name whenever possible.
- `booleans` (default: `true`) -- various optimizations for boolean context, - `booleans` (default: `true`) -- various optimizations for boolean context,
for example `!!a ? b : c → a ? b : c` for example `!!a ? b : c → a ? b : c`
@@ -605,8 +607,8 @@ If you're using the `X-SourceMap` header instead, you can just omit `sourceMap.u
side effects permitting. side effects permitting.
- `comparisons` (default: `true`) -- apply certain optimizations to binary nodes, - `comparisons` (default: `true`) -- apply certain optimizations to binary nodes,
e.g. `!(a <= b) → a > b` (only when `unsafe_comps`), attempts to negate binary e.g. `!(a <= b) → a > b`, attempts to negate binary nodes, e.g.
nodes, e.g. `a = !b && !c && !d && !e → a=!(b||c||d||e)` etc. `a = !b && !c && !d && !e → a=!(b||c||d||e)` etc.
- `conditionals` (default: `true`) -- apply optimizations for `if`-s and conditional - `conditionals` (default: `true`) -- apply optimizations for `if`-s and conditional
expressions expressions
@@ -730,12 +732,8 @@ If you're using the `X-SourceMap` header instead, you can just omit `sourceMap.u
- `unsafe` (default: `false`) -- apply "unsafe" transformations (discussion below) - `unsafe` (default: `false`) -- apply "unsafe" transformations (discussion below)
- `unsafe_comps` (default: `false`) -- Reverse `<` and `<=` to `>` and `>=` to - `unsafe_comps` (default: `false`) -- compress expressions like `a <= b` assuming
allow improved compression. This might be unsafe when an at least one of two none of the operands can be (coerced to) `NaN`.
operands is an object with computed values due the use of methods like `get`,
or `valueOf`. This could cause change in execution order after operands in the
comparison are switching. Compression only works if both `comparisons` and
`unsafe_comps` are both set to true.
- `unsafe_Function` (default: `false`) -- compress and mangle `Function(args, code)` - `unsafe_Function` (default: `false`) -- compress and mangle `Function(args, code)`
when both `args` and `code` are string literals. when both `args` and `code` are string literals.
@@ -838,8 +836,8 @@ can pass additional arguments that control the code output:
- `indent_start` (default `0`) -- prefix all lines by that many spaces - `indent_start` (default `0`) -- prefix all lines by that many spaces
- `inline_script` (default `false`) -- escape the slash in occurrences of - `inline_script` (default `true`) -- escape HTML comments and the slash in
`</script` in strings occurrences of `</script>` in strings
- `keep_quoted_props` (default `false`) -- when turned on, prevents stripping - `keep_quoted_props` (default `false`) -- when turned on, prevents stripping
quotes from property names in object literals. quotes from property names in object literals.

View File

@@ -48,6 +48,7 @@ function Compressor(options, false_by_default) {
return new Compressor(options, false_by_default); return new Compressor(options, false_by_default);
TreeTransformer.call(this, this.before, this.after); TreeTransformer.call(this, this.before, this.after);
this.options = defaults(options, { this.options = defaults(options, {
arguments : !false_by_default,
booleans : !false_by_default, booleans : !false_by_default,
collapse_vars : !false_by_default, collapse_vars : !false_by_default,
comparisons : !false_by_default, comparisons : !false_by_default,
@@ -516,6 +517,15 @@ merge(Compressor.prototype, {
pop(tw); pop(tw);
return true; return true;
}); });
def(AST_Case, function(tw) {
push(tw);
this.expression.walk(tw);
pop(tw);
push(tw);
walk_body(this, tw);
pop(tw);
return true;
});
def(AST_Conditional, function(tw) { def(AST_Conditional, function(tw) {
this.condition.walk(tw); this.condition.walk(tw);
push(tw); push(tw);
@@ -526,6 +536,12 @@ merge(Compressor.prototype, {
pop(tw); pop(tw);
return true; return true;
}); });
def(AST_Default, function(tw, descend) {
push(tw);
descend();
pop(tw);
return true;
});
def(AST_Defun, function(tw, descend, compressor) { def(AST_Defun, function(tw, descend, compressor) {
this.inlined = false; this.inlined = false;
var save_ids = tw.safe_ids; var save_ids = tw.safe_ids;
@@ -623,12 +639,6 @@ merge(Compressor.prototype, {
pop(tw); pop(tw);
return true; return true;
}); });
def(AST_SwitchBranch, function(tw, descend) {
push(tw);
descend();
pop(tw);
return true;
});
def(AST_SymbolCatch, function() { def(AST_SymbolCatch, function() {
this.definition().fixed = false; this.definition().fixed = false;
}); });
@@ -777,8 +787,7 @@ merge(Compressor.prototype, {
lhs = lhs.fixed_value(); lhs = lhs.fixed_value();
} }
if (!lhs) return true; if (!lhs) return true;
if (lhs instanceof AST_RegExp) return false; if (lhs.is_constant()) return true;
if (lhs instanceof AST_Constant) return true;
return is_lhs_read_only(lhs); return is_lhs_read_only(lhs);
} }
return false; return false;
@@ -890,6 +899,11 @@ merge(Compressor.prototype, {
return x; return x;
}; };
function root_expr(prop) {
while (prop instanceof AST_PropAccess) prop = prop.expression;
return prop;
}
function is_iife_call(node) { function is_iife_call(node) {
if (node.TYPE != "Call") return false; if (node.TYPE != "Call") return false;
return node.expression instanceof AST_Function || is_iife_call(node.expression); return node.expression instanceof AST_Function || is_iife_call(node.expression);
@@ -913,8 +927,8 @@ merge(Compressor.prototype, {
} }
function tighten_body(statements, compressor) { function tighten_body(statements, compressor) {
var scope = compressor.find_parent(AST_Scope); var in_loop, in_try, scope;
var in_loop = is_in_loop(); find_loop_scope_try();
var CHANGED, max_iter = 10; var CHANGED, max_iter = 10;
do { do {
CHANGED = false; CHANGED = false;
@@ -937,12 +951,20 @@ merge(Compressor.prototype, {
} }
} while (CHANGED && max_iter-- > 0); } while (CHANGED && max_iter-- > 0);
function is_in_loop() { function find_loop_scope_try() {
for (var node, level = 0; node = compressor.parent(level); level++) { var node = compressor.self(), level = 0;
if (node instanceof AST_IterationStatement) return true; do {
if (node instanceof AST_Scope) break; if (node instanceof AST_Catch || 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) {
in_try = true;
} }
return false; } while (node = compressor.parent(level++));
} }
// Search from right to left for assignment-like expressions: // Search from right to left for assignment-like expressions:
@@ -957,7 +979,6 @@ merge(Compressor.prototype, {
if (scope.uses_eval || scope.uses_with) return statements; if (scope.uses_eval || scope.uses_with) return statements;
var args; var args;
var candidates = []; var candidates = [];
var in_try = compressor.self() instanceof AST_Try;
var stat_index = statements.length; var stat_index = statements.length;
var scanner = new TreeTransformer(function(node, descend) { var scanner = new TreeTransformer(function(node, descend) {
if (abort) return node; if (abort) return node;
@@ -987,17 +1008,19 @@ merge(Compressor.prototype, {
return node; return node;
} }
// Stop only if candidate is found within conditional branches // Stop only if candidate is found within conditional branches
if (!stop_if_hit && (!lhs_local || !replace_all) if (!stop_if_hit
&& (parent instanceof AST_Binary && lazy_op(parent.operator) && parent.left !== node && (parent instanceof AST_Binary && lazy_op(parent.operator) && parent.left !== node
|| parent instanceof AST_Conditional && parent.condition !== node || parent instanceof AST_Conditional && parent.condition !== node
|| parent instanceof AST_If && parent.condition !== node)) { || parent instanceof AST_If && parent.condition !== node)) {
stop_if_hit = parent; stop_if_hit = parent;
} }
// Replace variable with assignment when found // Replace variable with assignment when found
var hit_lhs, hit_rhs;
if (can_replace if (can_replace
&& !(node instanceof AST_SymbolDeclaration) && !(node instanceof AST_SymbolDeclaration)
&& lhs.equivalent_to(node)) { && (scan_lhs && (hit_lhs = lhs.equivalent_to(node))
if (stop_if_hit) { || scan_rhs && (hit_rhs = rhs.equivalent_to(node)))) {
if (stop_if_hit && (hit_rhs || !lhs_local || !replace_all)) {
abort = true; abort = true;
return node; return node;
} }
@@ -1049,7 +1072,7 @@ merge(Compressor.prototype, {
|| node instanceof AST_PropAccess || node instanceof AST_PropAccess
&& (side_effects || node.expression.may_throw_on_access(compressor)) && (side_effects || node.expression.may_throw_on_access(compressor))
|| node instanceof AST_SymbolRef || node instanceof AST_SymbolRef
&& (lvalues[node.name] || side_effects && may_modify(node)) && (symbol_in_lvalues(node) || side_effects && may_modify(node))
|| node instanceof AST_VarDef && node.value || node instanceof AST_VarDef && node.value
&& (node.name.name in lvalues || side_effects && may_modify(node.name)) && (node.name.name in lvalues || side_effects && may_modify(node.name))
|| (sym = is_lhs(node.left, node)) || (sym = is_lhs(node.left, node))
@@ -1104,12 +1127,15 @@ merge(Compressor.prototype, {
var stop_after = null; var stop_after = null;
var stop_if_hit = null; var stop_if_hit = null;
var lhs = get_lhs(candidate); var lhs = get_lhs(candidate);
if (!lhs || is_lhs_read_only(lhs) || lhs.has_side_effects(compressor)) continue; var rhs = get_rhs(candidate);
var side_effects = lhs && lhs.has_side_effects(compressor);
var scan_lhs = lhs && !side_effects && !is_lhs_read_only(lhs);
var scan_rhs = rhs && foldable(rhs);
if (!scan_lhs && !scan_rhs) continue;
// Locate symbols which may execute code outside of scanning range // Locate symbols which may execute code outside of scanning range
var lvalues = get_lvalues(candidate); var lvalues = get_lvalues(candidate);
var lhs_local = is_lhs_local(lhs); var lhs_local = is_lhs_local(lhs);
if (lhs instanceof AST_SymbolRef) lvalues[lhs.name] = false; if (!side_effects) side_effects = value_has_side_effects(candidate);
var side_effects = value_has_side_effects(candidate);
var replace_all = replace_all_symbols(); var replace_all = replace_all_symbols();
var may_throw = candidate.may_throw(compressor); var may_throw = candidate.may_throw(compressor);
var funarg = candidate.name instanceof AST_SymbolFunarg; var funarg = candidate.name instanceof AST_SymbolFunarg;
@@ -1214,9 +1240,7 @@ merge(Compressor.prototype, {
function extract_candidates(expr) { function extract_candidates(expr) {
hit_stack.push(expr); hit_stack.push(expr);
if (expr instanceof AST_Assign) { if (expr instanceof AST_Assign) {
if (!expr.left.has_side_effects(compressor)) {
candidates.push(hit_stack.slice()); candidates.push(hit_stack.slice());
}
extract_candidates(expr.right); extract_candidates(expr.right);
} else if (expr instanceof AST_Binary) { } else if (expr instanceof AST_Binary) {
extract_candidates(expr.left); extract_candidates(expr.left);
@@ -1354,21 +1378,47 @@ merge(Compressor.prototype, {
} }
} }
function get_rhs(expr) {
if (!(candidate instanceof AST_Assign && candidate.operator == "=")) return;
return candidate.right;
}
function get_rvalue(expr) { function get_rvalue(expr) {
return expr[expr instanceof AST_Assign ? "right" : "value"]; return expr[expr instanceof AST_Assign ? "right" : "value"];
} }
function foldable(expr) {
if (expr.is_constant()) return true;
if (expr instanceof AST_Array) return false;
if (expr instanceof AST_Function) return false;
if (expr instanceof AST_Object) return false;
if (expr instanceof AST_RegExp) return false;
if (expr instanceof AST_Symbol) return true;
if (!(lhs instanceof AST_SymbolRef)) return false;
if (expr.has_side_effects(compressor)) return false;
var circular;
var def = lhs.definition();
expr.walk(new TreeWalker(function(node) {
if (circular) return true;
if (node instanceof AST_SymbolRef && node.definition() === def) {
circular = true;
}
}));
return !circular;
}
function get_lvalues(expr) { function get_lvalues(expr) {
var lvalues = Object.create(null); var lvalues = Object.create(null);
if (expr instanceof AST_Unary) return lvalues; if (candidate instanceof AST_VarDef) {
var tw = new TreeWalker(function(node, descend) { lvalues[candidate.name.name] = lhs;
var sym = node; }
while (sym instanceof AST_PropAccess) sym = sym.expression; var tw = new TreeWalker(function(node) {
var sym = root_expr(node);
if (sym instanceof AST_SymbolRef || sym instanceof AST_This) { if (sym instanceof AST_SymbolRef || sym instanceof AST_This) {
lvalues[sym.name] = lvalues[sym.name] || is_lhs(node, tw.parent()); lvalues[sym.name] = lvalues[sym.name] || is_lhs(node, tw.parent());
} }
}); });
get_rvalue(expr).walk(tw); expr.walk(tw);
return lvalues; return lvalues;
} }
@@ -1401,11 +1451,11 @@ merge(Compressor.prototype, {
} }
function is_lhs_local(lhs) { function is_lhs_local(lhs) {
while (lhs instanceof AST_PropAccess) lhs = lhs.expression; var sym = root_expr(lhs);
return lhs instanceof AST_SymbolRef return sym instanceof AST_SymbolRef
&& lhs.definition().scope === scope && sym.definition().scope === scope
&& !(in_loop && !(in_loop
&& (lhs.name in lvalues && (sym.name in lvalues && lvalues[sym.name] !== lhs
|| candidate instanceof AST_Unary || candidate instanceof AST_Unary
|| candidate instanceof AST_Assign && candidate.operator != "=")); || candidate instanceof AST_Assign && candidate.operator != "="));
} }
@@ -1427,12 +1477,22 @@ merge(Compressor.prototype, {
return false; return false;
} }
function symbol_in_lvalues(sym) {
var lvalue = lvalues[sym.name];
if (!lvalue) return;
if (lvalue !== lhs) return true;
scan_rhs = false;
}
function may_modify(sym) { function may_modify(sym) {
var def = sym.definition(); var def = sym.definition();
if (def.orig.length == 1 && def.orig[0] instanceof AST_SymbolDefun) return false; if (def.orig.length == 1 && def.orig[0] instanceof AST_SymbolDefun) return false;
if (def.scope !== scope) return true; if (def.scope !== scope) return true;
return !all(def.references, function(ref) { return !all(def.references, function(ref) {
return ref.scope === scope; var s = ref.scope;
// "block" scope within AST_Catch
if (s.TYPE == "Scope") s = s.parent_scope;
return s === scope;
}); });
} }
@@ -2314,7 +2374,11 @@ merge(Compressor.prototype, {
// descendant of AST_Node. // descendant of AST_Node.
AST_Node.DEFMETHOD("evaluate", function(compressor){ AST_Node.DEFMETHOD("evaluate", function(compressor){
if (!compressor.option("evaluate")) return this; if (!compressor.option("evaluate")) return this;
var val = this._eval(compressor, 1); var cached = [];
var val = this._eval(compressor, cached, 1);
cached.forEach(function(node) {
delete node._eval;
});
if (!val || val instanceof RegExp) return val; if (!val || val instanceof RegExp) return val;
if (typeof val == "function" || typeof val == "object") return this; if (typeof val == "function" || typeof val == "object") return this;
return val; return val;
@@ -2350,12 +2414,12 @@ merge(Compressor.prototype, {
} }
return this; return this;
}); });
def(AST_Array, function(compressor, depth) { def(AST_Array, function(compressor, cached, depth) {
if (compressor.option("unsafe")) { if (compressor.option("unsafe")) {
var elements = []; var elements = [];
for (var i = 0, len = this.elements.length; i < len; i++) { for (var i = 0, len = this.elements.length; i < len; i++) {
var element = this.elements[i]; var element = this.elements[i];
var value = element._eval(compressor, depth); var value = element._eval(compressor, cached, depth);
if (element === value) return this; if (element === value) return this;
elements.push(value); elements.push(value);
} }
@@ -2363,7 +2427,7 @@ merge(Compressor.prototype, {
} }
return this; return this;
}); });
def(AST_Object, function(compressor, depth) { def(AST_Object, function(compressor, cached, depth) {
if (compressor.option("unsafe")) { if (compressor.option("unsafe")) {
var val = {}; var val = {};
for (var i = 0, len = this.properties.length; i < len; i++) { for (var i = 0, len = this.properties.length; i < len; i++) {
@@ -2372,14 +2436,14 @@ merge(Compressor.prototype, {
if (key instanceof AST_Symbol) { if (key instanceof AST_Symbol) {
key = key.name; key = key.name;
} else if (key instanceof AST_Node) { } else if (key instanceof AST_Node) {
key = key._eval(compressor, depth); key = key._eval(compressor, cached, depth);
if (key === prop.key) return this; if (key === prop.key) return this;
} }
if (typeof Object.prototype[key] === 'function') { if (typeof Object.prototype[key] === 'function') {
return this; return this;
} }
if (prop.value instanceof AST_Function) continue; if (prop.value instanceof AST_Function) continue;
val[key] = prop.value._eval(compressor, depth); val[key] = prop.value._eval(compressor, cached, depth);
if (val[key] === prop.value) return this; if (val[key] === prop.value) return this;
} }
return val; return val;
@@ -2387,7 +2451,7 @@ merge(Compressor.prototype, {
return this; return this;
}); });
var non_converting_unary = makePredicate("! typeof void"); var non_converting_unary = makePredicate("! typeof void");
def(AST_UnaryPrefix, function(compressor, depth) { def(AST_UnaryPrefix, function(compressor, cached, depth) {
var e = this.expression; var e = this.expression;
// Function would be evaluated to an array and so typeof would // Function would be evaluated to an array and so typeof would
// incorrectly return 'object'. Hence making is a special case. // incorrectly return 'object'. Hence making is a special case.
@@ -2399,7 +2463,7 @@ merge(Compressor.prototype, {
return typeof function(){}; return typeof function(){};
} }
if (!non_converting_unary(this.operator)) depth++; if (!non_converting_unary(this.operator)) depth++;
e = e._eval(compressor, depth); e = e._eval(compressor, cached, depth);
if (e === this.expression) return this; if (e === this.expression) return this;
switch (this.operator) { switch (this.operator) {
case "!": return !e; case "!": return !e;
@@ -2416,11 +2480,11 @@ merge(Compressor.prototype, {
return this; return this;
}); });
var non_converting_binary = makePredicate("&& || === !=="); var non_converting_binary = makePredicate("&& || === !==");
def(AST_Binary, function(compressor, depth) { def(AST_Binary, function(compressor, cached, depth) {
if (!non_converting_binary(this.operator)) depth++; if (!non_converting_binary(this.operator)) depth++;
var left = this.left._eval(compressor, depth); var left = this.left._eval(compressor, cached, depth);
if (left === this.left) return this; if (left === this.left) return this;
var right = this.right._eval(compressor, depth); var right = this.right._eval(compressor, cached, depth);
if (right === this.right) return this; if (right === this.right) return this;
var result; var result;
switch (this.operator) { switch (this.operator) {
@@ -2454,27 +2518,28 @@ merge(Compressor.prototype, {
} }
return result; return result;
}); });
def(AST_Conditional, function(compressor, depth) { def(AST_Conditional, function(compressor, cached, depth) {
var condition = this.condition._eval(compressor, depth); var condition = this.condition._eval(compressor, cached, depth);
if (condition === this.condition) return this; if (condition === this.condition) return this;
var node = condition ? this.consequent : this.alternative; var node = condition ? this.consequent : this.alternative;
var value = node._eval(compressor, depth); var value = node._eval(compressor, cached, depth);
return value === node ? this : value; return value === node ? this : value;
}); });
def(AST_SymbolRef, function(compressor, depth) { def(AST_SymbolRef, function(compressor, cached, depth) {
var fixed = this.fixed_value(); var fixed = this.fixed_value();
if (!fixed) return this; if (!fixed) return this;
var value; var value;
if (HOP(fixed, "_eval")) { if (cached.indexOf(fixed) >= 0) {
value = fixed._eval(); value = fixed._eval();
} else { } else {
this._eval = return_this; this._eval = return_this;
value = fixed._eval(compressor, depth); value = fixed._eval(compressor, cached, depth);
delete this._eval; delete this._eval;
if (value === fixed) return this; if (value === fixed) return this;
fixed._eval = function() { fixed._eval = function() {
return value; return value;
}; };
cached.push(fixed);
} }
if (value && typeof value == "object") { if (value && typeof value == "object") {
var escaped = this.definition().escaped; var escaped = this.definition().escaped;
@@ -2509,11 +2574,11 @@ merge(Compressor.prototype, {
], ],
}; };
convert_to_predicate(static_values); convert_to_predicate(static_values);
def(AST_PropAccess, function(compressor, depth) { def(AST_PropAccess, function(compressor, cached, depth) {
if (compressor.option("unsafe")) { if (compressor.option("unsafe")) {
var key = this.property; var key = this.property;
if (key instanceof AST_Node) { if (key instanceof AST_Node) {
key = key._eval(compressor, depth); key = key._eval(compressor, cached, depth);
if (key === this.property) return this; if (key === this.property) return this;
} }
var exp = this.expression; var exp = this.expression;
@@ -2522,7 +2587,7 @@ merge(Compressor.prototype, {
if (!(static_values[exp.name] || return_false)(key)) return this; if (!(static_values[exp.name] || return_false)(key)) return this;
val = global_objs[exp.name]; val = global_objs[exp.name];
} else { } else {
val = exp._eval(compressor, depth + 1); val = exp._eval(compressor, cached, depth + 1);
if (!val || val === exp || !HOP(val, key)) return this; if (!val || val === exp || !HOP(val, key)) return this;
if (typeof val == "function") switch (key) { if (typeof val == "function") switch (key) {
case "name": case "name":
@@ -2537,12 +2602,12 @@ merge(Compressor.prototype, {
} }
return this; return this;
}); });
def(AST_Call, function(compressor, depth) { def(AST_Call, function(compressor, cached, depth) {
var exp = this.expression; var exp = this.expression;
if (compressor.option("unsafe") && exp instanceof AST_PropAccess) { if (compressor.option("unsafe") && exp instanceof AST_PropAccess) {
var key = exp.property; var key = exp.property;
if (key instanceof AST_Node) { if (key instanceof AST_Node) {
key = key._eval(compressor, depth); key = key._eval(compressor, cached, depth);
if (key === exp.property) return this; if (key === exp.property) return this;
} }
var val; var val;
@@ -2551,13 +2616,13 @@ merge(Compressor.prototype, {
if (!(static_fns[e.name] || return_false)(key)) return this; if (!(static_fns[e.name] || return_false)(key)) return this;
val = global_objs[e.name]; val = global_objs[e.name];
} else { } else {
val = e._eval(compressor, depth + 1); val = e._eval(compressor, cached, depth + 1);
if (val === e || !(val && native_fns[val.constructor.name] || return_false)(key)) return this; if (val === e || !(val && native_fns[val.constructor.name] || return_false)(key)) return this;
} }
var args = []; var args = [];
for (var i = 0, len = this.args.length; i < len; i++) { for (var i = 0, len = this.args.length; i < len; i++) {
var arg = this.args[i]; var arg = this.args[i];
var value = arg._eval(compressor, depth); var value = arg._eval(compressor, cached, depth);
if (arg === value) return this; if (arg === value) return this;
args.push(value); args.push(value);
} }
@@ -3014,6 +3079,16 @@ merge(Compressor.prototype, {
return self; return self;
}); });
OPT(AST_Lambda, function(self, compressor){
tighten_body(self.body, compressor);
if (compressor.option("side_effects")
&& self.body.length == 1
&& self.body[0] === compressor.has_directive("use strict")) {
self.body.length = 0;
}
return self;
});
AST_Scope.DEFMETHOD("drop_unused", function(compressor){ AST_Scope.DEFMETHOD("drop_unused", function(compressor){
if (!compressor.option("unused")) return; if (!compressor.option("unused")) return;
if (compressor.has_directive("use asm")) return; if (compressor.has_directive("use asm")) return;
@@ -3039,6 +3114,8 @@ merge(Compressor.prototype, {
var in_use = []; var in_use = [];
var in_use_ids = Object.create(null); // avoid expensive linear scans of in_use var in_use_ids = Object.create(null); // avoid expensive linear scans of in_use
var fixed_ids = Object.create(null); var fixed_ids = Object.create(null);
var value_read = Object.create(null);
var value_modified = Object.create(null);
if (self instanceof AST_Toplevel && compressor.top_retain) { if (self instanceof AST_Toplevel && compressor.top_retain) {
self.variables.each(function(def) { self.variables.each(function(def) {
if (compressor.top_retain(def) && !(def.id in in_use_ids)) { if (compressor.top_retain(def) && !(def.id in in_use_ids)) {
@@ -3306,6 +3383,17 @@ merge(Compressor.prototype, {
); );
self.transform(tt); self.transform(tt);
function verify_safe_usage(def, read, modified) {
if (def.id in in_use_ids) return;
if (read && modified) {
in_use_ids[def.id] = true;
in_use.push(def);
} else {
value_read[def.id] = read;
value_modified[def.id] = modified;
}
}
function scan_ref_scoped(node, descend) { function scan_ref_scoped(node, descend) {
var node_def, props = [], sym = assign_as_unused(node, props); var node_def, props = [], sym = assign_as_unused(node, props);
if (sym instanceof AST_SymbolRef if (sym instanceof AST_SymbolRef
@@ -3315,9 +3403,19 @@ merge(Compressor.prototype, {
}); });
if (node instanceof AST_Assign) { if (node instanceof AST_Assign) {
node.right.walk(tw); node.right.walk(tw);
if (node.left === sym && !node_def.chained && sym.fixed_value() === node.right) { if (node.left === sym) {
if (!node_def.chained && sym.fixed_value() === node.right) {
fixed_ids[node_def.id] = node; fixed_ids[node_def.id] = node;
} }
if (!node.write_only) {
verify_safe_usage(node_def, true, 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);
}
}
} }
return true; return true;
} }
@@ -3485,7 +3583,7 @@ merge(Compressor.prototype, {
AST_Scope.DEFMETHOD("make_var_name", function(prefix) { AST_Scope.DEFMETHOD("make_var_name", function(prefix) {
var var_names = this.var_names(); var var_names = this.var_names();
prefix = prefix.replace(/[^a-z_$]+/ig, "_"); prefix = prefix.replace(/(?:^[^a-z_$]|[^a-z0-9_$])/ig, "_");
var name = prefix; var name = prefix;
for (var i = 0; var_names[name]; i++) name = prefix + "$" + i; for (var i = 0; var_names[name]; i++) name = prefix + "$" + i;
var_names[name] = true; var_names[name] = true;
@@ -3583,7 +3681,15 @@ merge(Compressor.prototype, {
if (this.expression instanceof AST_Function if (this.expression instanceof AST_Function
&& (!this.expression.name || !this.expression.name.definition().references.length)) { && (!this.expression.name || !this.expression.name.definition().references.length)) {
var node = this.clone(); var node = this.clone();
node.expression.process_expression(false, compressor); var exp = node.expression;
exp.process_expression(false, compressor);
exp.walk(new TreeWalker(function(node) {
if (node instanceof AST_Return && node.value) {
node.value = node.value.drop_side_effect_free(compressor);
return true;
}
if (node instanceof AST_Scope && node !== exp) return true;
}));
return node; return node;
} }
return this; return this;
@@ -3619,10 +3725,7 @@ merge(Compressor.prototype, {
return this; return this;
} }
this.write_only = true; this.write_only = true;
while (left instanceof AST_PropAccess) { if (root_expr(left).is_constant_expression(compressor.find_parent(AST_Scope))) {
left = left.expression;
}
if (left.is_constant_expression(compressor.find_parent(AST_Scope))) {
return this.right.drop_side_effect_free(compressor); return this.right.drop_side_effect_free(compressor);
} }
return this; return this;
@@ -4404,7 +4507,6 @@ merge(Compressor.prototype, {
var comp = new Compressor(compressor.options); var comp = new Compressor(compressor.options);
ast = ast.transform(comp); ast = ast.transform(comp);
ast.figure_out_scope(mangle); ast.figure_out_scope(mangle);
base54.reset();
ast.compute_char_frequency(mangle); ast.compute_char_frequency(mangle);
ast.mangle_names(mangle); ast.mangle_names(mangle);
var fun; var fun;
@@ -4976,11 +5078,9 @@ merge(Compressor.prototype, {
}); });
self = best_of(compressor, self, negated); self = best_of(compressor, self, negated);
} }
if (compressor.option("unsafe_comps")) {
switch (self.operator) { switch (self.operator) {
case "<": reverse(">"); break; case ">": reverse("<"); break;
case "<=": reverse(">="); break; case ">=": reverse("<="); break;
}
} }
} }
if (self.operator == "+") { if (self.operator == "+") {
@@ -5664,6 +5764,18 @@ merge(Compressor.prototype, {
consequent consequent
]).optimize(compressor); ]).optimize(compressor);
} }
// x ? (y, w) : (z, w) --> x ? y : z, w
if ((consequent instanceof AST_Sequence || alternative instanceof AST_Sequence)
&& consequent.tail_node().equivalent_to(alternative.tail_node())) {
return make_sequence(self, [
make_node(AST_Conditional, self, {
condition: self.condition,
consequent: pop_seq(consequent),
alternative: pop_seq(alternative)
}),
consequent.tail_node()
]).optimize(compressor);
}
// x ? y || z : z --> x && y || z // x ? y || z : z --> x && y || z
if (consequent instanceof AST_Binary if (consequent instanceof AST_Binary
&& consequent.operator == "||" && consequent.operator == "||"
@@ -5766,6 +5878,13 @@ merge(Compressor.prototype, {
} }
} }
} }
function pop_seq(node) {
if (!(node instanceof AST_Sequence)) return make_node(AST_Number, node, {
value: 0
});
return make_sequence(node, node.expressions.slice(0, -1));
}
}); });
OPT(AST_Boolean, function(self, compressor){ OPT(AST_Boolean, function(self, compressor){
@@ -5867,6 +5986,31 @@ merge(Compressor.prototype, {
}); });
} }
} }
var fn;
if (compressor.option("arguments")
&& expr instanceof AST_SymbolRef
&& expr.name == "arguments"
&& expr.definition().orig.length == 1
&& (fn = expr.scope) instanceof AST_Lambda
&& prop instanceof AST_Number) {
var index = prop.getValue();
var argname = fn.argnames[index];
if (!argname && !compressor.option("keep_fargs")) {
while (index >= fn.argnames.length) {
argname = make_node(AST_SymbolFunarg, fn, {
name: fn.make_var_name("argument_" + fn.argnames.length),
scope: fn
});
fn.argnames.push(argname);
fn.enclosed.push(fn.def_variable(argname));
}
}
if (argname) {
var sym = make_node(AST_SymbolRef, self, argname);
sym.reference({});
return sym;
}
}
var ev = self.evaluate(compressor); var ev = self.evaluate(compressor);
if (ev !== self) { if (ev !== self) {
ev = make_node_from_constant(ev, self).optimize(compressor); ev = make_node_from_constant(ev, self).optimize(compressor);

View File

@@ -150,7 +150,6 @@ function minify(files, options) {
if (options.mangle) toplevel.figure_out_scope(options.mangle); if (options.mangle) toplevel.figure_out_scope(options.mangle);
if (timings) timings.mangle = Date.now(); if (timings) timings.mangle = Date.now();
if (options.mangle) { if (options.mangle) {
base54.reset();
toplevel.compute_char_frequency(options.mangle); toplevel.compute_char_frequency(options.mangle);
toplevel.mangle_names(options.mangle); toplevel.mangle_names(options.mangle);
} }

View File

@@ -178,7 +178,7 @@ function OutputStream(options) {
function encode_string(str, quote) { function encode_string(str, quote) {
var ret = make_string(str, quote); var ret = make_string(str, quote);
if (options.inline_script) { if (options.inline_script) {
ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1"); ret = ret.replace(/<\x2f(script)([>\/\t\n\f\r ])/gi, "<\\/$1$2");
ret = ret.replace(/\x3c!--/g, "\\x3c!--"); ret = ret.replace(/\x3c!--/g, "\\x3c!--");
ret = ret.replace(/--\x3e/g, "--\\x3e"); ret = ret.replace(/--\x3e/g, "--\\x3e");
} }
@@ -576,6 +576,7 @@ function OutputStream(options) {
indentation : function() { return indentation }, indentation : function() { return indentation },
current_width : function() { return current_col - indentation }, current_width : function() { return current_col - indentation },
should_break : function() { return options.width && this.current_width() >= options.width }, should_break : function() { return options.width && this.current_width() >= options.width },
has_parens : function() { return OUTPUT.slice(-1) == "(" },
newline : newline, newline : newline,
print : print, print : print,
space : space, space : space,
@@ -683,7 +684,7 @@ function OutputStream(options) {
// a function expression needs parens around it when it's provably // a function expression needs parens around it when it's provably
// the first token to appear in a statement. // the first token to appear in a statement.
PARENS(AST_Function, function(output){ PARENS(AST_Function, function(output){
if (first_in_statement(output)) { if (!output.has_parens() && first_in_statement(output)) {
return true; return true;
} }
@@ -704,7 +705,9 @@ function OutputStream(options) {
// same goes for an object literal, because otherwise it would be // same goes for an object literal, because otherwise it would be
// interpreted as a block of code. // interpreted as a block of code.
PARENS(AST_Object, first_in_statement); PARENS(AST_Object, function(output){
return !output.has_parens() && first_in_statement(output);
});
PARENS(AST_Unary, function(output){ PARENS(AST_Unary, function(output){
var p = output.parent(); var p = output.parent();
@@ -883,18 +886,19 @@ function OutputStream(options) {
self.body.print(output); self.body.print(output);
output.semicolon(); output.semicolon();
}); });
function print_bracketed(self, output, allow_directives) { function print_bracketed_empty(self, output) {
if (self.body.length > 0) {
output.with_block(function() {
display_body(self.body, false, output, allow_directives);
});
} else {
output.print("{"); output.print("{");
output.with_indent(output.next_indent(), function() { output.with_indent(output.next_indent(), function() {
output.append_comments(self, true); output.append_comments(self, true);
}); });
output.print("}"); output.print("}");
} }
function print_bracketed(self, output, allow_directives) {
if (self.body.length > 0) {
output.with_block(function() {
display_body(self.body, false, output, allow_directives);
});
} else print_bracketed_empty(self, output);
}; };
DEFPRINT(AST_BlockStatement, function(self, output){ DEFPRINT(AST_BlockStatement, function(self, output){
print_bracketed(self, output); print_bracketed(self, output);
@@ -1089,7 +1093,7 @@ function OutputStream(options) {
}); });
output.space(); output.space();
var last = self.body.length - 1; var last = self.body.length - 1;
if (last < 0) output.print("{}"); if (last < 0) print_bracketed_empty(self, output);
else output.with_block(function(){ else output.with_block(function(){
self.body.forEach(function(branch, i){ self.body.forEach(function(branch, i){
output.indent(true); output.indent(true);
@@ -1344,7 +1348,7 @@ function OutputStream(options) {
}); });
output.newline(); output.newline();
}); });
else output.print("{}"); else print_bracketed_empty(self, output);
}); });
function print_property_name(key, quote, output) { function print_property_name(key, quote, output) {

View File

@@ -74,17 +74,13 @@ SymbolDef.prototype = {
var cache = options.cache && options.cache.props; var cache = options.cache && options.cache.props;
if (this.global && cache && cache.has(this.name)) { if (this.global && cache && cache.has(this.name)) {
this.mangled_name = cache.get(this.name); this.mangled_name = cache.get(this.name);
} } else if (!this.mangled_name && !this.unmangleable(options)) {
else if (!this.mangled_name && !this.unmangleable(options)) {
var s = this.scope;
var sym = this.orig[0];
if (options.ie8 && sym instanceof AST_SymbolLambda)
s = s.parent_scope;
var def; var def;
if (def = this.redefined()) { if (def = this.redefined()) {
this.mangled_name = def.mangled_name || def.name; this.mangled_name = def.mangled_name || def.name;
} else } else {
this.mangled_name = s.next_mangled(options, this); this.mangled_name = next_mangled_name(this.scope, options, this);
}
if (this.global && cache) { if (this.global && cache) {
cache.set(this.name, this.mangled_name); cache.set(this.name, this.mangled_name);
} }
@@ -168,8 +164,8 @@ AST_Toplevel.DEFMETHOD("figure_out_scope", function(options){
var def = scope.find_variable(node); var def = scope.find_variable(node);
if (node.thedef !== def) { if (node.thedef !== def) {
node.thedef = def; node.thedef = def;
node.reference(options);
} }
node.reference(options);
} }
} }
else if (node instanceof AST_SymbolCatch) { else if (node instanceof AST_SymbolCatch) {
@@ -325,56 +321,62 @@ AST_Scope.DEFMETHOD("def_variable", function(symbol, init){
return symbol.thedef = def; return symbol.thedef = def;
}); });
function next_mangled(scope, options) { function names_in_use(scope, options) {
var ext = scope.enclosed; var names = scope.names_in_use;
out: while (true) { if (!names) {
var m = base54(++scope.cname); scope.names_in_use = names = Object.create(scope.mangled_names || null);
if (!is_identifier(m)) continue; // skip over "do" scope.cname_holes = [];
scope.enclosed.forEach(function(def) {
// https://github.com/mishoo/UglifyJS2/issues/242 -- do not if (def.unmangleable(options)) names[def.name] = true;
// shadow a name reserved from mangling.
if (member(m, options.reserved)) continue;
// we must ensure that the mangled name does not shadow a name
// from some parent scope that is referenced in this or in
// inner scopes.
for (var i = ext.length; --i >= 0;) {
var sym = ext[i];
var name = sym.mangled_name || (sym.unmangleable(options) && sym.name);
if (m == name) continue out;
}
return m;
}
}
AST_Scope.DEFMETHOD("next_mangled", function(options){
return next_mangled(this, options);
}); });
}
return names;
}
AST_Toplevel.DEFMETHOD("next_mangled", function(options){ function next_mangled_name(scope, options, def) {
var name; var in_use = names_in_use(scope, options);
do { var holes = scope.cname_holes;
name = next_mangled(this, options); var names = Object.create(null);
} while (member(name, this.mangled_names));
return name;
});
AST_Function.DEFMETHOD("next_mangled", function(options, def){
// #179, #326 // #179, #326
// in Safari strict mode, something like (function x(x){...}) is a syntax error; // in Safari strict mode, something like (function x(x){...}) is a syntax error;
// a function expression's argument cannot shadow the function expression's name // a function expression's argument cannot shadow the function expression's name
if (scope instanceof AST_Function && scope.name && def.orig[0] instanceof AST_SymbolFunarg) {
var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition(); var tricky_def = scope.name.definition();
// the function's mangled_name is null when keep_fnames is true // the function's mangled_name is null when keep_fnames is true
var tricky_name = tricky_def ? tricky_def.mangled_name || tricky_def.name : null; names[tricky_def.mangled_name || tricky_def.name] = true;
}
while (true) { var scopes = [ scope ];
var name = next_mangled(this, options); def.references.forEach(function(sym) {
if (!tricky_name || tricky_name != name) var scope = sym.scope;
do {
if (scopes.indexOf(scope) < 0) {
for (var name in names_in_use(scope, options)) {
names[name] = true;
}
scopes.push(scope);
} else break;
} while (scope = scope.parent_scope);
});
var name;
for (var i = 0, len = holes.length; i < len; i++) {
name = base54(holes[i]);
if (names[name]) continue;
holes.splice(i, 1);
scope.names_in_use[name] = true;
return name;
}
while (true) {
name = base54(++scope.cname);
if (in_use[name] || !is_identifier(name) || member(name, options.reserved)) continue;
if (!names[name]) break;
holes.push(scope.cname);
}
scope.names_in_use[name] = true;
if (options.ie8 && def.orig[0] instanceof AST_SymbolLambda) {
names_in_use(scope.parent_scope, options)[name] = true;
}
return name; return name;
} }
});
AST_Symbol.DEFMETHOD("unmangleable", function(options){ AST_Symbol.DEFMETHOD("unmangleable", function(options){
var def = this.definition(); var def = this.definition();
@@ -397,7 +399,7 @@ AST_Symbol.DEFMETHOD("global", function(){
return this.definition().global; return this.definition().global;
}); });
AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options) { function _default_mangler_options(options) {
options = defaults(options, { options = defaults(options, {
eval : false, eval : false,
ie8 : false, ie8 : false,
@@ -409,28 +411,25 @@ AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options) {
// Never mangle arguments // Never mangle arguments
push_uniq(options.reserved, "arguments"); push_uniq(options.reserved, "arguments");
return options; return options;
}); }
AST_Toplevel.DEFMETHOD("mangle_names", function(options){ AST_Toplevel.DEFMETHOD("mangle_names", function(options){
options = this._default_mangler_options(options); options = _default_mangler_options(options);
// We only need to mangle declaration nodes. Special logic wired // We only need to mangle declaration nodes. Special logic wired
// into the code generator will display the mangled name if it's // into the code generator will display the mangled name if it's
// present (and for AST_SymbolRef-s it'll use the mangled name of // present (and for AST_SymbolRef-s it'll use the mangled name of
// the AST_SymbolDeclaration that it points to). // the AST_SymbolDeclaration that it points to).
var lname = -1; var lname = -1;
var to_mangle = [];
var mangled_names = this.mangled_names = []; if (options.cache && options.cache.props) {
if (options.cache) { var mangled_names = this.mangled_names = Object.create(null);
this.globals.each(collect);
if (options.cache.props) {
options.cache.props.each(function(mangled_name) { options.cache.props.each(function(mangled_name) {
push_uniq(mangled_names, mangled_name); mangled_names[mangled_name] = true;
}); });
} }
}
var redefined = [];
var tw = new TreeWalker(function(node, descend){ var tw = new TreeWalker(function(node, descend){
if (node instanceof AST_LabeledStatement) { if (node instanceof AST_LabeledStatement) {
// lname is incremented when we get to the AST_Label // lname is incremented when we get to the AST_Label
@@ -440,8 +439,12 @@ AST_Toplevel.DEFMETHOD("mangle_names", function(options){
return true; // don't descend again in TreeWalker return true; // don't descend again in TreeWalker
} }
if (node instanceof AST_Scope) { if (node instanceof AST_Scope) {
node.variables.each(collect); descend();
return; if (options.cache && node instanceof AST_Toplevel) {
node.globals.each(mangle);
}
node.variables.each(mangle);
return true;
} }
if (node instanceof AST_Label) { if (node instanceof AST_Label) {
var name; var name;
@@ -449,17 +452,28 @@ AST_Toplevel.DEFMETHOD("mangle_names", function(options){
node.mangled_name = name; node.mangled_name = name;
return true; return true;
} }
if (!options.ie8 && node instanceof AST_SymbolCatch) { if (!options.ie8 && node instanceof AST_Catch) {
to_mangle.push(node.definition()); var def = node.argname.definition();
return; var redef = def.redefined();
if (redef) {
redefined.push(def);
def.references.forEach(function(ref) {
ref.thedef = redef;
ref.reference(options);
ref.thedef = def;
});
}
descend();
if (!redef) mangle(def);
return true;
} }
}); });
this.walk(tw); this.walk(tw);
to_mangle.forEach(function(def){ def.mangle(options) }); redefined.forEach(mangle);
function collect(symbol) { function mangle(def) {
if (!member(symbol.name, options.reserved)) { if (!member(def.name, options.reserved)) {
to_mangle.push(symbol); def.mangle(options);
} }
} }
}); });
@@ -490,7 +504,7 @@ AST_Toplevel.DEFMETHOD("find_colliding_names", function(options) {
AST_Toplevel.DEFMETHOD("expand_names", function(options) { AST_Toplevel.DEFMETHOD("expand_names", function(options) {
base54.reset(); base54.reset();
base54.sort(); base54.sort();
options = this._default_mangler_options(options); options = _default_mangler_options(options);
var avoid = this.find_colliding_names(options); var avoid = this.find_colliding_names(options);
var cname = 0; var cname = 0;
this.globals.each(rename); this.globals.each(rename);
@@ -528,7 +542,8 @@ AST_Sequence.DEFMETHOD("tail_node", function() {
}); });
AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options){ AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options){
options = this._default_mangler_options(options); options = _default_mangler_options(options);
base54.reset();
try { try {
AST_Node.prototype.print = function(stream, force_parens) { AST_Node.prototype.print = function(stream, force_parens) {
this._print(stream, force_parens); this._print(stream, force_parens);

View File

@@ -1,10 +1,9 @@
{ {
"name": "uglify-js", "name": "uglify-js",
"description": "JavaScript parser, mangler/compressor and beautifier toolkit", "description": "JavaScript parser, mangler/compressor and beautifier toolkit",
"homepage": "http://lisperator.net/uglifyjs",
"author": "Mihai Bazon <mihai.bazon@gmail.com> (http://lisperator.net/)", "author": "Mihai Bazon <mihai.bazon@gmail.com> (http://lisperator.net/)",
"license": "BSD-2-Clause", "license": "BSD-2-Clause",
"version": "3.3.12", "version": "3.3.15",
"engines": { "engines": {
"node": ">=0.8.0" "node": ">=0.8.0"
}, },
@@ -24,16 +23,39 @@
"LICENSE" "LICENSE"
], ],
"dependencies": { "dependencies": {
"commander": "~2.14.1", "commander": "~2.15.0",
"source-map": "~0.6.1" "source-map": "~0.6.1"
}, },
"devDependencies": { "devDependencies": {
"acorn": "~5.4.1", "acorn": "~5.5.3",
"mocha": "~3.5.1", "mocha": "~3.5.1",
"semver": "~5.5.0" "semver": "~5.5.0"
}, },
"scripts": { "scripts": {
"test": "node test/run-tests.js" "test": "node test/run-tests.js"
}, },
"keywords": ["uglify", "uglify-js", "minify", "minifier", "es5"] "keywords": [
"cli",
"compress",
"compressor",
"ecma",
"ecmascript",
"es",
"es5",
"javascript",
"js",
"jsmin",
"min",
"minification",
"minifier",
"minify",
"optimize",
"optimizer",
"pack",
"packer",
"parse",
"parser",
"uglifier",
"uglify"
]
} }

View File

@@ -28,6 +28,7 @@ var remaining = 2 * urls.length;
function done() { function done() {
if (!--remaining) { if (!--remaining) {
var failures = []; var failures = [];
var sum = { input: 0, output: 0, gzip: 0 };
urls.forEach(function(url) { urls.forEach(function(url) {
var info = results[url]; var info = results[url];
console.log(); console.log();
@@ -40,6 +41,9 @@ function done() {
if (info.code) { if (info.code) {
failures.push(url); failures.push(url);
} }
sum.input += info.input;
sum.output += info.output;
sum.gzip += info.gzip;
}); });
if (failures.length) { if (failures.length) {
console.error("Benchmark failed:"); console.error("Benchmark failed:");
@@ -47,6 +51,13 @@ function done() {
console.error(url); console.error(url);
}); });
process.exit(1); process.exit(1);
} else {
console.log();
console.log("Subtotal");
console.log();
console.log("Original:", sum.input, "bytes");
console.log("Uglified:", sum.output, "bytes");
console.log("GZipped: ", sum.gzip, "bytes");
} }
} }
} }

119
test/compress/arguments.js Normal file
View File

@@ -0,0 +1,119 @@
replace_index: {
options = {
arguments: true,
evaluate: true,
properties: true,
}
input: {
console.log(arguments && arguments[0]);
(function() {
console.log(arguments[1], arguments["1"], arguments["foo"]);
})("bar", 42);
(function(a, b) {
console.log(arguments[1], arguments["1"], arguments["foo"]);
})("bar", 42);
(function(arguments) {
console.log(arguments[1], arguments["1"], arguments["foo"]);
})("bar", 42);
(function() {
var arguments;
console.log(arguments[1], arguments["1"], arguments["foo"]);
})("bar", 42);
}
expect: {
console.log(arguments && arguments[0]);
(function() {
console.log(arguments[1], arguments[1], arguments.foo);
})("bar", 42);
(function(a, b) {
console.log(b, b, arguments.foo);
})("bar", 42);
(function(arguments) {
console.log(arguments[1], arguments[1], arguments.foo);
})("bar", 42);
(function() {
var arguments;
console.log(arguments[1], arguments[1], arguments.foo);
})("bar", 42);
}
expect_stdout: [
"undefined",
"42 42 undefined",
"42 42 undefined",
"a a undefined",
"42 42 undefined",
]
}
replace_index_keep_fargs: {
options = {
arguments: true,
evaluate: true,
keep_fargs: false,
properties: true,
}
input: {
console.log(arguments && arguments[0]);
(function() {
console.log(arguments[1], arguments["1"], arguments["foo"]);
})("bar", 42);
(function(a, b) {
console.log(arguments[1], arguments["1"], arguments["foo"]);
})("bar", 42);
(function(arguments) {
console.log(arguments[1], arguments["1"], arguments["foo"]);
})("bar", 42);
(function() {
var arguments;
console.log(arguments[1], arguments["1"], arguments["foo"]);
})("bar", 42);
}
expect: {
console.log(arguments && arguments[0]);
(function(argument_0, argument_1) {
console.log(argument_1, argument_1, arguments.foo);
})("bar", 42);
(function(a, b) {
console.log(b, b, arguments.foo);
})("bar", 42);
(function(arguments) {
console.log(arguments[1], arguments[1], arguments.foo);
})("bar", 42);
(function() {
var arguments;
console.log(arguments[1], arguments[1], arguments.foo);
})("bar", 42);
}
expect_stdout: [
"undefined",
"42 42 undefined",
"42 42 undefined",
"a a undefined",
"42 42 undefined",
]
}
modified: {
options = {
arguments: true,
}
input: {
(function(a, b) {
var c = arguments[0];
var d = arguments[1];
a = "foo";
b++;
console.log(a, b, c, d, arguments[0], arguments[1]);
})("bar", 42);
}
expect: {
(function(a, b) {
var c = a;
var d = b;
a = "foo";
b++;
console.log(a, b, c, d, a, b);
})("bar", 42);
}
expect_stdout: "foo 43 bar 42 foo 43"
}

View File

@@ -913,15 +913,15 @@ collapse_vars_unary: {
return delete x; return delete x;
} }
function f1(n) { function f1(n) {
return n > +!!n return +!!n < n;
} }
function f2(n) { function f2(n) {
var k = 7; var k = 7;
return k-- return k--;
} }
function f3(n) { function f3(n) {
var k = 7; var k = 7;
return ++k return ++k;
} }
function f4(n) { function f4(n) {
var k = 8 - n; var k = 8 - n;
@@ -2219,8 +2219,8 @@ unused_orig: {
console.log(function(b) { console.log(function(b) {
var c = b; var c = b;
for (var d in c) { for (var d in c) {
var a = c[0]; var a;
return --b + a; return --b + c[0];
} }
a && a.NaN; a && a.NaN;
}([2]), a); }([2]), a);
@@ -3124,7 +3124,57 @@ issue_2425_3: {
expect_stdout: "15" expect_stdout: "15"
} }
issue_2437: { issue_2437_1: {
options = {
collapse_vars: true,
conditionals: true,
inline: true,
join_vars: true,
passes: 2,
reduce_funcs: true,
reduce_vars: true,
side_effects: true,
sequences: true,
toplevel: true,
unused: true,
}
input: {
function foo() {
return bar();
}
function bar() {
if (xhrDesc) {
var req = new XMLHttpRequest();
var result = !!req.onreadystatechange;
Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', xhrDesc || {});
return result;
} else {
var req = new XMLHttpRequest();
var detectFunc = function () {};
req.onreadystatechange = detectFunc;
var result = req[SYMBOL_FAKE_ONREADYSTATECHANGE_1] === detectFunc;
req.onreadystatechange = null;
return result;
}
}
console.log(foo());
}
expect: {
console.log(function() {
if (xhrDesc) {
var result = !!(req = new XMLHttpRequest()).onreadystatechange;
return Object.defineProperty(XMLHttpRequest.prototype, "onreadystatechange", xhrDesc || {}),
result;
}
var req, detectFunc = function() {};
(req = new XMLHttpRequest()).onreadystatechange = detectFunc;
result = req[SYMBOL_FAKE_ONREADYSTATECHANGE_1] === detectFunc;
return req.onreadystatechange = null, result;
}());
}
}
issue_2437_2: {
options = { options = {
collapse_vars: true, collapse_vars: true,
conditionals: true, conditionals: true,
@@ -3161,14 +3211,12 @@ issue_2437: {
} }
expect: { expect: {
!function() { !function() {
if (xhrDesc) { if (xhrDesc)
var result = !!(req = new XMLHttpRequest()).onreadystatechange; return (req = new XMLHttpRequest()).onreadystatechange,
return Object.defineProperty(XMLHttpRequest.prototype, "onreadystatechange", xhrDesc || {}), Object.defineProperty(XMLHttpRequest.prototype, "onreadystatechange", xhrDesc || {});
result; var req;
} (req = new XMLHttpRequest).onreadystatechange = function(){},
var req, detectFunc = function() {}; req[SYMBOL_FAKE_ONREADYSTATECHANGE_1],
(req = new XMLHttpRequest()).onreadystatechange = detectFunc;
result = req[SYMBOL_FAKE_ONREADYSTATECHANGE_1] === detectFunc;
req.onreadystatechange = null; req.onreadystatechange = null;
}(); }();
} }
@@ -4665,3 +4713,533 @@ issue_2931: {
} }
expect_stdout: "undefined" expect_stdout: "undefined"
} }
issue_2954_1: {
options = {
collapse_vars: true,
}
input: {
var a = "PASS", b;
try {
do {
b = function() {
throw 0;
}();
a = "FAIL";
b && b.c;
} while (0);
} catch (e) {
}
console.log(a);
}
expect: {
var a = "PASS", b;
try {
do {
b = function() {
throw 0;
}();
a = "FAIL";
b && b.c;
} while (0);
} catch (e) {
}
console.log(a);
}
expect_stdout: "PASS"
}
issue_2954_2: {
options = {
collapse_vars: true,
}
input: {
var a = "FAIL_1", b;
try {
throw 0;
} catch (e) {
do {
b = function() {
throw new Error("PASS");
}();
a = "FAIL_2";
b && b.c;
} while (0);
}
console.log(a);
}
expect: {
var a = "FAIL_1", b;
try {
throw 0;
} catch (e) {
do {
a = "FAIL_2";
(b = function() {
throw new Error("PASS");
}()) && b.c;
} while (0);
}
console.log(a);
}
expect_stdout: Error("PASS")
}
issue_2954_3: {
options = {
collapse_vars: true,
}
input: {
var a = "FAIL_1", b;
try {
} finally {
do {
b = function() {
throw new Error("PASS");
}();
a = "FAIL_2";
b && b.c;
} while (0);
}
console.log(a);
}
expect: {
var a = "FAIL_1", b;
try {
} finally {
do {
a = "FAIL_2";
(b = function() {
throw new Error("PASS");
}()) && b.c;
} while (0);
}
console.log(a);
}
expect_stdout: Error("PASS")
}
collapse_rhs_conditional_1: {
options = {
collapse_vars: true,
}
input: {
var a = "PASS", b = "FAIL";
b = a;
"function" == typeof f && f(a);
console.log(a, b);
}
expect: {
var a = "PASS", b = "FAIL";
b = a;
"function" == typeof f && f(a);
console.log(a, b);
}
expect_stdout: "PASS PASS"
}
collapse_rhs_conditional_2: {
options = {
collapse_vars: true,
}
input: {
var a = "FAIL", b;
while ((a = "PASS", --b) && "PASS" == b);
console.log(a, b);
}
expect: {
var a = "FAIL", b;
while ((a = "PASS", --b) && "PASS" == b);
console.log(a, b);
}
expect_stdout: "PASS NaN"
}
collapse_rhs_lhs_1: {
options = {
collapse_vars: true,
}
input: {
var c = 0;
new function() {
this[c++] = 1;
c += 1;
}();
console.log(c);
}
expect: {
var c = 0;
new function() {
this[c++] = 1;
c += 1;
}();
console.log(c);
}
expect_stdout: "2"
}
collapse_rhs_lhs_2: {
options = {
collapse_vars: true,
}
input: {
var b = 1;
(function f(f) {
f = b;
f[b] = 0;
})();
console.log("PASS");
}
expect: {
var b = 1;
(function f(f) {
f = b;
f[b] = 0;
})();
console.log("PASS");
}
expect_stdout: "PASS"
}
collapse_rhs_side_effects: {
options = {
collapse_vars: true,
}
input: {
var a = 1, c = 0;
new function f() {
this[a-- && f()] = 1;
c += 1;
}();
console.log(c);
}
expect: {
var a = 1, c = 0;
new function f() {
this[a-- && f()] = 1;
c += 1;
}();
console.log(c);
}
expect_stdout: "2"
}
collapse_rhs_vardef: {
options = {
collapse_vars: true,
}
input: {
var a, b = 1;
a = --b + function c() {
var b;
c[--b] = 1;
}();
b |= a;
console.log(a, b);
}
expect: {
var a, b = 1;
a = --b + function c() {
var b;
c[--b] = 1;
}();
b |= a;
console.log(a, b);
}
expect_stdout: "NaN 0"
}
collapse_rhs_array: {
options = {
collapse_vars: true,
}
input: {
var a, b;
function f() {
a = [];
b = [];
return [];
}
var c = f();
console.log(a === b, b === c, c === a);
}
expect: {
var a, b;
function f() {
a = [];
b = [];
return [];
}
var c = f();
console.log(a === b, b === c, c === a);
}
expect_stdout: "false false false"
}
collapse_rhs_boolean: {
options = {
collapse_vars: true,
}
input: {
var a, b;
function f() {
a = !0;
b = !0;
return !0;
}
var c = f();
console.log(a === b, b === c, c === a);
}
expect: {
var a, b;
function f() {
return b = a = !0;
}
var c = f();
console.log(a === b, b === c, c === a);
}
expect_stdout: "true true true"
}
collapse_rhs_function: {
options = {
collapse_vars: true,
}
input: {
var a, b;
function f() {
a = function() {};
b = function() {};
return function() {};
}
var c = f();
console.log(a === b, b === c, c === a);
}
expect: {
var a, b;
function f() {
a = function() {};
b = function() {};
return function() {};
}
var c = f();
console.log(a === b, b === c, c === a);
}
expect_stdout: "false false false"
}
collapse_rhs_number: {
options = {
collapse_vars: true,
}
input: {
var a, b;
function f() {
a = 42;
b = 42;
return 42;
}
var c = f();
console.log(a === b, b === c, c === a);
}
expect: {
var a, b;
function f() {
return b = a = 42;
}
var c = f();
console.log(a === b, b === c, c === a);
}
expect_stdout: "true true true"
}
collapse_rhs_object: {
options = {
collapse_vars: true,
}
input: {
var a, b;
function f() {
a = {};
b = {};
return {};
}
var c = f();
console.log(a === b, b === c, c === a);
}
expect: {
var a, b;
function f() {
a = {};
b = {};
return {};
}
var c = f();
console.log(a === b, b === c, c === a);
}
expect_stdout: "false false false"
}
collapse_rhs_regexp: {
options = {
collapse_vars: true,
}
input: {
var a, b;
function f() {
a = /bar/;
b = /bar/;
return /bar/;
}
var c = f();
console.log(a === b, b === c, c === a);
}
expect: {
var a, b;
function f() {
a = /bar/;
b = /bar/;
return /bar/;
}
var c = f();
console.log(a === b, b === c, c === a);
}
expect_stdout: "false false false"
}
collapse_rhs_string: {
options = {
collapse_vars: true,
}
input: {
var a, b;
function f() {
a = "foo";
b = "foo";
return "foo";
}
var c = f();
console.log(a === b, b === c, c === a);
}
expect: {
var a, b;
function f() {
return b = a = "foo";
}
var c = f();
console.log(a === b, b === c, c === a);
}
expect_stdout: "true true true"
}
collapse_rhs_var: {
options = {
collapse_vars: true,
}
input: {
var a, b;
function f() {
a = f;
b = f;
return f;
}
var c = f();
console.log(a === b, b === c, c === a);
}
expect: {
var a, b;
function f() {
return b = a = f;
}
var c = f();
console.log(a === b, b === c, c === a);
}
expect_stdout: "true true true"
}
collapse_rhs_this: {
options = {
collapse_vars: true,
}
input: {
var a, b;
function f() {
a = this;
b = this;
return this;
}
var c = f();
console.log(a === b, b === c, c === a);
}
expect: {
var a, b;
function f() {
return b = a = this;
}
var c = f();
console.log(a === b, b === c, c === a);
}
expect_stdout: "true true true"
}
collapse_rhs_undefined: {
options = {
collapse_vars: true,
}
input: {
var a, b;
function f() {
a = void 0;
b = void 0;
return void 0;
}
var c = f();
console.log(a === b, b === c, c === a);
}
expect: {
var a, b;
function f() {
b = a = void 0;
return;
}
var c = f();
console.log(a === b, b === c, c === a);
}
expect_stdout: "true true true"
}
issue_2974: {
options = {
booleans: true,
collapse_vars: true,
evaluate: true,
loops: true,
passes: 2,
pure_getters: "strict",
reduce_vars: true,
sequences: true,
side_effects: true,
unused: true,
}
input: {
var c = 0;
(function f(b) {
var a = 2;
do {
b && b[b];
b && (b.null = -4);
c++;
} while (b.null && --a > 0);
})(true);
console.log(c);
}
expect: {
var c = 0;
(function(b) {
var a = 2;
for (; b.null = -4, c++, b.null && --a > 0;);
})(!0),
console.log(c);
}
expect_stdout: "1"
}

View File

@@ -1,62 +1,42 @@
keep_comparisons: { comparisons: {
options = { options = {
comparisons: true, comparisons: true,
unsafe_comps: false
} }
input: { input: {
var obj1 = { var obj1, obj2;
valueOf: function() {triggeredFirst();}
}
var obj2 = {
valueOf: function() {triggeredSecond();}
}
var result1 = obj1 <= obj2; var result1 = obj1 <= obj2;
var result2 = obj1 < obj2; var result2 = obj1 < obj2;
var result3 = obj1 >= obj2; var result3 = obj1 >= obj2;
var result4 = obj1 > obj2; var result4 = obj1 > obj2;
} }
expect: { expect: {
var obj1 = { var obj1, obj2;
valueOf: function() {triggeredFirst();}
}
var obj2 = {
valueOf: function() {triggeredSecond();}
}
var result1 = obj1 <= obj2; var result1 = obj1 <= obj2;
var result2 = obj1 < obj2; var result2 = obj1 < obj2;
var result3 = obj1 >= obj2; var result3 = obj2 <= obj1;
var result4 = obj1 > obj2; var result4 = obj2 < obj1;
} }
} }
keep_comparisons_with_unsafe_comps: { unsafe_comps: {
options = { options = {
comparisons: true, comparisons: true,
unsafe_comps: true conditionals: true,
unsafe_comps: true,
} }
input: { input: {
var obj1 = { var obj1, obj2;
valueOf: function() {triggeredFirst();} obj1 <= obj2 ? f1() : g1();
} obj1 < obj2 ? f2() : g2();
var obj2 = { obj1 >= obj2 ? f3() : g3();
valueOf: function() {triggeredSecond();} obj1 > obj2 ? f4() : g4();
}
var result1 = obj1 <= obj2;
var result2 = obj1 < obj2;
var result3 = obj1 >= obj2;
var result4 = obj1 > obj2;
} }
expect: { expect: {
var obj1 = { var obj1, obj2;
valueOf: function() {triggeredFirst();} obj2 < obj1 ? g1() : f1();
} obj1 < obj2 ? f2() : g2();
var obj2 = { obj1 < obj2 ? g3() : f3();
valueOf: function() {triggeredSecond();} obj2 < obj1 ? f4() : g4();
}
var result1 = obj2 >= obj1;
var result2 = obj2 > obj1;
var result3 = obj1 >= obj2;
var result4 = obj1 > obj2;
} }
} }

View File

@@ -332,7 +332,7 @@ cond_7: {
x = 'foo'; x = 'foo';
x = 'foo'; x = 'foo';
x = (condition(), 20); x = (condition(), 20);
x = z ? 'fuji' : (condition(), 'fuji'); x = (z || condition(), 'fuji');
x = (condition(), 'foobar'); x = (condition(), 'foobar');
x = y ? a : b; x = y ? a : b;
x = y ? 'foo' : 'fo'; x = y ? 'foo' : 'fo';

View File

@@ -1785,3 +1785,32 @@ issue_805_2: {
"bar", "bar",
] ]
} }
issue_2995: {
options = {
pure_getters: "strict",
reduce_vars: true,
unused: true,
}
input: {
function f(a) {
var b;
a.b = b = function() {};
b.c = "PASS";
}
var o = {};
f(o);
console.log(o.b.c);
}
expect: {
function f(a) {
var b;
a.b = b = function() {};
b.c = "PASS";
}
var o = {};
f(o);
console.log(o.b.c);
}
expect_stdout: "PASS"
}

View File

@@ -1535,3 +1535,34 @@ issue_2926_2: {
} }
expect_stdout: "function" expect_stdout: "function"
} }
issue_2968: {
options = {
collapse_vars: true,
evaluate: true,
inline: true,
passes: 2,
reduce_vars: true,
unused: true,
}
input: {
var c = "FAIL";
(function() {
(function(a, b) {
a <<= 0;
a && (a[(c = "PASS", 0 >>> (b += 1))] = 0);
})(42, -42);
})();
console.log(c);
}
expect: {
var c = "FAIL";
(function() {
b = -(a = 42),
void ((a <<= 0) && (a[(c = "PASS", 0 >>> (b += 1))] = 0));
var a, b;
})();
console.log(c);
}
expect_stdout: "PASS"
}

View File

@@ -2012,3 +2012,42 @@ issue_2898: {
} }
expect_stdout: "2" expect_stdout: "2"
} }
deduplicate_parenthesis: {
input: {
({}).a = b;
(({}).a = b)();
(function() {}).a = b;
((function() {}).a = b)();
}
expect_exact: "({}).a=b;({}.a=b)();(function(){}).a=b;(function(){}.a=b)();"
}
drop_lone_use_strict: {
options = {
side_effects: true,
}
input: {
function f1() {
"use strict";
}
function f2() {
"use strict";
function f3() {
"use strict";
}
}
(function f4() {
"use strict";
})();
}
expect: {
function f1() {
}
function f2() {
"use strict";
function f3() {
}
}
}
}

View File

@@ -239,14 +239,14 @@ name_collision_2: {
input: { input: {
var o = { var o = {
p: 1, p: 1,
0: function(x) { "+": function(x) {
return x; return x;
}, },
1: function(x) { "-": function(x) {
return x + 1; return x + 1;
} }
}, o__$0 = 2, o__$1 = 3; }, o__$0 = 2, o__$1 = 3;
console.log(o.p === o.p, o[0](4), o[1](5), o__$0, o__$1); console.log(o.p === o.p, o["+"](4), o["-"](5), o__$0, o__$1);
} }
expect: { expect: {
var o_p = 1, var o_p = 1,
@@ -273,14 +273,14 @@ name_collision_3: {
input: { input: {
var o = { var o = {
p: 1, p: 1,
0: function(x) { "+": function(x) {
return x; return x;
}, },
1: function(x) { "-": function(x) {
return x + 1; return x + 1;
} }
}, o__$0 = 2, o__$1 = 3; }, o__$0 = 2, o__$1 = 3;
console.log(o.p === o.p, o[0](4), o[1](5)); console.log(o.p === o.p, o["+"](4), o["-"](5));
} }
expect: { expect: {
var o_p = 1, var o_p = 1,

View File

@@ -243,7 +243,7 @@ issue_1089: {
expect: { expect: {
function x() { function x() {
var f = document.getElementById("fname"); var f = document.getElementById("fname");
if (f.files[0].size > 12345) if (12345 < f.files[0].size)
return alert("alert"), f.focus(), !1; return alert("alert"), f.focus(), !1;
} }
} }

View File

@@ -104,7 +104,7 @@ mangle_catch_toplevel: {
} }
console.log(a); console.log(a);
} }
expect_exact: 'var o="FAIL";try{throw 1}catch(c){o="PASS"}console.log(o);' expect_exact: 'var c="FAIL";try{throw 1}catch(o){c="PASS"}console.log(c);'
expect_stdout: "PASS" expect_stdout: "PASS"
} }
@@ -148,7 +148,7 @@ mangle_catch_var_toplevel: {
} }
console.log(a); console.log(a);
} }
expect_exact: 'var o="FAIL";try{throw 1}catch(r){var o="PASS"}console.log(o);' expect_exact: 'var r="FAIL";try{throw 1}catch(o){var r="PASS"}console.log(r);'
expect_stdout: "PASS" expect_stdout: "PASS"
} }
@@ -345,3 +345,95 @@ mangle_catch_redef_2_ie8_toplevel: {
expect_exact: 'try{throw"FAIL1"}catch(o){var o="FAIL2"}console.log(o);' expect_exact: 'try{throw"FAIL1"}catch(o){var o="FAIL2"}console.log(o);'
expect_stdout: "undefined" expect_stdout: "undefined"
} }
mangle_catch_redef_3: {
mangle = {
ie8: false,
toplevel: false,
}
input: {
var o = "PASS";
try {
throw 0;
} catch (o) {
(function() {
function f() {
o = "FAIL";
}
f(), f();
})();
}
console.log(o);
}
expect_exact: 'var o="PASS";try{throw 0}catch(o){(function(){function c(){o="FAIL"}c(),c()})()}console.log(o);'
expect_stdout: "PASS"
}
mangle_catch_redef_3_toplevel: {
mangle = {
ie8: false,
toplevel: true,
}
input: {
var o = "PASS";
try {
throw 0;
} catch (o) {
(function() {
function f() {
o = "FAIL";
}
f(), f();
})();
}
console.log(o);
}
expect_exact: 'var c="PASS";try{throw 0}catch(c){(function(){function o(){c="FAIL"}o(),o()})()}console.log(c);'
expect_stdout: "PASS"
}
mangle_catch_redef_ie8_3: {
mangle = {
ie8: true,
toplevel: false,
}
input: {
var o = "PASS";
try {
throw 0;
} catch (o) {
(function() {
function f() {
o = "FAIL";
}
f(), f();
})();
}
console.log(o);
}
expect_exact: 'var o="PASS";try{throw 0}catch(o){(function(){function c(){o="FAIL"}c(),c()})()}console.log(o);'
expect_stdout: "PASS"
}
mangle_catch_redef_3_ie8_toplevel: {
mangle = {
ie8: true,
toplevel: true,
}
input: {
var o = "PASS";
try {
throw 0;
} catch (o) {
(function() {
function f() {
o = "FAIL";
}
f(), f();
})();
}
console.log(o);
}
expect_exact: 'var c="PASS";try{throw 0}catch(c){(function(){function o(){c="FAIL"}o(),o()})()}console.log(c);'
expect_stdout: "PASS"
}

View File

@@ -15,7 +15,7 @@ function_iife_catch: {
} }
f(); f();
} }
expect_exact: "function f(o){!function(){try{throw 0}catch(c){var o=1;console.log(c,o)}}()}f();" expect_exact: "function f(o){!function(){try{throw 0}catch(o){var c=1;console.log(o,c)}}()}f();"
expect_stdout: "0 1" expect_stdout: "0 1"
} }
@@ -36,7 +36,7 @@ function_iife_catch_ie8: {
} }
f(); f();
} }
expect_exact: "function f(o){!function(){try{throw 0}catch(o){var c=1;console.log(o,c)}}()}f();" expect_exact: "function f(c){!function(){try{throw 0}catch(c){var o=1;console.log(c,o)}}()}f();"
expect_stdout: "0 1" expect_stdout: "0 1"
} }
@@ -61,7 +61,7 @@ function_catch_catch: {
} }
f(); f();
} }
expect_exact: "var o=0;function f(){try{throw 1}catch(c){try{throw 2}catch(o){var o=3;console.log(o)}}console.log(o)}f();" expect_exact: "var o=0;function f(){try{throw 1}catch(o){try{throw 2}catch(c){var c=3;console.log(c)}}console.log(c)}f();"
expect_stdout: [ expect_stdout: [
"3", "3",
"undefined", "undefined",

View File

@@ -0,0 +1,21 @@
inline_script_off: {
beautify = {
inline_script: false,
}
input: {
console.log("</sCrIpT>");
}
expect_exact: 'console.log("</sCrIpT>");'
expect_stdout: "</sCrIpT>"
}
inline_script_on: {
beautify = {
inline_script: true,
}
input: {
console.log("</sCrIpT>");
}
expect_exact: 'console.log("<\\/sCrIpT>");'
expect_stdout: "</sCrIpT>"
}

View File

@@ -830,3 +830,334 @@ issue_2938_4: {
} }
expect_stdout: "PASS" expect_stdout: "PASS"
} }
collapse_vars_1_true: {
options = {
collapse_vars: true,
pure_getters: true,
unused: true,
}
input: {
function f(a, b) {
for (;;) {
var c = a.g();
var d = b.p;
if (c || d) break;
}
}
}
expect: {
function f(a, b) {
for (;;) {
if (a.g() || b.p) break;
}
}
}
}
collapse_vars_1_false: {
options = {
collapse_vars: true,
pure_getters: false,
unused: true,
}
input: {
function f(a, b) {
for (;;) {
var c = a.g();
var d = b.p;
if (c || d) break;
}
}
}
expect: {
function f(a, b) {
for (;;) {
var c = a.g();
var d = b.p;
if (c || d) break;
}
}
}
}
collapse_vars_1_strict: {
options = {
collapse_vars: true,
pure_getters: "strict",
unused: true,
}
input: {
function f(a, b) {
for (;;) {
var c = a.g();
var d = b.p;
if (c || d) break;
}
}
}
expect: {
function f(a, b) {
for (;;) {
var c = a.g();
var d = b.p;
if (c || d) break;
}
}
}
}
collapse_vars_2_true: {
options = {
collapse_vars: true,
pure_getters: true,
reduce_vars: true,
}
input: {
function f() {
function g() {}
g.a = function() {};
g.b = g.a;
return g;
}
}
expect: {
function f() {
function g() {}
g.b = g.a = function() {};
return g;
}
}
}
collapse_vars_2_false: {
options = {
collapse_vars: true,
pure_getters: false,
reduce_vars: true,
}
input: {
function f() {
function g() {}
g.a = function() {};
g.b = g.a;
return g;
}
}
expect: {
function f() {
function g() {}
g.a = function() {};
g.b = g.a;
return g;
}
}
}
collapse_vars_2_strict: {
options = {
collapse_vars: true,
pure_getters: "strict",
reduce_vars: true,
}
input: {
function f() {
function g() {}
g.a = function() {};
g.b = g.a;
return g;
}
}
expect: {
function f() {
function g() {}
g.b = g.a = function() {};
return g;
}
}
}
collapse_rhs_true: {
options = {
collapse_vars: true,
pure_getters: true,
}
input: {
console.log((42..length = "PASS", "PASS"));
console.log(("foo".length = "PASS", "PASS"));
console.log((false.length = "PASS", "PASS"));
console.log((function() {}.length = "PASS", "PASS"));
console.log(({
get length() {
return "FAIL";
}
}.length = "PASS", "PASS"));
}
expect: {
console.log(42..length = "PASS");
console.log("foo".length = "PASS");
console.log(false.length = "PASS");
console.log(function() {}.length = "PASS");
console.log({
get length() {
return "FAIL";
}
}.length = "PASS");
}
expect_stdout: [
"PASS",
"PASS",
"PASS",
"PASS",
"PASS",
]
}
collapse_rhs_false: {
options = {
collapse_vars: true,
pure_getters: false,
}
input: {
console.log((42..length = "PASS", "PASS"));
console.log(("foo".length = "PASS", "PASS"));
console.log((false.length = "PASS", "PASS"));
console.log((function() {}.length = "PASS", "PASS"));
console.log(({
get length() {
return "FAIL";
}
}.length = "PASS", "PASS"));
}
expect: {
console.log(42..length = "PASS");
console.log("foo".length = "PASS");
console.log(false.length = "PASS");
console.log(function() {}.length = "PASS");
console.log({
get length() {
return "FAIL";
}
}.length = "PASS");
}
expect_stdout: [
"PASS",
"PASS",
"PASS",
"PASS",
"PASS",
]
}
collapse_rhs_strict: {
options = {
collapse_vars: true,
pure_getters: "strict",
}
input: {
console.log((42..length = "PASS", "PASS"));
console.log(("foo".length = "PASS", "PASS"));
console.log((false.length = "PASS", "PASS"));
console.log((function() {}.length = "PASS", "PASS"));
console.log(({
get length() {
return "FAIL";
}
}.length = "PASS", "PASS"));
}
expect: {
console.log(42..length = "PASS");
console.log("foo".length = "PASS");
console.log(false.length = "PASS");
console.log(function() {}.length = "PASS");
console.log({
get length() {
return "FAIL";
}
}.length = "PASS");
}
expect_stdout: [
"PASS",
"PASS",
"PASS",
"PASS",
"PASS",
]
}
collapse_rhs_setter: {
options = {
collapse_vars: true,
pure_getters: "strict",
}
input: {
try {
console.log(({
set length(v) {
throw "PASS";
}
}.length = "FAIL", "FAIL"));
} catch (e) {
console.log(e);
}
}
expect: {
try {
console.log({
set length(v) {
throw "PASS";
}
}.length = "FAIL");
} catch (e) {
console.log(e);
}
}
expect_stdout: "PASS"
}
collapse_rhs_call: {
options = {
collapse_vars: true,
passes: 2,
pure_getters: "strict",
reduce_vars: true,
toplevel: true,
unused: true,
}
input: {
var o = {};
function f() {
console.log("PASS");
}
o.f = f;
f();
}
expect: {
({}.f = function() {
console.log("PASS");
})();
}
expect_stdout: "PASS"
}
collapse_rhs_lhs: {
options = {
collapse_vars: true,
pure_getters: true,
}
input: {
function f(a, b) {
a.b = b, b += 2;
console.log(a.b, b);
}
f({}, 1);
}
expect: {
function f(a, b) {
a.b = b, b += 2;
console.log(a.b, b);
}
f({}, 1);
}
expect_stdout: "1 3"
}

View File

@@ -5545,3 +5545,33 @@ issue_2919: {
} }
expect_stdout: "function" expect_stdout: "function"
} }
issue_2992: {
options = {
evaluate: true,
reduce_vars: true,
}
input: {
var c = "PASS";
(function f(b) {
switch (0) {
case 0:
case b = 1:
b && (c = "FAIL");
}
})();
console.log(c);
}
expect: {
var c = "PASS";
(function f(b) {
switch (0) {
case 0:
case b = 1:
b && (c = "FAIL");
}
})();
console.log(c);
}
expect_stdout: "PASS"
}

View File

@@ -109,7 +109,7 @@ mangle_catch_toplevel: {
} }
console.log(a); console.log(a);
} }
expect_exact: 'var o="FAIL";try{throw 1}catch(c){o="PASS"}console.log(o);' expect_exact: 'var c="FAIL";try{throw 1}catch(o){c="PASS"}console.log(c);'
expect_stdout: "PASS" expect_stdout: "PASS"
} }
@@ -155,7 +155,7 @@ mangle_catch_var_toplevel: {
} }
console.log(a); console.log(a);
} }
expect_exact: 'var o="FAIL";try{throw 1}catch(r){var o="PASS"}console.log(o);' expect_exact: 'var r="FAIL";try{throw 1}catch(o){var r="PASS"}console.log(r);'
expect_stdout: "PASS" expect_stdout: "PASS"
} }
@@ -451,7 +451,7 @@ function_iife_catch: {
} }
f(); f();
} }
expect_exact: "function f(o){!function(){try{throw 0}catch(c){var o=1;console.log(c,o)}}()}f();" expect_exact: "function f(o){!function(){try{throw 0}catch(o){var c=1;console.log(o,c)}}()}f();"
expect_stdout: "0 1" expect_stdout: "0 1"
} }
@@ -473,7 +473,7 @@ function_iife_catch_ie8: {
} }
f(); f();
} }
expect_exact: "function f(o){!function(){try{throw 0}catch(o){var c=1;console.log(o,c)}}()}f();" expect_exact: "function f(c){!function(){try{throw 0}catch(c){var o=1;console.log(c,o)}}()}f();"
expect_stdout: "0 1" expect_stdout: "0 1"
} }
@@ -499,7 +499,7 @@ function_catch_catch: {
} }
f(); f();
} }
expect_exact: "var o=0;function f(){try{throw 1}catch(c){try{throw 2}catch(o){var o=3;console.log(o)}}console.log(o)}f();" expect_exact: "var o=0;function f(){try{throw 1}catch(o){try{throw 2}catch(c){var c=3;console.log(c)}}console.log(c)}f();"
expect_stdout: [ expect_stdout: [
"3", "3",
"undefined", "undefined",

View File

@@ -102,12 +102,12 @@ dont_screw_try_catch: {
}; };
} }
expect: { expect: {
bad = function(n){ bad = function(t){
return function(t){ return function(n){
try{ try{
n() t()
} catch(n) { } catch(t) {
t(n) n(t)
} }
} }
}; };
@@ -349,11 +349,11 @@ issue_2254_1: {
try { try {
console.log(f("PASS")); console.log(f("PASS"));
} catch (e) {} } catch (e) {}
function f(e) { function f(t) {
try { try {
throw "FAIL"; throw "FAIL";
} catch (t) { } catch (e) {
return e; return t;
} }
} }
} }
@@ -392,3 +392,75 @@ issue_2254_2: {
} }
expect_stdout: "PASS" expect_stdout: "PASS"
} }
issue_24_1: {
mangle = {
ie8: false,
}
input: {
(function(a) {
console.log(typeof function f(){} === typeof a ? "FAIL" : "PASS");
})();
}
expect: {
(function(o) {
console.log(typeof function o(){} === typeof o ? "FAIL" : "PASS");
})();
}
expect_stdout: "PASS"
}
issue_24_2: {
mangle = {
ie8: true,
}
input: {
(function(a) {
console.log(typeof function f(){} === typeof a ? "FAIL" : "PASS");
})();
}
expect: {
(function(n) {
console.log(typeof function o(){} === typeof n ? "FAIL" : "PASS");
})();
}
expect_stdout: "PASS"
}
issue_2976_1: {
mangle = {
ie8: false,
}
input: {
console.log(function f() {
var a;
return a === f ? "FAIL" : "PASS";
}());
}
expect: {
console.log(function n() {
var o;
return o === n ? "FAIL" : "PASS";
}());
}
expect_stdout: "PASS"
}
issue_2976_2: {
mangle = {
ie8: true,
}
input: {
console.log(function f() {
var a;
return a === f ? "FAIL" : "PASS";
}());
}
expect: {
console.log(function n() {
var o;
return o === n ? "FAIL" : "PASS";
}());
}
expect_stdout: "PASS"
}

View File

@@ -668,8 +668,7 @@ side_effects_cascade_2: {
} }
expect: { expect: {
function f(a, b) { function f(a, b) {
b = a, !(b = a) + (b += a) || (b += a),
!a + (b += a) || (b += a),
b = a; b = a;
} }
} }

View File

@@ -104,6 +104,7 @@ if_return: {
conditionals: true, conditionals: true,
if_return: true, if_return: true,
sequences: true, sequences: true,
side_effects: true,
} }
input: { input: {
function f(w, x, y, z) { function f(w, x, y, z) {
@@ -124,7 +125,7 @@ if_return: {
if (w) { if (w) {
if (y) return; if (y) return;
} else if (z) return; } else if (z) return;
return x == y || (x && w(), y && z(), !0); return x == y || (x && w(), y && z()), !0;
} }
} }
} }

View File

@@ -139,6 +139,26 @@ describe("Comment", function() {
assert.strictEqual(result.code, code); assert.strictEqual(result.code, code);
}); });
it("Should retain comments within brackets", function() {
var code = [
"{/* foo */}",
"a({/* foo */});",
"while (a) {/* foo */}",
"switch (a) {/* foo */}",
"if (a) {/* foo */} else {/* bar */}",
].join("\n\n");
var result = uglify.minify(code, {
compress: false,
mangle: false,
output: {
beautify: true,
comments: "all",
},
});
if (result.error) throw result.error;
assert.strictEqual(result.code, code);
});
it("Should correctly preserve new lines around comments", function() { it("Should correctly preserve new lines around comments", function() {
var tests = [ var tests = [
[ [

View File

@@ -46,10 +46,10 @@ describe("minify", function() {
assert.strictEqual(compressed, [ assert.strictEqual(compressed, [
"function n(n){return 3*n}", "function n(n){return 3*n}",
"function r(n){return n/2}", "function r(n){return n/2}",
"var o=console.log.bind(console);", "var c=console.log.bind(console);",
'function c(n){o("Foo:",2*n)}', 'function o(o){c("Foo:",2*o)}',
"var a=n(3),b=r(12);", "var a=n(3),b=r(12);",
'o("qux",a,b),c(11);', 'c("qux",a,b),o(11);',
].join("")); ].join(""));
assert.strictEqual(run_code(compressed), run_code(original)); assert.strictEqual(run_code(compressed), run_code(original));
}); });
@@ -79,10 +79,10 @@ describe("minify", function() {
assert.strictEqual(compressed, [ assert.strictEqual(compressed, [
"function n(n){return 3*n}", "function n(n){return 3*n}",
"function r(n){return n/2}", "function r(n){return n/2}",
"var o=console.log.bind(console);", "var c=console.log.bind(console);",
'function c(n){o("Foo:",2*n)}', 'function o(o){c("Foo:",2*o)}',
"var a=n(3),b=r(12);", "var a=n(3),b=r(12);",
'o("qux",a,b),c(11);', 'c("qux",a,b),o(11);',
].join("")); ].join(""));
assert.strictEqual(run_code(compressed), run_code(original)); assert.strictEqual(run_code(compressed), run_code(original));
}); });

View File

@@ -135,7 +135,6 @@ function run_compress_tests() {
var output = cmp.compress(input); var output = cmp.compress(input);
output.figure_out_scope(test.mangle); output.figure_out_scope(test.mangle);
if (test.mangle) { if (test.mangle) {
U.base54.reset();
output.compute_char_frequency(test.mangle); output.compute_char_frequency(test.mangle);
output.mangle_names(test.mangle); output.mangle_names(test.mangle);
if (test.mangle.properties) { if (test.mangle.properties) {
@@ -183,7 +182,7 @@ function run_compress_tests() {
} }
if (test.expect_stdout if (test.expect_stdout
&& (!test.node_version || semver.satisfies(process.version, test.node_version))) { && (!test.node_version || semver.satisfies(process.version, test.node_version))) {
var stdout = sandbox.run_code(input_code); var stdout = sandbox.run_code(input_code, true);
if (test.expect_stdout === true) { if (test.expect_stdout === true) {
test.expect_stdout = stdout; test.expect_stdout = stdout;
} }
@@ -197,7 +196,7 @@ function run_compress_tests() {
}); });
return false; return false;
} }
stdout = sandbox.run_code(output); stdout = sandbox.run_code(output, true);
if (!sandbox.same_stdout(test.expect_stdout, stdout)) { if (!sandbox.same_stdout(test.expect_stdout, stdout)) {
log("!!! failed\n---INPUT---\n{input}\n---EXPECTED {expected_type}---\n{expected}\n---ACTUAL {actual_type}---\n{actual}\n\n", { log("!!! failed\n---INPUT---\n{input}\n---EXPECTED {expected_type}---\n{expected}\n---ACTUAL {actual_type}---\n{actual}\n\n", {
input: input_formatted, input: input_formatted,
@@ -344,7 +343,6 @@ function parse_test(file) {
} }
function make_code(ast, options) { function make_code(ast, options) {
options.inline_script = true;
var stream = U.OutputStream(options); var stream = U.OutputStream(options);
ast.print(stream); ast.print(stream);
return stream.get(); return stream.get();
@@ -379,7 +377,7 @@ function reminify(orig_options, input_code, input_formatted, expect_stdout) {
}); });
return false; return false;
} else { } else {
var stdout = sandbox.run_code(result.code); var stdout = sandbox.run_code(result.code, true);
if (typeof expect_stdout != "string" && typeof stdout != "string" && expect_stdout.name == stdout.name) { if (typeof expect_stdout != "string" && typeof stdout != "string" && expect_stdout.name == stdout.name) {
stdout = expect_stdout; stdout = expect_stdout;
} }

View File

@@ -1,6 +1,27 @@
var semver = require("semver"); var semver = require("semver");
var vm = require("vm"); var vm = require("vm");
function createContext() {
var context = Object.create(null);
Object.defineProperty(context, "console", {
value: function() {
var con = Object.create(null);
Object.defineProperty(con, "log", {
value: function(msg) {
if (arguments.length == 1 && typeof msg == "string") {
return console.log("%s", msg);
}
return console.log.apply(console, [].map.call(arguments, function(arg) {
return safe_log(arg, 3);
}));
}
});
return con;
}()
});
return vm.createContext(context);
}
function safe_log(arg, level) { function safe_log(arg, level) {
if (arg) switch (typeof arg) { if (arg) switch (typeof arg) {
case "function": case "function":
@@ -9,7 +30,8 @@ function safe_log(arg, level) {
if (/Error$/.test(arg.name)) return arg.toString(); if (/Error$/.test(arg.name)) return arg.toString();
arg.constructor.toString(); arg.constructor.toString();
if (level--) for (var key in arg) { if (level--) for (var key in arg) {
if (!Object.getOwnPropertyDescriptor(arg, key).get) { var desc = Object.getOwnPropertyDescriptor(arg, key);
if (!desc || !desc.get) {
arg[key] = safe_log(arg[key], level); arg[key] = safe_log(arg[key], level);
} }
} }
@@ -21,6 +43,7 @@ function strip_func_ids(text) {
return text.toString().replace(/F[0-9]{6}N/g, "<F<>N>"); return text.toString().replace(/F[0-9]{6}N/g, "<F<>N>");
} }
var context;
var FUNC_TOSTRING = [ var FUNC_TOSTRING = [
"[ Array, Boolean, Error, Function, Number, Object, RegExp, String].forEach(function(f) {", "[ Array, Boolean, Error, Function, Number, Object, RegExp, String].forEach(function(f) {",
" f.toString = Function.prototype.toString;", " f.toString = Function.prototype.toString;",
@@ -43,35 +66,30 @@ var FUNC_TOSTRING = [
" };", " };",
"}();", "}();",
]).join("\n"); ]).join("\n");
exports.run_code = function(code) { exports.run_code = function(code, reuse) {
var stdout = ""; var stdout = "";
var original_write = process.stdout.write; var original_write = process.stdout.write;
process.stdout.write = function(chunk) { process.stdout.write = function(chunk) {
stdout += chunk; stdout += chunk;
}; };
try { try {
vm.runInNewContext([ if (!reuse || !context) context = createContext();
vm.runInContext([
FUNC_TOSTRING, FUNC_TOSTRING,
"!function() {", "!function() {",
code, code,
"}();", "}();",
].join("\n"), { ].join("\n"), context, { timeout: 5000 });
console: {
log: function(msg) {
if (arguments.length == 1 && typeof msg == "string") {
return console.log("%s", msg);
}
return console.log.apply(console, [].map.call(arguments, function(arg) {
return safe_log(arg, 3);
}));
}
}
}, { timeout: 5000 });
return stdout; return stdout;
} catch (ex) { } catch (ex) {
return ex; return ex;
} finally { } finally {
process.stdout.write = original_write; process.stdout.write = original_write;
if (!reuse || /prototype/.test(code)) {
context = null;
} else for (var key in context) {
delete context[key];
}
} }
}; };
exports.same_stdout = semver.satisfies(process.version, "0.12") ? function(expected, actual) { exports.same_stdout = semver.satisfies(process.version, "0.12") ? function(expected, actual) {