You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

6556 lines
273 KiB

4 years ago
  1. /***********************************************************************
  2. A JavaScript tokenizer / parser / beautifier / compressor.
  3. https://github.com/mishoo/UglifyJS2
  4. -------------------------------- (C) ---------------------------------
  5. Author: Mihai Bazon
  6. <mihai.bazon@gmail.com>
  7. http://mihai.bazon.net/blog
  8. Distributed under the BSD license:
  9. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  10. Redistribution and use in source and binary forms, with or without
  11. modification, are permitted provided that the following conditions
  12. are met:
  13. * Redistributions of source code must retain the above
  14. copyright notice, this list of conditions and the following
  15. disclaimer.
  16. * Redistributions in binary form must reproduce the above
  17. copyright notice, this list of conditions and the following
  18. disclaimer in the documentation and/or other materials
  19. provided with the distribution.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AS IS AND ANY
  21. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  23. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  24. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  25. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  26. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  27. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  29. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  30. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  31. SUCH DAMAGE.
  32. ***********************************************************************/
  33. "use strict";
  34. function Compressor(options, false_by_default) {
  35. if (!(this instanceof Compressor))
  36. return new Compressor(options, false_by_default);
  37. TreeTransformer.call(this, this.before, this.after);
  38. this.options = defaults(options, {
  39. arguments : !false_by_default,
  40. booleans : !false_by_default,
  41. collapse_vars : !false_by_default,
  42. comparisons : !false_by_default,
  43. conditionals : !false_by_default,
  44. dead_code : !false_by_default,
  45. directives : !false_by_default,
  46. drop_console : false,
  47. drop_debugger : !false_by_default,
  48. evaluate : !false_by_default,
  49. expression : false,
  50. global_defs : false,
  51. hoist_funs : false,
  52. hoist_props : !false_by_default,
  53. hoist_vars : false,
  54. ie8 : false,
  55. if_return : !false_by_default,
  56. inline : !false_by_default,
  57. join_vars : !false_by_default,
  58. keep_fargs : true,
  59. keep_fnames : false,
  60. keep_infinity : false,
  61. loops : !false_by_default,
  62. negate_iife : !false_by_default,
  63. passes : 1,
  64. properties : !false_by_default,
  65. pure_getters : !false_by_default && "strict",
  66. pure_funcs : null,
  67. reduce_funcs : !false_by_default,
  68. reduce_vars : !false_by_default,
  69. sequences : !false_by_default,
  70. side_effects : !false_by_default,
  71. switches : !false_by_default,
  72. top_retain : null,
  73. toplevel : !!(options && options["top_retain"]),
  74. typeofs : !false_by_default,
  75. unsafe : false,
  76. unsafe_comps : false,
  77. unsafe_Function : false,
  78. unsafe_math : false,
  79. unsafe_proto : false,
  80. unsafe_regexp : false,
  81. unsafe_undefined: false,
  82. unused : !false_by_default,
  83. warnings : false,
  84. }, true);
  85. var global_defs = this.options["global_defs"];
  86. if (typeof global_defs == "object") for (var key in global_defs) {
  87. if (/^@/.test(key) && HOP(global_defs, key)) {
  88. global_defs[key.slice(1)] = parse(global_defs[key], {
  89. expression: true
  90. });
  91. }
  92. }
  93. if (this.options["inline"] === true) this.options["inline"] = 3;
  94. var pure_funcs = this.options["pure_funcs"];
  95. if (typeof pure_funcs == "function") {
  96. this.pure_funcs = pure_funcs;
  97. } else if (typeof pure_funcs == "string") {
  98. this.pure_funcs = function(node) {
  99. return pure_funcs !== node.expression.print_to_string();
  100. };
  101. } else if (Array.isArray(pure_funcs)) {
  102. this.pure_funcs = function(node) {
  103. return pure_funcs.indexOf(node.expression.print_to_string()) < 0;
  104. };
  105. } else {
  106. this.pure_funcs = return_true;
  107. }
  108. var top_retain = this.options["top_retain"];
  109. if (top_retain instanceof RegExp) {
  110. this.top_retain = function(def) {
  111. return top_retain.test(def.name);
  112. };
  113. } else if (typeof top_retain == "function") {
  114. this.top_retain = top_retain;
  115. } else if (top_retain) {
  116. if (typeof top_retain == "string") {
  117. top_retain = top_retain.split(/,/);
  118. }
  119. this.top_retain = function(def) {
  120. return top_retain.indexOf(def.name) >= 0;
  121. };
  122. }
  123. var toplevel = this.options["toplevel"];
  124. this.toplevel = typeof toplevel == "string" ? {
  125. funcs: /funcs/.test(toplevel),
  126. vars: /vars/.test(toplevel)
  127. } : {
  128. funcs: toplevel,
  129. vars: toplevel
  130. };
  131. var sequences = this.options["sequences"];
  132. this.sequences_limit = sequences == 1 ? 800 : sequences | 0;
  133. this.warnings_produced = {};
  134. }
  135. Compressor.prototype = new TreeTransformer;
  136. merge(Compressor.prototype, {
  137. option: function(key) { return this.options[key] },
  138. exposed: function(def) {
  139. if (def.global) for (var i = 0, len = def.orig.length; i < len; i++)
  140. if (!this.toplevel[def.orig[i] instanceof AST_SymbolDefun ? "funcs" : "vars"])
  141. return true;
  142. return false;
  143. },
  144. compress: function(node) {
  145. node = node.resolve_defines(this);
  146. if (this.option("expression")) {
  147. node.process_expression(true);
  148. }
  149. var passes = +this.options.passes || 1;
  150. var min_count = 1 / 0;
  151. var stopping = false;
  152. var mangle = { ie8: this.option("ie8") };
  153. for (var pass = 0; pass < passes; pass++) {
  154. node.figure_out_scope(mangle);
  155. if (pass > 0 || this.option("reduce_vars"))
  156. node.reset_opt_flags(this);
  157. node = node.transform(this);
  158. if (passes > 1) {
  159. var count = 0;
  160. node.walk(new TreeWalker(function() {
  161. count++;
  162. }));
  163. this.info("pass " + pass + ": last_count: " + min_count + ", count: " + count);
  164. if (count < min_count) {
  165. min_count = count;
  166. stopping = false;
  167. } else if (stopping) {
  168. break;
  169. } else {
  170. stopping = true;
  171. }
  172. }
  173. }
  174. if (this.option("expression")) {
  175. node.process_expression(false);
  176. }
  177. return node;
  178. },
  179. info: function() {
  180. if (this.options.warnings == "verbose") {
  181. AST_Node.warn.apply(AST_Node, arguments);
  182. }
  183. },
  184. warn: function(text, props) {
  185. if (this.options.warnings) {
  186. // only emit unique warnings
  187. var message = string_template(text, props);
  188. if (!(message in this.warnings_produced)) {
  189. this.warnings_produced[message] = true;
  190. AST_Node.warn.apply(AST_Node, arguments);
  191. }
  192. }
  193. },
  194. clear_warnings: function() {
  195. this.warnings_produced = {};
  196. },
  197. before: function(node, descend, in_list) {
  198. if (node._squeezed) return node;
  199. var is_scope = node instanceof AST_Scope;
  200. if (is_scope) {
  201. node.hoist_properties(this);
  202. node.hoist_declarations(this);
  203. }
  204. // Before https://github.com/mishoo/UglifyJS2/pull/1602 AST_Node.optimize()
  205. // would call AST_Node.transform() if a different instance of AST_Node is
  206. // produced after OPT().
  207. // This corrupts TreeWalker.stack, which cause AST look-ups to malfunction.
  208. // Migrate and defer all children's AST_Node.transform() to below, which
  209. // will now happen after this parent AST_Node has been properly substituted
  210. // thus gives a consistent AST snapshot.
  211. descend(node, this);
  212. // Existing code relies on how AST_Node.optimize() worked, and omitting the
  213. // following replacement call would result in degraded efficiency of both
  214. // output and performance.
  215. descend(node, this);
  216. var opt = node.optimize(this);
  217. if (is_scope) {
  218. opt.drop_unused(this);
  219. descend(opt, this);
  220. }
  221. if (opt === node) opt._squeezed = true;
  222. return opt;
  223. }
  224. });
  225. (function(OPT) {
  226. OPT(AST_Node, function(self, compressor) {
  227. return self;
  228. });
  229. AST_Node.DEFMETHOD("equivalent_to", function(node) {
  230. return this.TYPE == node.TYPE && this.print_to_string() == node.print_to_string();
  231. });
  232. AST_Scope.DEFMETHOD("process_expression", function(insert, compressor) {
  233. var self = this;
  234. var tt = new TreeTransformer(function(node) {
  235. if (insert && node instanceof AST_SimpleStatement) {
  236. return make_node(AST_Return, node, {
  237. value: node.body
  238. });
  239. }
  240. if (!insert && node instanceof AST_Return) {
  241. if (compressor) {
  242. var value = node.value && node.value.drop_side_effect_free(compressor, true);
  243. return value ? make_node(AST_SimpleStatement, node, {
  244. body: value
  245. }) : make_node(AST_EmptyStatement, node);
  246. }
  247. return make_node(AST_SimpleStatement, node, {
  248. body: node.value || make_node(AST_UnaryPrefix, node, {
  249. operator: "void",
  250. expression: make_node(AST_Number, node, {
  251. value: 0
  252. })
  253. })
  254. });
  255. }
  256. if (node instanceof AST_Lambda && node !== self) {
  257. return node;
  258. }
  259. if (node instanceof AST_Block) {
  260. var index = node.body.length - 1;
  261. if (index >= 0) {
  262. node.body[index] = node.body[index].transform(tt);
  263. }
  264. } else if (node instanceof AST_If) {
  265. node.body = node.body.transform(tt);
  266. if (node.alternative) {
  267. node.alternative = node.alternative.transform(tt);
  268. }
  269. } else if (node instanceof AST_With) {
  270. node.body = node.body.transform(tt);
  271. }
  272. return node;
  273. });
  274. self.transform(tt);
  275. });
  276. function read_property(obj, key) {
  277. key = get_value(key);
  278. if (key instanceof AST_Node) return;
  279. var value;
  280. if (obj instanceof AST_Array) {
  281. var elements = obj.elements;
  282. if (key == "length") return make_node_from_constant(elements.length, obj);
  283. if (typeof key == "number" && key in elements) value = elements[key];
  284. } else if (obj instanceof AST_Object) {
  285. key = "" + key;
  286. var props = obj.properties;
  287. for (var i = props.length; --i >= 0;) {
  288. var prop = props[i];
  289. if (!(prop instanceof AST_ObjectKeyVal)) return;
  290. if (!value && props[i].key === key) value = props[i].value;
  291. }
  292. }
  293. return value instanceof AST_SymbolRef && value.fixed_value() || value;
  294. }
  295. function is_modified(compressor, tw, node, value, level, immutable) {
  296. var parent = tw.parent(level);
  297. var lhs = is_lhs(node, parent);
  298. if (lhs) return lhs;
  299. if (!immutable
  300. && parent instanceof AST_Call
  301. && parent.expression === node
  302. && !parent.is_expr_pure(compressor)
  303. && (!(value instanceof AST_Function)
  304. || !(parent instanceof AST_New) && value.contains_this())) {
  305. return true;
  306. }
  307. if (parent instanceof AST_Array) {
  308. return is_modified(compressor, tw, parent, parent, level + 1);
  309. }
  310. if (parent instanceof AST_ObjectKeyVal && node === parent.value) {
  311. var obj = tw.parent(level + 1);
  312. return is_modified(compressor, tw, obj, obj, level + 2);
  313. }
  314. if (parent instanceof AST_PropAccess && parent.expression === node) {
  315. var prop = read_property(value, parent.property);
  316. return !immutable && is_modified(compressor, tw, parent, prop, level + 1);
  317. }
  318. }
  319. (function(def) {
  320. def(AST_Node, noop);
  321. function reset_def(tw, compressor, def) {
  322. def.assignments = 0;
  323. def.chained = false;
  324. def.direct_access = false;
  325. def.escaped = false;
  326. def.fixed = !def.scope.pinned()
  327. && !compressor.exposed(def)
  328. && !(def.init instanceof AST_Function && def.init !== def.scope)
  329. && def.init;
  330. if (def.fixed instanceof AST_Defun && !all(def.references, function(ref) {
  331. var scope = ref.scope;
  332. do {
  333. if (def.scope === scope) return true;
  334. } while (scope instanceof AST_Function && (scope = scope.parent_scope));
  335. })) {
  336. tw.defun_ids[def.id] = false;
  337. }
  338. def.recursive_refs = 0;
  339. def.references = [];
  340. def.should_replace = undefined;
  341. def.single_use = undefined;
  342. }
  343. function reset_variables(tw, compressor, scope) {
  344. scope.variables.each(function(def) {
  345. reset_def(tw, compressor, def);
  346. if (def.fixed === null) {
  347. def.safe_ids = tw.safe_ids;
  348. mark(tw, def, true);
  349. } else if (def.fixed) {
  350. tw.loop_ids[def.id] = tw.in_loop;
  351. mark(tw, def, true);
  352. }
  353. });
  354. scope.may_call_this = function() {
  355. scope.may_call_this = noop;
  356. if (!scope.contains_this()) return;
  357. scope.functions.each(function(def) {
  358. if (def.init instanceof AST_Defun && !(def.id in tw.defun_ids)) {
  359. tw.defun_ids[def.id] = false;
  360. }
  361. });
  362. };
  363. }
  364. function mark_defun(tw, def) {
  365. if (def.id in tw.defun_ids) {
  366. var marker = tw.defun_ids[def.id];
  367. if (!marker) return;
  368. var visited = tw.defun_visited[def.id];
  369. if (marker === tw.safe_ids) {
  370. if (!visited) return def.fixed;
  371. } else if (visited) {
  372. def.init.enclosed.forEach(function(d) {
  373. if (def.init.variables.get(d.name) === d) return;
  374. if (!safe_to_read(tw, d)) d.fixed = false;
  375. });
  376. } else {
  377. tw.defun_ids[def.id] = false;
  378. }
  379. } else {
  380. if (!tw.in_loop) {
  381. tw.defun_ids[def.id] = tw.safe_ids;
  382. return def.fixed;
  383. }
  384. tw.defun_ids[def.id] = false;
  385. }
  386. }
  387. function walk_defuns(tw, scope) {
  388. scope.functions.each(function(def) {
  389. if (def.init instanceof AST_Defun && !tw.defun_visited[def.id]) {
  390. tw.defun_ids[def.id] = tw.safe_ids;
  391. def.init.walk(tw);
  392. }
  393. });
  394. }
  395. function push(tw) {
  396. tw.safe_ids = Object.create(tw.safe_ids);
  397. }
  398. function pop(tw) {
  399. tw.safe_ids = Object.getPrototypeOf(tw.safe_ids);
  400. }
  401. function mark(tw, def, safe) {
  402. tw.safe_ids[def.id] = safe;
  403. }
  404. function safe_to_read(tw, def) {
  405. if (def.single_use == "m") return false;
  406. if (tw.safe_ids[def.id]) {
  407. if (def.fixed == null) {
  408. var orig = def.orig[0];
  409. if (orig instanceof AST_SymbolFunarg || orig.name == "arguments") return false;
  410. def.fixed = make_node(AST_Undefined, orig);
  411. }
  412. return true;
  413. }
  414. return def.fixed instanceof AST_Defun;
  415. }
  416. function safe_to_assign(tw, def, scope, value) {
  417. if (def.fixed === undefined) return true;
  418. if (def.fixed === null && def.safe_ids) {
  419. def.safe_ids[def.id] = false;
  420. delete def.safe_ids;
  421. return true;
  422. }
  423. if (!HOP(tw.safe_ids, def.id)) return false;
  424. if (!safe_to_read(tw, def)) return false;
  425. if (def.fixed === false) return false;
  426. if (def.fixed != null && (!value || def.references.length > def.assignments)) return false;
  427. if (def.fixed instanceof AST_Defun) {
  428. return value instanceof AST_Node && def.fixed.parent_scope === scope;
  429. }
  430. return all(def.orig, function(sym) {
  431. return !(sym instanceof AST_SymbolDefun || sym instanceof AST_SymbolLambda);
  432. });
  433. }
  434. function ref_once(tw, compressor, def) {
  435. return compressor.option("unused")
  436. && !def.scope.pinned()
  437. && def.references.length - def.recursive_refs == 1
  438. && tw.loop_ids[def.id] === tw.in_loop;
  439. }
  440. function is_immutable(value) {
  441. if (!value) return false;
  442. return value.is_constant()
  443. || value instanceof AST_Lambda
  444. || value instanceof AST_This;
  445. }
  446. function mark_escaped(tw, d, scope, node, value, level, depth) {
  447. var parent = tw.parent(level);
  448. if (value && value.is_constant()) return;
  449. if (parent instanceof AST_Assign && parent.operator == "=" && node === parent.right
  450. || parent instanceof AST_Call && (node !== parent.expression || parent instanceof AST_New)
  451. || parent instanceof AST_Exit && node === parent.value && node.scope !== d.scope
  452. || parent instanceof AST_VarDef && node === parent.value) {
  453. if (depth > 1 && !(value && value.is_constant_expression(scope))) depth = 1;
  454. if (!d.escaped || d.escaped > depth) d.escaped = depth;
  455. return;
  456. } else if (parent instanceof AST_Array
  457. || parent instanceof AST_Binary && lazy_op[parent.operator]
  458. || parent instanceof AST_Conditional && node !== parent.condition
  459. || parent instanceof AST_Sequence && node === parent.tail_node()) {
  460. mark_escaped(tw, d, scope, parent, parent, level + 1, depth);
  461. } else if (parent instanceof AST_ObjectKeyVal && node === parent.value) {
  462. var obj = tw.parent(level + 1);
  463. mark_escaped(tw, d, scope, obj, obj, level + 2, depth);
  464. } else if (parent instanceof AST_PropAccess && node === parent.expression) {
  465. value = read_property(value, parent.property);
  466. mark_escaped(tw, d, scope, parent, value, level + 1, depth + 1);
  467. if (value) return;
  468. }
  469. if (level > 0) return;
  470. if (parent instanceof AST_Sequence && node !== parent.tail_node()) return;
  471. if (parent instanceof AST_SimpleStatement) return;
  472. d.direct_access = true;
  473. }
  474. function mark_assignment_to_arguments(node) {
  475. if (!(node instanceof AST_Sub)) return;
  476. var expr = node.expression;
  477. var prop = node.property;
  478. if (expr instanceof AST_SymbolRef && expr.name == "arguments" && prop instanceof AST_Number) {
  479. expr.definition().reassigned = true;
  480. }
  481. }
  482. var suppressor = new TreeWalker(function(node) {
  483. if (!(node instanceof AST_Symbol)) return;
  484. var d = node.definition();
  485. if (!d) return;
  486. if (node instanceof AST_SymbolRef) d.references.push(node);
  487. d.fixed = false;
  488. });
  489. def(AST_Accessor, function(tw, descend, compressor) {
  490. push(tw);
  491. reset_variables(tw, compressor, this);
  492. descend();
  493. pop(tw);
  494. walk_defuns(tw, this);
  495. return true;
  496. });
  497. def(AST_Assign, function(tw, descend, compressor) {
  498. var node = this;
  499. var sym = node.left;
  500. if (!(sym instanceof AST_SymbolRef)) {
  501. mark_assignment_to_arguments(sym);
  502. return;
  503. }
  504. var d = sym.definition();
  505. var safe = safe_to_assign(tw, d, sym.scope, node.right);
  506. d.assignments++;
  507. if (!safe) return;
  508. var fixed = d.fixed;
  509. if (!fixed && node.operator != "=") return;
  510. var eq = node.operator == "=";
  511. var value = eq ? node.right : node;
  512. if (is_modified(compressor, tw, node, value, 0)) return;
  513. d.references.push(sym);
  514. if (!eq) d.chained = true;
  515. d.fixed = eq ? function() {
  516. return node.right;
  517. } : function() {
  518. return make_node(AST_Binary, node, {
  519. operator: node.operator.slice(0, -1),
  520. left: fixed instanceof AST_Node ? fixed : fixed(),
  521. right: node.right
  522. });
  523. };
  524. mark(tw, d, false);
  525. node.right.walk(tw);
  526. mark(tw, d, true);
  527. mark_escaped(tw, d, sym.scope, node, value, 0, 1);
  528. return true;
  529. });
  530. def(AST_Binary, function(tw) {
  531. if (!lazy_op[this.operator]) return;
  532. this.left.walk(tw);
  533. push(tw);
  534. this.right.walk(tw);
  535. pop(tw);
  536. return true;
  537. });
  538. def(AST_Call, function(tw, descend) {
  539. tw.find_parent(AST_Scope).may_call_this();
  540. var exp = this.expression;
  541. if (!(exp instanceof AST_SymbolRef)) return;
  542. var def = exp.definition();
  543. if (!(def.fixed instanceof AST_Defun)) return;
  544. var defun = mark_defun(tw, def);
  545. if (!defun) return;
  546. descend();
  547. defun.walk(tw);
  548. return true;
  549. });
  550. def(AST_Case, function(tw) {
  551. push(tw);
  552. this.expression.walk(tw);
  553. pop(tw);
  554. push(tw);
  555. walk_body(this, tw);
  556. pop(tw);
  557. return true;
  558. });
  559. def(AST_Conditional, function(tw) {
  560. this.condition.walk(tw);
  561. push(tw);
  562. this.consequent.walk(tw);
  563. pop(tw);
  564. push(tw);
  565. this.alternative.walk(tw);
  566. pop(tw);
  567. return true;
  568. });
  569. def(AST_Default, function(tw, descend) {
  570. push(tw);
  571. descend();
  572. pop(tw);
  573. return true;
  574. });
  575. def(AST_Defun, function(tw, descend, compressor) {
  576. var id = this.name.definition().id;
  577. if (tw.defun_visited[id]) return true;
  578. if (tw.defun_ids[id] !== tw.safe_ids) return true;
  579. tw.defun_visited[id] = true;
  580. this.inlined = false;
  581. push(tw);
  582. reset_variables(tw, compressor, this);
  583. descend();
  584. pop(tw);
  585. walk_defuns(tw, this);
  586. return true;
  587. });
  588. def(AST_Do, function(tw) {
  589. var saved_loop = tw.in_loop;
  590. tw.in_loop = this;
  591. push(tw);
  592. this.body.walk(tw);
  593. if (has_break_or_continue(this)) {
  594. pop(tw);
  595. push(tw);
  596. }
  597. this.condition.walk(tw);
  598. pop(tw);
  599. tw.in_loop = saved_loop;
  600. return true;
  601. });
  602. def(AST_For, function(tw) {
  603. if (this.init) this.init.walk(tw);
  604. var saved_loop = tw.in_loop;
  605. tw.in_loop = this;
  606. push(tw);
  607. if (this.condition) this.condition.walk(tw);
  608. this.body.walk(tw);
  609. if (this.step) {
  610. if (has_break_or_continue(this)) {
  611. pop(tw);
  612. push(tw);
  613. }
  614. this.step.walk(tw);
  615. }
  616. pop(tw);
  617. tw.in_loop = saved_loop;
  618. return true;
  619. });
  620. def(AST_ForIn, function(tw) {
  621. this.init.walk(suppressor);
  622. this.object.walk(tw);
  623. var saved_loop = tw.in_loop;
  624. tw.in_loop = this;
  625. push(tw);
  626. this.body.walk(tw);
  627. pop(tw);
  628. tw.in_loop = saved_loop;
  629. return true;
  630. });
  631. def(AST_Function, function(tw, descend, compressor) {
  632. var node = this;
  633. node.inlined = false;
  634. push(tw);
  635. reset_variables(tw, compressor, node);
  636. var iife;
  637. if (!node.name
  638. && (iife = tw.parent()) instanceof AST_Call
  639. && iife.expression === node) {
  640. // Virtually turn IIFE parameters into variable definitions:
  641. // (function(a,b) {...})(c,d) => (function() {var a=c,b=d; ...})()
  642. // So existing transformation rules can work on them.
  643. node.argnames.forEach(function(arg, i) {
  644. var d = arg.definition();
  645. if (d.fixed === undefined && (!node.uses_arguments || tw.has_directive("use strict"))) {
  646. d.fixed = function() {
  647. return iife.args[i] || make_node(AST_Undefined, iife);
  648. };
  649. tw.loop_ids[d.id] = tw.in_loop;
  650. mark(tw, d, true);
  651. } else {
  652. d.fixed = false;
  653. }
  654. });
  655. }
  656. descend();
  657. pop(tw);
  658. walk_defuns(tw, node);
  659. return true;
  660. });
  661. def(AST_If, function(tw) {
  662. this.condition.walk(tw);
  663. push(tw);
  664. this.body.walk(tw);
  665. pop(tw);
  666. if (this.alternative) {
  667. push(tw);
  668. this.alternative.walk(tw);
  669. pop(tw);
  670. }
  671. return true;
  672. });
  673. def(AST_LabeledStatement, function(tw) {
  674. push(tw);
  675. this.body.walk(tw);
  676. pop(tw);
  677. return true;
  678. });
  679. def(AST_SymbolCatch, function() {
  680. this.definition().fixed = false;
  681. });
  682. def(AST_SymbolRef, function(tw, descend, compressor) {
  683. var d = this.definition();
  684. d.references.push(this);
  685. if (d.references.length == 1
  686. && !d.fixed
  687. && d.orig[0] instanceof AST_SymbolDefun) {
  688. tw.loop_ids[d.id] = tw.in_loop;
  689. }
  690. var value;
  691. if (d.fixed === undefined || !safe_to_read(tw, d)) {
  692. d.fixed = false;
  693. } else if (d.fixed) {
  694. value = this.fixed_value();
  695. if (value instanceof AST_Lambda && recursive_ref(tw, d)) {
  696. d.recursive_refs++;
  697. } else if (value && ref_once(tw, compressor, d)) {
  698. d.single_use = value instanceof AST_Lambda && !value.pinned()
  699. || d.scope === this.scope && value.is_constant_expression();
  700. } else {
  701. d.single_use = false;
  702. }
  703. if (is_modified(compressor, tw, this, value, 0, is_immutable(value))) {
  704. if (d.single_use) {
  705. d.single_use = "m";
  706. } else {
  707. d.fixed = false;
  708. }
  709. }
  710. }
  711. mark_escaped(tw, d, this.scope, this, value, 0, 1);
  712. var parent;
  713. if (d.fixed instanceof AST_Defun
  714. && !((parent = tw.parent()) instanceof AST_Call && parent.expression === this)) {
  715. var defun = mark_defun(tw, d);
  716. if (defun) defun.walk(tw);
  717. }
  718. });
  719. def(AST_Toplevel, function(tw, descend, compressor) {
  720. this.globals.each(function(def) {
  721. reset_def(tw, compressor, def);
  722. });
  723. push(tw);
  724. reset_variables(tw, compressor, this);
  725. descend();
  726. pop(tw);
  727. walk_defuns(tw, this);
  728. return true;
  729. });
  730. def(AST_Try, function(tw) {
  731. push(tw);
  732. walk_body(this, tw);
  733. pop(tw);
  734. if (this.bcatch) {
  735. push(tw);
  736. this.bcatch.walk(tw);
  737. pop(tw);
  738. }
  739. if (this.bfinally) this.bfinally.walk(tw);
  740. return true;
  741. });
  742. def(AST_Unary, function(tw, descend) {
  743. var node = this;
  744. if (node.operator != "++" && node.operator != "--") return;
  745. var exp = node.expression;
  746. if (!(exp instanceof AST_SymbolRef)) {
  747. mark_assignment_to_arguments(exp);
  748. return;
  749. }
  750. var d = exp.definition();
  751. var safe = safe_to_assign(tw, d, exp.scope, true);
  752. d.assignments++;
  753. if (!safe) return;
  754. var fixed = d.fixed;
  755. if (!fixed) return;
  756. d.references.push(exp);
  757. d.chained = true;
  758. d.fixed = function() {
  759. return make_node(AST_Binary, node, {
  760. operator: node.operator.slice(0, -1),
  761. left: make_node(AST_UnaryPrefix, node, {
  762. operator: "+",
  763. expression: fixed instanceof AST_Node ? fixed : fixed()
  764. }),
  765. right: make_node(AST_Number, node, {
  766. value: 1
  767. })
  768. });
  769. };
  770. mark(tw, d, true);
  771. return true;
  772. });
  773. def(AST_VarDef, function(tw, descend) {
  774. var node = this;
  775. var d = node.name.definition();
  776. if (node.value) {
  777. if (safe_to_assign(tw, d, node.name.scope, node.value)) {
  778. d.fixed = function() {
  779. return node.value;
  780. };
  781. tw.loop_ids[d.id] = tw.in_loop;
  782. mark(tw, d, false);
  783. descend();
  784. mark(tw, d, true);
  785. return true;
  786. } else {
  787. d.fixed = false;
  788. }
  789. }
  790. });
  791. def(AST_While, function(tw, descend) {
  792. var saved_loop = tw.in_loop;
  793. tw.in_loop = this;
  794. push(tw);
  795. descend();
  796. pop(tw);
  797. tw.in_loop = saved_loop;
  798. return true;
  799. });
  800. })(function(node, func) {
  801. node.DEFMETHOD("reduce_vars", func);
  802. });
  803. AST_Toplevel.DEFMETHOD("reset_opt_flags", function(compressor) {
  804. var tw = new TreeWalker(compressor.option("reduce_vars") ? function(node, descend) {
  805. node._squeezed = false;
  806. node._optimized = false;
  807. return node.reduce_vars(tw, descend, compressor);
  808. } : function(node) {
  809. node._squeezed = false;
  810. node._optimized = false;
  811. });
  812. // Flow control for visiting `AST_Defun`s
  813. tw.defun_ids = Object.create(null);
  814. tw.defun_visited = Object.create(null);
  815. // Record the loop body in which `AST_SymbolDeclaration` is first encountered
  816. tw.in_loop = null;
  817. tw.loop_ids = Object.create(null);
  818. // Stack of look-up tables to keep track of whether a `SymbolDef` has been
  819. // properly assigned before use:
  820. // - `push()` & `pop()` when visiting conditional branches
  821. // - backup & restore via `save_ids` when visiting out-of-order sections
  822. tw.safe_ids = Object.create(null);
  823. this.walk(tw);
  824. });
  825. AST_Symbol.DEFMETHOD("fixed_value", function() {
  826. var fixed = this.definition().fixed;
  827. if (!fixed || fixed instanceof AST_Node) return fixed;
  828. return fixed();
  829. });
  830. AST_SymbolRef.DEFMETHOD("is_immutable", function() {
  831. var orig = this.definition().orig;
  832. return orig.length == 1 && orig[0] instanceof AST_SymbolLambda;
  833. });
  834. function is_lhs_read_only(lhs) {
  835. if (lhs instanceof AST_This) return true;
  836. if (lhs instanceof AST_SymbolRef) return lhs.definition().orig[0] instanceof AST_SymbolLambda;
  837. if (lhs instanceof AST_PropAccess) {
  838. lhs = lhs.expression;
  839. if (lhs instanceof AST_SymbolRef) {
  840. if (lhs.is_immutable()) return false;
  841. lhs = lhs.fixed_value();
  842. }
  843. if (!lhs) return true;
  844. if (lhs.is_constant()) return true;
  845. return is_lhs_read_only(lhs);
  846. }
  847. return false;
  848. }
  849. function find_variable(compressor, name) {
  850. var scope, i = 0;
  851. while (scope = compressor.parent(i++)) {
  852. if (scope instanceof AST_Scope) break;
  853. if (scope instanceof AST_Catch) {
  854. scope = scope.argname.definition().scope;
  855. break;
  856. }
  857. }
  858. return scope.find_variable(name);
  859. }
  860. function make_node(ctor, orig, props) {
  861. if (!props) props = {};
  862. if (orig) {
  863. if (!props.start) props.start = orig.start;
  864. if (!props.end) props.end = orig.end;
  865. }
  866. return new ctor(props);
  867. }
  868. function make_sequence(orig, expressions) {
  869. if (expressions.length == 1) return expressions[0];
  870. return make_node(AST_Sequence, orig, {
  871. expressions: expressions.reduce(merge_sequence, [])
  872. });
  873. }
  874. function make_node_from_constant(val, orig) {
  875. switch (typeof val) {
  876. case "string":
  877. return make_node(AST_String, orig, {
  878. value: val
  879. });
  880. case "number":
  881. if (isNaN(val)) return make_node(AST_NaN, orig);
  882. if (isFinite(val)) {
  883. return 1 / val < 0 ? make_node(AST_UnaryPrefix, orig, {
  884. operator: "-",
  885. expression: make_node(AST_Number, orig, { value: -val })
  886. }) : make_node(AST_Number, orig, { value: val });
  887. }
  888. return val < 0 ? make_node(AST_UnaryPrefix, orig, {
  889. operator: "-",
  890. expression: make_node(AST_Infinity, orig)
  891. }) : make_node(AST_Infinity, orig);
  892. case "boolean":
  893. return make_node(val ? AST_True : AST_False, orig);
  894. case "undefined":
  895. return make_node(AST_Undefined, orig);
  896. default:
  897. if (val === null) {
  898. return make_node(AST_Null, orig, { value: null });
  899. }
  900. if (val instanceof RegExp) {
  901. return make_node(AST_RegExp, orig, { value: val });
  902. }
  903. throw new Error(string_template("Can't handle constant of type: {type}", {
  904. type: typeof val
  905. }));
  906. }
  907. }
  908. function needs_unbinding(compressor, val) {
  909. return val instanceof AST_PropAccess
  910. || compressor.has_directive("use strict")
  911. && is_undeclared_ref(val)
  912. && val.name == "eval";
  913. }
  914. // we shouldn't compress (1,func)(something) to
  915. // func(something) because that changes the meaning of
  916. // the func (becomes lexical instead of global).
  917. function maintain_this_binding(compressor, parent, orig, val) {
  918. if (parent instanceof AST_UnaryPrefix && parent.operator == "delete"
  919. || parent.TYPE == "Call" && parent.expression === orig && needs_unbinding(compressor, val)) {
  920. return make_sequence(orig, [ make_node(AST_Number, orig, { value: 0 }), val ]);
  921. }
  922. return val;
  923. }
  924. function merge_sequence(array, node) {
  925. if (node instanceof AST_Sequence) {
  926. array.push.apply(array, node.expressions);
  927. } else {
  928. array.push(node);
  929. }
  930. return array;
  931. }
  932. function as_statement_array(thing) {
  933. if (thing === null) return [];
  934. if (thing instanceof AST_BlockStatement) return thing.body;
  935. if (thing instanceof AST_EmptyStatement) return [];
  936. if (thing instanceof AST_Statement) return [ thing ];
  937. throw new Error("Can't convert thing to statement array");
  938. }
  939. function is_empty(thing) {
  940. if (thing === null) return true;
  941. if (thing instanceof AST_EmptyStatement) return true;
  942. if (thing instanceof AST_BlockStatement) return thing.body.length == 0;
  943. return false;
  944. }
  945. function loop_body(x) {
  946. if (x instanceof AST_IterationStatement) {
  947. return x.body instanceof AST_BlockStatement ? x.body : x;
  948. }
  949. return x;
  950. }
  951. function root_expr(prop) {
  952. while (prop instanceof AST_PropAccess) prop = prop.expression;
  953. return prop;
  954. }
  955. function is_iife_call(node) {
  956. if (node.TYPE != "Call") return false;
  957. return node.expression instanceof AST_Function || is_iife_call(node.expression);
  958. }
  959. function is_undeclared_ref(node) {
  960. return node instanceof AST_SymbolRef && node.definition().undeclared;
  961. }
  962. var global_names = makePredicate("Array Boolean clearInterval clearTimeout console Date decodeURI decodeURIComponent encodeURI encodeURIComponent Error escape eval EvalError Function isFinite isNaN JSON Math Number parseFloat parseInt RangeError ReferenceError RegExp Object setInterval setTimeout String SyntaxError TypeError unescape URIError");
  963. AST_SymbolRef.DEFMETHOD("is_declared", function(compressor) {
  964. return !this.definition().undeclared
  965. || compressor.option("unsafe") && global_names[this.name];
  966. });
  967. var identifier_atom = makePredicate("Infinity NaN undefined");
  968. function is_identifier_atom(node) {
  969. return node instanceof AST_Infinity
  970. || node instanceof AST_NaN
  971. || node instanceof AST_Undefined;
  972. }
  973. function tighten_body(statements, compressor) {
  974. var in_loop, in_try, scope;
  975. find_loop_scope_try();
  976. var CHANGED, max_iter = 10;
  977. do {
  978. CHANGED = false;
  979. eliminate_spurious_blocks(statements);
  980. if (compressor.option("dead_code")) {
  981. eliminate_dead_code(statements, compressor);
  982. }
  983. if (compressor.option("if_return")) {
  984. handle_if_return(statements, compressor);
  985. }
  986. if (compressor.sequences_limit > 0) {
  987. sequencesize(statements, compressor);
  988. sequencesize_2(statements, compressor);
  989. }
  990. if (compressor.option("join_vars")) {
  991. join_consecutive_vars(statements);
  992. }
  993. if (compressor.option("collapse_vars")) {
  994. collapse(statements, compressor);
  995. }
  996. } while (CHANGED && max_iter-- > 0);
  997. function find_loop_scope_try() {
  998. var node = compressor.self(), level = 0;
  999. do {
  1000. if (node instanceof AST_Catch || node instanceof AST_Finally) {
  1001. level++;
  1002. } else if (node instanceof AST_IterationStatement) {
  1003. in_loop = true;
  1004. } else if (node instanceof AST_Scope) {
  1005. scope = node;
  1006. break;
  1007. } else if (node instanceof AST_Try) {
  1008. in_try = true;
  1009. }
  1010. } while (node = compressor.parent(level++));
  1011. }
  1012. // Search from right to left for assignment-like expressions:
  1013. // - `var a = x;`
  1014. // - `a = x;`
  1015. // - `++a`
  1016. // For each candidate, scan from left to right for first usage, then try
  1017. // to fold assignment into the site for compression.
  1018. // Will not attempt to collapse assignments into or past code blocks
  1019. // which are not sequentially executed, e.g. loops and conditionals.
  1020. function collapse(statements, compressor) {
  1021. if (scope.pinned()) return statements;
  1022. var args;
  1023. var candidates = [];
  1024. var stat_index = statements.length;
  1025. var scanner = new TreeTransformer(function(node) {
  1026. if (abort) return node;
  1027. // Skip nodes before `candidate` as quickly as possible
  1028. if (!hit) {
  1029. if (node !== hit_stack[hit_index]) return node;
  1030. hit_index++;
  1031. if (hit_index < hit_stack.length) return handle_custom_scan_order(node);
  1032. hit = true;
  1033. stop_after = find_stop(node, 0);
  1034. if (stop_after === node) abort = true;
  1035. return node;
  1036. }
  1037. // Stop immediately if these node types are encountered
  1038. var parent = scanner.parent();
  1039. if (should_stop(node, parent)) {
  1040. abort = true;
  1041. return node;
  1042. }
  1043. // Stop only if candidate is found within conditional branches
  1044. if (!stop_if_hit && in_conditional(node, parent)) {
  1045. stop_if_hit = parent;
  1046. }
  1047. // Replace variable with assignment when found
  1048. var hit_lhs, hit_rhs;
  1049. if (can_replace
  1050. && !(node instanceof AST_SymbolDeclaration)
  1051. && (scan_lhs && (hit_lhs = lhs.equivalent_to(node))
  1052. || scan_rhs && (hit_rhs = scan_rhs(node, this)))) {
  1053. if (stop_if_hit && (hit_rhs || !lhs_local || !replace_all)) {
  1054. abort = true;
  1055. return node;
  1056. }
  1057. if (is_lhs(node, parent)) {
  1058. if (value_def) replaced++;
  1059. return node;
  1060. } else {
  1061. replaced++;
  1062. if (value_def && candidate instanceof AST_VarDef) return node;
  1063. }
  1064. CHANGED = abort = true;
  1065. compressor.info("Collapsing {name} [{file}:{line},{col}]", {
  1066. name: node.print_to_string(),
  1067. file: node.start.file,
  1068. line: node.start.line,
  1069. col: node.start.col
  1070. });
  1071. if (candidate instanceof AST_UnaryPostfix) {
  1072. return make_node(AST_UnaryPrefix, candidate, candidate);
  1073. }
  1074. if (candidate instanceof AST_VarDef) {
  1075. var def = candidate.name.definition();
  1076. if (def.references.length - def.replaced == 1 && !compressor.exposed(def)) {
  1077. def.replaced++;
  1078. return maintain_this_binding(compressor, parent, node, candidate.value);
  1079. }
  1080. return make_node(AST_Assign, candidate, {
  1081. operator: "=",
  1082. left: make_node(AST_SymbolRef, candidate.name, candidate.name),
  1083. right: candidate.value
  1084. });
  1085. }
  1086. candidate.write_only = false;
  1087. return candidate;
  1088. }
  1089. // These node types have child nodes that execute sequentially,
  1090. // but are otherwise not safe to scan into or beyond them.
  1091. var sym;
  1092. if (is_last_node(node, parent) || may_throw(node)) {
  1093. stop_after = node;
  1094. if (node instanceof AST_Scope) abort = true;
  1095. }
  1096. return handle_custom_scan_order(node);
  1097. }, function(node) {
  1098. if (abort) return;
  1099. if (stop_after === node) abort = true;
  1100. if (stop_if_hit === node) stop_if_hit = null;
  1101. });
  1102. var multi_replacer = new TreeTransformer(function(node) {
  1103. if (abort) return node;
  1104. // Skip nodes before `candidate` as quickly as possible
  1105. if (!hit) {
  1106. if (node !== hit_stack[hit_index]) return node;
  1107. hit_index++;
  1108. if (hit_index < hit_stack.length) return;
  1109. hit = true;
  1110. return node;
  1111. }
  1112. // Replace variable when found
  1113. if (node instanceof AST_SymbolRef
  1114. && node.name == def.name) {
  1115. if (!--replaced) abort = true;
  1116. if (is_lhs(node, multi_replacer.parent())) return node;
  1117. def.replaced++;
  1118. value_def.replaced--;
  1119. return candidate.value.clone();
  1120. }
  1121. // Skip (non-executed) functions and (leading) default case in switch statements
  1122. if (node instanceof AST_Default || node instanceof AST_Scope) return node;
  1123. });
  1124. while (--stat_index >= 0) {
  1125. // Treat parameters as collapsible in IIFE, i.e.
  1126. // function(a, b){ ... }(x());
  1127. // would be translated into equivalent assignments:
  1128. // var a = x(), b = undefined;
  1129. if (stat_index == 0 && compressor.option("unused")) extract_args();
  1130. // Find collapsible assignments
  1131. var hit_stack = [];
  1132. extract_candidates(statements[stat_index]);
  1133. while (candidates.length > 0) {
  1134. hit_stack = candidates.pop();
  1135. var hit_index = 0;
  1136. var candidate = hit_stack[hit_stack.length - 1];
  1137. var value_def = null;
  1138. var stop_after = null;
  1139. var stop_if_hit = null;
  1140. var lhs = get_lhs(candidate);
  1141. var rhs = get_rhs(candidate);
  1142. var side_effects = lhs && lhs.has_side_effects(compressor);
  1143. var scan_lhs = lhs && !side_effects && !is_lhs_read_only(lhs);
  1144. var scan_rhs = rhs && foldable(rhs);
  1145. if (!scan_lhs && !scan_rhs) continue;
  1146. // Locate symbols which may execute code outside of scanning range
  1147. var lvalues = get_lvalues(candidate);
  1148. var lhs_local = is_lhs_local(lhs);
  1149. if (!side_effects) side_effects = value_has_side_effects(candidate);
  1150. var replace_all = replace_all_symbols();
  1151. var may_throw = candidate.may_throw(compressor) ? in_try ? function(node) {
  1152. return node.has_side_effects(compressor);
  1153. } : side_effects_external : return_false;
  1154. var funarg = candidate.name instanceof AST_SymbolFunarg;
  1155. var hit = funarg;
  1156. var abort = false, replaced = 0, can_replace = !args || !hit;
  1157. if (!can_replace) {
  1158. for (var j = compressor.self().argnames.lastIndexOf(candidate.name) + 1; !abort && j < args.length; j++) {
  1159. args[j].transform(scanner);
  1160. }
  1161. can_replace = true;
  1162. }
  1163. for (var i = stat_index; !abort && i < statements.length; i++) {
  1164. statements[i].transform(scanner);
  1165. }
  1166. if (value_def) {
  1167. var def = candidate.name.definition();
  1168. if (abort && def.references.length - def.replaced > replaced) replaced = false;
  1169. else {
  1170. abort = false;
  1171. hit_index = 0;
  1172. hit = funarg;
  1173. for (var i = stat_index; !abort && i < statements.length; i++) {
  1174. statements[i].transform(multi_replacer);
  1175. }
  1176. value_def.single_use = false;
  1177. }
  1178. }
  1179. if (replaced && !remove_candidate(candidate)) statements.splice(stat_index, 1);
  1180. }
  1181. }
  1182. function handle_custom_scan_order(node) {
  1183. // Skip (non-executed) functions
  1184. if (node instanceof AST_Scope) return node;
  1185. // Scan case expressions first in a switch statement
  1186. if (node instanceof AST_Switch) {
  1187. node.expression = node.expression.transform(scanner);
  1188. for (var i = 0, len = node.body.length; !abort && i < len; i++) {
  1189. var branch = node.body[i];
  1190. if (branch instanceof AST_Case) {
  1191. if (!hit) {
  1192. if (branch !== hit_stack[hit_index]) continue;
  1193. hit_index++;
  1194. }
  1195. branch.expression = branch.expression.transform(scanner);
  1196. if (!replace_all) break;
  1197. }
  1198. }
  1199. abort = true;
  1200. return node;
  1201. }
  1202. }
  1203. function should_stop(node, parent) {
  1204. if (parent instanceof AST_For) return node !== parent.init;
  1205. if (node instanceof AST_Assign) {
  1206. return node.operator != "=" && lhs.equivalent_to(node.left);
  1207. }
  1208. if (node instanceof AST_Call) {
  1209. return lhs instanceof AST_PropAccess && lhs.equivalent_to(node.expression);
  1210. }
  1211. if (node instanceof AST_Debugger) return true;
  1212. if (node instanceof AST_IterationStatement) return !(node instanceof AST_For);
  1213. if (node instanceof AST_LoopControl) return true;
  1214. if (node instanceof AST_Try) return true;
  1215. if (node instanceof AST_With) return true;
  1216. if (replace_all) return false;
  1217. return node instanceof AST_SymbolRef && !node.is_declared(compressor);
  1218. }
  1219. function in_conditional(node, parent) {
  1220. if (parent instanceof AST_Binary) return lazy_op[parent.operator] && parent.left !== node;
  1221. if (parent instanceof AST_Conditional) return parent.condition !== node;
  1222. return parent instanceof AST_If && parent.condition !== node;
  1223. }
  1224. function is_last_node(node, parent) {
  1225. if (node instanceof AST_Call) return true;
  1226. if (node instanceof AST_Exit) {
  1227. return side_effects || lhs instanceof AST_PropAccess || may_modify(lhs);
  1228. }
  1229. if (node instanceof AST_Function) {
  1230. return compressor.option("ie8") && node.name && node.name.name in lvalues;
  1231. }
  1232. if (node instanceof AST_PropAccess) {
  1233. return side_effects || node.expression.may_throw_on_access(compressor);
  1234. }
  1235. if (node instanceof AST_SymbolRef) {
  1236. if (symbol_in_lvalues(node, parent)) {
  1237. return !parent || parent.operator != "=" || parent.left !== node;
  1238. }
  1239. return side_effects && may_modify(node);
  1240. }
  1241. if (node instanceof AST_This) return symbol_in_lvalues(node, parent);
  1242. if (node instanceof AST_VarDef) {
  1243. if (!node.value) return false;
  1244. return node.name.name in lvalues || side_effects && may_modify(node.name);
  1245. }
  1246. var sym = is_lhs(node.left, node);
  1247. if (sym && sym.name in lvalues) return true;
  1248. if (sym instanceof AST_PropAccess) return true;
  1249. }
  1250. function extract_args() {
  1251. var iife, fn = compressor.self();
  1252. if (fn instanceof AST_Function
  1253. && !fn.name
  1254. && !fn.uses_arguments
  1255. && !fn.pinned()
  1256. && (iife = compressor.parent()) instanceof AST_Call
  1257. && iife.expression === fn) {
  1258. var fn_strict = compressor.has_directive("use strict");
  1259. if (fn_strict && !member(fn_strict, fn.body)) fn_strict = false;
  1260. var len = fn.argnames.length;
  1261. args = iife.args.slice(len);
  1262. var names = Object.create(null);
  1263. for (var i = len; --i >= 0;) {
  1264. var sym = fn.argnames[i];
  1265. var arg = iife.args[i];
  1266. args.unshift(make_node(AST_VarDef, sym, {
  1267. name: sym,
  1268. value: arg
  1269. }));
  1270. if (sym.name in names) continue;
  1271. names[sym.name] = true;
  1272. if (!arg) {
  1273. arg = make_node(AST_Undefined, sym).transform(compressor);
  1274. } else if (arg instanceof AST_Lambda && arg.pinned()) {
  1275. arg = null;
  1276. } else {
  1277. arg.walk(new TreeWalker(function(node) {
  1278. if (!arg) return true;
  1279. if (node instanceof AST_SymbolRef && fn.variables.has(node.name)) {
  1280. var s = node.definition().scope;
  1281. if (s !== scope) while (s = s.parent_scope) {
  1282. if (s === scope) return true;
  1283. }
  1284. arg = null;
  1285. }
  1286. if (node instanceof AST_This && (fn_strict || !this.find_parent(AST_Scope))) {
  1287. arg = null;
  1288. return true;
  1289. }
  1290. }));
  1291. }
  1292. if (arg) candidates.unshift([ make_node(AST_VarDef, sym, {
  1293. name: sym,
  1294. value: arg
  1295. }) ]);
  1296. }
  1297. }
  1298. }
  1299. function extract_candidates(expr) {
  1300. hit_stack.push(expr);
  1301. if (expr instanceof AST_Assign) {
  1302. candidates.push(hit_stack.slice());
  1303. extract_candidates(expr.right);
  1304. } else if (expr instanceof AST_Binary) {
  1305. extract_candidates(expr.left);
  1306. extract_candidates(expr.right);
  1307. } else if (expr instanceof AST_Call) {
  1308. extract_candidates(expr.expression);
  1309. expr.args.forEach(extract_candidates);
  1310. } else if (expr instanceof AST_Case) {
  1311. extract_candidates(expr.expression);
  1312. } else if (expr instanceof AST_Conditional) {
  1313. extract_candidates(expr.condition);
  1314. extract_candidates(expr.consequent);
  1315. extract_candidates(expr.alternative);
  1316. } else if (expr instanceof AST_Definitions) {
  1317. expr.definitions.forEach(extract_candidates);
  1318. } else if (expr instanceof AST_DWLoop) {
  1319. extract_candidates(expr.condition);
  1320. if (!(expr.body instanceof AST_Block)) {
  1321. extract_candidates(expr.body);
  1322. }
  1323. } else if (expr instanceof AST_Exit) {
  1324. if (expr.value) extract_candidates(expr.value);
  1325. } else if (expr instanceof AST_For) {
  1326. if (expr.init) extract_candidates(expr.init);
  1327. if (expr.condition) extract_candidates(expr.condition);
  1328. if (expr.step) extract_candidates(expr.step);
  1329. if (!(expr.body instanceof AST_Block)) {
  1330. extract_candidates(expr.body);
  1331. }
  1332. } else if (expr instanceof AST_ForIn) {
  1333. extract_candidates(expr.object);
  1334. if (!(expr.body instanceof AST_Block)) {
  1335. extract_candidates(expr.body);
  1336. }
  1337. } else if (expr instanceof AST_If) {
  1338. extract_candidates(expr.condition);
  1339. if (!(expr.body instanceof AST_Block)) {
  1340. extract_candidates(expr.body);
  1341. }
  1342. if (expr.alternative && !(expr.alternative instanceof AST_Block)) {
  1343. extract_candidates(expr.alternative);
  1344. }
  1345. } else if (expr instanceof AST_Sequence) {
  1346. expr.expressions.forEach(extract_candidates);
  1347. } else if (expr instanceof AST_SimpleStatement) {
  1348. extract_candidates(expr.body);
  1349. } else if (expr instanceof AST_Switch) {
  1350. extract_candidates(expr.expression);
  1351. expr.body.forEach(extract_candidates);
  1352. } else if (expr instanceof AST_Unary) {
  1353. if (expr.operator == "++" || expr.operator == "--") {
  1354. candidates.push(hit_stack.slice());
  1355. } else {
  1356. extract_candidates(expr.expression);
  1357. }
  1358. } else if (expr instanceof AST_VarDef) {
  1359. if (expr.value) {
  1360. var def = expr.name.definition();
  1361. if (def.references.length > def.replaced) {
  1362. candidates.push(hit_stack.slice());
  1363. }
  1364. extract_candidates(expr.value);
  1365. }
  1366. }
  1367. hit_stack.pop();
  1368. }
  1369. function find_stop(node, level, write_only) {
  1370. var parent = scanner.parent(level);
  1371. if (parent instanceof AST_Assign) {
  1372. if (write_only
  1373. && !(parent.left instanceof AST_PropAccess
  1374. || parent.left.name in lvalues)) {
  1375. return find_stop(parent, level + 1, write_only);
  1376. }
  1377. return node;
  1378. }
  1379. if (parent instanceof AST_Binary) {
  1380. if (write_only && (!lazy_op[parent.operator] || parent.left === node)) {
  1381. return find_stop(parent, level + 1, write_only);
  1382. }
  1383. return node;
  1384. }
  1385. if (parent instanceof AST_Call) return node;
  1386. if (parent instanceof AST_Case) return node;
  1387. if (parent instanceof AST_Conditional) {
  1388. if (write_only && parent.condition === node) {
  1389. return find_stop(parent, level + 1, write_only);
  1390. }
  1391. return node;
  1392. }
  1393. if (parent instanceof AST_Definitions) {
  1394. return find_stop(parent, level + 1, true);
  1395. }
  1396. if (parent instanceof AST_Exit) {
  1397. return write_only ? find_stop(parent, level + 1, write_only) : node;
  1398. }
  1399. if (parent instanceof AST_If) {
  1400. if (write_only && parent.condition === node) {
  1401. return find_stop(parent, level + 1, write_only);
  1402. }
  1403. return node;
  1404. }
  1405. if (parent instanceof AST_IterationStatement) return node;
  1406. if (parent instanceof AST_Sequence) {
  1407. return find_stop(parent, level + 1, parent.tail_node() !== node);
  1408. }
  1409. if (parent instanceof AST_SimpleStatement) {
  1410. return find_stop(parent, level + 1, true);
  1411. }
  1412. if (parent instanceof AST_Switch) return node;
  1413. if (parent instanceof AST_Unary) return node;
  1414. if (parent instanceof AST_VarDef) return node;
  1415. return null;
  1416. }
  1417. function mangleable_var(var_def) {
  1418. var value = var_def.value;
  1419. if (!(value instanceof AST_SymbolRef)) return;
  1420. if (value.name == "arguments") return;
  1421. var def = value.definition();
  1422. if (def.undeclared) return;
  1423. return value_def = def;
  1424. }
  1425. function get_lhs(expr) {
  1426. if (expr instanceof AST_VarDef) {
  1427. var def = expr.name.definition();
  1428. if (!member(expr.name, def.orig)) return;
  1429. var referenced = def.references.length - def.replaced;
  1430. var declared = def.orig.length - def.eliminated;
  1431. if (declared > 1 && !(expr.name instanceof AST_SymbolFunarg)
  1432. || (referenced > 1 ? mangleable_var(expr) : !compressor.exposed(def))) {
  1433. return make_node(AST_SymbolRef, expr.name, expr.name);
  1434. }
  1435. } else {
  1436. return expr[expr instanceof AST_Assign ? "left" : "expression"];
  1437. }
  1438. }
  1439. function get_rhs(expr) {
  1440. return candidate instanceof AST_Assign && candidate.operator == "=" && candidate.right;
  1441. }
  1442. function get_rvalue(expr) {
  1443. return expr[expr instanceof AST_Assign ? "right" : "value"];
  1444. }
  1445. function invariant(expr) {
  1446. if (expr instanceof AST_Array) return false;
  1447. if (expr instanceof AST_Binary && lazy_op[expr.operator]) {
  1448. return invariant(expr.left) && invariant(expr.right);
  1449. }
  1450. if (expr instanceof AST_Call) return false;
  1451. if (expr instanceof AST_Conditional) {
  1452. return invariant(expr.consequent) && invariant(expr.alternative);
  1453. }
  1454. if (expr instanceof AST_Object) return false;
  1455. return !expr.has_side_effects(compressor);
  1456. }
  1457. function foldable(expr) {
  1458. if (expr instanceof AST_SymbolRef) {
  1459. var value = expr.evaluate(compressor);
  1460. if (value === expr) return rhs_exact_match;
  1461. return rhs_fuzzy_match(value, rhs_exact_match);
  1462. }
  1463. if (expr instanceof AST_This) return rhs_exact_match;
  1464. if (expr.is_truthy()) return rhs_fuzzy_match(true, return_false);
  1465. if (expr.is_constant()) {
  1466. return rhs_fuzzy_match(expr.evaluate(compressor), rhs_exact_match);
  1467. }
  1468. if (!(lhs instanceof AST_SymbolRef)) return false;
  1469. if (!invariant(expr)) return false;
  1470. var circular;
  1471. var def = lhs.definition();
  1472. expr.walk(new TreeWalker(function(node) {
  1473. if (circular) return true;
  1474. if (node instanceof AST_SymbolRef && node.definition() === def) {
  1475. circular = true;
  1476. }
  1477. }));
  1478. return !circular && rhs_exact_match;
  1479. }
  1480. function rhs_exact_match(node) {
  1481. return rhs.equivalent_to(node);
  1482. }
  1483. function rhs_fuzzy_match(value, fallback) {
  1484. return function(node, tw) {
  1485. if (tw.in_boolean_context()) {
  1486. if (value && node.is_truthy() && !node.has_side_effects(compressor)) {
  1487. return true;
  1488. }
  1489. if (node.is_constant()) {
  1490. return !node.evaluate(compressor) == !value;
  1491. }
  1492. }
  1493. return fallback(node);
  1494. };
  1495. }
  1496. function get_lvalues(expr) {
  1497. var lvalues = Object.create(null);
  1498. if (candidate instanceof AST_VarDef) {
  1499. lvalues[candidate.name.name] = lhs;
  1500. }
  1501. var tw = new TreeWalker(function(node) {
  1502. var sym = root_expr(node);
  1503. if (sym instanceof AST_SymbolRef || sym instanceof AST_This) {
  1504. lvalues[sym.name] = lvalues[sym.name] || is_modified(compressor, tw, node, node, 0);
  1505. }
  1506. });
  1507. expr.walk(tw);
  1508. return lvalues;
  1509. }
  1510. function remove_candidate(expr) {
  1511. if (expr.name instanceof AST_SymbolFunarg) {
  1512. var index = compressor.self().argnames.indexOf(expr.name);
  1513. var args = compressor.parent().args;
  1514. if (args[index]) args[index] = make_node(AST_Number, args[index], {
  1515. value: 0
  1516. });
  1517. return true;
  1518. }
  1519. var found = false;
  1520. return statements[stat_index].transform(new TreeTransformer(function(node, descend, in_list) {
  1521. if (found) return node;
  1522. if (node !== expr && node.body !== expr) return;
  1523. if (node instanceof AST_VarDef) {
  1524. found = true;
  1525. node.value = null;
  1526. return node;
  1527. }
  1528. if (in_list) {
  1529. found = true;
  1530. return MAP.skip;
  1531. }
  1532. if (!this.parent()) {
  1533. found = true;
  1534. return null;
  1535. }
  1536. }, function(node) {
  1537. if (node instanceof AST_Sequence) switch (node.expressions.length) {
  1538. case 0: return null;
  1539. case 1: return node.expressions[0];
  1540. }
  1541. }));
  1542. }
  1543. function is_lhs_local(lhs) {
  1544. var sym = root_expr(lhs);
  1545. return sym instanceof AST_SymbolRef
  1546. && sym.definition().scope === scope
  1547. && !(in_loop
  1548. && (sym.name in lvalues && lvalues[sym.name] !== lhs
  1549. || candidate instanceof AST_Unary
  1550. || candidate instanceof AST_Assign && candidate.operator != "="));
  1551. }
  1552. function value_has_side_effects(expr) {
  1553. if (expr instanceof AST_Unary) return false;
  1554. return get_rvalue(expr).has_side_effects(compressor);
  1555. }
  1556. function replace_all_symbols() {
  1557. if (side_effects) return false;
  1558. if (value_def) return true;
  1559. if (lhs instanceof AST_SymbolRef) {
  1560. var def = lhs.definition();
  1561. if (def.references.length - def.replaced == (candidate instanceof AST_VarDef ? 1 : 2)) {
  1562. return true;
  1563. }
  1564. }
  1565. return false;
  1566. }
  1567. function symbol_in_lvalues(sym, parent) {
  1568. var lvalue = lvalues[sym.name];
  1569. if (!lvalue) return;
  1570. if (lvalue !== lhs) return !(parent instanceof AST_Call && parent.expression === sym);
  1571. scan_rhs = false;
  1572. }
  1573. function may_modify(sym) {
  1574. var def = sym.definition();
  1575. if (def.orig.length == 1 && def.orig[0] instanceof AST_SymbolDefun) return false;
  1576. if (def.scope !== scope) return true;
  1577. return !all(def.references, function(ref) {
  1578. return ref.scope.resolve() === scope;
  1579. });
  1580. }
  1581. function side_effects_external(node, lhs) {
  1582. if (node instanceof AST_Assign) return side_effects_external(node.left, true);
  1583. if (node instanceof AST_Unary) return side_effects_external(node.expression, true);
  1584. if (node instanceof AST_VarDef) return node.value && side_effects_external(node.value);
  1585. if (lhs) {
  1586. if (node instanceof AST_Dot) return side_effects_external(node.expression, true);
  1587. if (node instanceof AST_Sub) return side_effects_external(node.expression, true);
  1588. if (node instanceof AST_SymbolRef) return node.definition().scope !== scope;
  1589. }
  1590. return false;
  1591. }
  1592. }
  1593. function eliminate_spurious_blocks(statements) {
  1594. var seen_dirs = [];
  1595. for (var i = 0; i < statements.length;) {
  1596. var stat = statements[i];
  1597. if (stat instanceof AST_BlockStatement) {
  1598. CHANGED = true;
  1599. eliminate_spurious_blocks(stat.body);
  1600. [].splice.apply(statements, [i, 1].concat(stat.body));
  1601. i += stat.body.length;
  1602. } else if (stat instanceof AST_EmptyStatement) {
  1603. CHANGED = true;
  1604. statements.splice(i, 1);
  1605. } else if (stat instanceof AST_Directive) {
  1606. if (seen_dirs.indexOf(stat.value) < 0) {
  1607. i++;
  1608. seen_dirs.push(stat.value);
  1609. } else {
  1610. CHANGED = true;
  1611. statements.splice(i, 1);
  1612. }
  1613. } else i++;
  1614. }
  1615. }
  1616. function handle_if_return(statements, compressor) {
  1617. var self = compressor.self();
  1618. var multiple_if_returns = has_multiple_if_returns(statements);
  1619. var in_lambda = self instanceof AST_Lambda;
  1620. for (var i = statements.length; --i >= 0;) {
  1621. var stat = statements[i];
  1622. var j = next_index(i);
  1623. var next = statements[j];
  1624. if (in_lambda && !next && stat instanceof AST_Return) {
  1625. if (!stat.value) {
  1626. CHANGED = true;
  1627. statements.splice(i, 1);
  1628. continue;
  1629. }
  1630. if (stat.value instanceof AST_UnaryPrefix && stat.value.operator == "void") {
  1631. CHANGED = true;
  1632. statements[i] = make_node(AST_SimpleStatement, stat, {
  1633. body: stat.value.expression
  1634. });
  1635. continue;
  1636. }
  1637. }
  1638. if (stat instanceof AST_If) {
  1639. var ab = aborts(stat.body);
  1640. if (can_merge_flow(ab)) {
  1641. if (ab.label) {
  1642. remove(ab.label.thedef.references, ab);
  1643. }
  1644. CHANGED = true;
  1645. stat = stat.clone();
  1646. stat.condition = stat.condition.negate(compressor);
  1647. var body = as_statement_array_with_return(stat.body, ab);
  1648. stat.body = make_node(AST_BlockStatement, stat, {
  1649. body: as_statement_array(stat.alternative).concat(extract_functions())
  1650. });
  1651. stat.alternative = make_node(AST_BlockStatement, stat, {
  1652. body: body
  1653. });
  1654. statements[i] = stat.transform(compressor);
  1655. continue;
  1656. }
  1657. if (ab && !stat.alternative && stat.body instanceof AST_BlockStatement && next instanceof AST_Jump) {
  1658. var negated = stat.condition.negate(compressor);
  1659. if (negated.print_to_string().length <= stat.condition.print_to_string().length) {
  1660. CHANGED = true;
  1661. stat = stat.clone();
  1662. stat.condition = negated;
  1663. statements[j] = stat.body;
  1664. stat.body = next;
  1665. statements[i] = stat.transform(compressor);
  1666. continue;
  1667. }
  1668. }
  1669. var ab = aborts(stat.alternative);
  1670. if (can_merge_flow(ab)) {
  1671. if (ab.label) {
  1672. remove(ab.label.thedef.references, ab);
  1673. }
  1674. CHANGED = true;
  1675. stat = stat.clone();
  1676. stat.body = make_node(AST_BlockStatement, stat.body, {
  1677. body: as_statement_array(stat.body).concat(extract_functions())
  1678. });
  1679. var body = as_statement_array_with_return(stat.alternative, ab);
  1680. stat.alternative = make_node(AST_BlockStatement, stat.alternative, {
  1681. body: body
  1682. });
  1683. statements[i] = stat.transform(compressor);
  1684. continue;
  1685. }
  1686. }
  1687. if (stat instanceof AST_If && stat.body instanceof AST_Return) {
  1688. var value = stat.body.value;
  1689. //---
  1690. // pretty silly case, but:
  1691. // if (foo()) return; return; ==> foo(); return;
  1692. if (!value && !stat.alternative
  1693. && (in_lambda && !next || next instanceof AST_Return && !next.value)) {
  1694. CHANGED = true;
  1695. statements[i] = make_node(AST_SimpleStatement, stat.condition, {
  1696. body: stat.condition
  1697. });
  1698. continue;
  1699. }
  1700. //---
  1701. // if (foo()) return x; return y; ==> return foo() ? x : y;
  1702. if (value && !stat.alternative && next instanceof AST_Return && next.value) {
  1703. CHANGED = true;
  1704. stat = stat.clone();
  1705. stat.alternative = next;
  1706. statements.splice(i, 1, stat.transform(compressor));
  1707. statements.splice(j, 1);
  1708. continue;
  1709. }
  1710. //---
  1711. // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined;
  1712. if (value && !stat.alternative
  1713. && (!next && in_lambda && multiple_if_returns
  1714. || next instanceof AST_Return)) {
  1715. CHANGED = true;
  1716. stat = stat.clone();
  1717. stat.alternative = next || make_node(AST_Return, stat, {
  1718. value: null
  1719. });
  1720. statements.splice(i, 1, stat.transform(compressor));
  1721. if (next) statements.splice(j, 1);
  1722. continue;
  1723. }
  1724. //---
  1725. // if (a) return b; if (c) return d; e; ==> return a ? b : c ? d : void e;
  1726. //
  1727. // if sequences is not enabled, this can lead to an endless loop (issue #866).
  1728. // however, with sequences on this helps producing slightly better output for
  1729. // the example code.
  1730. var prev = statements[prev_index(i)];
  1731. if (compressor.option("sequences") && in_lambda && !stat.alternative
  1732. && prev instanceof AST_If && prev.body instanceof AST_Return
  1733. && next_index(j) == statements.length && next instanceof AST_SimpleStatement) {
  1734. CHANGED = true;
  1735. stat = stat.clone();
  1736. stat.alternative = make_node(AST_BlockStatement, next, {
  1737. body: [
  1738. next,
  1739. make_node(AST_Return, next, {
  1740. value: null
  1741. })
  1742. ]
  1743. });
  1744. statements.splice(i, 1, stat.transform(compressor));
  1745. statements.splice(j, 1);
  1746. continue;
  1747. }
  1748. }
  1749. }
  1750. function has_multiple_if_returns(statements) {
  1751. var n = 0;
  1752. for (var i = statements.length; --i >= 0;) {
  1753. var stat = statements[i];
  1754. if (stat instanceof AST_If && stat.body instanceof AST_Return) {
  1755. if (++n > 1) return true;
  1756. }
  1757. }
  1758. return false;
  1759. }
  1760. function is_return_void(value) {
  1761. return !value || value instanceof AST_UnaryPrefix && value.operator == "void";
  1762. }
  1763. function can_merge_flow(ab) {
  1764. if (!ab) return false;
  1765. var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab) : null;
  1766. return ab instanceof AST_Return && in_lambda && is_return_void(ab.value)
  1767. || ab instanceof AST_Continue && self === loop_body(lct)
  1768. || ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct;
  1769. }
  1770. function extract_functions() {
  1771. var tail = statements.slice(i + 1);
  1772. statements.length = i + 1;
  1773. return tail.filter(function(stat) {
  1774. if (stat instanceof AST_Defun) {
  1775. statements.push(stat);
  1776. return false;
  1777. }
  1778. return true;
  1779. });
  1780. }
  1781. function as_statement_array_with_return(node, ab) {
  1782. var body = as_statement_array(node).slice(0, -1);
  1783. if (ab.value) {
  1784. body.push(make_node(AST_SimpleStatement, ab.value, {
  1785. body: ab.value.expression
  1786. }));
  1787. }
  1788. return body;
  1789. }
  1790. function next_index(i) {
  1791. for (var j = i + 1, len = statements.length; j < len; j++) {
  1792. var stat = statements[j];
  1793. if (!(stat instanceof AST_Var && declarations_only(stat))) {
  1794. break;
  1795. }
  1796. }
  1797. return j;
  1798. }
  1799. function prev_index(i) {
  1800. for (var j = i; --j >= 0;) {
  1801. var stat = statements[j];
  1802. if (!(stat instanceof AST_Var && declarations_only(stat))) {
  1803. break;
  1804. }
  1805. }
  1806. return j;
  1807. }
  1808. }
  1809. function eliminate_dead_code(statements, compressor) {
  1810. var has_quit;
  1811. var self = compressor.self();
  1812. for (var i = 0, n = 0, len = statements.length; i < len; i++) {
  1813. var stat = statements[i];
  1814. if (stat instanceof AST_LoopControl) {
  1815. var lct = compressor.loopcontrol_target(stat);
  1816. if (stat instanceof AST_Break
  1817. && !(lct instanceof AST_IterationStatement)
  1818. && loop_body(lct) === self
  1819. || stat instanceof AST_Continue
  1820. && loop_body(lct) === self) {
  1821. if (stat.label) {
  1822. remove(stat.label.thedef.references, stat);
  1823. }
  1824. } else {
  1825. statements[n++] = stat;
  1826. }
  1827. } else {
  1828. statements[n++] = stat;
  1829. }
  1830. if (aborts(stat)) {
  1831. has_quit = statements.slice(i + 1);
  1832. break;
  1833. }
  1834. }
  1835. statements.length = n;
  1836. CHANGED = n != len;
  1837. if (has_quit) has_quit.forEach(function(stat) {
  1838. extract_declarations_from_unreachable_code(compressor, stat, statements);
  1839. });
  1840. }
  1841. function declarations_only(node) {
  1842. return all(node.definitions, function(var_def) {
  1843. return !var_def.value;
  1844. });
  1845. }
  1846. function sequencesize(statements, compressor) {
  1847. if (statements.length < 2) return;
  1848. var seq = [], n = 0;
  1849. function push_seq() {
  1850. if (!seq.length) return;
  1851. var body = make_sequence(seq[0], seq);
  1852. statements[n++] = make_node(AST_SimpleStatement, body, { body: body });
  1853. seq = [];
  1854. }
  1855. for (var i = 0, len = statements.length; i < len; i++) {
  1856. var stat = statements[i];
  1857. if (stat instanceof AST_SimpleStatement) {
  1858. if (seq.length >= compressor.sequences_limit) push_seq();
  1859. var body = stat.body;
  1860. if (seq.length > 0) body = body.drop_side_effect_free(compressor);
  1861. if (body) merge_sequence(seq, body);
  1862. } else if (stat instanceof AST_Definitions && declarations_only(stat)
  1863. || stat instanceof AST_Defun) {
  1864. statements[n++] = stat;
  1865. } else {
  1866. push_seq();
  1867. statements[n++] = stat;
  1868. }
  1869. }
  1870. push_seq();
  1871. statements.length = n;
  1872. if (n != len) CHANGED = true;
  1873. }
  1874. function to_simple_statement(block, decls) {
  1875. if (!(block instanceof AST_BlockStatement)) return block;
  1876. var stat = null;
  1877. for (var i = 0, len = block.body.length; i < len; i++) {
  1878. var line = block.body[i];
  1879. if (line instanceof AST_Var && declarations_only(line)) {
  1880. decls.push(line);
  1881. } else if (stat) {
  1882. return false;
  1883. } else {
  1884. stat = line;
  1885. }
  1886. }
  1887. return stat;
  1888. }
  1889. function sequencesize_2(statements, compressor) {
  1890. function cons_seq(right) {
  1891. n--;
  1892. CHANGED = true;
  1893. var left = prev.body;
  1894. return make_sequence(left, [ left, right ]).transform(compressor);
  1895. }
  1896. var n = 0, prev;
  1897. for (var i = 0; i < statements.length; i++) {
  1898. var stat = statements[i];
  1899. if (prev) {
  1900. if (stat instanceof AST_Exit) {
  1901. stat.value = cons_seq(stat.value || make_node(AST_Undefined, stat).transform(compressor));
  1902. } else if (stat instanceof AST_For) {
  1903. if (!(stat.init instanceof AST_Definitions)) {
  1904. var abort = false;
  1905. prev.body.walk(new TreeWalker(function(node) {
  1906. if (abort || node instanceof AST_Scope) return true;
  1907. if (node instanceof AST_Binary && node.operator == "in") {
  1908. abort = true;
  1909. return true;
  1910. }
  1911. }));
  1912. if (!abort) {
  1913. if (stat.init) stat.init = cons_seq(stat.init);
  1914. else {
  1915. stat.init = prev.body;
  1916. n--;
  1917. CHANGED = true;
  1918. }
  1919. }
  1920. }
  1921. } else if (stat instanceof AST_ForIn) {
  1922. stat.object = cons_seq(stat.object);
  1923. } else if (stat instanceof AST_If) {
  1924. stat.condition = cons_seq(stat.condition);
  1925. } else if (stat instanceof AST_Switch) {
  1926. stat.expression = cons_seq(stat.expression);
  1927. } else if (stat instanceof AST_With) {
  1928. stat.expression = cons_seq(stat.expression);
  1929. }
  1930. }
  1931. if (compressor.option("conditionals") && stat instanceof AST_If) {
  1932. var decls = [];
  1933. var body = to_simple_statement(stat.body, decls);
  1934. var alt = to_simple_statement(stat.alternative, decls);
  1935. if (body !== false && alt !== false && decls.length > 0) {
  1936. var len = decls.length;
  1937. decls.push(make_node(AST_If, stat, {
  1938. condition: stat.condition,
  1939. body: body || make_node(AST_EmptyStatement, stat.body),
  1940. alternative: alt
  1941. }));
  1942. decls.unshift(n, 1);
  1943. [].splice.apply(statements, decls);
  1944. i += len;
  1945. n += len + 1;
  1946. prev = null;
  1947. CHANGED = true;
  1948. continue;
  1949. }
  1950. }
  1951. statements[n++] = stat;
  1952. prev = stat instanceof AST_SimpleStatement ? stat : null;
  1953. }
  1954. statements.length = n;
  1955. }
  1956. function join_assigns(defn, body) {
  1957. var exprs;
  1958. if (body instanceof AST_Assign) {
  1959. exprs = [ body ];
  1960. } else if (body instanceof AST_Sequence) {
  1961. exprs = body.expressions.slice();
  1962. }
  1963. if (!exprs) return;
  1964. if (defn instanceof AST_Definitions) {
  1965. var def = defn.definitions[defn.definitions.length - 1];
  1966. if (trim_assigns(def.name, def.value, exprs)) return exprs;
  1967. }
  1968. for (var i = exprs.length - 1; --i >= 0;) {
  1969. var expr = exprs[i];
  1970. if (!(expr instanceof AST_Assign)) continue;
  1971. if (expr.operator != "=") continue;
  1972. if (!(expr.left instanceof AST_SymbolRef)) continue;
  1973. var tail = exprs.slice(i + 1);
  1974. if (!trim_assigns(expr.left, expr.right, tail)) continue;
  1975. return exprs.slice(0, i + 1).concat(tail);
  1976. }
  1977. }
  1978. function trim_assigns(name, value, exprs) {
  1979. if (!(value instanceof AST_Object)) return;
  1980. var trimmed = false;
  1981. do {
  1982. var node = exprs[0];
  1983. if (!(node instanceof AST_Assign)) break;
  1984. if (node.operator != "=") break;
  1985. if (!(node.left instanceof AST_PropAccess)) break;
  1986. var sym = node.left.expression;
  1987. if (!(sym instanceof AST_SymbolRef)) break;
  1988. if (name.name != sym.name) break;
  1989. if (!node.right.is_constant_expression(scope)) break;
  1990. var prop = node.left.property;
  1991. if (prop instanceof AST_Node) {
  1992. prop = prop.evaluate(compressor);
  1993. }
  1994. if (prop instanceof AST_Node) break;
  1995. prop = "" + prop;
  1996. var diff = compressor.has_directive("use strict") ? function(node) {
  1997. return node.key != prop && node.key.name != prop;
  1998. } : function(node) {
  1999. return node.key.name != prop;
  2000. };
  2001. if (!all(value.properties, diff)) break;
  2002. value.properties.push(make_node(AST_ObjectKeyVal, node, {
  2003. key: prop,
  2004. value: node.right
  2005. }));
  2006. exprs.shift();
  2007. trimmed = true;
  2008. } while (exprs.length);
  2009. return trimmed;
  2010. }
  2011. function join_consecutive_vars(statements) {
  2012. var defs;
  2013. for (var i = 0, j = -1, len = statements.length; i < len; i++) {
  2014. var stat = statements[i];
  2015. var prev = statements[j];
  2016. if (stat instanceof AST_Definitions) {
  2017. if (prev && prev.TYPE == stat.TYPE) {
  2018. prev.definitions = prev.definitions.concat(stat.definitions);
  2019. CHANGED = true;
  2020. } else if (defs && defs.TYPE == stat.TYPE && declarations_only(stat)) {
  2021. defs.definitions = defs.definitions.concat(stat.definitions);
  2022. CHANGED = true;
  2023. } else {
  2024. statements[++j] = stat;
  2025. defs = stat;
  2026. }
  2027. } else if (stat instanceof AST_Exit) {
  2028. stat.value = join_assigns_expr(stat.value);
  2029. } else if (stat instanceof AST_For) {
  2030. var exprs = join_assigns(prev, stat.init);
  2031. if (exprs) {
  2032. CHANGED = true;
  2033. stat.init = exprs.length ? make_sequence(stat.init, exprs) : null;
  2034. statements[++j] = stat;
  2035. } else if (prev instanceof AST_Var && (!stat.init || stat.init.TYPE == prev.TYPE)) {
  2036. if (stat.init) {
  2037. prev.definitions = prev.definitions.concat(stat.init.definitions);
  2038. }
  2039. stat.init = prev;
  2040. statements[j] = stat;
  2041. CHANGED = true;
  2042. } else if (defs && stat.init && defs.TYPE == stat.init.TYPE && declarations_only(stat.init)) {
  2043. defs.definitions = defs.definitions.concat(stat.init.definitions);
  2044. stat.init = null;
  2045. statements[++j] = stat;
  2046. CHANGED = true;
  2047. } else {
  2048. statements[++j] = stat;
  2049. }
  2050. } else if (stat instanceof AST_ForIn) {
  2051. stat.object = join_assigns_expr(stat.object);
  2052. } else if (stat instanceof AST_If) {
  2053. stat.condition = join_assigns_expr(stat.condition);
  2054. } else if (stat instanceof AST_SimpleStatement) {
  2055. var exprs = join_assigns(prev, stat.body);
  2056. if (exprs) {
  2057. CHANGED = true;
  2058. if (!exprs.length) continue;
  2059. stat.body = make_sequence(stat.body, exprs);
  2060. }
  2061. statements[++j] = stat;
  2062. } else if (stat instanceof AST_Switch) {
  2063. stat.expression = join_assigns_expr(stat.expression);
  2064. } else if (stat instanceof AST_With) {
  2065. stat.expression = join_assigns_expr(stat.expression);
  2066. } else {
  2067. statements[++j] = stat;
  2068. }
  2069. }
  2070. statements.length = j + 1;
  2071. function join_assigns_expr(value) {
  2072. statements[++j] = stat;
  2073. var exprs = join_assigns(prev, value);
  2074. if (!exprs) return value;
  2075. CHANGED = true;
  2076. var tail = value.tail_node();
  2077. if (exprs[exprs.length - 1] !== tail) exprs.push(tail.left);
  2078. return make_sequence(value, exprs);
  2079. }
  2080. }
  2081. }
  2082. function extract_declarations_from_unreachable_code(compressor, stat, target) {
  2083. if (!(stat instanceof AST_Defun)) {
  2084. compressor.warn("Dropping unreachable code [{file}:{line},{col}]", stat.start);
  2085. }
  2086. stat.walk(new TreeWalker(function(node) {
  2087. if (node instanceof AST_Definitions) {
  2088. compressor.warn("Declarations in unreachable code! [{file}:{line},{col}]", node.start);
  2089. node.remove_initializers();
  2090. target.push(node);
  2091. return true;
  2092. }
  2093. if (node instanceof AST_Defun) {
  2094. target.push(node);
  2095. return true;
  2096. }
  2097. if (node instanceof AST_Scope) {
  2098. return true;
  2099. }
  2100. }));
  2101. }
  2102. function get_value(key) {
  2103. if (key instanceof AST_Constant) {
  2104. return key.getValue();
  2105. }
  2106. if (key instanceof AST_UnaryPrefix
  2107. && key.operator == "void"
  2108. && key.expression instanceof AST_Constant) {
  2109. return;
  2110. }
  2111. return key;
  2112. }
  2113. function is_undefined(node, compressor) {
  2114. return node.is_undefined
  2115. || node instanceof AST_Undefined
  2116. || node instanceof AST_UnaryPrefix
  2117. && node.operator == "void"
  2118. && !node.expression.has_side_effects(compressor);
  2119. }
  2120. // is_truthy()
  2121. // return true if `!!node === true`
  2122. (function(def) {
  2123. def(AST_Node, return_false);
  2124. def(AST_Array, return_true);
  2125. def(AST_Assign, function() {
  2126. return this.operator == "=" && this.right.is_truthy();
  2127. });
  2128. def(AST_Lambda, return_true);
  2129. def(AST_Object, return_true);
  2130. def(AST_RegExp, return_true);
  2131. def(AST_Sequence, function() {
  2132. return this.tail_node().is_truthy();
  2133. });
  2134. def(AST_SymbolRef, function() {
  2135. var fixed = this.fixed_value();
  2136. return fixed && fixed.is_truthy();
  2137. });
  2138. })(function(node, func) {
  2139. node.DEFMETHOD("is_truthy", func);
  2140. });
  2141. // may_throw_on_access()
  2142. // returns true if this node may be null, undefined or contain `AST_Accessor`
  2143. (function(def) {
  2144. AST_Node.DEFMETHOD("may_throw_on_access", function(compressor) {
  2145. return !compressor.option("pure_getters")
  2146. || this._dot_throw(compressor);
  2147. });
  2148. function is_strict(compressor) {
  2149. return /strict/.test(compressor.option("pure_getters"));
  2150. }
  2151. def(AST_Node, is_strict);
  2152. def(AST_Null, return_true);
  2153. def(AST_Undefined, return_true);
  2154. def(AST_Constant, return_false);
  2155. def(AST_Array, return_false);
  2156. def(AST_Object, function(compressor) {
  2157. if (!is_strict(compressor)) return false;
  2158. for (var i = this.properties.length; --i >=0;)
  2159. if (this.properties[i].value instanceof AST_Accessor) return true;
  2160. return false;
  2161. });
  2162. def(AST_Lambda, return_false);
  2163. def(AST_UnaryPostfix, return_false);
  2164. def(AST_UnaryPrefix, function() {
  2165. return this.operator == "void";
  2166. });
  2167. def(AST_Binary, function(compressor) {
  2168. return (this.operator == "&&" || this.operator == "||")
  2169. && (this.left._dot_throw(compressor) || this.right._dot_throw(compressor));
  2170. })
  2171. def(AST_Assign, function(compressor) {
  2172. return this.operator == "="
  2173. && this.right._dot_throw(compressor);
  2174. })
  2175. def(AST_Conditional, function(compressor) {
  2176. return this.consequent._dot_throw(compressor)
  2177. || this.alternative._dot_throw(compressor);
  2178. })
  2179. def(AST_Dot, function(compressor) {
  2180. if (!is_strict(compressor)) return false;
  2181. var exp = this.expression;
  2182. if (exp instanceof AST_SymbolRef) exp = exp.fixed_value();
  2183. return !(exp instanceof AST_Lambda && this.property == "prototype");
  2184. });
  2185. def(AST_Sequence, function(compressor) {
  2186. return this.tail_node()._dot_throw(compressor);
  2187. });
  2188. def(AST_SymbolRef, function(compressor) {
  2189. if (this.is_undefined) return true;
  2190. if (!is_strict(compressor)) return false;
  2191. if (is_undeclared_ref(this) && this.is_declared(compressor)) return false;
  2192. if (this.is_immutable()) return false;
  2193. var fixed = this.fixed_value();
  2194. return !fixed || fixed._dot_throw(compressor);
  2195. });
  2196. })(function(node, func) {
  2197. node.DEFMETHOD("_dot_throw", func);
  2198. });
  2199. /* -----[ boolean/negation helpers ]----- */
  2200. // methods to determine whether an expression has a boolean result type
  2201. (function(def) {
  2202. def(AST_Node, return_false);
  2203. def(AST_Assign, function(compressor) {
  2204. return this.operator == "=" && this.right.is_boolean(compressor);
  2205. });
  2206. var binary = makePredicate("in instanceof == != === !== < <= >= >");
  2207. def(AST_Binary, function(compressor) {
  2208. return binary[this.operator] || lazy_op[this.operator]
  2209. && this.left.is_boolean(compressor)
  2210. && this.right.is_boolean(compressor);
  2211. });
  2212. def(AST_Boolean, return_true);
  2213. var fn = makePredicate("every hasOwnProperty isPrototypeOf propertyIsEnumerable some");
  2214. def(AST_Call, function(compressor) {
  2215. if (!compressor.option("unsafe")) return false;
  2216. var exp = this.expression;
  2217. return exp instanceof AST_Dot && (fn[exp.property]
  2218. || exp.property == "test" && exp.expression instanceof AST_RegExp);
  2219. });
  2220. def(AST_Conditional, function(compressor) {
  2221. return this.consequent.is_boolean(compressor) && this.alternative.is_boolean(compressor);
  2222. });
  2223. def(AST_New, return_false);
  2224. def(AST_Sequence, function(compressor) {
  2225. return this.tail_node().is_boolean(compressor);
  2226. });
  2227. var unary = makePredicate("! delete");
  2228. def(AST_UnaryPrefix, function() {
  2229. return unary[this.operator];
  2230. });
  2231. })(function(node, func) {
  2232. node.DEFMETHOD("is_boolean", func);
  2233. });
  2234. // methods to determine if an expression has a numeric result type
  2235. (function(def) {
  2236. def(AST_Node, return_false);
  2237. var binary = makePredicate("- * / % & | ^ << >> >>>");
  2238. def(AST_Assign, function(compressor) {
  2239. return binary[this.operator.slice(0, -1)]
  2240. || this.operator == "=" && this.right.is_number(compressor);
  2241. });
  2242. def(AST_Binary, function(compressor) {
  2243. return binary[this.operator] || this.operator == "+"
  2244. && this.left.is_number(compressor)
  2245. && this.right.is_number(compressor);
  2246. });
  2247. var fn = makePredicate([
  2248. "charCodeAt",
  2249. "getDate",
  2250. "getDay",
  2251. "getFullYear",
  2252. "getHours",
  2253. "getMilliseconds",
  2254. "getMinutes",
  2255. "getMonth",
  2256. "getSeconds",
  2257. "getTime",
  2258. "getTimezoneOffset",
  2259. "getUTCDate",
  2260. "getUTCDay",
  2261. "getUTCFullYear",
  2262. "getUTCHours",
  2263. "getUTCMilliseconds",
  2264. "getUTCMinutes",
  2265. "getUTCMonth",
  2266. "getUTCSeconds",
  2267. "getYear",
  2268. "indexOf",
  2269. "lastIndexOf",
  2270. "localeCompare",
  2271. "push",
  2272. "search",
  2273. "setDate",
  2274. "setFullYear",
  2275. "setHours",
  2276. "setMilliseconds",
  2277. "setMinutes",
  2278. "setMonth",
  2279. "setSeconds",
  2280. "setTime",
  2281. "setUTCDate",
  2282. "setUTCFullYear",
  2283. "setUTCHours",
  2284. "setUTCMilliseconds",
  2285. "setUTCMinutes",
  2286. "setUTCMonth",
  2287. "setUTCSeconds",
  2288. "setYear",
  2289. "toExponential",
  2290. "toFixed",
  2291. "toPrecision",
  2292. ]);
  2293. def(AST_Call, function(compressor) {
  2294. if (!compressor.option("unsafe")) return false;
  2295. var exp = this.expression;
  2296. return exp instanceof AST_Dot && (fn[exp.property]
  2297. || is_undeclared_ref(exp.expression) && exp.expression.name == "Math");
  2298. });
  2299. def(AST_Conditional, function(compressor) {
  2300. return this.consequent.is_number(compressor) && this.alternative.is_number(compressor);
  2301. });
  2302. def(AST_New, return_false);
  2303. def(AST_Number, return_true);
  2304. def(AST_Sequence, function(compressor) {
  2305. return this.tail_node().is_number(compressor);
  2306. });
  2307. var unary = makePredicate("+ - ~ ++ --");
  2308. def(AST_Unary, function() {
  2309. return unary[this.operator];
  2310. });
  2311. })(function(node, func) {
  2312. node.DEFMETHOD("is_number", func);
  2313. });
  2314. // methods to determine if an expression has a string result type
  2315. (function(def) {
  2316. def(AST_Node, return_false);
  2317. def(AST_String, return_true);
  2318. def(AST_UnaryPrefix, function() {
  2319. return this.operator == "typeof";
  2320. });
  2321. def(AST_Binary, function(compressor) {
  2322. return this.operator == "+" &&
  2323. (this.left.is_string(compressor) || this.right.is_string(compressor));
  2324. });
  2325. def(AST_Assign, function(compressor) {
  2326. return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor);
  2327. });
  2328. def(AST_Sequence, function(compressor) {
  2329. return this.tail_node().is_string(compressor);
  2330. });
  2331. def(AST_Conditional, function(compressor) {
  2332. return this.consequent.is_string(compressor) && this.alternative.is_string(compressor);
  2333. });
  2334. })(function(node, func) {
  2335. node.DEFMETHOD("is_string", func);
  2336. });
  2337. var lazy_op = makePredicate("&& ||");
  2338. var unary_side_effects = makePredicate("delete ++ --");
  2339. function is_lhs(node, parent) {
  2340. if (parent instanceof AST_Unary && unary_side_effects[parent.operator]) return parent.expression;
  2341. if (parent instanceof AST_Assign && parent.left === node) return node;
  2342. }
  2343. (function(def) {
  2344. function to_node(value, orig) {
  2345. if (value instanceof AST_Node) return make_node(value.CTOR, orig, value);
  2346. if (Array.isArray(value)) return make_node(AST_Array, orig, {
  2347. elements: value.map(function(value) {
  2348. return to_node(value, orig);
  2349. })
  2350. });
  2351. if (value && typeof value == "object") {
  2352. var props = [];
  2353. for (var key in value) if (HOP(value, key)) {
  2354. props.push(make_node(AST_ObjectKeyVal, orig, {
  2355. key: key,
  2356. value: to_node(value[key], orig)
  2357. }));
  2358. }
  2359. return make_node(AST_Object, orig, {
  2360. properties: props
  2361. });
  2362. }
  2363. return make_node_from_constant(value, orig);
  2364. }
  2365. function warn(compressor, node) {
  2366. compressor.warn("global_defs " + node.print_to_string() + " redefined [{file}:{line},{col}]", node.start);
  2367. }
  2368. AST_Toplevel.DEFMETHOD("resolve_defines", function(compressor) {
  2369. if (!compressor.option("global_defs")) return this;
  2370. this.figure_out_scope({ ie8: compressor.option("ie8") });
  2371. return this.transform(new TreeTransformer(function(node) {
  2372. var def = node._find_defs(compressor, "");
  2373. if (!def) return;
  2374. var level = 0, child = node, parent;
  2375. while (parent = this.parent(level++)) {
  2376. if (!(parent instanceof AST_PropAccess)) break;
  2377. if (parent.expression !== child) break;
  2378. child = parent;
  2379. }
  2380. if (is_lhs(child, parent)) {
  2381. warn(compressor, node);
  2382. return;
  2383. }
  2384. return def;
  2385. }));
  2386. });
  2387. def(AST_Node, noop);
  2388. def(AST_Dot, function(compressor, suffix) {
  2389. return this.expression._find_defs(compressor, "." + this.property + suffix);
  2390. });
  2391. def(AST_SymbolDeclaration, function(compressor) {
  2392. if (!this.global()) return;
  2393. if (HOP(compressor.option("global_defs"), this.name)) warn(compressor, this);
  2394. });
  2395. def(AST_SymbolRef, function(compressor, suffix) {
  2396. if (!this.global()) return;
  2397. var defines = compressor.option("global_defs");
  2398. var name = this.name + suffix;
  2399. if (HOP(defines, name)) return to_node(defines[name], this);
  2400. });
  2401. })(function(node, func) {
  2402. node.DEFMETHOD("_find_defs", func);
  2403. });
  2404. function best_of_expression(ast1, ast2) {
  2405. return ast1.print_to_string().length >
  2406. ast2.print_to_string().length
  2407. ? ast2 : ast1;
  2408. }
  2409. function best_of_statement(ast1, ast2) {
  2410. return best_of_expression(make_node(AST_SimpleStatement, ast1, {
  2411. body: ast1
  2412. }), make_node(AST_SimpleStatement, ast2, {
  2413. body: ast2
  2414. })).body;
  2415. }
  2416. function best_of(compressor, ast1, ast2) {
  2417. return (first_in_statement(compressor) ? best_of_statement : best_of_expression)(ast1, ast2);
  2418. }
  2419. function convert_to_predicate(obj) {
  2420. for (var key in obj) {
  2421. obj[key] = makePredicate(obj[key]);
  2422. }
  2423. }
  2424. var object_fns = [
  2425. "constructor",
  2426. "toString",
  2427. "valueOf",
  2428. ];
  2429. var native_fns = {
  2430. Array: [
  2431. "indexOf",
  2432. "join",
  2433. "lastIndexOf",
  2434. "slice",
  2435. ].concat(object_fns),
  2436. Boolean: object_fns,
  2437. Function: object_fns,
  2438. Number: [
  2439. "toExponential",
  2440. "toFixed",
  2441. "toPrecision",
  2442. ].concat(object_fns),
  2443. Object: object_fns,
  2444. RegExp: [
  2445. "test",
  2446. ].concat(object_fns),
  2447. String: [
  2448. "charAt",
  2449. "charCodeAt",
  2450. "concat",
  2451. "indexOf",
  2452. "italics",
  2453. "lastIndexOf",
  2454. "match",
  2455. "replace",
  2456. "search",
  2457. "slice",
  2458. "split",
  2459. "substr",
  2460. "substring",
  2461. "toLowerCase",
  2462. "toUpperCase",
  2463. "trim",
  2464. ].concat(object_fns),
  2465. };
  2466. convert_to_predicate(native_fns);
  2467. var static_fns = {
  2468. Array: [
  2469. "isArray",
  2470. ],
  2471. Math: [
  2472. "abs",
  2473. "acos",
  2474. "asin",
  2475. "atan",
  2476. "ceil",
  2477. "cos",
  2478. "exp",
  2479. "floor",
  2480. "log",
  2481. "round",
  2482. "sin",
  2483. "sqrt",
  2484. "tan",
  2485. "atan2",
  2486. "pow",
  2487. "max",
  2488. "min",
  2489. ],
  2490. Number: [
  2491. "isFinite",
  2492. "isNaN",
  2493. ],
  2494. Object: [
  2495. "create",
  2496. "getOwnPropertyDescriptor",
  2497. "getOwnPropertyNames",
  2498. "getPrototypeOf",
  2499. "isExtensible",
  2500. "isFrozen",
  2501. "isSealed",
  2502. "keys",
  2503. ],
  2504. String: [
  2505. "fromCharCode",
  2506. ],
  2507. };
  2508. convert_to_predicate(static_fns);
  2509. // methods to evaluate a constant expression
  2510. (function(def) {
  2511. // If the node has been successfully reduced to a constant,
  2512. // then its value is returned; otherwise the element itself
  2513. // is returned.
  2514. // They can be distinguished as constant value is never a
  2515. // descendant of AST_Node.
  2516. AST_Node.DEFMETHOD("evaluate", function(compressor) {
  2517. if (!compressor.option("evaluate")) return this;
  2518. var cached = [];
  2519. var val = this._eval(compressor, cached, 1);
  2520. cached.forEach(function(node) {
  2521. delete node._eval;
  2522. });
  2523. if (!val || val instanceof RegExp) return val;
  2524. if (typeof val == "function" || typeof val == "object") return this;
  2525. return val;
  2526. });
  2527. var unaryPrefix = makePredicate("! ~ - + void");
  2528. AST_Node.DEFMETHOD("is_constant", function() {
  2529. // Accomodate when compress option evaluate=false
  2530. // as well as the common constant expressions !0 and -1
  2531. if (this instanceof AST_Constant) {
  2532. return !(this instanceof AST_RegExp);
  2533. } else {
  2534. return this instanceof AST_UnaryPrefix
  2535. && this.expression instanceof AST_Constant
  2536. && unaryPrefix[this.operator];
  2537. }
  2538. });
  2539. def(AST_Statement, function() {
  2540. throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start));
  2541. });
  2542. def(AST_Lambda, return_this);
  2543. def(AST_Node, return_this);
  2544. def(AST_Constant, function() {
  2545. return this.getValue();
  2546. });
  2547. def(AST_Function, function(compressor) {
  2548. if (compressor.option("unsafe")) {
  2549. var fn = function() {};
  2550. fn.node = this;
  2551. fn.toString = function() {
  2552. return "function(){}";
  2553. };
  2554. return fn;
  2555. }
  2556. return this;
  2557. });
  2558. def(AST_Array, function(compressor, cached, depth) {
  2559. if (compressor.option("unsafe")) {
  2560. var elements = [];
  2561. for (var i = 0, len = this.elements.length; i < len; i++) {
  2562. var element = this.elements[i];
  2563. var value = element._eval(compressor, cached, depth);
  2564. if (element === value) return this;
  2565. elements.push(value);
  2566. }
  2567. return elements;
  2568. }
  2569. return this;
  2570. });
  2571. def(AST_Object, function(compressor, cached, depth) {
  2572. if (compressor.option("unsafe")) {
  2573. var val = {};
  2574. for (var i = 0, len = this.properties.length; i < len; i++) {
  2575. var prop = this.properties[i];
  2576. var key = prop.key;
  2577. if (key instanceof AST_Symbol) {
  2578. key = key.name;
  2579. } else if (key instanceof AST_Node) {
  2580. key = key._eval(compressor, cached, depth);
  2581. if (key === prop.key) return this;
  2582. }
  2583. if (typeof Object.prototype[key] === 'function') {
  2584. return this;
  2585. }
  2586. if (prop.value instanceof AST_Function) continue;
  2587. val[key] = prop.value._eval(compressor, cached, depth);
  2588. if (val[key] === prop.value) return this;
  2589. }
  2590. return val;
  2591. }
  2592. return this;
  2593. });
  2594. var non_converting_unary = makePredicate("! typeof void");
  2595. def(AST_UnaryPrefix, function(compressor, cached, depth) {
  2596. var e = this.expression;
  2597. // Function would be evaluated to an array and so typeof would
  2598. // incorrectly return 'object'. Hence making is a special case.
  2599. if (compressor.option("typeofs")
  2600. && this.operator == "typeof"
  2601. && (e instanceof AST_Lambda
  2602. || e instanceof AST_SymbolRef
  2603. && e.fixed_value() instanceof AST_Lambda)) {
  2604. return typeof function(){};
  2605. }
  2606. if (!non_converting_unary[this.operator]) depth++;
  2607. var v = e._eval(compressor, cached, depth);
  2608. if (v === this.expression) return this;
  2609. switch (this.operator) {
  2610. case "!": return !v;
  2611. case "typeof":
  2612. // typeof <RegExp> returns "object" or "function" on different platforms
  2613. // so cannot evaluate reliably
  2614. if (v instanceof RegExp) return this;
  2615. return typeof v;
  2616. case "void": return void v;
  2617. case "~": return ~v;
  2618. case "-": return -v;
  2619. case "+": return +v;
  2620. case "++":
  2621. case "--":
  2622. if (e instanceof AST_SymbolRef) {
  2623. var refs = e.definition().references;
  2624. if (refs[refs.length - 1] === e) return v;
  2625. }
  2626. }
  2627. return this;
  2628. });
  2629. var non_converting_binary = makePredicate("&& || === !==");
  2630. def(AST_Binary, function(compressor, cached, depth) {
  2631. if (!non_converting_binary[this.operator]) depth++;
  2632. var left = this.left._eval(compressor, cached, depth);
  2633. if (left === this.left) return this;
  2634. var right = this.right._eval(compressor, cached, depth);
  2635. if (right === this.right) return this;
  2636. var result;
  2637. switch (this.operator) {
  2638. case "&&" : result = left && right; break;
  2639. case "||" : result = left || right; break;
  2640. case "|" : result = left | right; break;
  2641. case "&" : result = left & right; break;
  2642. case "^" : result = left ^ right; break;
  2643. case "+" : result = left + right; break;
  2644. case "*" : result = left * right; break;
  2645. case "/" : result = left / right; break;
  2646. case "%" : result = left % right; break;
  2647. case "-" : result = left - right; break;
  2648. case "<<" : result = left << right; break;
  2649. case ">>" : result = left >> right; break;
  2650. case ">>>": result = left >>> right; break;
  2651. case "==" : result = left == right; break;
  2652. case "===": result = left === right; break;
  2653. case "!=" : result = left != right; break;
  2654. case "!==": result = left !== right; break;
  2655. case "<" : result = left < right; break;
  2656. case "<=" : result = left <= right; break;
  2657. case ">" : result = left > right; break;
  2658. case ">=" : result = left >= right; break;
  2659. default : return this;
  2660. }
  2661. return isNaN(result) && compressor.find_parent(AST_With) ? this : result;
  2662. });
  2663. def(AST_Conditional, function(compressor, cached, depth) {
  2664. var condition = this.condition._eval(compressor, cached, depth);
  2665. if (condition === this.condition) return this;
  2666. var node = condition ? this.consequent : this.alternative;
  2667. var value = node._eval(compressor, cached, depth);
  2668. return value === node ? this : value;
  2669. });
  2670. def(AST_SymbolRef, function(compressor, cached, depth) {
  2671. var fixed = this.fixed_value();
  2672. if (!fixed) return this;
  2673. var value;
  2674. if (cached.indexOf(fixed) >= 0) {
  2675. value = fixed._eval();
  2676. } else {
  2677. this._eval = return_this;
  2678. value = fixed._eval(compressor, cached, depth);
  2679. delete this._eval;
  2680. if (value === fixed) return this;
  2681. fixed._eval = function() {
  2682. return value;
  2683. };
  2684. cached.push(fixed);
  2685. }
  2686. if (value && typeof value == "object") {
  2687. var escaped = this.definition().escaped;
  2688. if (escaped && depth > escaped) return this;
  2689. }
  2690. return value;
  2691. });
  2692. var global_objs = {
  2693. Array: Array,
  2694. Math: Math,
  2695. Number: Number,
  2696. Object: Object,
  2697. String: String,
  2698. };
  2699. var static_values = {
  2700. Math: [
  2701. "E",
  2702. "LN10",
  2703. "LN2",
  2704. "LOG2E",
  2705. "LOG10E",
  2706. "PI",
  2707. "SQRT1_2",
  2708. "SQRT2",
  2709. ],
  2710. Number: [
  2711. "MAX_VALUE",
  2712. "MIN_VALUE",
  2713. "NaN",
  2714. "NEGATIVE_INFINITY",
  2715. "POSITIVE_INFINITY",
  2716. ],
  2717. };
  2718. convert_to_predicate(static_values);
  2719. def(AST_PropAccess, function(compressor, cached, depth) {
  2720. if (compressor.option("unsafe")) {
  2721. var key = this.property;
  2722. if (key instanceof AST_Node) {
  2723. key = key._eval(compressor, cached, depth);
  2724. if (key === this.property) return this;
  2725. }
  2726. var exp = this.expression;
  2727. var val;
  2728. if (is_undeclared_ref(exp)) {
  2729. var static_value = static_values[exp.name];
  2730. if (!static_value || !static_value[key]) return this;
  2731. val = global_objs[exp.name];
  2732. } else {
  2733. val = exp._eval(compressor, cached, depth + 1);
  2734. if (!val || val === exp || !HOP(val, key)) return this;
  2735. if (typeof val == "function") switch (key) {
  2736. case "name":
  2737. return val.node.name ? val.node.name.name : "";
  2738. case "length":
  2739. return val.node.argnames.length;
  2740. default:
  2741. return this;
  2742. }
  2743. }
  2744. return val[key];
  2745. }
  2746. return this;
  2747. });
  2748. def(AST_Call, function(compressor, cached, depth) {
  2749. var exp = this.expression;
  2750. if (compressor.option("unsafe") && exp instanceof AST_PropAccess) {
  2751. var key = exp.property;
  2752. if (key instanceof AST_Node) {
  2753. key = key._eval(compressor, cached, depth);
  2754. if (key === exp.property) return this;
  2755. }
  2756. var val;
  2757. var e = exp.expression;
  2758. if (is_undeclared_ref(e)) {
  2759. var static_fn = static_fns[e.name];
  2760. if (!static_fn || !static_fn[key]) return this;
  2761. val = global_objs[e.name];
  2762. } else {
  2763. val = e._eval(compressor, cached, depth + 1);
  2764. if (val === e || !val) return this;
  2765. var native_fn = native_fns[val.constructor.name];
  2766. if (!native_fn || !native_fn[key]) return this;
  2767. }
  2768. var args = [];
  2769. for (var i = 0, len = this.args.length; i < len; i++) {
  2770. var arg = this.args[i];
  2771. var value = arg._eval(compressor, cached, depth);
  2772. if (arg === value) return this;
  2773. args.push(value);
  2774. }
  2775. try {
  2776. return val[key].apply(val, args);
  2777. } catch (ex) {
  2778. compressor.warn("Error evaluating {code} [{file}:{line},{col}]", {
  2779. code: this.print_to_string(),
  2780. file: this.start.file,
  2781. line: this.start.line,
  2782. col: this.start.col
  2783. });
  2784. }
  2785. }
  2786. return this;
  2787. });
  2788. def(AST_New, return_this);
  2789. })(function(node, func) {
  2790. node.DEFMETHOD("_eval", func);
  2791. });
  2792. // method to negate an expression
  2793. (function(def) {
  2794. function basic_negation(exp) {
  2795. return make_node(AST_UnaryPrefix, exp, {
  2796. operator: "!",
  2797. expression: exp
  2798. });
  2799. }
  2800. function best(orig, alt, first_in_statement) {
  2801. var negated = basic_negation(orig);
  2802. if (first_in_statement) {
  2803. var stat = make_node(AST_SimpleStatement, alt, {
  2804. body: alt
  2805. });
  2806. return best_of_expression(negated, stat) === stat ? alt : negated;
  2807. }
  2808. return best_of_expression(negated, alt);
  2809. }
  2810. def(AST_Node, function() {
  2811. return basic_negation(this);
  2812. });
  2813. def(AST_Statement, function() {
  2814. throw new Error("Cannot negate a statement");
  2815. });
  2816. def(AST_Function, function() {
  2817. return basic_negation(this);
  2818. });
  2819. def(AST_UnaryPrefix, function() {
  2820. if (this.operator == "!")
  2821. return this.expression;
  2822. return basic_negation(this);
  2823. });
  2824. def(AST_Sequence, function(compressor) {
  2825. var expressions = this.expressions.slice();
  2826. expressions.push(expressions.pop().negate(compressor));
  2827. return make_sequence(this, expressions);
  2828. });
  2829. def(AST_Conditional, function(compressor, first_in_statement) {
  2830. var self = this.clone();
  2831. self.consequent = self.consequent.negate(compressor);
  2832. self.alternative = self.alternative.negate(compressor);
  2833. return best(this, self, first_in_statement);
  2834. });
  2835. def(AST_Binary, function(compressor, first_in_statement) {
  2836. var self = this.clone(), op = this.operator;
  2837. if (compressor.option("unsafe_comps")) {
  2838. switch (op) {
  2839. case "<=" : self.operator = ">" ; return self;
  2840. case "<" : self.operator = ">=" ; return self;
  2841. case ">=" : self.operator = "<" ; return self;
  2842. case ">" : self.operator = "<=" ; return self;
  2843. }
  2844. }
  2845. switch (op) {
  2846. case "==" : self.operator = "!="; return self;
  2847. case "!=" : self.operator = "=="; return self;
  2848. case "===": self.operator = "!=="; return self;
  2849. case "!==": self.operator = "==="; return self;
  2850. case "&&":
  2851. self.operator = "||";
  2852. self.left = self.left.negate(compressor, first_in_statement);
  2853. self.right = self.right.negate(compressor);
  2854. return best(this, self, first_in_statement);
  2855. case "||":
  2856. self.operator = "&&";
  2857. self.left = self.left.negate(compressor, first_in_statement);
  2858. self.right = self.right.negate(compressor);
  2859. return best(this, self, first_in_statement);
  2860. }
  2861. return basic_negation(this);
  2862. });
  2863. })(function(node, func) {
  2864. node.DEFMETHOD("negate", function(compressor, first_in_statement) {
  2865. return func.call(this, compressor, first_in_statement);
  2866. });
  2867. });
  2868. 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");
  2869. AST_Call.DEFMETHOD("is_expr_pure", function(compressor) {
  2870. if (compressor.option("unsafe")) {
  2871. var expr = this.expression;
  2872. if (is_undeclared_ref(expr) && global_pure_fns[expr.name]) return true;
  2873. if (expr instanceof AST_Dot && is_undeclared_ref(expr.expression)) {
  2874. var static_fn = static_fns[expr.expression.name];
  2875. return static_fn && static_fn[expr.property];
  2876. }
  2877. }
  2878. return this.pure || !compressor.pure_funcs(this);
  2879. });
  2880. AST_Node.DEFMETHOD("is_call_pure", return_false);
  2881. AST_Dot.DEFMETHOD("is_call_pure", function(compressor) {
  2882. if (!compressor.option("unsafe")) return;
  2883. var expr = this.expression;
  2884. var map;
  2885. if (expr instanceof AST_Array) {
  2886. map = native_fns.Array;
  2887. } else if (expr.is_boolean(compressor)) {
  2888. map = native_fns.Boolean;
  2889. } else if (expr.is_number(compressor)) {
  2890. map = native_fns.Number;
  2891. } else if (expr instanceof AST_RegExp) {
  2892. map = native_fns.RegExp;
  2893. } else if (expr.is_string(compressor)) {
  2894. map = native_fns.String;
  2895. } else if (!this.may_throw_on_access(compressor)) {
  2896. map = native_fns.Object;
  2897. }
  2898. return map && map[this.property];
  2899. });
  2900. // determine if expression has side effects
  2901. (function(def) {
  2902. function any(list, compressor) {
  2903. for (var i = list.length; --i >= 0;)
  2904. if (list[i].has_side_effects(compressor))
  2905. return true;
  2906. return false;
  2907. }
  2908. def(AST_Node, return_true);
  2909. def(AST_Array, function(compressor) {
  2910. return any(this.elements, compressor);
  2911. });
  2912. def(AST_Assign, return_true);
  2913. def(AST_Binary, function(compressor) {
  2914. return this.left.has_side_effects(compressor)
  2915. || this.right.has_side_effects(compressor);
  2916. });
  2917. def(AST_Block, function(compressor) {
  2918. return any(this.body, compressor);
  2919. });
  2920. def(AST_Call, function(compressor) {
  2921. if (!this.is_expr_pure(compressor)
  2922. && (!this.expression.is_call_pure(compressor)
  2923. || this.expression.has_side_effects(compressor))) {
  2924. return true;
  2925. }
  2926. return any(this.args, compressor);
  2927. });
  2928. def(AST_Case, function(compressor) {
  2929. return this.expression.has_side_effects(compressor)
  2930. || any(this.body, compressor);
  2931. });
  2932. def(AST_Conditional, function(compressor) {
  2933. return this.condition.has_side_effects(compressor)
  2934. || this.consequent.has_side_effects(compressor)
  2935. || this.alternative.has_side_effects(compressor);
  2936. });
  2937. def(AST_Constant, return_false);
  2938. def(AST_Definitions, function(compressor) {
  2939. return any(this.definitions, compressor);
  2940. });
  2941. def(AST_Dot, function(compressor) {
  2942. return this.expression.may_throw_on_access(compressor)
  2943. || this.expression.has_side_effects(compressor);
  2944. });
  2945. def(AST_EmptyStatement, return_false);
  2946. def(AST_If, function(compressor) {
  2947. return this.condition.has_side_effects(compressor)
  2948. || this.body && this.body.has_side_effects(compressor)
  2949. || this.alternative && this.alternative.has_side_effects(compressor);
  2950. });
  2951. def(AST_LabeledStatement, function(compressor) {
  2952. return this.body.has_side_effects(compressor);
  2953. });
  2954. def(AST_Lambda, return_false);
  2955. def(AST_Object, function(compressor) {
  2956. return any(this.properties, compressor);
  2957. });
  2958. def(AST_ObjectProperty, function(compressor) {
  2959. return this.value.has_side_effects(compressor);
  2960. });
  2961. def(AST_Sub, function(compressor) {
  2962. return this.expression.may_throw_on_access(compressor)
  2963. || this.expression.has_side_effects(compressor)
  2964. || this.property.has_side_effects(compressor);
  2965. });
  2966. def(AST_Sequence, function(compressor) {
  2967. return any(this.expressions, compressor);
  2968. });
  2969. def(AST_SimpleStatement, function(compressor) {
  2970. return this.body.has_side_effects(compressor);
  2971. });
  2972. def(AST_Switch, function(compressor) {
  2973. return this.expression.has_side_effects(compressor)
  2974. || any(this.body, compressor);
  2975. });
  2976. def(AST_SymbolDeclaration, return_false);
  2977. def(AST_SymbolRef, function(compressor) {
  2978. return !this.is_declared(compressor);
  2979. });
  2980. def(AST_This, return_false);
  2981. def(AST_Try, function(compressor) {
  2982. return any(this.body, compressor)
  2983. || this.bcatch && this.bcatch.has_side_effects(compressor)
  2984. || this.bfinally && this.bfinally.has_side_effects(compressor);
  2985. });
  2986. def(AST_Unary, function(compressor) {
  2987. return unary_side_effects[this.operator]
  2988. || this.expression.has_side_effects(compressor);
  2989. });
  2990. def(AST_VarDef, function(compressor) {
  2991. return this.value;
  2992. });
  2993. })(function(node, func) {
  2994. node.DEFMETHOD("has_side_effects", func);
  2995. });
  2996. // determine if expression may throw
  2997. (function(def) {
  2998. def(AST_Node, return_true);
  2999. def(AST_Constant, return_false);
  3000. def(AST_EmptyStatement, return_false);
  3001. def(AST_Lambda, return_false);
  3002. def(AST_SymbolDeclaration, return_false);
  3003. def(AST_This, return_false);
  3004. function any(list, compressor) {
  3005. for (var i = list.length; --i >= 0;)
  3006. if (list[i].may_throw(compressor))
  3007. return true;
  3008. return false;
  3009. }
  3010. def(AST_Array, function(compressor) {
  3011. return any(this.elements, compressor);
  3012. });
  3013. def(AST_Assign, function(compressor) {
  3014. if (this.right.may_throw(compressor)) return true;
  3015. if (!compressor.has_directive("use strict")
  3016. && this.operator == "="
  3017. && this.left instanceof AST_SymbolRef) {
  3018. return false;
  3019. }
  3020. return this.left.may_throw(compressor);
  3021. });
  3022. def(AST_Binary, function(compressor) {
  3023. return this.left.may_throw(compressor)
  3024. || this.right.may_throw(compressor);
  3025. });
  3026. def(AST_Block, function(compressor) {
  3027. return any(this.body, compressor);
  3028. });
  3029. def(AST_Call, function(compressor) {
  3030. if (any(this.args, compressor)) return true;
  3031. if (this.is_expr_pure(compressor)) return false;
  3032. if (this.expression.may_throw(compressor)) return true;
  3033. return !(this.expression instanceof AST_Lambda)
  3034. || any(this.expression.body, compressor);
  3035. });
  3036. def(AST_Case, function(compressor) {
  3037. return this.expression.may_throw(compressor)
  3038. || any(this.body, compressor);
  3039. });
  3040. def(AST_Conditional, function(compressor) {
  3041. return this.condition.may_throw(compressor)
  3042. || this.consequent.may_throw(compressor)
  3043. || this.alternative.may_throw(compressor);
  3044. });
  3045. def(AST_Definitions, function(compressor) {
  3046. return any(this.definitions, compressor);
  3047. });
  3048. def(AST_Dot, function(compressor) {
  3049. return this.expression.may_throw_on_access(compressor)
  3050. || this.expression.may_throw(compressor);
  3051. });
  3052. def(AST_If, function(compressor) {
  3053. return this.condition.may_throw(compressor)
  3054. || this.body && this.body.may_throw(compressor)
  3055. || this.alternative && this.alternative.may_throw(compressor);
  3056. });
  3057. def(AST_LabeledStatement, function(compressor) {
  3058. return this.body.may_throw(compressor);
  3059. });
  3060. def(AST_Object, function(compressor) {
  3061. return any(this.properties, compressor);
  3062. });
  3063. def(AST_ObjectProperty, function(compressor) {
  3064. return this.value.may_throw(compressor);
  3065. });
  3066. def(AST_Return, function(compressor) {
  3067. return this.value && this.value.may_throw(compressor);
  3068. });
  3069. def(AST_Sequence, function(compressor) {
  3070. return any(this.expressions, compressor);
  3071. });
  3072. def(AST_SimpleStatement, function(compressor) {
  3073. return this.body.may_throw(compressor);
  3074. });
  3075. def(AST_Sub, function(compressor) {
  3076. return this.expression.may_throw_on_access(compressor)
  3077. || this.expression.may_throw(compressor)
  3078. || this.property.may_throw(compressor);
  3079. });
  3080. def(AST_Switch, function(compressor) {
  3081. return this.expression.may_throw(compressor)
  3082. || any(this.body, compressor);
  3083. });
  3084. def(AST_SymbolRef, function(compressor) {
  3085. return !this.is_declared(compressor);
  3086. });
  3087. def(AST_Try, function(compressor) {
  3088. return this.bcatch ? this.bcatch.may_throw(compressor) : any(this.body, compressor)
  3089. || this.bfinally && this.bfinally.may_throw(compressor);
  3090. });
  3091. def(AST_Unary, function(compressor) {
  3092. if (this.operator == "typeof" && this.expression instanceof AST_SymbolRef)
  3093. return false;
  3094. return this.expression.may_throw(compressor);
  3095. });
  3096. def(AST_VarDef, function(compressor) {
  3097. if (!this.value) return false;
  3098. return this.value.may_throw(compressor);
  3099. });
  3100. })(function(node, func) {
  3101. node.DEFMETHOD("may_throw", func);
  3102. });
  3103. // determine if expression is constant
  3104. (function(def) {
  3105. function all(list) {
  3106. for (var i = list.length; --i >= 0;)
  3107. if (!list[i].is_constant_expression())
  3108. return false;
  3109. return true;
  3110. }
  3111. def(AST_Node, return_false);
  3112. def(AST_Constant, return_true);
  3113. def(AST_Lambda, function(scope) {
  3114. var self = this;
  3115. var result = true;
  3116. self.walk(new TreeWalker(function(node) {
  3117. if (!result) return true;
  3118. if (node instanceof AST_SymbolRef) {
  3119. if (self.inlined) {
  3120. result = false;
  3121. return true;
  3122. }
  3123. var def = node.definition();
  3124. if (member(def, self.enclosed)
  3125. && !self.variables.has(def.name)) {
  3126. if (scope) {
  3127. var scope_def = scope.find_variable(node);
  3128. if (def.undeclared ? !scope_def : scope_def === def) {
  3129. result = "f";
  3130. return true;
  3131. }
  3132. }
  3133. result = false;
  3134. }
  3135. return true;
  3136. }
  3137. }));
  3138. return result;
  3139. });
  3140. def(AST_Unary, function() {
  3141. return this.expression.is_constant_expression();
  3142. });
  3143. def(AST_Binary, function() {
  3144. return this.left.is_constant_expression() && this.right.is_constant_expression();
  3145. });
  3146. def(AST_Array, function() {
  3147. return all(this.elements);
  3148. });
  3149. def(AST_Object, function() {
  3150. return all(this.properties);
  3151. });
  3152. def(AST_ObjectProperty, function() {
  3153. return this.value.is_constant_expression();
  3154. });
  3155. })(function(node, func) {
  3156. node.DEFMETHOD("is_constant_expression", func);
  3157. });
  3158. // tell me if a statement aborts
  3159. function aborts(thing) {
  3160. return thing && thing.aborts();
  3161. }
  3162. (function(def) {
  3163. def(AST_Statement, return_null);
  3164. def(AST_Jump, return_this);
  3165. function block_aborts() {
  3166. var n = this.body.length;
  3167. return n > 0 && aborts(this.body[n - 1]);
  3168. }
  3169. def(AST_BlockStatement, block_aborts);
  3170. def(AST_SwitchBranch, block_aborts);
  3171. def(AST_If, function() {
  3172. return this.alternative && aborts(this.body) && aborts(this.alternative) && this;
  3173. });
  3174. })(function(node, func) {
  3175. node.DEFMETHOD("aborts", func);
  3176. });
  3177. /* -----[ optimizers ]----- */
  3178. var directives = makePredicate(["use asm", "use strict"]);
  3179. OPT(AST_Directive, function(self, compressor) {
  3180. if (compressor.option("directives")
  3181. && (!directives[self.value] || compressor.has_directive(self.value) !== self)) {
  3182. return make_node(AST_EmptyStatement, self);
  3183. }
  3184. return self;
  3185. });
  3186. OPT(AST_Debugger, function(self, compressor) {
  3187. if (compressor.option("drop_debugger"))
  3188. return make_node(AST_EmptyStatement, self);
  3189. return self;
  3190. });
  3191. OPT(AST_LabeledStatement, function(self, compressor) {
  3192. if (self.body instanceof AST_Break
  3193. && compressor.loopcontrol_target(self.body) === self.body) {
  3194. return make_node(AST_EmptyStatement, self);
  3195. }
  3196. return self.label.references.length == 0 ? self.body : self;
  3197. });
  3198. OPT(AST_Block, function(self, compressor) {
  3199. tighten_body(self.body, compressor);
  3200. return self;
  3201. });
  3202. OPT(AST_BlockStatement, function(self, compressor) {
  3203. tighten_body(self.body, compressor);
  3204. switch (self.body.length) {
  3205. case 1: return self.body[0];
  3206. case 0: return make_node(AST_EmptyStatement, self);
  3207. }
  3208. return self;
  3209. });
  3210. OPT(AST_Lambda, function(self, compressor) {
  3211. tighten_body(self.body, compressor);
  3212. if (compressor.option("side_effects")
  3213. && self.body.length == 1
  3214. && self.body[0] === compressor.has_directive("use strict")) {
  3215. self.body.length = 0;
  3216. }
  3217. return self;
  3218. });
  3219. AST_Scope.DEFMETHOD("drop_unused", function(compressor) {
  3220. if (!compressor.option("unused")) return;
  3221. if (compressor.has_directive("use asm")) return;
  3222. var self = this;
  3223. if (self.pinned()) return;
  3224. var drop_funcs = !(self instanceof AST_Toplevel) || compressor.toplevel.funcs;
  3225. var drop_vars = !(self instanceof AST_Toplevel) || compressor.toplevel.vars;
  3226. var assign_as_unused = /keep_assign/.test(compressor.option("unused")) ? return_false : function(node, props) {
  3227. var sym;
  3228. if (node instanceof AST_Assign && (node.write_only || node.operator == "=")) {
  3229. sym = node.left;
  3230. } else if (node instanceof AST_Unary && node.write_only) {
  3231. sym = node.expression;
  3232. }
  3233. if (!/strict/.test(compressor.option("pure_getters"))) return sym instanceof AST_SymbolRef && sym;
  3234. while (sym instanceof AST_PropAccess && !sym.expression.may_throw_on_access(compressor)) {
  3235. if (sym instanceof AST_Sub) props.unshift(sym.property);
  3236. sym = sym.expression;
  3237. }
  3238. return sym instanceof AST_SymbolRef && all(sym.definition().orig, function(sym) {
  3239. return !(sym instanceof AST_SymbolLambda);
  3240. }) && sym;
  3241. };
  3242. var in_use = [];
  3243. var in_use_ids = Object.create(null); // avoid expensive linear scans of in_use
  3244. var fixed_ids = Object.create(null);
  3245. var value_read = Object.create(null);
  3246. var value_modified = Object.create(null);
  3247. if (self instanceof AST_Toplevel && compressor.top_retain) {
  3248. self.variables.each(function(def) {
  3249. if (compressor.top_retain(def) && !(def.id in in_use_ids)) {
  3250. in_use_ids[def.id] = true;
  3251. in_use.push(def);
  3252. }
  3253. });
  3254. }
  3255. var var_defs_by_id = new Dictionary();
  3256. var initializations = new Dictionary();
  3257. // pass 1: find out which symbols are directly used in
  3258. // this scope (not in nested scopes).
  3259. var scope = this;
  3260. var tw = new TreeWalker(function(node, descend) {
  3261. if (node instanceof AST_Lambda && node.uses_arguments && !tw.has_directive("use strict")) {
  3262. node.argnames.forEach(function(argname) {
  3263. var def = argname.definition();
  3264. if (!(def.id in in_use_ids)) {
  3265. in_use_ids[def.id] = true;
  3266. in_use.push(def);
  3267. }
  3268. });
  3269. }
  3270. if (node === self) return;
  3271. if (node instanceof AST_Defun) {
  3272. var node_def = node.name.definition();
  3273. if (!drop_funcs && scope === self) {
  3274. if (!(node_def.id in in_use_ids)) {
  3275. in_use_ids[node_def.id] = true;
  3276. in_use.push(node_def);
  3277. }
  3278. }
  3279. initializations.add(node_def.id, node);
  3280. return true; // don't go in nested scopes
  3281. }
  3282. if (node instanceof AST_SymbolFunarg && scope === self) {
  3283. var_defs_by_id.add(node.definition().id, node);
  3284. }
  3285. if (node instanceof AST_Definitions && scope === self) {
  3286. node.definitions.forEach(function(def) {
  3287. var node_def = def.name.definition();
  3288. if (def.name instanceof AST_SymbolVar) {
  3289. var_defs_by_id.add(node_def.id, def);
  3290. }
  3291. if (!drop_vars) {
  3292. if (!(node_def.id in in_use_ids)) {
  3293. in_use_ids[node_def.id] = true;
  3294. in_use.push(node_def);
  3295. }
  3296. }
  3297. if (def.value) {
  3298. initializations.add(node_def.id, def.value);
  3299. if (def.value.has_side_effects(compressor)) {
  3300. def.value.walk(tw);
  3301. }
  3302. if (!node_def.chained && def.name.fixed_value() === def.value) {
  3303. fixed_ids[node_def.id] = def;
  3304. }
  3305. }
  3306. });
  3307. return true;
  3308. }
  3309. return scan_ref_scoped(node, descend);
  3310. });
  3311. self.walk(tw);
  3312. // pass 2: for every used symbol we need to walk its
  3313. // initialization code to figure out if it uses other
  3314. // symbols (that may not be in_use).
  3315. tw = new TreeWalker(scan_ref_scoped);
  3316. for (var i = 0; i < in_use.length; i++) {
  3317. var init = initializations.get(in_use[i].id);
  3318. if (init) init.forEach(function(init) {
  3319. init.walk(tw);
  3320. });
  3321. }
  3322. var drop_fn_name = compressor.option("keep_fnames") ? return_false : compressor.option("ie8") ? function(def) {
  3323. return !compressor.exposed(def) && !def.references.length;
  3324. } : function(def) {
  3325. // any declarations with same name will overshadow
  3326. // name of this anonymous function and can therefore
  3327. // never be used anywhere
  3328. return !(def.id in in_use_ids) || def.orig.length > 1;
  3329. };
  3330. // pass 3: we should drop declarations not in_use
  3331. var tt = new TreeTransformer(function(node, descend, in_list) {
  3332. var parent = tt.parent();
  3333. if (drop_vars) {
  3334. var props = [], sym = assign_as_unused(node, props);
  3335. if (sym) {
  3336. var def = sym.definition();
  3337. var in_use = def.id in in_use_ids;
  3338. var value = null;
  3339. if (node instanceof AST_Assign) {
  3340. if (!in_use || node.left === sym && def.id in fixed_ids && fixed_ids[def.id] !== node) {
  3341. value = node.right;
  3342. }
  3343. } else if (!in_use) {
  3344. value = make_node(AST_Number, node, {
  3345. value: 0
  3346. });
  3347. }
  3348. if (value) {
  3349. props.push(value);
  3350. return maintain_this_binding(compressor, parent, node, make_sequence(node, props.map(function(prop) {
  3351. return prop.transform(tt);
  3352. })));
  3353. }
  3354. }
  3355. }
  3356. if (scope !== self) return;
  3357. if (node instanceof AST_Function && node.name && drop_fn_name(node.name.definition())) {
  3358. node.name = null;
  3359. }
  3360. if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) {
  3361. var trim = !compressor.option("keep_fargs");
  3362. for (var a = node.argnames, i = a.length; --i >= 0;) {
  3363. var sym = a[i];
  3364. if (!(sym.definition().id in in_use_ids)) {
  3365. sym.__unused = true;
  3366. if (trim) {
  3367. a.pop();
  3368. compressor[sym.unreferenced() ? "warn" : "info"]("Dropping unused function argument {name} [{file}:{line},{col}]", template(sym));
  3369. }
  3370. } else {
  3371. trim = false;
  3372. }
  3373. }
  3374. }
  3375. if (drop_funcs && node instanceof AST_Defun && node !== self) {
  3376. var def = node.name.definition();
  3377. if (!(def.id in in_use_ids)) {
  3378. compressor[node.name.unreferenced() ? "warn" : "info"]("Dropping unused function {name} [{file}:{line},{col}]", template(node.name));
  3379. def.eliminated++;
  3380. return make_node(AST_EmptyStatement, node);
  3381. }
  3382. }
  3383. if (node instanceof AST_Definitions && !(parent instanceof AST_ForIn && parent.init === node)) {
  3384. // place uninitialized names at the start
  3385. var body = [], head = [], tail = [];
  3386. // for unused names whose initialization has
  3387. // side effects, we can cascade the init. code
  3388. // into the next one, or next statement.
  3389. var side_effects = [];
  3390. node.definitions.forEach(function(def) {
  3391. if (def.value) def.value = def.value.transform(tt);
  3392. var sym = def.name.definition();
  3393. if (!drop_vars || sym.id in in_use_ids) {
  3394. if (def.value && sym.id in fixed_ids && fixed_ids[sym.id] !== def) {
  3395. def.value = def.value.drop_side_effect_free(compressor);
  3396. }
  3397. if (def.name instanceof AST_SymbolVar) {
  3398. var var_defs = var_defs_by_id.get(sym.id);
  3399. if (var_defs.length > 1 && (!def.value || sym.orig.indexOf(def.name) > sym.eliminated)) {
  3400. compressor.warn("Dropping duplicated definition of variable {name} [{file}:{line},{col}]", template(def.name));
  3401. if (def.value) {
  3402. var ref = make_node(AST_SymbolRef, def.name, def.name);
  3403. sym.references.push(ref);
  3404. var assign = make_node(AST_Assign, def, {
  3405. operator: "=",
  3406. left: ref,
  3407. right: def.value
  3408. });
  3409. if (fixed_ids[sym.id] === def) {
  3410. fixed_ids[sym.id] = assign;
  3411. }
  3412. side_effects.push(assign.transform(tt));
  3413. }
  3414. remove(var_defs, def);
  3415. sym.eliminated++;
  3416. return;
  3417. }
  3418. }
  3419. if (def.value) {
  3420. if (side_effects.length > 0) {
  3421. if (tail.length > 0) {
  3422. side_effects.push(def.value);
  3423. def.value = make_sequence(def.value, side_effects);
  3424. } else {
  3425. body.push(make_node(AST_SimpleStatement, node, {
  3426. body: make_sequence(node, side_effects)
  3427. }));
  3428. }
  3429. side_effects = [];
  3430. }
  3431. tail.push(def);
  3432. } else {
  3433. head.push(def);
  3434. }
  3435. } else if (sym.orig[0] instanceof AST_SymbolCatch) {
  3436. var value = def.value && def.value.drop_side_effect_free(compressor);
  3437. if (value) side_effects.push(value);
  3438. def.value = null;
  3439. head.push(def);
  3440. } else {
  3441. var value = def.value && def.value.drop_side_effect_free(compressor);
  3442. if (value) {
  3443. compressor.warn("Side effects in initialization of unused variable {name} [{file}:{line},{col}]", template(def.name));
  3444. side_effects.push(value);
  3445. } else {
  3446. compressor[def.name.unreferenced() ? "warn" : "info"]("Dropping unused variable {name} [{file}:{line},{col}]", template(def.name));
  3447. }
  3448. sym.eliminated++;
  3449. }
  3450. });
  3451. if (head.length > 0 || tail.length > 0) {
  3452. node.definitions = head.concat(tail);
  3453. body.push(node);
  3454. }
  3455. if (side_effects.length > 0) {
  3456. body.push(make_node(AST_SimpleStatement, node, {
  3457. body: make_sequence(node, side_effects)
  3458. }));
  3459. }
  3460. switch (body.length) {
  3461. case 0:
  3462. return in_list ? MAP.skip : make_node(AST_EmptyStatement, node);
  3463. case 1:
  3464. return body[0];
  3465. default:
  3466. return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, {
  3467. body: body
  3468. });
  3469. }
  3470. }
  3471. // certain combination of unused name + side effect leads to:
  3472. // https://github.com/mishoo/UglifyJS2/issues/44
  3473. // https://github.com/mishoo/UglifyJS2/issues/1830
  3474. // https://github.com/mishoo/UglifyJS2/issues/1838
  3475. // that's an invalid AST.
  3476. // We fix it at this stage by moving the `var` outside the `for`.
  3477. if (node instanceof AST_For) {
  3478. descend(node, this);
  3479. var block;
  3480. if (node.init instanceof AST_BlockStatement) {
  3481. block = node.init;
  3482. node.init = block.body.pop();
  3483. block.body.push(node);
  3484. }
  3485. if (node.init instanceof AST_SimpleStatement) {
  3486. node.init = node.init.body;
  3487. } else if (is_empty(node.init)) {
  3488. node.init = null;
  3489. }
  3490. return !block ? node : in_list ? MAP.splice(block.body) : block;
  3491. }
  3492. if (node instanceof AST_LabeledStatement && node.body instanceof AST_For) {
  3493. descend(node, this);
  3494. if (node.body instanceof AST_BlockStatement) {
  3495. var block = node.body;
  3496. node.body = block.body.pop();
  3497. block.body.push(node);
  3498. return in_list ? MAP.splice(block.body) : block;
  3499. }
  3500. return node;
  3501. }
  3502. if (node instanceof AST_Scope) {
  3503. var save_scope = scope;
  3504. scope = node;
  3505. descend(node, this);
  3506. scope = save_scope;
  3507. return node;
  3508. }
  3509. function template(sym) {
  3510. return {
  3511. name : sym.name,
  3512. file : sym.start.file,
  3513. line : sym.start.line,
  3514. col : sym.start.col
  3515. };
  3516. }
  3517. });
  3518. self.transform(tt);
  3519. function verify_safe_usage(def, read, modified) {
  3520. if (def.id in in_use_ids) return;
  3521. if (read && modified) {
  3522. in_use_ids[def.id] = true;
  3523. in_use.push(def);
  3524. } else {
  3525. value_read[def.id] = read;
  3526. value_modified[def.id] = modified;
  3527. }
  3528. }
  3529. function scan_ref_scoped(node, descend) {
  3530. var node_def, props = [], sym = assign_as_unused(node, props);
  3531. if (sym && self.variables.get(sym.name) === (node_def = sym.definition())) {
  3532. props.forEach(function(prop) {
  3533. prop.walk(tw);
  3534. });
  3535. if (node instanceof AST_Assign) {
  3536. node.right.walk(tw);
  3537. if (node.left === sym) {
  3538. if (!node_def.chained && sym.fixed_value() === node.right) {
  3539. fixed_ids[node_def.id] = node;
  3540. }
  3541. if (!node.write_only) {
  3542. verify_safe_usage(node_def, true, value_modified[node_def.id]);
  3543. }
  3544. } else {
  3545. var fixed = sym.fixed_value();
  3546. if (!fixed || !fixed.is_constant()) {
  3547. verify_safe_usage(node_def, value_read[node_def.id], true);
  3548. }
  3549. }
  3550. }
  3551. return true;
  3552. }
  3553. if (node instanceof AST_SymbolRef) {
  3554. node_def = node.definition();
  3555. if (!(node_def.id in in_use_ids)) {
  3556. in_use_ids[node_def.id] = true;
  3557. in_use.push(node_def);
  3558. }
  3559. return true;
  3560. }
  3561. if (node instanceof AST_Scope) {
  3562. var save_scope = scope;
  3563. scope = node;
  3564. descend();
  3565. scope = save_scope;
  3566. return true;
  3567. }
  3568. }
  3569. });
  3570. AST_Scope.DEFMETHOD("hoist_declarations", function(compressor) {
  3571. if (compressor.has_directive("use asm")) return;
  3572. var hoist_funs = compressor.option("hoist_funs");
  3573. var hoist_vars = compressor.option("hoist_vars");
  3574. var self = this;
  3575. if (hoist_vars) {
  3576. // let's count var_decl first, we seem to waste a lot of
  3577. // space if we hoist `var` when there's only one.
  3578. var var_decl = 0;
  3579. self.walk(new TreeWalker(function(node) {
  3580. if (var_decl > 1) return true;
  3581. if (node instanceof AST_Scope && node !== self) return true;
  3582. if (node instanceof AST_Var) {
  3583. var_decl++;
  3584. return true;
  3585. }
  3586. }));
  3587. if (var_decl <= 1) hoist_vars = false;
  3588. }
  3589. if (!hoist_funs && !hoist_vars) return;
  3590. var dirs = [];
  3591. var hoisted = [];
  3592. var vars = new Dictionary(), vars_found = 0;
  3593. var tt = new TreeTransformer(function(node) {
  3594. if (node === self) return;
  3595. if (node instanceof AST_Directive) {
  3596. dirs.push(node);
  3597. return make_node(AST_EmptyStatement, node);
  3598. }
  3599. if (hoist_funs && node instanceof AST_Defun
  3600. && (tt.parent() === self || !compressor.has_directive("use strict"))) {
  3601. hoisted.push(node);
  3602. return make_node(AST_EmptyStatement, node);
  3603. }
  3604. if (hoist_vars && node instanceof AST_Var) {
  3605. node.definitions.forEach(function(def) {
  3606. vars.set(def.name.name, def);
  3607. ++vars_found;
  3608. });
  3609. var seq = node.to_assignments(compressor);
  3610. var p = tt.parent();
  3611. if (p instanceof AST_ForIn && p.init === node) {
  3612. if (seq) return seq;
  3613. var def = node.definitions[0].name;
  3614. return make_node(AST_SymbolRef, def, def);
  3615. }
  3616. if (p instanceof AST_For && p.init === node) return seq;
  3617. if (!seq) return make_node(AST_EmptyStatement, node);
  3618. return make_node(AST_SimpleStatement, node, {
  3619. body: seq
  3620. });
  3621. }
  3622. if (node instanceof AST_Scope) return node;
  3623. });
  3624. self.transform(tt);
  3625. if (vars_found > 0) {
  3626. // collect only vars which don't show up in self's arguments list
  3627. var defs = [];
  3628. vars.each(function(def, name) {
  3629. if (self instanceof AST_Lambda
  3630. && !all(self.argnames, function(argname) {
  3631. return argname.name != name;
  3632. })) {
  3633. vars.del(name);
  3634. } else {
  3635. def = def.clone();
  3636. def.value = null;
  3637. defs.push(def);
  3638. vars.set(name, def);
  3639. }
  3640. });
  3641. if (defs.length > 0) {
  3642. // try to merge in assignments
  3643. for (var i = 0; i < self.body.length;) {
  3644. if (self.body[i] instanceof AST_SimpleStatement) {
  3645. var expr = self.body[i].body, sym, assign;
  3646. if (expr instanceof AST_Assign
  3647. && expr.operator == "="
  3648. && (sym = expr.left) instanceof AST_Symbol
  3649. && vars.has(sym.name))
  3650. {
  3651. var def = vars.get(sym.name);
  3652. if (def.value) break;
  3653. def.value = expr.right;
  3654. remove(defs, def);
  3655. defs.push(def);
  3656. self.body.splice(i, 1);
  3657. continue;
  3658. }
  3659. if (expr instanceof AST_Sequence
  3660. && (assign = expr.expressions[0]) instanceof AST_Assign
  3661. && assign.operator == "="
  3662. && (sym = assign.left) instanceof AST_Symbol
  3663. && vars.has(sym.name))
  3664. {
  3665. var def = vars.get(sym.name);
  3666. if (def.value) break;
  3667. def.value = assign.right;
  3668. remove(defs, def);
  3669. defs.push(def);
  3670. self.body[i].body = make_sequence(expr, expr.expressions.slice(1));
  3671. continue;
  3672. }
  3673. }
  3674. if (self.body[i] instanceof AST_EmptyStatement) {
  3675. self.body.splice(i, 1);
  3676. continue;
  3677. }
  3678. if (self.body[i] instanceof AST_BlockStatement) {
  3679. var tmp = [ i, 1 ].concat(self.body[i].body);
  3680. self.body.splice.apply(self.body, tmp);
  3681. continue;
  3682. }
  3683. break;
  3684. }
  3685. defs = make_node(AST_Var, self, {
  3686. definitions: defs
  3687. });
  3688. hoisted.push(defs);
  3689. }
  3690. }
  3691. self.body = dirs.concat(hoisted, self.body);
  3692. });
  3693. AST_Scope.DEFMETHOD("var_names", function() {
  3694. var var_names = this._var_names;
  3695. if (!var_names) {
  3696. this._var_names = var_names = Object.create(null);
  3697. this.enclosed.forEach(function(def) {
  3698. var_names[def.name] = true;
  3699. });
  3700. this.variables.each(function(def, name) {
  3701. var_names[name] = true;
  3702. });
  3703. }
  3704. return var_names;
  3705. });
  3706. AST_Scope.DEFMETHOD("make_var_name", function(prefix) {
  3707. var var_names = this.var_names();
  3708. prefix = prefix.replace(/(?:^[^a-z_$]|[^a-z0-9_$])/ig, "_");
  3709. var name = prefix;
  3710. for (var i = 0; var_names[name]; i++) name = prefix + "$" + i;
  3711. var_names[name] = true;
  3712. return name;
  3713. });
  3714. AST_Scope.DEFMETHOD("hoist_properties", function(compressor) {
  3715. if (!compressor.option("hoist_props") || compressor.has_directive("use asm")) return;
  3716. var self = this;
  3717. var top_retain = self instanceof AST_Toplevel && compressor.top_retain || return_false;
  3718. var defs_by_id = Object.create(null);
  3719. self.transform(new TreeTransformer(function(node, descend) {
  3720. if (node instanceof AST_Assign
  3721. && node.operator == "="
  3722. && node.write_only
  3723. && can_hoist(node.left, node.right, 1)) {
  3724. descend(node, this);
  3725. var defs = new Dictionary();
  3726. var assignments = [];
  3727. var decls = [];
  3728. node.right.properties.forEach(function(prop) {
  3729. var decl = make_sym(node.left, prop.key);
  3730. decls.push(make_node(AST_VarDef, node, {
  3731. name: decl,
  3732. value: null
  3733. }));
  3734. var sym = make_node(AST_SymbolRef, node, {
  3735. name: decl.name,
  3736. scope: self,
  3737. thedef: decl.definition()
  3738. });
  3739. sym.reference({});
  3740. assignments.push(make_node(AST_Assign, node, {
  3741. operator: "=",
  3742. left: sym,
  3743. right: prop.value
  3744. }));
  3745. });
  3746. defs_by_id[node.left.definition().id] = defs;
  3747. self.body.splice(self.body.indexOf(this.stack[1]) + 1, 0, make_node(AST_Var, node, {
  3748. definitions: decls
  3749. }));
  3750. return make_sequence(node, assignments);
  3751. }
  3752. if (node instanceof AST_VarDef && can_hoist(node.name, node.value, 0)) {
  3753. descend(node, this);
  3754. var defs = new Dictionary();
  3755. var var_defs = [];
  3756. node.value.properties.forEach(function(prop) {
  3757. var_defs.push(make_node(AST_VarDef, node, {
  3758. name: make_sym(node.name, prop.key),
  3759. value: prop.value
  3760. }));
  3761. });
  3762. defs_by_id[node.name.definition().id] = defs;
  3763. return MAP.splice(var_defs);
  3764. }
  3765. if (node instanceof AST_PropAccess && node.expression instanceof AST_SymbolRef) {
  3766. var defs = defs_by_id[node.expression.definition().id];
  3767. if (defs) {
  3768. var def = defs.get(get_value(node.property));
  3769. var sym = make_node(AST_SymbolRef, node, {
  3770. name: def.name,
  3771. scope: node.expression.scope,
  3772. thedef: def
  3773. });
  3774. sym.reference({});
  3775. return sym;
  3776. }
  3777. }
  3778. function can_hoist(sym, right, count) {
  3779. if (sym.scope !== self) return;
  3780. var def = sym.definition();
  3781. if (def.assignments != count) return;
  3782. if (def.direct_access) return;
  3783. if (def.escaped == 1) return;
  3784. if (def.references.length == count) return;
  3785. if (def.single_use) return;
  3786. if (top_retain(def)) return;
  3787. if (sym.fixed_value() !== right) return;
  3788. return right instanceof AST_Object;
  3789. }
  3790. function make_sym(sym, key) {
  3791. var new_var = make_node(AST_SymbolVar, sym, {
  3792. name: self.make_var_name(sym.name + "_" + key),
  3793. scope: self
  3794. });
  3795. var def = self.def_variable(new_var);
  3796. defs.set(key, def);
  3797. self.enclosed.push(def);
  3798. return new_var;
  3799. }
  3800. }));
  3801. });
  3802. // drop_side_effect_free()
  3803. // remove side-effect-free parts which only affects return value
  3804. (function(def) {
  3805. // Drop side-effect-free elements from an array of expressions.
  3806. // Returns an array of expressions with side-effects or null
  3807. // if all elements were dropped. Note: original array may be
  3808. // returned if nothing changed.
  3809. function trim(nodes, compressor, first_in_statement) {
  3810. var len = nodes.length;
  3811. if (!len) return null;
  3812. var ret = [], changed = false;
  3813. for (var i = 0; i < len; i++) {
  3814. var node = nodes[i].drop_side_effect_free(compressor, first_in_statement);
  3815. changed |= node !== nodes[i];
  3816. if (node) {
  3817. ret.push(node);
  3818. first_in_statement = false;
  3819. }
  3820. }
  3821. return changed ? ret.length ? ret : null : nodes;
  3822. }
  3823. def(AST_Node, return_this);
  3824. def(AST_Accessor, return_null);
  3825. def(AST_Array, function(compressor, first_in_statement) {
  3826. var values = trim(this.elements, compressor, first_in_statement);
  3827. return values && make_sequence(this, values);
  3828. });
  3829. def(AST_Assign, function(compressor) {
  3830. var left = this.left;
  3831. if (left.has_side_effects(compressor)
  3832. || compressor.has_directive("use strict")
  3833. && left instanceof AST_PropAccess
  3834. && left.expression.is_constant()) {
  3835. return this;
  3836. }
  3837. this.write_only = true;
  3838. if (root_expr(left).is_constant_expression(compressor.find_parent(AST_Scope))) {
  3839. return this.right.drop_side_effect_free(compressor);
  3840. }
  3841. return this;
  3842. });
  3843. def(AST_Binary, function(compressor, first_in_statement) {
  3844. var right = this.right.drop_side_effect_free(compressor);
  3845. if (!right) return this.left.drop_side_effect_free(compressor, first_in_statement);
  3846. if (lazy_op[this.operator]) {
  3847. if (right === this.right) return this;
  3848. var node = this.clone();
  3849. node.right = right;
  3850. return node;
  3851. } else {
  3852. var left = this.left.drop_side_effect_free(compressor, first_in_statement);
  3853. if (!left) return this.right.drop_side_effect_free(compressor, first_in_statement);
  3854. return make_sequence(this, [ left, right ]);
  3855. }
  3856. });
  3857. def(AST_Call, function(compressor, first_in_statement) {
  3858. if (!this.is_expr_pure(compressor)) {
  3859. if (this.expression.is_call_pure(compressor)) {
  3860. var exprs = this.args.slice();
  3861. exprs.unshift(this.expression.expression);
  3862. exprs = trim(exprs, compressor, first_in_statement);
  3863. return exprs && make_sequence(this, exprs);
  3864. }
  3865. if (this.expression instanceof AST_Function
  3866. && (!this.expression.name || !this.expression.name.definition().references.length)) {
  3867. var node = this.clone();
  3868. var exp = node.expression;
  3869. exp.process_expression(false, compressor);
  3870. exp.walk(new TreeWalker(function(node) {
  3871. if (node instanceof AST_Return && node.value) {
  3872. node.value = node.value.drop_side_effect_free(compressor);
  3873. return true;
  3874. }
  3875. if (node instanceof AST_Scope && node !== exp) return true;
  3876. }));
  3877. return node;
  3878. }
  3879. return this;
  3880. }
  3881. if (this.pure) {
  3882. compressor.warn("Dropping __PURE__ call [{file}:{line},{col}]", this.start);
  3883. }
  3884. var args = trim(this.args, compressor, first_in_statement);
  3885. return args && make_sequence(this, args);
  3886. });
  3887. def(AST_Conditional, function(compressor) {
  3888. var consequent = this.consequent.drop_side_effect_free(compressor);
  3889. var alternative = this.alternative.drop_side_effect_free(compressor);
  3890. if (consequent === this.consequent && alternative === this.alternative) return this;
  3891. if (!consequent) return alternative ? make_node(AST_Binary, this, {
  3892. operator: "||",
  3893. left: this.condition,
  3894. right: alternative
  3895. }) : this.condition.drop_side_effect_free(compressor);
  3896. if (!alternative) return make_node(AST_Binary, this, {
  3897. operator: "&&",
  3898. left: this.condition,
  3899. right: consequent
  3900. });
  3901. var node = this.clone();
  3902. node.consequent = consequent;
  3903. node.alternative = alternative;
  3904. return node;
  3905. });
  3906. def(AST_Constant, return_null);
  3907. def(AST_Dot, function(compressor, first_in_statement) {
  3908. if (this.expression.may_throw_on_access(compressor)) return this;
  3909. return this.expression.drop_side_effect_free(compressor, first_in_statement);
  3910. });
  3911. def(AST_Function, function(compressor) {
  3912. return this.name && compressor.option("ie8") ? this : null;
  3913. });
  3914. def(AST_Unary, function(compressor, first_in_statement) {
  3915. if (unary_side_effects[this.operator]) {
  3916. this.write_only = !this.expression.has_side_effects(compressor);
  3917. return this;
  3918. }
  3919. if (this.operator == "typeof" && this.expression instanceof AST_SymbolRef) return null;
  3920. var expression = this.expression.drop_side_effect_free(compressor, first_in_statement);
  3921. if (first_in_statement && expression && is_iife_call(expression)) {
  3922. if (expression === this.expression && this.operator == "!") return this;
  3923. return expression.negate(compressor, first_in_statement);
  3924. }
  3925. return expression;
  3926. });
  3927. def(AST_Object, function(compressor, first_in_statement) {
  3928. var values = trim(this.properties, compressor, first_in_statement);
  3929. return values && make_sequence(this, values);
  3930. });
  3931. def(AST_ObjectProperty, function(compressor, first_in_statement) {
  3932. return this.value.drop_side_effect_free(compressor, first_in_statement);
  3933. });
  3934. def(AST_Sequence, function(compressor) {
  3935. var last = this.tail_node();
  3936. var expr = last.drop_side_effect_free(compressor);
  3937. if (expr === last) return this;
  3938. var expressions = this.expressions.slice(0, -1);
  3939. if (expr) expressions.push(expr);
  3940. return make_sequence(this, expressions);
  3941. });
  3942. def(AST_Sub, function(compressor, first_in_statement) {
  3943. if (this.expression.may_throw_on_access(compressor)) return this;
  3944. var expression = this.expression.drop_side_effect_free(compressor, first_in_statement);
  3945. if (!expression) return this.property.drop_side_effect_free(compressor, first_in_statement);
  3946. var property = this.property.drop_side_effect_free(compressor);
  3947. if (!property) return expression;
  3948. return make_sequence(this, [ expression, property ]);
  3949. });
  3950. def(AST_SymbolRef, function(compressor) {
  3951. return this.is_declared(compressor) ? null : this;
  3952. });
  3953. def(AST_This, return_null);
  3954. })(function(node, func) {
  3955. node.DEFMETHOD("drop_side_effect_free", func);
  3956. });
  3957. OPT(AST_SimpleStatement, function(self, compressor) {
  3958. if (compressor.option("side_effects")) {
  3959. var body = self.body;
  3960. var node = body.drop_side_effect_free(compressor, true);
  3961. if (!node) {
  3962. compressor.warn("Dropping side-effect-free statement [{file}:{line},{col}]", self.start);
  3963. return make_node(AST_EmptyStatement, self);
  3964. }
  3965. if (node !== body) {
  3966. return make_node(AST_SimpleStatement, self, { body: node });
  3967. }
  3968. }
  3969. return self;
  3970. });
  3971. OPT(AST_While, function(self, compressor) {
  3972. return compressor.option("loops") ? make_node(AST_For, self, self).optimize(compressor) : self;
  3973. });
  3974. function has_break_or_continue(loop, parent) {
  3975. var found = false;
  3976. var tw = new TreeWalker(function(node) {
  3977. if (found || node instanceof AST_Scope) return true;
  3978. if (node instanceof AST_LoopControl && tw.loopcontrol_target(node) === loop) {
  3979. return found = true;
  3980. }
  3981. });
  3982. if (parent instanceof AST_LabeledStatement) tw.push(parent);
  3983. tw.push(loop);
  3984. loop.body.walk(tw);
  3985. return found;
  3986. }
  3987. OPT(AST_Do, function(self, compressor) {
  3988. if (!compressor.option("loops")) return self;
  3989. var cond = self.condition.is_truthy() || self.condition.tail_node().evaluate(compressor);
  3990. if (!(cond instanceof AST_Node)) {
  3991. if (cond) return make_node(AST_For, self, {
  3992. body: make_node(AST_BlockStatement, self.body, {
  3993. body: [
  3994. self.body,
  3995. make_node(AST_SimpleStatement, self.condition, {
  3996. body: self.condition
  3997. })
  3998. ]
  3999. })
  4000. }).optimize(compressor);
  4001. if (!has_break_or_continue(self, compressor.parent())) {
  4002. return make_node(AST_BlockStatement, self.body, {
  4003. body: [
  4004. self.body,
  4005. make_node(AST_SimpleStatement, self.condition, {
  4006. body: self.condition
  4007. })
  4008. ]
  4009. }).optimize(compressor);
  4010. }
  4011. }
  4012. if (self.body instanceof AST_SimpleStatement) return make_node(AST_For, self, {
  4013. condition: make_sequence(self.condition, [
  4014. self.body.body,
  4015. self.condition
  4016. ]),
  4017. body: make_node(AST_EmptyStatement, self)
  4018. }).optimize(compressor);
  4019. return self;
  4020. });
  4021. function if_break_in_loop(self, compressor) {
  4022. var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body;
  4023. if (compressor.option("dead_code") && is_break(first)) {
  4024. var body = [];
  4025. if (self.init instanceof AST_Statement) {
  4026. body.push(self.init);
  4027. } else if (self.init) {
  4028. body.push(make_node(AST_SimpleStatement, self.init, {
  4029. body: self.init
  4030. }));
  4031. }
  4032. if (self.condition) {
  4033. body.push(make_node(AST_SimpleStatement, self.condition, {
  4034. body: self.condition
  4035. }));
  4036. }
  4037. extract_declarations_from_unreachable_code(compressor, self.body, body);
  4038. return make_node(AST_BlockStatement, self, {
  4039. body: body
  4040. });
  4041. }
  4042. if (first instanceof AST_If) {
  4043. if (is_break(first.body)) {
  4044. if (self.condition) {
  4045. self.condition = make_node(AST_Binary, self.condition, {
  4046. left: self.condition,
  4047. operator: "&&",
  4048. right: first.condition.negate(compressor),
  4049. });
  4050. } else {
  4051. self.condition = first.condition.negate(compressor);
  4052. }
  4053. drop_it(first.alternative);
  4054. } else if (is_break(first.alternative)) {
  4055. if (self.condition) {
  4056. self.condition = make_node(AST_Binary, self.condition, {
  4057. left: self.condition,
  4058. operator: "&&",
  4059. right: first.condition,
  4060. });
  4061. } else {
  4062. self.condition = first.condition;
  4063. }
  4064. drop_it(first.body);
  4065. }
  4066. }
  4067. return self;
  4068. function is_break(node) {
  4069. return node instanceof AST_Break
  4070. && compressor.loopcontrol_target(node) === compressor.self();
  4071. }
  4072. function drop_it(rest) {
  4073. rest = as_statement_array(rest);
  4074. if (self.body instanceof AST_BlockStatement) {
  4075. self.body = self.body.clone();
  4076. self.body.body = rest.concat(self.body.body.slice(1));
  4077. self.body = self.body.transform(compressor);
  4078. } else {
  4079. self.body = make_node(AST_BlockStatement, self.body, {
  4080. body: rest
  4081. }).transform(compressor);
  4082. }
  4083. self = if_break_in_loop(self, compressor);
  4084. }
  4085. }
  4086. OPT(AST_For, function(self, compressor) {
  4087. if (!compressor.option("loops")) return self;
  4088. if (compressor.option("side_effects") && self.init) {
  4089. self.init = self.init.drop_side_effect_free(compressor);
  4090. }
  4091. if (self.condition) {
  4092. var cond = self.condition.evaluate(compressor);
  4093. if (!(cond instanceof AST_Node)) {
  4094. if (cond) self.condition = null;
  4095. else if (!compressor.option("dead_code")) {
  4096. var orig = self.condition;
  4097. self.condition = make_node_from_constant(cond, self.condition);
  4098. self.condition = best_of_expression(self.condition.transform(compressor), orig);
  4099. }
  4100. }
  4101. if (cond instanceof AST_Node) {
  4102. cond = self.condition.is_truthy() || self.condition.tail_node().evaluate(compressor);
  4103. }
  4104. if (!cond) {
  4105. if (compressor.option("dead_code")) {
  4106. var body = [];
  4107. extract_declarations_from_unreachable_code(compressor, self.body, body);
  4108. if (self.init instanceof AST_Statement) {
  4109. body.push(self.init);
  4110. } else if (self.init) {
  4111. body.push(make_node(AST_SimpleStatement, self.init, {
  4112. body: self.init
  4113. }));
  4114. }
  4115. body.push(make_node(AST_SimpleStatement, self.condition, {
  4116. body: self.condition
  4117. }));
  4118. return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor);
  4119. }
  4120. } else if (self.condition && !(cond instanceof AST_Node)) {
  4121. self.body = make_node(AST_BlockStatement, self.body, {
  4122. body: [
  4123. make_node(AST_SimpleStatement, self.condition, {
  4124. body: self.condition
  4125. }),
  4126. self.body
  4127. ]
  4128. });
  4129. self.condition = null;
  4130. }
  4131. }
  4132. return if_break_in_loop(self, compressor);
  4133. });
  4134. OPT(AST_If, function(self, compressor) {
  4135. if (is_empty(self.alternative)) self.alternative = null;
  4136. if (!compressor.option("conditionals")) return self;
  4137. // if condition can be statically determined, warn and drop
  4138. // one of the blocks. note, statically determined implies
  4139. // “has no side effects”; also it doesn't work for cases like
  4140. // `x && true`, though it probably should.
  4141. var cond = self.condition.evaluate(compressor);
  4142. if (!compressor.option("dead_code") && !(cond instanceof AST_Node)) {
  4143. var orig = self.condition;
  4144. self.condition = make_node_from_constant(cond, orig);
  4145. self.condition = best_of_expression(self.condition.transform(compressor), orig);
  4146. }
  4147. if (compressor.option("dead_code")) {
  4148. if (cond instanceof AST_Node) {
  4149. cond = self.condition.is_truthy() || self.condition.tail_node().evaluate(compressor);
  4150. }
  4151. if (!cond) {
  4152. compressor.warn("Condition always false [{file}:{line},{col}]", self.condition.start);
  4153. var body = [];
  4154. extract_declarations_from_unreachable_code(compressor, self.body, body);
  4155. body.push(make_node(AST_SimpleStatement, self.condition, {
  4156. body: self.condition
  4157. }));
  4158. if (self.alternative) body.push(self.alternative);
  4159. return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor);
  4160. } else if (!(cond instanceof AST_Node)) {
  4161. compressor.warn("Condition always true [{file}:{line},{col}]", self.condition.start);
  4162. var body = [];
  4163. if (self.alternative) {
  4164. extract_declarations_from_unreachable_code(compressor, self.alternative, body);
  4165. }
  4166. body.push(make_node(AST_SimpleStatement, self.condition, {
  4167. body: self.condition
  4168. }));
  4169. body.push(self.body);
  4170. return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor);
  4171. }
  4172. }
  4173. var negated = self.condition.negate(compressor);
  4174. var self_condition_length = self.condition.print_to_string().length;
  4175. var negated_length = negated.print_to_string().length;
  4176. var negated_is_best = negated_length < self_condition_length;
  4177. if (self.alternative && negated_is_best) {
  4178. negated_is_best = false; // because we already do the switch here.
  4179. // no need to swap values of self_condition_length and negated_length
  4180. // here because they are only used in an equality comparison later on.
  4181. self.condition = negated;
  4182. var tmp = self.body;
  4183. self.body = self.alternative || make_node(AST_EmptyStatement, self);
  4184. self.alternative = tmp;
  4185. }
  4186. if (is_empty(self.body) && is_empty(self.alternative)) {
  4187. return make_node(AST_SimpleStatement, self.condition, {
  4188. body: self.condition.clone()
  4189. }).optimize(compressor);
  4190. }
  4191. if (self.body instanceof AST_SimpleStatement
  4192. && self.alternative instanceof AST_SimpleStatement) {
  4193. return make_node(AST_SimpleStatement, self, {
  4194. body: make_node(AST_Conditional, self, {
  4195. condition : self.condition,
  4196. consequent : self.body.body,
  4197. alternative : self.alternative.body
  4198. })
  4199. }).optimize(compressor);
  4200. }
  4201. if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) {
  4202. if (self_condition_length === negated_length && !negated_is_best
  4203. && self.condition instanceof AST_Binary && self.condition.operator == "||") {
  4204. // although the code length of self.condition and negated are the same,
  4205. // negated does not require additional surrounding parentheses.
  4206. // see https://github.com/mishoo/UglifyJS2/issues/979
  4207. negated_is_best = true;
  4208. }
  4209. if (negated_is_best) return make_node(AST_SimpleStatement, self, {
  4210. body: make_node(AST_Binary, self, {
  4211. operator : "||",
  4212. left : negated,
  4213. right : self.body.body
  4214. })
  4215. }).optimize(compressor);
  4216. return make_node(AST_SimpleStatement, self, {
  4217. body: make_node(AST_Binary, self, {
  4218. operator : "&&",
  4219. left : self.condition,
  4220. right : self.body.body
  4221. })
  4222. }).optimize(compressor);
  4223. }
  4224. if (self.body instanceof AST_EmptyStatement
  4225. && self.alternative instanceof AST_SimpleStatement) {
  4226. return make_node(AST_SimpleStatement, self, {
  4227. body: make_node(AST_Binary, self, {
  4228. operator : "||",
  4229. left : self.condition,
  4230. right : self.alternative.body
  4231. })
  4232. }).optimize(compressor);
  4233. }
  4234. if (self.body instanceof AST_Exit
  4235. && self.alternative instanceof AST_Exit
  4236. && self.body.TYPE == self.alternative.TYPE) {
  4237. return make_node(self.body.CTOR, self, {
  4238. value: make_node(AST_Conditional, self, {
  4239. condition : self.condition,
  4240. consequent : self.body.value || make_node(AST_Undefined, self.body),
  4241. alternative : self.alternative.value || make_node(AST_Undefined, self.alternative)
  4242. }).transform(compressor)
  4243. }).optimize(compressor);
  4244. }
  4245. if (self.body instanceof AST_If
  4246. && !self.body.alternative
  4247. && !self.alternative) {
  4248. self = make_node(AST_If, self, {
  4249. condition: make_node(AST_Binary, self.condition, {
  4250. operator: "&&",
  4251. left: self.condition,
  4252. right: self.body.condition
  4253. }),
  4254. body: self.body.body,
  4255. alternative: null
  4256. });
  4257. }
  4258. if (aborts(self.body)) {
  4259. if (self.alternative) {
  4260. var alt = self.alternative;
  4261. self.alternative = null;
  4262. return make_node(AST_BlockStatement, self, {
  4263. body: [ self, alt ]
  4264. }).optimize(compressor);
  4265. }
  4266. }
  4267. if (aborts(self.alternative)) {
  4268. var body = self.body;
  4269. self.body = self.alternative;
  4270. self.condition = negated_is_best ? negated : self.condition.negate(compressor);
  4271. self.alternative = null;
  4272. return make_node(AST_BlockStatement, self, {
  4273. body: [ self, body ]
  4274. }).optimize(compressor);
  4275. }
  4276. return self;
  4277. });
  4278. OPT(AST_Switch, function(self, compressor) {
  4279. if (!compressor.option("switches")) return self;
  4280. var branch;
  4281. var value = self.expression.evaluate(compressor);
  4282. if (!(value instanceof AST_Node)) {
  4283. var orig = self.expression;
  4284. self.expression = make_node_from_constant(value, orig);
  4285. self.expression = best_of_expression(self.expression.transform(compressor), orig);
  4286. }
  4287. if (!compressor.option("dead_code")) return self;
  4288. if (value instanceof AST_Node) {
  4289. value = self.expression.tail_node().evaluate(compressor);
  4290. }
  4291. var decl = [];
  4292. var body = [];
  4293. var default_branch;
  4294. var exact_match;
  4295. for (var i = 0, len = self.body.length; i < len && !exact_match; i++) {
  4296. branch = self.body[i];
  4297. if (branch instanceof AST_Default) {
  4298. if (!default_branch) {
  4299. default_branch = branch;
  4300. } else {
  4301. eliminate_branch(branch, body[body.length - 1]);
  4302. }
  4303. } else if (!(value instanceof AST_Node)) {
  4304. var exp = branch.expression.evaluate(compressor);
  4305. if (!(exp instanceof AST_Node) && exp !== value) {
  4306. eliminate_branch(branch, body[body.length - 1]);
  4307. continue;
  4308. }
  4309. if (exp instanceof AST_Node) exp = branch.expression.tail_node().evaluate(compressor);
  4310. if (exp === value) {
  4311. exact_match = branch;
  4312. if (default_branch) {
  4313. var default_index = body.indexOf(default_branch);
  4314. body.splice(default_index, 1);
  4315. eliminate_branch(default_branch, body[default_index - 1]);
  4316. default_branch = null;
  4317. }
  4318. }
  4319. }
  4320. if (aborts(branch)) {
  4321. var prev = body[body.length - 1];
  4322. if (aborts(prev) && prev.body.length == branch.body.length
  4323. && make_node(AST_BlockStatement, prev, prev).equivalent_to(make_node(AST_BlockStatement, branch, branch))) {
  4324. prev.body = [];
  4325. }
  4326. }
  4327. body.push(branch);
  4328. }
  4329. while (i < len) eliminate_branch(self.body[i++], body[body.length - 1]);
  4330. if (body.length > 0) {
  4331. body[0].body = decl.concat(body[0].body);
  4332. }
  4333. self.body = body;
  4334. while (branch = body[body.length - 1]) {
  4335. var stat = branch.body[branch.body.length - 1];
  4336. if (stat instanceof AST_Break && compressor.loopcontrol_target(stat) === self)
  4337. branch.body.pop();
  4338. if (branch.body.length || branch instanceof AST_Case
  4339. && (default_branch || branch.expression.has_side_effects(compressor))) break;
  4340. if (body.pop() === default_branch) default_branch = null;
  4341. }
  4342. if (body.length == 0) {
  4343. return make_node(AST_BlockStatement, self, {
  4344. body: decl.concat(make_node(AST_SimpleStatement, self.expression, {
  4345. body: self.expression
  4346. }))
  4347. }).optimize(compressor);
  4348. }
  4349. if (body.length == 1 && (body[0] === exact_match || body[0] === default_branch)) {
  4350. var has_break = false;
  4351. var tw = new TreeWalker(function(node) {
  4352. if (has_break
  4353. || node instanceof AST_Lambda
  4354. || node instanceof AST_SimpleStatement) return true;
  4355. if (node instanceof AST_Break && tw.loopcontrol_target(node) === self)
  4356. has_break = true;
  4357. });
  4358. self.walk(tw);
  4359. if (!has_break) {
  4360. var statements = body[0].body.slice();
  4361. var exp = body[0].expression;
  4362. if (exp) statements.unshift(make_node(AST_SimpleStatement, exp, {
  4363. body: exp
  4364. }));
  4365. statements.unshift(make_node(AST_SimpleStatement, self.expression, {
  4366. body:self.expression
  4367. }));
  4368. return make_node(AST_BlockStatement, self, {
  4369. body: statements
  4370. }).optimize(compressor);
  4371. }
  4372. }
  4373. return self;
  4374. function eliminate_branch(branch, prev) {
  4375. if (prev && !aborts(prev)) {
  4376. prev.body = prev.body.concat(branch.body);
  4377. } else {
  4378. extract_declarations_from_unreachable_code(compressor, branch, decl);
  4379. }
  4380. }
  4381. });
  4382. OPT(AST_Try, function(self, compressor) {
  4383. tighten_body(self.body, compressor);
  4384. if (self.bcatch && self.bfinally && all(self.bfinally.body, is_empty)) self.bfinally = null;
  4385. if (compressor.option("dead_code") && all(self.body, is_empty)) {
  4386. var body = [];
  4387. if (self.bcatch) {
  4388. extract_declarations_from_unreachable_code(compressor, self.bcatch, body);
  4389. body.forEach(function(stat) {
  4390. if (!(stat instanceof AST_Definitions)) return;
  4391. stat.definitions.forEach(function(var_def) {
  4392. var def = var_def.name.definition().redefined();
  4393. if (!def) return;
  4394. var_def.name = var_def.name.clone();
  4395. var_def.name.thedef = def;
  4396. });
  4397. });
  4398. }
  4399. if (self.bfinally) body = body.concat(self.bfinally.body);
  4400. return make_node(AST_BlockStatement, self, {
  4401. body: body
  4402. }).optimize(compressor);
  4403. }
  4404. return self;
  4405. });
  4406. AST_Definitions.DEFMETHOD("remove_initializers", function() {
  4407. this.definitions.forEach(function(def) {
  4408. def.value = null;
  4409. });
  4410. });
  4411. AST_Definitions.DEFMETHOD("to_assignments", function(compressor) {
  4412. var reduce_vars = compressor.option("reduce_vars");
  4413. var assignments = this.definitions.reduce(function(a, def) {
  4414. if (def.value) {
  4415. var name = make_node(AST_SymbolRef, def.name, def.name);
  4416. a.push(make_node(AST_Assign, def, {
  4417. operator : "=",
  4418. left : name,
  4419. right : def.value
  4420. }));
  4421. if (reduce_vars) name.definition().fixed = false;
  4422. }
  4423. def = def.name.definition();
  4424. def.eliminated++;
  4425. def.replaced--;
  4426. return a;
  4427. }, []);
  4428. if (assignments.length == 0) return null;
  4429. return make_sequence(this, assignments);
  4430. });
  4431. OPT(AST_Definitions, function(self, compressor) {
  4432. if (self.definitions.length == 0)
  4433. return make_node(AST_EmptyStatement, self);
  4434. return self;
  4435. });
  4436. AST_Call.DEFMETHOD("lift_sequences", function(compressor) {
  4437. if (!compressor.option("sequences")) return this;
  4438. var exp = this.expression;
  4439. if (!(exp instanceof AST_Sequence)) return this;
  4440. var tail = exp.tail_node();
  4441. if (needs_unbinding(compressor, tail) && !(this instanceof AST_New)) return this;
  4442. var expressions = exp.expressions.slice(0, -1);
  4443. var node = this.clone();
  4444. node.expression = tail;
  4445. expressions.push(node);
  4446. return make_sequence(this, expressions).optimize(compressor);
  4447. });
  4448. OPT(AST_Call, function(self, compressor) {
  4449. var seq = self.lift_sequences(compressor);
  4450. if (seq !== self) {
  4451. return seq;
  4452. }
  4453. var exp = self.expression;
  4454. var fn = exp;
  4455. if (compressor.option("reduce_vars") && fn instanceof AST_SymbolRef) {
  4456. fn = fn.fixed_value();
  4457. }
  4458. var is_func = fn instanceof AST_Lambda;
  4459. if (compressor.option("unused")
  4460. && is_func
  4461. && !fn.uses_arguments
  4462. && !fn.pinned()) {
  4463. var pos = 0, last = 0;
  4464. for (var i = 0, len = self.args.length; i < len; i++) {
  4465. var trim = i >= fn.argnames.length;
  4466. if (trim || fn.argnames[i].__unused) {
  4467. var node = self.args[i].drop_side_effect_free(compressor);
  4468. if (node) {
  4469. self.args[pos++] = node;
  4470. } else if (!trim) {
  4471. self.args[pos++] = make_node(AST_Number, self.args[i], {
  4472. value: 0
  4473. });
  4474. continue;
  4475. }
  4476. } else {
  4477. self.args[pos++] = self.args[i];
  4478. }
  4479. last = pos;
  4480. }
  4481. self.args.length = last;
  4482. }
  4483. if (compressor.option("unsafe")) {
  4484. if (is_undeclared_ref(exp)) switch (exp.name) {
  4485. case "Array":
  4486. if (self.args.length != 1) {
  4487. return make_node(AST_Array, self, {
  4488. elements: self.args
  4489. }).optimize(compressor);
  4490. }
  4491. break;
  4492. case "Object":
  4493. if (self.args.length == 0) {
  4494. return make_node(AST_Object, self, {
  4495. properties: []
  4496. });
  4497. }
  4498. break;
  4499. case "String":
  4500. if (self.args.length == 0) return make_node(AST_String, self, {
  4501. value: ""
  4502. });
  4503. if (self.args.length <= 1) return make_node(AST_Binary, self, {
  4504. left: self.args[0],
  4505. operator: "+",
  4506. right: make_node(AST_String, self, { value: "" })
  4507. }).optimize(compressor);
  4508. break;
  4509. case "Number":
  4510. if (self.args.length == 0) return make_node(AST_Number, self, {
  4511. value: 0
  4512. });
  4513. if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
  4514. expression: self.args[0],
  4515. operator: "+"
  4516. }).optimize(compressor);
  4517. case "Boolean":
  4518. if (self.args.length == 0) return make_node(AST_False, self);
  4519. if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
  4520. expression: make_node(AST_UnaryPrefix, self, {
  4521. expression: self.args[0],
  4522. operator: "!"
  4523. }),
  4524. operator: "!"
  4525. }).optimize(compressor);
  4526. break;
  4527. case "RegExp":
  4528. var params = [];
  4529. if (all(self.args, function(arg) {
  4530. var value = arg.evaluate(compressor);
  4531. params.unshift(value);
  4532. return arg !== value;
  4533. })) {
  4534. try {
  4535. return best_of(compressor, self, make_node(AST_RegExp, self, {
  4536. value: RegExp.apply(RegExp, params),
  4537. }));
  4538. } catch (ex) {
  4539. compressor.warn("Error converting {expr} [{file}:{line},{col}]", {
  4540. expr: self.print_to_string(),
  4541. file: self.start.file,
  4542. line: self.start.line,
  4543. col: self.start.col
  4544. });
  4545. }
  4546. }
  4547. break;
  4548. } else if (exp instanceof AST_Dot) switch(exp.property) {
  4549. case "toString":
  4550. if (self.args.length == 0 && !exp.expression.may_throw_on_access(compressor)) {
  4551. return make_node(AST_Binary, self, {
  4552. left: make_node(AST_String, self, { value: "" }),
  4553. operator: "+",
  4554. right: exp.expression
  4555. }).optimize(compressor);
  4556. }
  4557. break;
  4558. case "join":
  4559. if (exp.expression instanceof AST_Array) EXIT: {
  4560. var separator;
  4561. if (self.args.length > 0) {
  4562. separator = self.args[0].evaluate(compressor);
  4563. if (separator === self.args[0]) break EXIT; // not a constant
  4564. }
  4565. var elements = [];
  4566. var consts = [];
  4567. exp.expression.elements.forEach(function(el) {
  4568. var value = el.evaluate(compressor);
  4569. if (value !== el) {
  4570. consts.push(value);
  4571. } else {
  4572. if (consts.length > 0) {
  4573. elements.push(make_node(AST_String, self, {
  4574. value: consts.join(separator)
  4575. }));
  4576. consts.length = 0;
  4577. }
  4578. elements.push(el);
  4579. }
  4580. });
  4581. if (consts.length > 0) {
  4582. elements.push(make_node(AST_String, self, {
  4583. value: consts.join(separator)
  4584. }));
  4585. }
  4586. if (elements.length == 0) return make_node(AST_String, self, { value: "" });
  4587. if (elements.length == 1) {
  4588. if (elements[0].is_string(compressor)) {
  4589. return elements[0];
  4590. }
  4591. return make_node(AST_Binary, elements[0], {
  4592. operator : "+",
  4593. left : make_node(AST_String, self, { value: "" }),
  4594. right : elements[0]
  4595. });
  4596. }
  4597. if (separator == "") {
  4598. var first;
  4599. if (elements[0].is_string(compressor)
  4600. || elements[1].is_string(compressor)) {
  4601. first = elements.shift();
  4602. } else {
  4603. first = make_node(AST_String, self, { value: "" });
  4604. }
  4605. return elements.reduce(function(prev, el) {
  4606. return make_node(AST_Binary, el, {
  4607. operator : "+",
  4608. left : prev,
  4609. right : el
  4610. });
  4611. }, first).optimize(compressor);
  4612. }
  4613. // need this awkward cloning to not affect original element
  4614. // best_of will decide which one to get through.
  4615. var node = self.clone();
  4616. node.expression = node.expression.clone();
  4617. node.expression.expression = node.expression.expression.clone();
  4618. node.expression.expression.elements = elements;
  4619. return best_of(compressor, self, node);
  4620. }
  4621. break;
  4622. case "charAt":
  4623. if (exp.expression.is_string(compressor)) {
  4624. var arg = self.args[0];
  4625. var index = arg ? arg.evaluate(compressor) : 0;
  4626. if (index !== arg) {
  4627. return make_node(AST_Sub, exp, {
  4628. expression: exp.expression,
  4629. property: make_node_from_constant(index | 0, arg || exp)
  4630. }).optimize(compressor);
  4631. }
  4632. }
  4633. break;
  4634. case "apply":
  4635. if (self.args.length == 2 && self.args[1] instanceof AST_Array) {
  4636. var args = self.args[1].elements.slice();
  4637. args.unshift(self.args[0]);
  4638. return make_node(AST_Call, self, {
  4639. expression: make_node(AST_Dot, exp, {
  4640. expression: exp.expression,
  4641. property: "call"
  4642. }),
  4643. args: args
  4644. }).optimize(compressor);
  4645. }
  4646. break;
  4647. case "call":
  4648. var func = exp.expression;
  4649. if (func instanceof AST_SymbolRef) {
  4650. func = func.fixed_value();
  4651. }
  4652. if (func instanceof AST_Lambda && !func.contains_this()) {
  4653. return (self.args.length ? make_sequence(this, [
  4654. self.args[0],
  4655. make_node(AST_Call, self, {
  4656. expression: exp.expression,
  4657. args: self.args.slice(1)
  4658. })
  4659. ]) : make_node(AST_Call, self, {
  4660. expression: exp.expression,
  4661. args: []
  4662. })).optimize(compressor);
  4663. }
  4664. break;
  4665. }
  4666. }
  4667. if (compressor.option("unsafe_Function")
  4668. && is_undeclared_ref(exp)
  4669. && exp.name == "Function") {
  4670. // new Function() => function(){}
  4671. if (self.args.length == 0) return make_node(AST_Function, self, {
  4672. argnames: [],
  4673. body: []
  4674. });
  4675. if (all(self.args, function(x) {
  4676. return x instanceof AST_String;
  4677. })) {
  4678. // quite a corner-case, but we can handle it:
  4679. // https://github.com/mishoo/UglifyJS2/issues/203
  4680. // if the code argument is a constant, then we can minify it.
  4681. try {
  4682. var code = "n(function(" + self.args.slice(0, -1).map(function(arg) {
  4683. return arg.value;
  4684. }).join(",") + "){" + self.args[self.args.length - 1].value + "})";
  4685. var ast = parse(code);
  4686. var mangle = { ie8: compressor.option("ie8") };
  4687. ast.figure_out_scope(mangle);
  4688. var comp = new Compressor(compressor.options);
  4689. ast = ast.transform(comp);
  4690. ast.figure_out_scope(mangle);
  4691. ast.compute_char_frequency(mangle);
  4692. ast.mangle_names(mangle);
  4693. var fun;
  4694. ast.walk(new TreeWalker(function(node) {
  4695. if (fun) return true;
  4696. if (node instanceof AST_Lambda) {
  4697. fun = node;
  4698. return true;
  4699. }
  4700. }));
  4701. var code = OutputStream();
  4702. AST_BlockStatement.prototype._codegen.call(fun, fun, code);
  4703. self.args = [
  4704. make_node(AST_String, self, {
  4705. value: fun.argnames.map(function(arg) {
  4706. return arg.print_to_string();
  4707. }).join(",")
  4708. }),
  4709. make_node(AST_String, self.args[self.args.length - 1], {
  4710. value: code.get().replace(/^\{|\}$/g, "")
  4711. })
  4712. ];
  4713. return self;
  4714. } catch (ex) {
  4715. if (ex instanceof JS_Parse_Error) {
  4716. compressor.warn("Error parsing code passed to new Function [{file}:{line},{col}]", self.args[self.args.length - 1].start);
  4717. compressor.warn(ex.toString());
  4718. } else {
  4719. throw ex;
  4720. }
  4721. }
  4722. }
  4723. }
  4724. var stat = is_func && fn.body[0];
  4725. var can_inline = compressor.option("inline") && !self.is_expr_pure(compressor);
  4726. if (can_inline && stat instanceof AST_Return) {
  4727. var value = stat.value;
  4728. if (!value || value.is_constant_expression()) {
  4729. if (value) {
  4730. value = value.clone(true);
  4731. } else {
  4732. value = make_node(AST_Undefined, self);
  4733. }
  4734. var args = self.args.concat(value);
  4735. return make_sequence(self, args).optimize(compressor);
  4736. }
  4737. }
  4738. if (is_func) {
  4739. var def, value, scope, in_loop, level = -1;
  4740. if (can_inline
  4741. && !fn.uses_arguments
  4742. && !fn.pinned()
  4743. && !(fn.name && fn instanceof AST_Function)
  4744. && (value = can_flatten_body(stat))
  4745. && (exp === fn
  4746. || compressor.option("unused")
  4747. && (def = exp.definition()).references.length == 1
  4748. && !recursive_ref(compressor, def)
  4749. && fn.is_constant_expression(exp.scope))
  4750. && !self.pure
  4751. && !fn.contains_this()
  4752. && can_inject_symbols()) {
  4753. fn._squeezed = true;
  4754. return make_sequence(self, flatten_fn()).optimize(compressor);
  4755. }
  4756. if (compressor.option("side_effects") && all(fn.body, is_empty)) {
  4757. var args = self.args.concat(make_node(AST_Undefined, self));
  4758. return make_sequence(self, args).optimize(compressor);
  4759. }
  4760. }
  4761. if (compressor.option("drop_console")) {
  4762. if (exp instanceof AST_PropAccess) {
  4763. var name = exp.expression;
  4764. while (name.expression) {
  4765. name = name.expression;
  4766. }
  4767. if (is_undeclared_ref(name) && name.name == "console") {
  4768. return make_node(AST_Undefined, self).optimize(compressor);
  4769. }
  4770. }
  4771. }
  4772. if (compressor.option("negate_iife")
  4773. && compressor.parent() instanceof AST_SimpleStatement
  4774. && is_iife_call(self)) {
  4775. return self.negate(compressor, true);
  4776. }
  4777. var ev = self.evaluate(compressor);
  4778. if (ev !== self) {
  4779. ev = make_node_from_constant(ev, self).optimize(compressor);
  4780. return best_of(compressor, ev, self);
  4781. }
  4782. return self;
  4783. function return_value(stat) {
  4784. if (!stat) return make_node(AST_Undefined, self);
  4785. if (stat instanceof AST_Return) {
  4786. if (!stat.value) return make_node(AST_Undefined, self);
  4787. return stat.value.clone(true);
  4788. }
  4789. if (stat instanceof AST_SimpleStatement) {
  4790. return make_node(AST_UnaryPrefix, stat, {
  4791. operator: "void",
  4792. expression: stat.body.clone(true)
  4793. });
  4794. }
  4795. }
  4796. function can_flatten_body(stat) {
  4797. var len = fn.body.length;
  4798. if (compressor.option("inline") < 3) {
  4799. return len == 1 && return_value(stat);
  4800. }
  4801. stat = null;
  4802. for (var i = 0; i < len; i++) {
  4803. var line = fn.body[i];
  4804. if (line instanceof AST_Var) {
  4805. if (stat && !all(line.definitions, function(var_def) {
  4806. return !var_def.value;
  4807. })) {
  4808. return false;
  4809. }
  4810. } else if (line instanceof AST_EmptyStatement) {
  4811. continue;
  4812. } else if (stat) {
  4813. return false;
  4814. } else {
  4815. stat = line;
  4816. }
  4817. }
  4818. return return_value(stat);
  4819. }
  4820. function can_inject_args(catches, safe_to_inject) {
  4821. for (var i = 0, len = fn.argnames.length; i < len; i++) {
  4822. var arg = fn.argnames[i];
  4823. if (arg.__unused) continue;
  4824. if (!safe_to_inject
  4825. || catches[arg.name]
  4826. || identifier_atom[arg.name]
  4827. || scope.var_names()[arg.name]) {
  4828. return false;
  4829. }
  4830. if (in_loop) in_loop.push(arg.definition());
  4831. }
  4832. return true;
  4833. }
  4834. function can_inject_vars(catches, safe_to_inject) {
  4835. var len = fn.body.length;
  4836. for (var i = 0; i < len; i++) {
  4837. var stat = fn.body[i];
  4838. if (!(stat instanceof AST_Var)) continue;
  4839. if (!safe_to_inject) return false;
  4840. for (var j = stat.definitions.length; --j >= 0;) {
  4841. var name = stat.definitions[j].name;
  4842. if (catches[name.name]
  4843. || identifier_atom[name.name]
  4844. || scope.var_names()[name.name]) {
  4845. return false;
  4846. }
  4847. if (in_loop) in_loop.push(name.definition());
  4848. }
  4849. }
  4850. return true;
  4851. }
  4852. function can_inject_symbols() {
  4853. var catches = Object.create(null);
  4854. do {
  4855. scope = compressor.parent(++level);
  4856. if (scope instanceof AST_Catch) {
  4857. catches[scope.argname.name] = true;
  4858. } else if (scope instanceof AST_IterationStatement) {
  4859. in_loop = [];
  4860. } else if (scope instanceof AST_SymbolRef) {
  4861. if (scope.fixed_value() instanceof AST_Scope) return false;
  4862. }
  4863. } while (!(scope instanceof AST_Scope));
  4864. var safe_to_inject = !(scope instanceof AST_Toplevel) || compressor.toplevel.vars;
  4865. var inline = compressor.option("inline");
  4866. if (!can_inject_vars(catches, inline >= 3 && safe_to_inject)) return false;
  4867. if (!can_inject_args(catches, inline >= 2 && safe_to_inject)) return false;
  4868. return !in_loop || in_loop.length == 0 || !is_reachable(fn, in_loop);
  4869. }
  4870. function append_var(decls, expressions, name, value) {
  4871. var def = name.definition();
  4872. scope.variables.set(name.name, def);
  4873. scope.enclosed.push(def);
  4874. if (!scope.var_names()[name.name]) {
  4875. scope.var_names()[name.name] = true;
  4876. decls.push(make_node(AST_VarDef, name, {
  4877. name: name,
  4878. value: null
  4879. }));
  4880. }
  4881. var sym = make_node(AST_SymbolRef, name, name);
  4882. def.references.push(sym);
  4883. if (value) expressions.push(make_node(AST_Assign, self, {
  4884. operator: "=",
  4885. left: sym,
  4886. right: value
  4887. }));
  4888. }
  4889. function flatten_args(decls, expressions) {
  4890. var len = fn.argnames.length;
  4891. for (var i = self.args.length; --i >= len;) {
  4892. expressions.push(self.args[i]);
  4893. }
  4894. for (i = len; --i >= 0;) {
  4895. var name = fn.argnames[i];
  4896. var value = self.args[i];
  4897. if (name.__unused || scope.var_names()[name.name]) {
  4898. if (value) expressions.push(value);
  4899. } else {
  4900. var symbol = make_node(AST_SymbolVar, name, name);
  4901. name.definition().orig.push(symbol);
  4902. if (!value && in_loop) value = make_node(AST_Undefined, self);
  4903. append_var(decls, expressions, symbol, value);
  4904. }
  4905. }
  4906. decls.reverse();
  4907. expressions.reverse();
  4908. }
  4909. function flatten_vars(decls, expressions) {
  4910. var pos = expressions.length;
  4911. for (var i = 0, lines = fn.body.length; i < lines; i++) {
  4912. var stat = fn.body[i];
  4913. if (!(stat instanceof AST_Var)) continue;
  4914. for (var j = 0, defs = stat.definitions.length; j < defs; j++) {
  4915. var var_def = stat.definitions[j];
  4916. var name = var_def.name;
  4917. var redef = name.definition().redefined();
  4918. if (redef) {
  4919. name = name.clone();
  4920. name.thedef = redef;
  4921. }
  4922. append_var(decls, expressions, name, var_def.value);
  4923. if (in_loop && all(fn.argnames, function(argname) {
  4924. return argname.name != name.name;
  4925. })) {
  4926. var def = fn.variables.get(name.name);
  4927. var sym = make_node(AST_SymbolRef, name, name);
  4928. def.references.push(sym);
  4929. expressions.splice(pos++, 0, make_node(AST_Assign, var_def, {
  4930. operator: "=",
  4931. left: sym,
  4932. right: make_node(AST_Undefined, name)
  4933. }));
  4934. }
  4935. }
  4936. }
  4937. }
  4938. function flatten_fn() {
  4939. var decls = [];
  4940. var expressions = [];
  4941. flatten_args(decls, expressions);
  4942. flatten_vars(decls, expressions);
  4943. expressions.push(value);
  4944. if (decls.length) {
  4945. i = scope.body.indexOf(compressor.parent(level - 1)) + 1;
  4946. scope.body.splice(i, 0, make_node(AST_Var, fn, {
  4947. definitions: decls
  4948. }));
  4949. }
  4950. return expressions;
  4951. }
  4952. });
  4953. OPT(AST_New, function(self, compressor) {
  4954. var seq = self.lift_sequences(compressor);
  4955. if (seq !== self) {
  4956. return seq;
  4957. }
  4958. if (compressor.option("unsafe")) {
  4959. var exp = self.expression;
  4960. if (is_undeclared_ref(exp)) {
  4961. switch (exp.name) {
  4962. case "Object":
  4963. case "RegExp":
  4964. case "Function":
  4965. case "Error":
  4966. case "Array":
  4967. return make_node(AST_Call, self, self).transform(compressor);
  4968. }
  4969. }
  4970. }
  4971. return self;
  4972. });
  4973. OPT(AST_Sequence, function(self, compressor) {
  4974. if (!compressor.option("side_effects")) return self;
  4975. var expressions = [];
  4976. filter_for_side_effects();
  4977. var end = expressions.length - 1;
  4978. trim_right_for_undefined();
  4979. if (end == 0) {
  4980. self = maintain_this_binding(compressor, compressor.parent(), compressor.self(), expressions[0]);
  4981. if (!(self instanceof AST_Sequence)) self = self.optimize(compressor);
  4982. return self;
  4983. }
  4984. self.expressions = expressions;
  4985. return self;
  4986. function filter_for_side_effects() {
  4987. var first = first_in_statement(compressor);
  4988. var last = self.expressions.length - 1;
  4989. self.expressions.forEach(function(expr, index) {
  4990. if (index < last) expr = expr.drop_side_effect_free(compressor, first);
  4991. if (expr) {
  4992. merge_sequence(expressions, expr);
  4993. first = false;
  4994. }
  4995. });
  4996. }
  4997. function trim_right_for_undefined() {
  4998. while (end > 0 && is_undefined(expressions[end], compressor)) end--;
  4999. if (end < expressions.length - 1) {
  5000. expressions[end] = make_node(AST_UnaryPrefix, self, {
  5001. operator : "void",
  5002. expression : expressions[end]
  5003. });
  5004. expressions.length = end + 1;
  5005. }
  5006. }
  5007. });
  5008. AST_Unary.DEFMETHOD("lift_sequences", function(compressor) {
  5009. if (compressor.option("sequences") && this.expression instanceof AST_Sequence) {
  5010. var x = this.expression.expressions.slice();
  5011. var e = this.clone();
  5012. e.expression = x.pop();
  5013. x.push(e);
  5014. return make_sequence(this, x).optimize(compressor);
  5015. }
  5016. return this;
  5017. });
  5018. OPT(AST_UnaryPostfix, function(self, compressor) {
  5019. return self.lift_sequences(compressor);
  5020. });
  5021. OPT(AST_UnaryPrefix, function(self, compressor) {
  5022. var e = self.expression;
  5023. if (self.operator == "delete"
  5024. && !(e instanceof AST_SymbolRef
  5025. || e instanceof AST_PropAccess
  5026. || is_identifier_atom(e))) {
  5027. if (e instanceof AST_Sequence) {
  5028. e = e.expressions.slice();
  5029. e.push(make_node(AST_True, self));
  5030. return make_sequence(self, e).optimize(compressor);
  5031. }
  5032. return make_sequence(self, [ e, make_node(AST_True, self) ]).optimize(compressor);
  5033. }
  5034. var seq = self.lift_sequences(compressor);
  5035. if (seq !== self) {
  5036. return seq;
  5037. }
  5038. if (compressor.option("side_effects") && self.operator == "void") {
  5039. e = e.drop_side_effect_free(compressor);
  5040. if (e) {
  5041. self.expression = e;
  5042. return self;
  5043. } else {
  5044. return make_node(AST_Undefined, self).optimize(compressor);
  5045. }
  5046. }
  5047. if (compressor.option("booleans")) {
  5048. if (self.operator == "!" && e.is_truthy()) {
  5049. return make_sequence(self, [ e, make_node(AST_False, self) ]).optimize(compressor);
  5050. } else if (compressor.in_boolean_context()) switch (self.operator) {
  5051. case "!":
  5052. if (e instanceof AST_UnaryPrefix && e.operator == "!") {
  5053. // !!foo ==> foo, if we're in boolean context
  5054. return e.expression;
  5055. }
  5056. if (e instanceof AST_Binary) {
  5057. self = best_of(compressor, self, e.negate(compressor, first_in_statement(compressor)));
  5058. }
  5059. break;
  5060. case "typeof":
  5061. // typeof always returns a non-empty string, thus it's
  5062. // always true in booleans
  5063. compressor.warn("Boolean expression always true [{file}:{line},{col}]", self.start);
  5064. return (e instanceof AST_SymbolRef ? make_node(AST_True, self) : make_sequence(self, [
  5065. e,
  5066. make_node(AST_True, self)
  5067. ])).optimize(compressor);
  5068. }
  5069. }
  5070. if (self.operator == "-" && e instanceof AST_Infinity) {
  5071. e = e.transform(compressor);
  5072. }
  5073. if (e instanceof AST_Binary
  5074. && (self.operator == "+" || self.operator == "-")
  5075. && (e.operator == "*" || e.operator == "/" || e.operator == "%")) {
  5076. return make_node(AST_Binary, self, {
  5077. operator: e.operator,
  5078. left: make_node(AST_UnaryPrefix, e.left, {
  5079. operator: self.operator,
  5080. expression: e.left
  5081. }),
  5082. right: e.right
  5083. });
  5084. }
  5085. // avoids infinite recursion of numerals
  5086. if (self.operator != "-"
  5087. || !(e instanceof AST_Number || e instanceof AST_Infinity)) {
  5088. var ev = self.evaluate(compressor);
  5089. if (ev !== self) {
  5090. ev = make_node_from_constant(ev, self).optimize(compressor);
  5091. return best_of(compressor, ev, self);
  5092. }
  5093. }
  5094. return self;
  5095. });
  5096. AST_Binary.DEFMETHOD("lift_sequences", function(compressor) {
  5097. if (compressor.option("sequences")) {
  5098. if (this.left instanceof AST_Sequence) {
  5099. var x = this.left.expressions.slice();
  5100. var e = this.clone();
  5101. e.left = x.pop();
  5102. x.push(e);
  5103. return make_sequence(this, x).optimize(compressor);
  5104. }
  5105. if (this.right instanceof AST_Sequence && !this.left.has_side_effects(compressor)) {
  5106. var assign = this.operator == "=" && this.left instanceof AST_SymbolRef;
  5107. var x = this.right.expressions;
  5108. var last = x.length - 1;
  5109. for (var i = 0; i < last; i++) {
  5110. if (!assign && x[i].has_side_effects(compressor)) break;
  5111. }
  5112. if (i == last) {
  5113. x = x.slice();
  5114. var e = this.clone();
  5115. e.right = x.pop();
  5116. x.push(e);
  5117. return make_sequence(this, x).optimize(compressor);
  5118. } else if (i > 0) {
  5119. var e = this.clone();
  5120. e.right = make_sequence(this.right, x.slice(i));
  5121. x = x.slice(0, i);
  5122. x.push(e);
  5123. return make_sequence(this, x).optimize(compressor);
  5124. }
  5125. }
  5126. }
  5127. return this;
  5128. });
  5129. var commutativeOperators = makePredicate("== === != !== * & | ^");
  5130. function is_object(node) {
  5131. return node instanceof AST_Array
  5132. || node instanceof AST_Lambda
  5133. || node instanceof AST_Object;
  5134. }
  5135. OPT(AST_Binary, function(self, compressor) {
  5136. function reversible() {
  5137. return self.left.is_constant()
  5138. || self.right.is_constant()
  5139. || !self.left.has_side_effects(compressor)
  5140. && !self.right.has_side_effects(compressor);
  5141. }
  5142. function reverse(op) {
  5143. if (reversible()) {
  5144. if (op) self.operator = op;
  5145. var tmp = self.left;
  5146. self.left = self.right;
  5147. self.right = tmp;
  5148. }
  5149. }
  5150. if (commutativeOperators[self.operator]) {
  5151. if (self.right.is_constant()
  5152. && !self.left.is_constant()) {
  5153. // if right is a constant, whatever side effects the
  5154. // left side might have could not influence the
  5155. // result. hence, force switch.
  5156. if (!(self.left instanceof AST_Binary
  5157. && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) {
  5158. reverse();
  5159. }
  5160. }
  5161. }
  5162. self = self.lift_sequences(compressor);
  5163. if (compressor.option("comparisons")) switch (self.operator) {
  5164. case "===":
  5165. case "!==":
  5166. var is_strict_comparison = true;
  5167. if ((self.left.is_string(compressor) && self.right.is_string(compressor)) ||
  5168. (self.left.is_number(compressor) && self.right.is_number(compressor)) ||
  5169. (self.left.is_boolean(compressor) && self.right.is_boolean(compressor)) ||
  5170. self.left.equivalent_to(self.right)) {
  5171. self.operator = self.operator.substr(0, 2);
  5172. }
  5173. // XXX: intentionally falling down to the next case
  5174. case "==":
  5175. case "!=":
  5176. // void 0 == x => null == x
  5177. if (!is_strict_comparison && is_undefined(self.left, compressor)) {
  5178. self.left = make_node(AST_Null, self.left);
  5179. }
  5180. // "undefined" == typeof x => undefined === x
  5181. else if (compressor.option("typeofs")
  5182. && self.left instanceof AST_String
  5183. && self.left.value == "undefined"
  5184. && self.right instanceof AST_UnaryPrefix
  5185. && self.right.operator == "typeof") {
  5186. var expr = self.right.expression;
  5187. if (expr instanceof AST_SymbolRef ? expr.is_declared(compressor)
  5188. : !(expr instanceof AST_PropAccess && compressor.option("ie8"))) {
  5189. self.right = expr;
  5190. self.left = make_node(AST_Undefined, self.left).optimize(compressor);
  5191. if (self.operator.length == 2) self.operator += "=";
  5192. }
  5193. }
  5194. // obj !== obj => false
  5195. else if (self.left instanceof AST_SymbolRef
  5196. && self.right instanceof AST_SymbolRef
  5197. && self.left.definition() === self.right.definition()
  5198. && is_object(self.left.fixed_value())) {
  5199. return make_node(self.operator[0] == "=" ? AST_True : AST_False, self);
  5200. }
  5201. break;
  5202. case "&&":
  5203. case "||":
  5204. var lhs = self.left;
  5205. if (lhs.operator == self.operator) {
  5206. lhs = lhs.right;
  5207. }
  5208. if (lhs instanceof AST_Binary
  5209. && lhs.operator == (self.operator == "&&" ? "!==" : "===")
  5210. && self.right instanceof AST_Binary
  5211. && lhs.operator == self.right.operator
  5212. && (is_undefined(lhs.left, compressor) && self.right.left instanceof AST_Null
  5213. || lhs.left instanceof AST_Null && is_undefined(self.right.left, compressor))
  5214. && !lhs.right.has_side_effects(compressor)
  5215. && lhs.right.equivalent_to(self.right.right)) {
  5216. var combined = make_node(AST_Binary, self, {
  5217. operator: lhs.operator.slice(0, -1),
  5218. left: make_node(AST_Null, self),
  5219. right: lhs.right
  5220. });
  5221. if (lhs !== self.left) {
  5222. combined = make_node(AST_Binary, self, {
  5223. operator: self.operator,
  5224. left: self.left.left,
  5225. right: combined
  5226. });
  5227. }
  5228. return combined;
  5229. }
  5230. break;
  5231. }
  5232. if (compressor.option("booleans") && self.operator == "+" && compressor.in_boolean_context()) {
  5233. var ll = self.left.evaluate(compressor);
  5234. var rr = self.right.evaluate(compressor);
  5235. if (ll && typeof ll == "string") {
  5236. compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start);
  5237. return make_sequence(self, [
  5238. self.right,
  5239. make_node(AST_True, self)
  5240. ]).optimize(compressor);
  5241. }
  5242. if (rr && typeof rr == "string") {
  5243. compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start);
  5244. return make_sequence(self, [
  5245. self.left,
  5246. make_node(AST_True, self)
  5247. ]).optimize(compressor);
  5248. }
  5249. }
  5250. if (compressor.option("comparisons") && self.is_boolean(compressor)) {
  5251. if (!(compressor.parent() instanceof AST_Binary)
  5252. || compressor.parent() instanceof AST_Assign) {
  5253. var negated = make_node(AST_UnaryPrefix, self, {
  5254. operator: "!",
  5255. expression: self.negate(compressor, first_in_statement(compressor))
  5256. });
  5257. self = best_of(compressor, self, negated);
  5258. }
  5259. switch (self.operator) {
  5260. case ">": reverse("<"); break;
  5261. case ">=": reverse("<="); break;
  5262. }
  5263. }
  5264. if (self.operator == "+") {
  5265. if (self.right instanceof AST_String
  5266. && self.right.getValue() == ""
  5267. && self.left.is_string(compressor)) {
  5268. return self.left;
  5269. }
  5270. if (self.left instanceof AST_String
  5271. && self.left.getValue() == ""
  5272. && self.right.is_string(compressor)) {
  5273. return self.right;
  5274. }
  5275. if (self.left instanceof AST_Binary
  5276. && self.left.operator == "+"
  5277. && self.left.left instanceof AST_String
  5278. && self.left.left.getValue() == ""
  5279. && self.right.is_string(compressor)) {
  5280. self.left = self.left.right;
  5281. return self.transform(compressor);
  5282. }
  5283. }
  5284. if (compressor.option("evaluate")) {
  5285. switch (self.operator) {
  5286. case "&&":
  5287. var ll = fuzzy_eval(self.left);
  5288. if (!ll) {
  5289. compressor.warn("Condition left of && always false [{file}:{line},{col}]", self.start);
  5290. return maintain_this_binding(compressor, compressor.parent(), compressor.self(), self.left).optimize(compressor);
  5291. } else if (!(ll instanceof AST_Node)) {
  5292. compressor.warn("Condition left of && always true [{file}:{line},{col}]", self.start);
  5293. return make_sequence(self, [ self.left, self.right ]).optimize(compressor);
  5294. }
  5295. var rr = self.right.evaluate(compressor);
  5296. if (!rr) {
  5297. if (compressor.option("booleans") && compressor.in_boolean_context()) {
  5298. compressor.warn("Boolean && always false [{file}:{line},{col}]", self.start);
  5299. return make_sequence(self, [
  5300. self.left,
  5301. make_node(AST_False, self)
  5302. ]).optimize(compressor);
  5303. } else self.falsy = true;
  5304. } else if (!(rr instanceof AST_Node)) {
  5305. var parent = compressor.parent();
  5306. if (parent.operator == "&&" && parent.left === compressor.self()
  5307. || compressor.option("booleans") && compressor.in_boolean_context()) {
  5308. compressor.warn("Dropping side-effect-free && [{file}:{line},{col}]", self.start);
  5309. return self.left.optimize(compressor);
  5310. }
  5311. }
  5312. // x || false && y ---> x ? y : false
  5313. if (self.left.operator == "||") {
  5314. var lr = self.left.right.evaluate(compressor);
  5315. if (!lr) return make_node(AST_Conditional, self, {
  5316. condition: self.left.left,
  5317. consequent: self.right,
  5318. alternative: self.left.right
  5319. }).optimize(compressor);
  5320. }
  5321. break;
  5322. case "||":
  5323. var ll = fuzzy_eval(self.left);
  5324. if (!ll) {
  5325. compressor.warn("Condition left of || always false [{file}:{line},{col}]", self.start);
  5326. return make_sequence(self, [ self.left, self.right ]).optimize(compressor);
  5327. } else if (!(ll instanceof AST_Node)) {
  5328. compressor.warn("Condition left of || always true [{file}:{line},{col}]", self.start);
  5329. return maintain_this_binding(compressor, compressor.parent(), compressor.self(), self.left).optimize(compressor);
  5330. }
  5331. var rr = self.right.evaluate(compressor);
  5332. if (!rr) {
  5333. var parent = compressor.parent();
  5334. if (parent.operator == "||" && parent.left === compressor.self()
  5335. || compressor.option("booleans") && compressor.in_boolean_context()) {
  5336. compressor.warn("Dropping side-effect-free || [{file}:{line},{col}]", self.start);
  5337. return self.left.optimize(compressor);
  5338. }
  5339. } else if (!(rr instanceof AST_Node)) {
  5340. if (compressor.option("booleans") && compressor.in_boolean_context()) {
  5341. compressor.warn("Boolean || always true [{file}:{line},{col}]", self.start);
  5342. return make_sequence(self, [
  5343. self.left,
  5344. make_node(AST_True, self)
  5345. ]).optimize(compressor);
  5346. } else self.truthy = true;
  5347. }
  5348. if (self.left.operator == "&&") {
  5349. var lr = self.left.right.evaluate(compressor);
  5350. if (lr && !(lr instanceof AST_Node)) return make_node(AST_Conditional, self, {
  5351. condition: self.left.left,
  5352. consequent: self.left.right,
  5353. alternative: self.right
  5354. }).optimize(compressor);
  5355. }
  5356. break;
  5357. }
  5358. var associative = true;
  5359. switch (self.operator) {
  5360. case "+":
  5361. // "foo" + ("bar" + x) => "foobar" + x
  5362. if (self.left instanceof AST_Constant
  5363. && self.right instanceof AST_Binary
  5364. && self.right.operator == "+"
  5365. && self.right.left instanceof AST_Constant
  5366. && self.right.is_string(compressor)) {
  5367. self = make_node(AST_Binary, self, {
  5368. operator: "+",
  5369. left: make_node(AST_String, self.left, {
  5370. value: "" + self.left.getValue() + self.right.left.getValue(),
  5371. start: self.left.start,
  5372. end: self.right.left.end
  5373. }),
  5374. right: self.right.right
  5375. });
  5376. }
  5377. // (x + "foo") + "bar" => x + "foobar"
  5378. if (self.right instanceof AST_Constant
  5379. && self.left instanceof AST_Binary
  5380. && self.left.operator == "+"
  5381. && self.left.right instanceof AST_Constant
  5382. && self.left.is_string(compressor)) {
  5383. self = make_node(AST_Binary, self, {
  5384. operator: "+",
  5385. left: self.left.left,
  5386. right: make_node(AST_String, self.right, {
  5387. value: "" + self.left.right.getValue() + self.right.getValue(),
  5388. start: self.left.right.start,
  5389. end: self.right.end
  5390. })
  5391. });
  5392. }
  5393. // (x + "foo") + ("bar" + y) => (x + "foobar") + y
  5394. if (self.left instanceof AST_Binary
  5395. && self.left.operator == "+"
  5396. && self.left.is_string(compressor)
  5397. && self.left.right instanceof AST_Constant
  5398. && self.right instanceof AST_Binary
  5399. && self.right.operator == "+"
  5400. && self.right.left instanceof AST_Constant
  5401. && self.right.is_string(compressor)) {
  5402. self = make_node(AST_Binary, self, {
  5403. operator: "+",
  5404. left: make_node(AST_Binary, self.left, {
  5405. operator: "+",
  5406. left: self.left.left,
  5407. right: make_node(AST_String, self.left.right, {
  5408. value: "" + self.left.right.getValue() + self.right.left.getValue(),
  5409. start: self.left.right.start,
  5410. end: self.right.left.end
  5411. })
  5412. }),
  5413. right: self.right.right
  5414. });
  5415. }
  5416. // a + -b => a - b
  5417. if (self.right instanceof AST_UnaryPrefix
  5418. && self.right.operator == "-"
  5419. && self.left.is_number(compressor)) {
  5420. self = make_node(AST_Binary, self, {
  5421. operator: "-",
  5422. left: self.left,
  5423. right: self.right.expression
  5424. });
  5425. break;
  5426. }
  5427. // -a + b => b - a
  5428. if (self.left instanceof AST_UnaryPrefix
  5429. && self.left.operator == "-"
  5430. && reversible()
  5431. && self.right.is_number(compressor)) {
  5432. self = make_node(AST_Binary, self, {
  5433. operator: "-",
  5434. left: self.right,
  5435. right: self.left.expression
  5436. });
  5437. break;
  5438. }
  5439. case "*":
  5440. associative = compressor.option("unsafe_math");
  5441. case "&":
  5442. case "|":
  5443. case "^":
  5444. // a + +b => +b + a
  5445. if (self.left.is_number(compressor)
  5446. && self.right.is_number(compressor)
  5447. && reversible()
  5448. && !(self.left instanceof AST_Binary
  5449. && self.left.operator != self.operator
  5450. && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) {
  5451. var reversed = make_node(AST_Binary, self, {
  5452. operator: self.operator,
  5453. left: self.right,
  5454. right: self.left
  5455. });
  5456. if (self.right instanceof AST_Constant
  5457. && !(self.left instanceof AST_Constant)) {
  5458. self = best_of(compressor, reversed, self);
  5459. } else {
  5460. self = best_of(compressor, self, reversed);
  5461. }
  5462. }
  5463. if (associative && self.is_number(compressor)) {
  5464. // a + (b + c) => (a + b) + c
  5465. if (self.right instanceof AST_Binary
  5466. && self.right.operator == self.operator) {
  5467. self = make_node(AST_Binary, self, {
  5468. operator: self.operator,
  5469. left: make_node(AST_Binary, self.left, {
  5470. operator: self.operator,
  5471. left: self.left,
  5472. right: self.right.left,
  5473. start: self.left.start,
  5474. end: self.right.left.end
  5475. }),
  5476. right: self.right.right
  5477. });
  5478. }
  5479. // (n + 2) + 3 => 5 + n
  5480. // (2 * n) * 3 => 6 + n
  5481. if (self.right instanceof AST_Constant
  5482. && self.left instanceof AST_Binary
  5483. && self.left.operator == self.operator) {
  5484. if (self.left.left instanceof AST_Constant) {
  5485. self = make_node(AST_Binary, self, {
  5486. operator: self.operator,
  5487. left: make_node(AST_Binary, self.left, {
  5488. operator: self.operator,
  5489. left: self.left.left,
  5490. right: self.right,
  5491. start: self.left.left.start,
  5492. end: self.right.end
  5493. }),
  5494. right: self.left.right
  5495. });
  5496. } else if (self.left.right instanceof AST_Constant) {
  5497. self = make_node(AST_Binary, self, {
  5498. operator: self.operator,
  5499. left: make_node(AST_Binary, self.left, {
  5500. operator: self.operator,
  5501. left: self.left.right,
  5502. right: self.right,
  5503. start: self.left.right.start,
  5504. end: self.right.end
  5505. }),
  5506. right: self.left.left
  5507. });
  5508. }
  5509. }
  5510. // (a | 1) | (2 | d) => (3 | a) | b
  5511. if (self.left instanceof AST_Binary
  5512. && self.left.operator == self.operator
  5513. && self.left.right instanceof AST_Constant
  5514. && self.right instanceof AST_Binary
  5515. && self.right.operator == self.operator
  5516. && self.right.left instanceof AST_Constant) {
  5517. self = make_node(AST_Binary, self, {
  5518. operator: self.operator,
  5519. left: make_node(AST_Binary, self.left, {
  5520. operator: self.operator,
  5521. left: make_node(AST_Binary, self.left.left, {
  5522. operator: self.operator,
  5523. left: self.left.right,
  5524. right: self.right.left,
  5525. start: self.left.right.start,
  5526. end: self.right.left.end
  5527. }),
  5528. right: self.left.left
  5529. }),
  5530. right: self.right.right
  5531. });
  5532. }
  5533. }
  5534. }
  5535. }
  5536. // x && (y && z) ==> x && y && z
  5537. // x || (y || z) ==> x || y || z
  5538. // x + ("y" + z) ==> x + "y" + z
  5539. // "x" + (y + "z")==> "x" + y + "z"
  5540. if (self.right instanceof AST_Binary
  5541. && self.right.operator == self.operator
  5542. && (lazy_op[self.operator]
  5543. || (self.operator == "+"
  5544. && (self.right.left.is_string(compressor)
  5545. || (self.left.is_string(compressor)
  5546. && self.right.right.is_string(compressor))))))
  5547. {
  5548. self.left = make_node(AST_Binary, self.left, {
  5549. operator : self.operator,
  5550. left : self.left,
  5551. right : self.right.left
  5552. });
  5553. self.right = self.right.right;
  5554. return self.transform(compressor);
  5555. }
  5556. var ev = self.evaluate(compressor);
  5557. if (ev !== self) {
  5558. ev = make_node_from_constant(ev, self).optimize(compressor);
  5559. return best_of(compressor, ev, self);
  5560. }
  5561. return self;
  5562. function fuzzy_eval(node) {
  5563. if (node.truthy) return true;
  5564. if (node.falsy) return false;
  5565. if (node.is_truthy()) return true;
  5566. return node.evaluate(compressor);
  5567. }
  5568. });
  5569. function recursive_ref(compressor, def) {
  5570. var node;
  5571. for (var i = 0; node = compressor.parent(i); i++) {
  5572. if (node instanceof AST_Lambda) {
  5573. var name = node.name;
  5574. if (name && name.definition() === def) break;
  5575. }
  5576. }
  5577. return node;
  5578. }
  5579. OPT(AST_SymbolRef, function(self, compressor) {
  5580. if (!compressor.option("ie8")
  5581. && is_undeclared_ref(self)
  5582. // testing against `self.scope.uses_with` is an optimization
  5583. && !(self.scope.uses_with && compressor.find_parent(AST_With))) {
  5584. switch (self.name) {
  5585. case "undefined":
  5586. return make_node(AST_Undefined, self).optimize(compressor);
  5587. case "NaN":
  5588. return make_node(AST_NaN, self).optimize(compressor);
  5589. case "Infinity":
  5590. return make_node(AST_Infinity, self).optimize(compressor);
  5591. }
  5592. }
  5593. var parent = compressor.parent();
  5594. if (compressor.option("reduce_vars") && is_lhs(self, parent) !== self) {
  5595. var def = self.definition();
  5596. var fixed = self.fixed_value();
  5597. var single_use = def.single_use && !(parent instanceof AST_Call && parent.is_expr_pure(compressor));
  5598. if (single_use && fixed instanceof AST_Lambda) {
  5599. if (def.scope !== self.scope
  5600. && (!compressor.option("reduce_funcs") || def.escaped == 1 || fixed.inlined)) {
  5601. single_use = false;
  5602. } else if (recursive_ref(compressor, def)) {
  5603. single_use = false;
  5604. } else if (def.scope !== self.scope || def.orig[0] instanceof AST_SymbolFunarg) {
  5605. single_use = fixed.is_constant_expression(self.scope);
  5606. if (single_use == "f") {
  5607. var scope = self.scope;
  5608. do if (scope instanceof AST_Defun || scope instanceof AST_Function) {
  5609. scope.inlined = true;
  5610. } while (scope = scope.parent_scope);
  5611. }
  5612. }
  5613. }
  5614. if (single_use && fixed) {
  5615. def.single_use = false;
  5616. fixed._squeezed = true;
  5617. if (fixed instanceof AST_Defun) {
  5618. fixed = make_node(AST_Function, fixed, fixed);
  5619. fixed.name = make_node(AST_SymbolLambda, fixed.name, fixed.name);
  5620. }
  5621. var value;
  5622. if (def.recursive_refs > 0) {
  5623. value = fixed.clone(true);
  5624. var defun_def = value.name.definition();
  5625. var lambda_def = value.variables.get(value.name.name);
  5626. var name = lambda_def && lambda_def.orig[0];
  5627. if (!(name instanceof AST_SymbolLambda)) {
  5628. name = make_node(AST_SymbolLambda, value.name, value.name);
  5629. name.scope = value;
  5630. value.name = name;
  5631. lambda_def = value.def_function(name);
  5632. }
  5633. value.walk(new TreeWalker(function(node) {
  5634. if (!(node instanceof AST_SymbolRef)) return;
  5635. var def = node.definition();
  5636. if (def === defun_def) {
  5637. node.thedef = lambda_def;
  5638. lambda_def.references.push(node);
  5639. } else {
  5640. def.single_use = false;
  5641. var fn = node.fixed_value();
  5642. if (!(fn instanceof AST_Lambda)) return;
  5643. if (!fn.name) return;
  5644. if (fixed.variables.get(fn.name.name) !== fn.name.definition()) return;
  5645. fn.name = fn.name.clone();
  5646. var value_def = value.variables.get(fn.name.name) || value.def_function(fn.name);
  5647. node.thedef = value_def;
  5648. value_def.references.push(node);
  5649. }
  5650. }));
  5651. } else {
  5652. value = fixed.optimize(compressor);
  5653. if (value === fixed) value = fixed.clone(true);
  5654. }
  5655. return value;
  5656. }
  5657. if (fixed && def.should_replace === undefined) {
  5658. var init;
  5659. if (fixed instanceof AST_This) {
  5660. if (!(def.orig[0] instanceof AST_SymbolFunarg) && all(def.references, function(ref) {
  5661. return def.scope === ref.scope;
  5662. })) {
  5663. init = fixed;
  5664. }
  5665. } else {
  5666. var ev = fixed.evaluate(compressor);
  5667. if (ev !== fixed && (compressor.option("unsafe_regexp") || !(ev instanceof RegExp))) {
  5668. init = make_node_from_constant(ev, fixed);
  5669. }
  5670. }
  5671. if (init) {
  5672. var value_length = init.optimize(compressor).print_to_string().length;
  5673. var fn;
  5674. if (has_symbol_ref(fixed)) {
  5675. fn = function() {
  5676. var result = init.optimize(compressor);
  5677. return result === init ? result.clone(true) : result;
  5678. };
  5679. } else {
  5680. value_length = Math.min(value_length, fixed.print_to_string().length);
  5681. fn = function() {
  5682. var result = best_of_expression(init.optimize(compressor), fixed);
  5683. return result === init || result === fixed ? result.clone(true) : result;
  5684. };
  5685. }
  5686. var name_length = def.name.length;
  5687. var overhead = 0;
  5688. if (compressor.option("unused") && !compressor.exposed(def)) {
  5689. overhead = (name_length + 2 + value_length) / (def.references.length - def.assignments);
  5690. }
  5691. def.should_replace = value_length <= name_length + overhead ? fn : false;
  5692. } else {
  5693. def.should_replace = false;
  5694. }
  5695. }
  5696. if (def.should_replace) {
  5697. return def.should_replace();
  5698. }
  5699. }
  5700. return self;
  5701. function has_symbol_ref(value) {
  5702. var found;
  5703. value.walk(new TreeWalker(function(node) {
  5704. if (node instanceof AST_SymbolRef) found = true;
  5705. if (found) return true;
  5706. }));
  5707. return found;
  5708. }
  5709. });
  5710. function is_atomic(lhs, self) {
  5711. return lhs instanceof AST_SymbolRef || lhs.TYPE === self.TYPE;
  5712. }
  5713. OPT(AST_Undefined, function(self, compressor) {
  5714. if (compressor.option("unsafe_undefined")) {
  5715. var undef = find_variable(compressor, "undefined");
  5716. if (undef) {
  5717. var ref = make_node(AST_SymbolRef, self, {
  5718. name : "undefined",
  5719. scope : undef.scope,
  5720. thedef : undef
  5721. });
  5722. ref.is_undefined = true;
  5723. return ref;
  5724. }
  5725. }
  5726. var lhs = is_lhs(compressor.self(), compressor.parent());
  5727. if (lhs && is_atomic(lhs, self)) return self;
  5728. return make_node(AST_UnaryPrefix, self, {
  5729. operator: "void",
  5730. expression: make_node(AST_Number, self, {
  5731. value: 0
  5732. })
  5733. });
  5734. });
  5735. OPT(AST_Infinity, function(self, compressor) {
  5736. var lhs = is_lhs(compressor.self(), compressor.parent());
  5737. if (lhs && is_atomic(lhs, self)) return self;
  5738. if (compressor.option("keep_infinity")
  5739. && !(lhs && !is_atomic(lhs, self))
  5740. && !find_variable(compressor, "Infinity"))
  5741. return self;
  5742. return make_node(AST_Binary, self, {
  5743. operator: "/",
  5744. left: make_node(AST_Number, self, {
  5745. value: 1
  5746. }),
  5747. right: make_node(AST_Number, self, {
  5748. value: 0
  5749. })
  5750. });
  5751. });
  5752. OPT(AST_NaN, function(self, compressor) {
  5753. var lhs = is_lhs(compressor.self(), compressor.parent());
  5754. if (lhs && !is_atomic(lhs, self)
  5755. || find_variable(compressor, "NaN")) {
  5756. return make_node(AST_Binary, self, {
  5757. operator: "/",
  5758. left: make_node(AST_Number, self, {
  5759. value: 0
  5760. }),
  5761. right: make_node(AST_Number, self, {
  5762. value: 0
  5763. })
  5764. });
  5765. }
  5766. return self;
  5767. });
  5768. function is_reachable(self, defs) {
  5769. var reachable = false;
  5770. var find_ref = new TreeWalker(function(node) {
  5771. if (reachable) return true;
  5772. if (node instanceof AST_SymbolRef && member(node.definition(), defs)) {
  5773. return reachable = true;
  5774. }
  5775. });
  5776. var scan_scope = new TreeWalker(function(node) {
  5777. if (reachable) return true;
  5778. if (node instanceof AST_Scope && node !== self) {
  5779. var parent = scan_scope.parent();
  5780. if (parent instanceof AST_Call && parent.expression === node) return;
  5781. node.walk(find_ref);
  5782. return true;
  5783. }
  5784. });
  5785. self.walk(scan_scope);
  5786. return reachable;
  5787. }
  5788. var ASSIGN_OPS = makePredicate("+ - / * % >> << >>> | ^ &");
  5789. var ASSIGN_OPS_COMMUTATIVE = makePredicate("* | ^ &");
  5790. OPT(AST_Assign, function(self, compressor) {
  5791. var def;
  5792. if (compressor.option("dead_code")
  5793. && self.left instanceof AST_SymbolRef
  5794. && (def = self.left.definition()).scope === compressor.find_parent(AST_Lambda)) {
  5795. var level = 0, node, parent = self;
  5796. do {
  5797. node = parent;
  5798. parent = compressor.parent(level++);
  5799. if (parent instanceof AST_Exit) {
  5800. if (in_try(level, parent)) break;
  5801. if (is_reachable(def.scope, [ def ])) break;
  5802. if (self.operator == "=") return self.right;
  5803. def.fixed = false;
  5804. return make_node(AST_Binary, self, {
  5805. operator: self.operator.slice(0, -1),
  5806. left: self.left,
  5807. right: self.right
  5808. }).optimize(compressor);
  5809. }
  5810. } while (parent instanceof AST_Binary && parent.right === node
  5811. || parent instanceof AST_Sequence && parent.tail_node() === node);
  5812. }
  5813. self = self.lift_sequences(compressor);
  5814. if (self.operator == "=" && self.left instanceof AST_SymbolRef && self.right instanceof AST_Binary) {
  5815. // x = expr1 OP expr2
  5816. if (self.right.left instanceof AST_SymbolRef
  5817. && self.right.left.name == self.left.name
  5818. && ASSIGN_OPS[self.right.operator]) {
  5819. // x = x - 2 ---> x -= 2
  5820. self.operator = self.right.operator + "=";
  5821. self.right = self.right.right;
  5822. }
  5823. else if (self.right.right instanceof AST_SymbolRef
  5824. && self.right.right.name == self.left.name
  5825. && ASSIGN_OPS_COMMUTATIVE[self.right.operator]
  5826. && !self.right.left.has_side_effects(compressor)) {
  5827. // x = 2 & x ---> x &= 2
  5828. self.operator = self.right.operator + "=";
  5829. self.right = self.right.left;
  5830. }
  5831. }
  5832. return self;
  5833. function in_try(level, node) {
  5834. var right = self.right;
  5835. self.right = make_node(AST_Null, right);
  5836. var may_throw = node.may_throw(compressor);
  5837. self.right = right;
  5838. var scope = self.left.definition().scope;
  5839. var parent;
  5840. while ((parent = compressor.parent(level++)) !== scope) {
  5841. if (parent instanceof AST_Try) {
  5842. if (parent.bfinally) return true;
  5843. if (may_throw && parent.bcatch) return true;
  5844. }
  5845. }
  5846. }
  5847. });
  5848. OPT(AST_Conditional, function(self, compressor) {
  5849. if (!compressor.option("conditionals")) return self;
  5850. // This looks like lift_sequences(), should probably be under "sequences"
  5851. if (self.condition instanceof AST_Sequence) {
  5852. var expressions = self.condition.expressions.slice();
  5853. self.condition = expressions.pop();
  5854. expressions.push(self);
  5855. return make_sequence(self, expressions);
  5856. }
  5857. var cond = self.condition.is_truthy() || self.condition.tail_node().evaluate(compressor);
  5858. if (!cond) {
  5859. compressor.warn("Condition always false [{file}:{line},{col}]", self.start);
  5860. return make_sequence(self, [ self.condition, self.alternative ]).optimize(compressor);
  5861. } else if (!(cond instanceof AST_Node)) {
  5862. compressor.warn("Condition always true [{file}:{line},{col}]", self.start);
  5863. return make_sequence(self, [ self.condition, self.consequent ]).optimize(compressor);
  5864. }
  5865. var negated = cond.negate(compressor, first_in_statement(compressor));
  5866. if (best_of(compressor, cond, negated) === negated) {
  5867. self = make_node(AST_Conditional, self, {
  5868. condition: negated,
  5869. consequent: self.alternative,
  5870. alternative: self.consequent
  5871. });
  5872. }
  5873. var condition = self.condition;
  5874. var consequent = self.consequent;
  5875. var alternative = self.alternative;
  5876. // x?x:y --> x||y
  5877. if (condition instanceof AST_SymbolRef
  5878. && consequent instanceof AST_SymbolRef
  5879. && condition.definition() === consequent.definition()) {
  5880. return make_node(AST_Binary, self, {
  5881. operator: "||",
  5882. left: condition,
  5883. right: alternative
  5884. });
  5885. }
  5886. // if (foo) exp = something; else exp = something_else;
  5887. // |
  5888. // v
  5889. // exp = foo ? something : something_else;
  5890. var seq_tail = consequent.tail_node();
  5891. if (seq_tail instanceof AST_Assign) {
  5892. var is_eq = seq_tail.operator == "=";
  5893. var alt_tail = is_eq ? alternative.tail_node() : alternative;
  5894. if ((is_eq || consequent === seq_tail)
  5895. && alt_tail instanceof AST_Assign
  5896. && seq_tail.operator == alt_tail.operator
  5897. && seq_tail.left.equivalent_to(alt_tail.left)
  5898. && (is_eq && !seq_tail.left.has_side_effects(compressor)
  5899. || !condition.has_side_effects(compressor)
  5900. && can_shift_lhs_of_tail(consequent)
  5901. && can_shift_lhs_of_tail(alternative))) {
  5902. return make_node(AST_Assign, self, {
  5903. operator: seq_tail.operator,
  5904. left: seq_tail.left,
  5905. right: make_node(AST_Conditional, self, {
  5906. condition: condition,
  5907. consequent: pop_lhs(consequent),
  5908. alternative: pop_lhs(alternative)
  5909. })
  5910. });
  5911. }
  5912. }
  5913. // x ? y(a) : y(b) --> y(x ? a : b)
  5914. var arg_index;
  5915. if (consequent instanceof AST_Call
  5916. && alternative.TYPE === consequent.TYPE
  5917. && consequent.args.length > 0
  5918. && consequent.args.length == alternative.args.length
  5919. && consequent.expression.equivalent_to(alternative.expression)
  5920. && !condition.has_side_effects(compressor)
  5921. && !consequent.expression.has_side_effects(compressor)
  5922. && typeof (arg_index = single_arg_diff()) == "number") {
  5923. var node = consequent.clone();
  5924. node.args[arg_index] = make_node(AST_Conditional, self, {
  5925. condition: condition,
  5926. consequent: consequent.args[arg_index],
  5927. alternative: alternative.args[arg_index]
  5928. });
  5929. return node;
  5930. }
  5931. // x?y?z:a:a --> x&&y?z:a
  5932. if (consequent instanceof AST_Conditional
  5933. && consequent.alternative.equivalent_to(alternative)) {
  5934. return make_node(AST_Conditional, self, {
  5935. condition: make_node(AST_Binary, self, {
  5936. left: condition,
  5937. operator: "&&",
  5938. right: consequent.condition
  5939. }),
  5940. consequent: consequent.consequent,
  5941. alternative: alternative
  5942. });
  5943. }
  5944. // x ? y : y --> x, y
  5945. if (consequent.equivalent_to(alternative)) {
  5946. return make_sequence(self, [
  5947. condition,
  5948. consequent
  5949. ]).optimize(compressor);
  5950. }
  5951. // x ? (y, w) : (z, w) --> x ? y : z, w
  5952. if ((consequent instanceof AST_Sequence || alternative instanceof AST_Sequence)
  5953. && consequent.tail_node().equivalent_to(alternative.tail_node())) {
  5954. return make_sequence(self, [
  5955. make_node(AST_Conditional, self, {
  5956. condition: condition,
  5957. consequent: pop_seq(consequent),
  5958. alternative: pop_seq(alternative)
  5959. }),
  5960. consequent.tail_node()
  5961. ]).optimize(compressor);
  5962. }
  5963. // x ? y || z : z --> x && y || z
  5964. if (consequent instanceof AST_Binary
  5965. && consequent.operator == "||"
  5966. && consequent.right.equivalent_to(alternative)) {
  5967. return make_node(AST_Binary, self, {
  5968. operator: "||",
  5969. left: make_node(AST_Binary, self, {
  5970. operator: "&&",
  5971. left: condition,
  5972. right: consequent.left
  5973. }),
  5974. right: alternative
  5975. }).optimize(compressor);
  5976. }
  5977. var in_bool = compressor.option("booleans") && compressor.in_boolean_context();
  5978. if (is_true(self.consequent)) {
  5979. if (is_false(self.alternative)) {
  5980. // c ? true : false ---> !!c
  5981. return booleanize(condition);
  5982. }
  5983. // c ? true : x ---> !!c || x
  5984. return make_node(AST_Binary, self, {
  5985. operator: "||",
  5986. left: booleanize(condition),
  5987. right: self.alternative
  5988. });
  5989. }
  5990. if (is_false(self.consequent)) {
  5991. if (is_true(self.alternative)) {
  5992. // c ? false : true ---> !c
  5993. return booleanize(condition.negate(compressor));
  5994. }
  5995. // c ? false : x ---> !c && x
  5996. return make_node(AST_Binary, self, {
  5997. operator: "&&",
  5998. left: booleanize(condition.negate(compressor)),
  5999. right: self.alternative
  6000. });
  6001. }
  6002. if (is_true(self.alternative)) {
  6003. // c ? x : true ---> !c || x
  6004. return make_node(AST_Binary, self, {
  6005. operator: "||",
  6006. left: booleanize(condition.negate(compressor)),
  6007. right: self.consequent
  6008. });
  6009. }
  6010. if (is_false(self.alternative)) {
  6011. // c ? x : false ---> !!c && x
  6012. return make_node(AST_Binary, self, {
  6013. operator: "&&",
  6014. left: booleanize(condition),
  6015. right: self.consequent
  6016. });
  6017. }
  6018. return self;
  6019. function booleanize(node) {
  6020. if (node.is_boolean(compressor)) return node;
  6021. // !!expression
  6022. return make_node(AST_UnaryPrefix, node, {
  6023. operator: "!",
  6024. expression: node.negate(compressor)
  6025. });
  6026. }
  6027. // AST_True or !0
  6028. function is_true(node) {
  6029. return node instanceof AST_True
  6030. || in_bool
  6031. && node instanceof AST_Constant
  6032. && node.getValue()
  6033. || (node instanceof AST_UnaryPrefix
  6034. && node.operator == "!"
  6035. && node.expression instanceof AST_Constant
  6036. && !node.expression.getValue());
  6037. }
  6038. // AST_False or !1
  6039. function is_false(node) {
  6040. return node instanceof AST_False
  6041. || in_bool
  6042. && node instanceof AST_Constant
  6043. && !node.getValue()
  6044. || (node instanceof AST_UnaryPrefix
  6045. && node.operator == "!"
  6046. && node.expression instanceof AST_Constant
  6047. && node.expression.getValue());
  6048. }
  6049. function single_arg_diff() {
  6050. var a = consequent.args;
  6051. var b = alternative.args;
  6052. for (var i = 0, len = a.length; i < len; i++) {
  6053. if (!a[i].equivalent_to(b[i])) {
  6054. for (var j = i + 1; j < len; j++) {
  6055. if (!a[j].equivalent_to(b[j])) return;
  6056. }
  6057. return i;
  6058. }
  6059. }
  6060. }
  6061. function can_shift_lhs_of_tail(node) {
  6062. if (node === node.tail_node()) return true;
  6063. var exprs = node.expressions;
  6064. for (var i = exprs.length - 1; --i >= 0;) {
  6065. var expr = exprs[i];
  6066. if (!(expr instanceof AST_Assign) && expr.has_side_effects(compressor)
  6067. || expr.operator != "="
  6068. || expr.left.has_side_effects(compressor)
  6069. || expr.right.has_side_effects(compressor)) return false;
  6070. }
  6071. return true;
  6072. }
  6073. function pop_lhs(node) {
  6074. if (!(node instanceof AST_Sequence)) return node.right;
  6075. var exprs = node.expressions.slice();
  6076. exprs.push(exprs.pop().right);
  6077. return make_sequence(node, exprs);
  6078. }
  6079. function pop_seq(node) {
  6080. if (!(node instanceof AST_Sequence)) return make_node(AST_Number, node, {
  6081. value: 0
  6082. });
  6083. return make_sequence(node, node.expressions.slice(0, -1));
  6084. }
  6085. });
  6086. OPT(AST_Boolean, function(self, compressor) {
  6087. if (!compressor.option("booleans")) return self;
  6088. if (compressor.in_boolean_context()) return make_node(AST_Number, self, {
  6089. value: +self.value
  6090. });
  6091. var p = compressor.parent();
  6092. if (p instanceof AST_Binary && (p.operator == "==" || p.operator == "!=")) {
  6093. compressor.warn("Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]", {
  6094. operator : p.operator,
  6095. value : self.value,
  6096. file : p.start.file,
  6097. line : p.start.line,
  6098. col : p.start.col,
  6099. });
  6100. return make_node(AST_Number, self, {
  6101. value: +self.value
  6102. });
  6103. }
  6104. return make_node(AST_UnaryPrefix, self, {
  6105. operator: "!",
  6106. expression: make_node(AST_Number, self, {
  6107. value: 1 - self.value
  6108. })
  6109. });
  6110. });
  6111. function safe_to_flatten(value, compressor) {
  6112. if (value instanceof AST_SymbolRef) {
  6113. value = value.fixed_value();
  6114. }
  6115. if (!value) return false;
  6116. return !(value instanceof AST_Lambda)
  6117. || compressor.parent() instanceof AST_New
  6118. || !value.contains_this();
  6119. }
  6120. OPT(AST_Sub, function(self, compressor) {
  6121. var expr = self.expression;
  6122. var prop = self.property;
  6123. if (compressor.option("properties")) {
  6124. var key = prop.evaluate(compressor);
  6125. if (key !== prop) {
  6126. if (typeof key == "string") {
  6127. if (key == "undefined") {
  6128. key = undefined;
  6129. } else {
  6130. var value = parseFloat(key);
  6131. if (value.toString() == key) {
  6132. key = value;
  6133. }
  6134. }
  6135. }
  6136. prop = self.property = best_of_expression(prop, make_node_from_constant(key, prop).transform(compressor));
  6137. var property = "" + key;
  6138. if (is_identifier_string(property)
  6139. && property.length <= prop.print_to_string().length + 1) {
  6140. return make_node(AST_Dot, self, {
  6141. expression: expr,
  6142. property: property
  6143. }).optimize(compressor);
  6144. }
  6145. }
  6146. }
  6147. var fn;
  6148. if (compressor.option("arguments")
  6149. && expr instanceof AST_SymbolRef
  6150. && expr.name == "arguments"
  6151. && expr.definition().orig.length == 1
  6152. && prop instanceof AST_Number
  6153. && (fn = expr.scope) === compressor.find_parent(AST_Lambda)) {
  6154. var index = prop.getValue();
  6155. var argname = fn.argnames[index];
  6156. if (argname && compressor.has_directive("use strict")) {
  6157. var def = argname.definition();
  6158. if (!compressor.option("reduce_vars")
  6159. || expr.definition().reassigned
  6160. || def.assignments
  6161. || def.orig.length > 1) {
  6162. argname = null;
  6163. }
  6164. } else if (!argname && !compressor.option("keep_fargs") && index < fn.argnames.length + 5) {
  6165. while (index >= fn.argnames.length) {
  6166. argname = make_node(AST_SymbolFunarg, fn, {
  6167. name: fn.make_var_name("argument_" + fn.argnames.length),
  6168. scope: fn
  6169. });
  6170. fn.argnames.push(argname);
  6171. fn.enclosed.push(fn.def_variable(argname));
  6172. }
  6173. }
  6174. if (argname && find_if(function(node) {
  6175. return node.name === argname.name;
  6176. }, fn.argnames) === argname) {
  6177. var sym = make_node(AST_SymbolRef, self, argname);
  6178. sym.reference({});
  6179. delete argname.__unused;
  6180. return sym;
  6181. }
  6182. }
  6183. if (is_lhs(self, compressor.parent())) return self;
  6184. if (key !== prop) {
  6185. var sub = self.flatten_object(property, compressor);
  6186. if (sub) {
  6187. expr = self.expression = sub.expression;
  6188. prop = self.property = sub.property;
  6189. }
  6190. }
  6191. if (compressor.option("properties") && compressor.option("side_effects")
  6192. && prop instanceof AST_Number && expr instanceof AST_Array) {
  6193. var index = prop.getValue();
  6194. var elements = expr.elements;
  6195. var retValue = elements[index];
  6196. if (safe_to_flatten(retValue, compressor)) {
  6197. var flatten = true;
  6198. var values = [];
  6199. for (var i = elements.length; --i > index;) {
  6200. var value = elements[i].drop_side_effect_free(compressor);
  6201. if (value) {
  6202. values.unshift(value);
  6203. if (flatten && value.has_side_effects(compressor)) flatten = false;
  6204. }
  6205. }
  6206. retValue = retValue instanceof AST_Hole ? make_node(AST_Undefined, retValue) : retValue;
  6207. if (!flatten) values.unshift(retValue);
  6208. while (--i >= 0) {
  6209. var value = elements[i].drop_side_effect_free(compressor);
  6210. if (value) values.unshift(value);
  6211. else index--;
  6212. }
  6213. if (flatten) {
  6214. values.push(retValue);
  6215. return make_sequence(self, values).optimize(compressor);
  6216. } else return make_node(AST_Sub, self, {
  6217. expression: make_node(AST_Array, expr, {
  6218. elements: values
  6219. }),
  6220. property: make_node(AST_Number, prop, {
  6221. value: index
  6222. })
  6223. });
  6224. }
  6225. }
  6226. var ev = self.evaluate(compressor);
  6227. if (ev !== self) {
  6228. ev = make_node_from_constant(ev, self).optimize(compressor);
  6229. return best_of(compressor, ev, self);
  6230. }
  6231. return self;
  6232. });
  6233. AST_Scope.DEFMETHOD("contains_this", function() {
  6234. var result;
  6235. var self = this;
  6236. self.walk(new TreeWalker(function(node) {
  6237. if (result) return true;
  6238. if (node instanceof AST_This) return result = true;
  6239. if (node !== self && node instanceof AST_Scope) return true;
  6240. }));
  6241. return result;
  6242. });
  6243. AST_PropAccess.DEFMETHOD("flatten_object", function(key, compressor) {
  6244. if (!compressor.option("properties")) return;
  6245. var expr = this.expression;
  6246. if (expr instanceof AST_Object) {
  6247. var props = expr.properties;
  6248. for (var i = props.length; --i >= 0;) {
  6249. var prop = props[i];
  6250. if ("" + prop.key == key) {
  6251. if (!all(props, function(prop) {
  6252. return prop instanceof AST_ObjectKeyVal;
  6253. })) break;
  6254. if (!safe_to_flatten(prop.value, compressor)) break;
  6255. return make_node(AST_Sub, this, {
  6256. expression: make_node(AST_Array, expr, {
  6257. elements: props.map(function(prop) {
  6258. return prop.value;
  6259. })
  6260. }),
  6261. property: make_node(AST_Number, this, {
  6262. value: i
  6263. })
  6264. });
  6265. }
  6266. }
  6267. }
  6268. });
  6269. OPT(AST_Dot, function(self, compressor) {
  6270. if (self.property == "arguments" || self.property == "caller") {
  6271. compressor.warn("Function.prototype.{prop} not supported [{file}:{line},{col}]", {
  6272. prop: self.property,
  6273. file: self.start.file,
  6274. line: self.start.line,
  6275. col: self.start.col
  6276. });
  6277. }
  6278. if (is_lhs(self, compressor.parent())) return self;
  6279. if (compressor.option("unsafe_proto")
  6280. && self.expression instanceof AST_Dot
  6281. && self.expression.property == "prototype") {
  6282. var exp = self.expression.expression;
  6283. if (is_undeclared_ref(exp)) switch (exp.name) {
  6284. case "Array":
  6285. self.expression = make_node(AST_Array, self.expression, {
  6286. elements: []
  6287. });
  6288. break;
  6289. case "Function":
  6290. self.expression = make_node(AST_Function, self.expression, {
  6291. argnames: [],
  6292. body: []
  6293. });
  6294. break;
  6295. case "Number":
  6296. self.expression = make_node(AST_Number, self.expression, {
  6297. value: 0
  6298. });
  6299. break;
  6300. case "Object":
  6301. self.expression = make_node(AST_Object, self.expression, {
  6302. properties: []
  6303. });
  6304. break;
  6305. case "RegExp":
  6306. self.expression = make_node(AST_RegExp, self.expression, {
  6307. value: /t/
  6308. });
  6309. break;
  6310. case "String":
  6311. self.expression = make_node(AST_String, self.expression, {
  6312. value: ""
  6313. });
  6314. break;
  6315. }
  6316. }
  6317. var sub = self.flatten_object(self.property, compressor);
  6318. if (sub) return sub.optimize(compressor);
  6319. var ev = self.evaluate(compressor);
  6320. if (ev !== self) {
  6321. ev = make_node_from_constant(ev, self).optimize(compressor);
  6322. return best_of(compressor, ev, self);
  6323. }
  6324. return self;
  6325. });
  6326. OPT(AST_Return, function(self, compressor) {
  6327. if (self.value && is_undefined(self.value, compressor)) {
  6328. self.value = null;
  6329. }
  6330. return self;
  6331. });
  6332. })(function(node, optimizer) {
  6333. node.DEFMETHOD("optimize", function(compressor) {
  6334. var self = this;
  6335. if (self._optimized) return self;
  6336. if (compressor.has_directive("use asm")) return self;
  6337. var opt = optimizer(self, compressor);
  6338. opt._optimized = true;
  6339. return opt;
  6340. });
  6341. });