A Twitch.tv viewer reward and games system.
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.

2358 lines
100 KiB

  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. sequences : !false_by_default,
  40. properties : !false_by_default,
  41. dead_code : !false_by_default,
  42. drop_debugger : !false_by_default,
  43. unsafe : false,
  44. unsafe_comps : false,
  45. conditionals : !false_by_default,
  46. comparisons : !false_by_default,
  47. evaluate : !false_by_default,
  48. booleans : !false_by_default,
  49. loops : !false_by_default,
  50. unused : !false_by_default,
  51. hoist_funs : !false_by_default,
  52. hoist_vars : false,
  53. if_return : !false_by_default,
  54. join_vars : !false_by_default,
  55. cascade : !false_by_default,
  56. side_effects : !false_by_default,
  57. pure_getters : false,
  58. pure_funcs : null,
  59. negate_iife : !false_by_default,
  60. screw_ie8 : false,
  61. drop_console : false,
  62. angular : false,
  63. warnings : true,
  64. global_defs : {}
  65. }, true);
  66. };
  67. Compressor.prototype = new TreeTransformer;
  68. merge(Compressor.prototype, {
  69. option: function(key) { return this.options[key] },
  70. warn: function() {
  71. if (this.options.warnings)
  72. AST_Node.warn.apply(AST_Node, arguments);
  73. },
  74. before: function(node, descend, in_list) {
  75. if (node._squeezed) return node;
  76. var was_scope = false;
  77. if (node instanceof AST_Scope) {
  78. node = node.hoist_declarations(this);
  79. was_scope = true;
  80. }
  81. descend(node, this);
  82. node = node.optimize(this);
  83. if (was_scope && node instanceof AST_Scope) {
  84. node.drop_unused(this);
  85. descend(node, this);
  86. }
  87. node._squeezed = true;
  88. return node;
  89. }
  90. });
  91. (function(){
  92. function OPT(node, optimizer) {
  93. node.DEFMETHOD("optimize", function(compressor){
  94. var self = this;
  95. if (self._optimized) return self;
  96. var opt = optimizer(self, compressor);
  97. opt._optimized = true;
  98. if (opt === self) return opt;
  99. return opt.transform(compressor);
  100. });
  101. };
  102. OPT(AST_Node, function(self, compressor){
  103. return self;
  104. });
  105. AST_Node.DEFMETHOD("equivalent_to", function(node){
  106. // XXX: this is a rather expensive way to test two node's equivalence:
  107. return this.print_to_string() == node.print_to_string();
  108. });
  109. function make_node(ctor, orig, props) {
  110. if (!props) props = {};
  111. if (orig) {
  112. if (!props.start) props.start = orig.start;
  113. if (!props.end) props.end = orig.end;
  114. }
  115. return new ctor(props);
  116. };
  117. function make_node_from_constant(compressor, val, orig) {
  118. // XXX: WIP.
  119. // if (val instanceof AST_Node) return val.transform(new TreeTransformer(null, function(node){
  120. // if (node instanceof AST_SymbolRef) {
  121. // var scope = compressor.find_parent(AST_Scope);
  122. // var def = scope.find_variable(node);
  123. // node.thedef = def;
  124. // return node;
  125. // }
  126. // })).transform(compressor);
  127. if (val instanceof AST_Node) return val.transform(compressor);
  128. switch (typeof val) {
  129. case "string":
  130. return make_node(AST_String, orig, {
  131. value: val
  132. }).optimize(compressor);
  133. case "number":
  134. return make_node(isNaN(val) ? AST_NaN : AST_Number, orig, {
  135. value: val
  136. }).optimize(compressor);
  137. case "boolean":
  138. return make_node(val ? AST_True : AST_False, orig).optimize(compressor);
  139. case "undefined":
  140. return make_node(AST_Undefined, orig).optimize(compressor);
  141. default:
  142. if (val === null) {
  143. return make_node(AST_Null, orig).optimize(compressor);
  144. }
  145. if (val instanceof RegExp) {
  146. return make_node(AST_RegExp, orig).optimize(compressor);
  147. }
  148. throw new Error(string_template("Can't handle constant of type: {type}", {
  149. type: typeof val
  150. }));
  151. }
  152. };
  153. function as_statement_array(thing) {
  154. if (thing === null) return [];
  155. if (thing instanceof AST_BlockStatement) return thing.body;
  156. if (thing instanceof AST_EmptyStatement) return [];
  157. if (thing instanceof AST_Statement) return [ thing ];
  158. throw new Error("Can't convert thing to statement array");
  159. };
  160. function is_empty(thing) {
  161. if (thing === null) return true;
  162. if (thing instanceof AST_EmptyStatement) return true;
  163. if (thing instanceof AST_BlockStatement) return thing.body.length == 0;
  164. return false;
  165. };
  166. function loop_body(x) {
  167. if (x instanceof AST_Switch) return x;
  168. if (x instanceof AST_For || x instanceof AST_ForIn || x instanceof AST_DWLoop) {
  169. return (x.body instanceof AST_BlockStatement ? x.body : x);
  170. }
  171. return x;
  172. };
  173. function tighten_body(statements, compressor) {
  174. var CHANGED;
  175. do {
  176. CHANGED = false;
  177. if (compressor.option("angular")) {
  178. statements = process_for_angular(statements);
  179. }
  180. statements = eliminate_spurious_blocks(statements);
  181. if (compressor.option("dead_code")) {
  182. statements = eliminate_dead_code(statements, compressor);
  183. }
  184. if (compressor.option("if_return")) {
  185. statements = handle_if_return(statements, compressor);
  186. }
  187. if (compressor.option("sequences")) {
  188. statements = sequencesize(statements, compressor);
  189. }
  190. if (compressor.option("join_vars")) {
  191. statements = join_consecutive_vars(statements, compressor);
  192. }
  193. } while (CHANGED);
  194. if (compressor.option("negate_iife")) {
  195. negate_iifes(statements, compressor);
  196. }
  197. return statements;
  198. function process_for_angular(statements) {
  199. function make_injector(func, name) {
  200. return make_node(AST_SimpleStatement, func, {
  201. body: make_node(AST_Assign, func, {
  202. operator: "=",
  203. left: make_node(AST_Dot, name, {
  204. expression: make_node(AST_SymbolRef, name, name),
  205. property: "$inject"
  206. }),
  207. right: make_node(AST_Array, func, {
  208. elements: func.argnames.map(function(sym){
  209. return make_node(AST_String, sym, { value: sym.name });
  210. })
  211. })
  212. })
  213. });
  214. }
  215. return statements.reduce(function(a, stat){
  216. a.push(stat);
  217. var token = stat.start;
  218. var comments = token.comments_before;
  219. if (comments && comments.length > 0) {
  220. var last = comments.pop();
  221. if (/@ngInject/.test(last.value)) {
  222. // case 1: defun
  223. if (stat instanceof AST_Defun) {
  224. a.push(make_injector(stat, stat.name));
  225. }
  226. else if (stat instanceof AST_Definitions) {
  227. stat.definitions.forEach(function(def){
  228. if (def.value && def.value instanceof AST_Lambda) {
  229. a.push(make_injector(def.value, def.name));
  230. }
  231. });
  232. }
  233. else {
  234. compressor.warn("Unknown statement marked with @ngInject [{file}:{line},{col}]", token);
  235. }
  236. }
  237. }
  238. return a;
  239. }, []);
  240. }
  241. function eliminate_spurious_blocks(statements) {
  242. var seen_dirs = [];
  243. return statements.reduce(function(a, stat){
  244. if (stat instanceof AST_BlockStatement) {
  245. CHANGED = true;
  246. a.push.apply(a, eliminate_spurious_blocks(stat.body));
  247. } else if (stat instanceof AST_EmptyStatement) {
  248. CHANGED = true;
  249. } else if (stat instanceof AST_Directive) {
  250. if (seen_dirs.indexOf(stat.value) < 0) {
  251. a.push(stat);
  252. seen_dirs.push(stat.value);
  253. } else {
  254. CHANGED = true;
  255. }
  256. } else {
  257. a.push(stat);
  258. }
  259. return a;
  260. }, []);
  261. };
  262. function handle_if_return(statements, compressor) {
  263. var self = compressor.self();
  264. var in_lambda = self instanceof AST_Lambda;
  265. var ret = [];
  266. loop: for (var i = statements.length; --i >= 0;) {
  267. var stat = statements[i];
  268. switch (true) {
  269. case (in_lambda && stat instanceof AST_Return && !stat.value && ret.length == 0):
  270. CHANGED = true;
  271. // note, ret.length is probably always zero
  272. // because we drop unreachable code before this
  273. // step. nevertheless, it's good to check.
  274. continue loop;
  275. case stat instanceof AST_If:
  276. if (stat.body instanceof AST_Return) {
  277. //---
  278. // pretty silly case, but:
  279. // if (foo()) return; return; ==> foo(); return;
  280. if (((in_lambda && ret.length == 0)
  281. || (ret[0] instanceof AST_Return && !ret[0].value))
  282. && !stat.body.value && !stat.alternative) {
  283. CHANGED = true;
  284. var cond = make_node(AST_SimpleStatement, stat.condition, {
  285. body: stat.condition
  286. });
  287. ret.unshift(cond);
  288. continue loop;
  289. }
  290. //---
  291. // if (foo()) return x; return y; ==> return foo() ? x : y;
  292. if (ret[0] instanceof AST_Return && stat.body.value && ret[0].value && !stat.alternative) {
  293. CHANGED = true;
  294. stat = stat.clone();
  295. stat.alternative = ret[0];
  296. ret[0] = stat.transform(compressor);
  297. continue loop;
  298. }
  299. //---
  300. // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined;
  301. if ((ret.length == 0 || ret[0] instanceof AST_Return) && stat.body.value && !stat.alternative && in_lambda) {
  302. CHANGED = true;
  303. stat = stat.clone();
  304. stat.alternative = ret[0] || make_node(AST_Return, stat, {
  305. value: make_node(AST_Undefined, stat)
  306. });
  307. ret[0] = stat.transform(compressor);
  308. continue loop;
  309. }
  310. //---
  311. // if (foo()) return; [ else x... ]; y... ==> if (!foo()) { x...; y... }
  312. if (!stat.body.value && in_lambda) {
  313. CHANGED = true;
  314. stat = stat.clone();
  315. stat.condition = stat.condition.negate(compressor);
  316. stat.body = make_node(AST_BlockStatement, stat, {
  317. body: as_statement_array(stat.alternative).concat(ret)
  318. });
  319. stat.alternative = null;
  320. ret = [ stat.transform(compressor) ];
  321. continue loop;
  322. }
  323. //---
  324. if (ret.length == 1 && in_lambda && ret[0] instanceof AST_SimpleStatement
  325. && (!stat.alternative || stat.alternative instanceof AST_SimpleStatement)) {
  326. CHANGED = true;
  327. ret.push(make_node(AST_Return, ret[0], {
  328. value: make_node(AST_Undefined, ret[0])
  329. }).transform(compressor));
  330. ret = as_statement_array(stat.alternative).concat(ret);
  331. ret.unshift(stat);
  332. continue loop;
  333. }
  334. }
  335. var ab = aborts(stat.body);
  336. var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null;
  337. if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda)
  338. || (ab instanceof AST_Continue && self === loop_body(lct))
  339. || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) {
  340. if (ab.label) {
  341. remove(ab.label.thedef.references, ab);
  342. }
  343. CHANGED = true;
  344. var body = as_statement_array(stat.body).slice(0, -1);
  345. stat = stat.clone();
  346. stat.condition = stat.condition.negate(compressor);
  347. stat.body = make_node(AST_BlockStatement, stat, {
  348. body: ret
  349. });
  350. stat.alternative = make_node(AST_BlockStatement, stat, {
  351. body: body
  352. });
  353. ret = [ stat.transform(compressor) ];
  354. continue loop;
  355. }
  356. var ab = aborts(stat.alternative);
  357. var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null;
  358. if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda)
  359. || (ab instanceof AST_Continue && self === loop_body(lct))
  360. || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) {
  361. if (ab.label) {
  362. remove(ab.label.thedef.references, ab);
  363. }
  364. CHANGED = true;
  365. stat = stat.clone();
  366. stat.body = make_node(AST_BlockStatement, stat.body, {
  367. body: as_statement_array(stat.body).concat(ret)
  368. });
  369. stat.alternative = make_node(AST_BlockStatement, stat.alternative, {
  370. body: as_statement_array(stat.alternative).slice(0, -1)
  371. });
  372. ret = [ stat.transform(compressor) ];
  373. continue loop;
  374. }
  375. ret.unshift(stat);
  376. break;
  377. default:
  378. ret.unshift(stat);
  379. break;
  380. }
  381. }
  382. return ret;
  383. };
  384. function eliminate_dead_code(statements, compressor) {
  385. var has_quit = false;
  386. var orig = statements.length;
  387. var self = compressor.self();
  388. statements = statements.reduce(function(a, stat){
  389. if (has_quit) {
  390. extract_declarations_from_unreachable_code(compressor, stat, a);
  391. } else {
  392. if (stat instanceof AST_LoopControl) {
  393. var lct = compressor.loopcontrol_target(stat.label);
  394. if ((stat instanceof AST_Break
  395. && lct instanceof AST_BlockStatement
  396. && loop_body(lct) === self) || (stat instanceof AST_Continue
  397. && loop_body(lct) === self)) {
  398. if (stat.label) {
  399. remove(stat.label.thedef.references, stat);
  400. }
  401. } else {
  402. a.push(stat);
  403. }
  404. } else {
  405. a.push(stat);
  406. }
  407. if (aborts(stat)) has_quit = true;
  408. }
  409. return a;
  410. }, []);
  411. CHANGED = statements.length != orig;
  412. return statements;
  413. };
  414. function sequencesize(statements, compressor) {
  415. if (statements.length < 2) return statements;
  416. var seq = [], ret = [];
  417. function push_seq() {
  418. seq = AST_Seq.from_array(seq);
  419. if (seq) ret.push(make_node(AST_SimpleStatement, seq, {
  420. body: seq
  421. }));
  422. seq = [];
  423. };
  424. statements.forEach(function(stat){
  425. if (stat instanceof AST_SimpleStatement) seq.push(stat.body);
  426. else push_seq(), ret.push(stat);
  427. });
  428. push_seq();
  429. ret = sequencesize_2(ret, compressor);
  430. CHANGED = ret.length != statements.length;
  431. return ret;
  432. };
  433. function sequencesize_2(statements, compressor) {
  434. function cons_seq(right) {
  435. ret.pop();
  436. var left = prev.body;
  437. if (left instanceof AST_Seq) {
  438. left.add(right);
  439. } else {
  440. left = AST_Seq.cons(left, right);
  441. }
  442. return left.transform(compressor);
  443. };
  444. var ret = [], prev = null;
  445. statements.forEach(function(stat){
  446. if (prev) {
  447. if (stat instanceof AST_For) {
  448. var opera = {};
  449. try {
  450. prev.body.walk(new TreeWalker(function(node){
  451. if (node instanceof AST_Binary && node.operator == "in")
  452. throw opera;
  453. }));
  454. if (stat.init && !(stat.init instanceof AST_Definitions)) {
  455. stat.init = cons_seq(stat.init);
  456. }
  457. else if (!stat.init) {
  458. stat.init = prev.body;
  459. ret.pop();
  460. }
  461. } catch(ex) {
  462. if (ex !== opera) throw ex;
  463. }
  464. }
  465. else if (stat instanceof AST_If) {
  466. stat.condition = cons_seq(stat.condition);
  467. }
  468. else if (stat instanceof AST_With) {
  469. stat.expression = cons_seq(stat.expression);
  470. }
  471. else if (stat instanceof AST_Exit && stat.value) {
  472. stat.value = cons_seq(stat.value);
  473. }
  474. else if (stat instanceof AST_Exit) {
  475. stat.value = cons_seq(make_node(AST_Undefined, stat));
  476. }
  477. else if (stat instanceof AST_Switch) {
  478. stat.expression = cons_seq(stat.expression);
  479. }
  480. }
  481. ret.push(stat);
  482. prev = stat instanceof AST_SimpleStatement ? stat : null;
  483. });
  484. return ret;
  485. };
  486. function join_consecutive_vars(statements, compressor) {
  487. var prev = null;
  488. return statements.reduce(function(a, stat){
  489. if (stat instanceof AST_Definitions && prev && prev.TYPE == stat.TYPE) {
  490. prev.definitions = prev.definitions.concat(stat.definitions);
  491. CHANGED = true;
  492. }
  493. else if (stat instanceof AST_For
  494. && prev instanceof AST_Definitions
  495. && (!stat.init || stat.init.TYPE == prev.TYPE)) {
  496. CHANGED = true;
  497. a.pop();
  498. if (stat.init) {
  499. stat.init.definitions = prev.definitions.concat(stat.init.definitions);
  500. } else {
  501. stat.init = prev;
  502. }
  503. a.push(stat);
  504. prev = stat;
  505. }
  506. else {
  507. prev = stat;
  508. a.push(stat);
  509. }
  510. return a;
  511. }, []);
  512. };
  513. function negate_iifes(statements, compressor) {
  514. statements.forEach(function(stat){
  515. if (stat instanceof AST_SimpleStatement) {
  516. stat.body = (function transform(thing) {
  517. return thing.transform(new TreeTransformer(function(node){
  518. if (node instanceof AST_Call && node.expression instanceof AST_Function) {
  519. return make_node(AST_UnaryPrefix, node, {
  520. operator: "!",
  521. expression: node
  522. });
  523. }
  524. else if (node instanceof AST_Call) {
  525. node.expression = transform(node.expression);
  526. }
  527. else if (node instanceof AST_Seq) {
  528. node.car = transform(node.car);
  529. }
  530. else if (node instanceof AST_Conditional) {
  531. var expr = transform(node.condition);
  532. if (expr !== node.condition) {
  533. // it has been negated, reverse
  534. node.condition = expr;
  535. var tmp = node.consequent;
  536. node.consequent = node.alternative;
  537. node.alternative = tmp;
  538. }
  539. }
  540. return node;
  541. }));
  542. })(stat.body);
  543. }
  544. });
  545. };
  546. };
  547. function extract_declarations_from_unreachable_code(compressor, stat, target) {
  548. compressor.warn("Dropping unreachable code [{file}:{line},{col}]", stat.start);
  549. stat.walk(new TreeWalker(function(node){
  550. if (node instanceof AST_Definitions) {
  551. compressor.warn("Declarations in unreachable code! [{file}:{line},{col}]", node.start);
  552. node.remove_initializers();
  553. target.push(node);
  554. return true;
  555. }
  556. if (node instanceof AST_Defun) {
  557. target.push(node);
  558. return true;
  559. }
  560. if (node instanceof AST_Scope) {
  561. return true;
  562. }
  563. }));
  564. };
  565. /* -----[ boolean/negation helpers ]----- */
  566. // methods to determine whether an expression has a boolean result type
  567. (function (def){
  568. var unary_bool = [ "!", "delete" ];
  569. var binary_bool = [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ];
  570. def(AST_Node, function(){ return false });
  571. def(AST_UnaryPrefix, function(){
  572. return member(this.operator, unary_bool);
  573. });
  574. def(AST_Binary, function(){
  575. return member(this.operator, binary_bool) ||
  576. ( (this.operator == "&&" || this.operator == "||") &&
  577. this.left.is_boolean() && this.right.is_boolean() );
  578. });
  579. def(AST_Conditional, function(){
  580. return this.consequent.is_boolean() && this.alternative.is_boolean();
  581. });
  582. def(AST_Assign, function(){
  583. return this.operator == "=" && this.right.is_boolean();
  584. });
  585. def(AST_Seq, function(){
  586. return this.cdr.is_boolean();
  587. });
  588. def(AST_True, function(){ return true });
  589. def(AST_False, function(){ return true });
  590. })(function(node, func){
  591. node.DEFMETHOD("is_boolean", func);
  592. });
  593. // methods to determine if an expression has a string result type
  594. (function (def){
  595. def(AST_Node, function(){ return false });
  596. def(AST_String, function(){ return true });
  597. def(AST_UnaryPrefix, function(){
  598. return this.operator == "typeof";
  599. });
  600. def(AST_Binary, function(compressor){
  601. return this.operator == "+" &&
  602. (this.left.is_string(compressor) || this.right.is_string(compressor));
  603. });
  604. def(AST_Assign, function(compressor){
  605. return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor);
  606. });
  607. def(AST_Seq, function(compressor){
  608. return this.cdr.is_string(compressor);
  609. });
  610. def(AST_Conditional, function(compressor){
  611. return this.consequent.is_string(compressor) && this.alternative.is_string(compressor);
  612. });
  613. def(AST_Call, function(compressor){
  614. return compressor.option("unsafe")
  615. && this.expression instanceof AST_SymbolRef
  616. && this.expression.name == "String"
  617. && this.expression.undeclared();
  618. });
  619. })(function(node, func){
  620. node.DEFMETHOD("is_string", func);
  621. });
  622. function best_of(ast1, ast2) {
  623. return ast1.print_to_string().length >
  624. ast2.print_to_string().length
  625. ? ast2 : ast1;
  626. };
  627. // methods to evaluate a constant expression
  628. (function (def){
  629. // The evaluate method returns an array with one or two
  630. // elements. If the node has been successfully reduced to a
  631. // constant, then the second element tells us the value;
  632. // otherwise the second element is missing. The first element
  633. // of the array is always an AST_Node descendant; if
  634. // evaluation was successful it's a node that represents the
  635. // constant; otherwise it's the original or a replacement node.
  636. AST_Node.DEFMETHOD("evaluate", function(compressor){
  637. if (!compressor.option("evaluate")) return [ this ];
  638. try {
  639. var val = this._eval(compressor);
  640. return [ best_of(make_node_from_constant(compressor, val, this), this), val ];
  641. } catch(ex) {
  642. if (ex !== def) throw ex;
  643. return [ this ];
  644. }
  645. });
  646. def(AST_Statement, function(){
  647. throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start));
  648. });
  649. def(AST_Function, function(){
  650. // XXX: AST_Function inherits from AST_Scope, which itself
  651. // inherits from AST_Statement; however, an AST_Function
  652. // isn't really a statement. This could byte in other
  653. // places too. :-( Wish JS had multiple inheritance.
  654. throw def;
  655. });
  656. function ev(node, compressor) {
  657. if (!compressor) throw new Error("Compressor must be passed");
  658. return node._eval(compressor);
  659. };
  660. def(AST_Node, function(){
  661. throw def; // not constant
  662. });
  663. def(AST_Constant, function(){
  664. return this.getValue();
  665. });
  666. def(AST_UnaryPrefix, function(compressor){
  667. var e = this.expression;
  668. switch (this.operator) {
  669. case "!": return !ev(e, compressor);
  670. case "typeof":
  671. // Function would be evaluated to an array and so typeof would
  672. // incorrectly return 'object'. Hence making is a special case.
  673. if (e instanceof AST_Function) return typeof function(){};
  674. e = ev(e, compressor);
  675. // typeof <RegExp> returns "object" or "function" on different platforms
  676. // so cannot evaluate reliably
  677. if (e instanceof RegExp) throw def;
  678. return typeof e;
  679. case "void": return void ev(e, compressor);
  680. case "~": return ~ev(e, compressor);
  681. case "-":
  682. e = ev(e, compressor);
  683. if (e === 0) throw def;
  684. return -e;
  685. case "+": return +ev(e, compressor);
  686. }
  687. throw def;
  688. });
  689. def(AST_Binary, function(c){
  690. var left = this.left, right = this.right;
  691. switch (this.operator) {
  692. case "&&" : return ev(left, c) && ev(right, c);
  693. case "||" : return ev(left, c) || ev(right, c);
  694. case "|" : return ev(left, c) | ev(right, c);
  695. case "&" : return ev(left, c) & ev(right, c);
  696. case "^" : return ev(left, c) ^ ev(right, c);
  697. case "+" : return ev(left, c) + ev(right, c);
  698. case "*" : return ev(left, c) * ev(right, c);
  699. case "/" : return ev(left, c) / ev(right, c);
  700. case "%" : return ev(left, c) % ev(right, c);
  701. case "-" : return ev(left, c) - ev(right, c);
  702. case "<<" : return ev(left, c) << ev(right, c);
  703. case ">>" : return ev(left, c) >> ev(right, c);
  704. case ">>>" : return ev(left, c) >>> ev(right, c);
  705. case "==" : return ev(left, c) == ev(right, c);
  706. case "===" : return ev(left, c) === ev(right, c);
  707. case "!=" : return ev(left, c) != ev(right, c);
  708. case "!==" : return ev(left, c) !== ev(right, c);
  709. case "<" : return ev(left, c) < ev(right, c);
  710. case "<=" : return ev(left, c) <= ev(right, c);
  711. case ">" : return ev(left, c) > ev(right, c);
  712. case ">=" : return ev(left, c) >= ev(right, c);
  713. case "in" : return ev(left, c) in ev(right, c);
  714. case "instanceof" : return ev(left, c) instanceof ev(right, c);
  715. }
  716. throw def;
  717. });
  718. def(AST_Conditional, function(compressor){
  719. return ev(this.condition, compressor)
  720. ? ev(this.consequent, compressor)
  721. : ev(this.alternative, compressor);
  722. });
  723. def(AST_SymbolRef, function(compressor){
  724. var d = this.definition();
  725. if (d && d.constant && d.init) return ev(d.init, compressor);
  726. throw def;
  727. });
  728. })(function(node, func){
  729. node.DEFMETHOD("_eval", func);
  730. });
  731. // method to negate an expression
  732. (function(def){
  733. function basic_negation(exp) {
  734. return make_node(AST_UnaryPrefix, exp, {
  735. operator: "!",
  736. expression: exp
  737. });
  738. };
  739. def(AST_Node, function(){
  740. return basic_negation(this);
  741. });
  742. def(AST_Statement, function(){
  743. throw new Error("Cannot negate a statement");
  744. });
  745. def(AST_Function, function(){
  746. return basic_negation(this);
  747. });
  748. def(AST_UnaryPrefix, function(){
  749. if (this.operator == "!")
  750. return this.expression;
  751. return basic_negation(this);
  752. });
  753. def(AST_Seq, function(compressor){
  754. var self = this.clone();
  755. self.cdr = self.cdr.negate(compressor);
  756. return self;
  757. });
  758. def(AST_Conditional, function(compressor){
  759. var self = this.clone();
  760. self.consequent = self.consequent.negate(compressor);
  761. self.alternative = self.alternative.negate(compressor);
  762. return best_of(basic_negation(this), self);
  763. });
  764. def(AST_Binary, function(compressor){
  765. var self = this.clone(), op = this.operator;
  766. if (compressor.option("unsafe_comps")) {
  767. switch (op) {
  768. case "<=" : self.operator = ">" ; return self;
  769. case "<" : self.operator = ">=" ; return self;
  770. case ">=" : self.operator = "<" ; return self;
  771. case ">" : self.operator = "<=" ; return self;
  772. }
  773. }
  774. switch (op) {
  775. case "==" : self.operator = "!="; return self;
  776. case "!=" : self.operator = "=="; return self;
  777. case "===": self.operator = "!=="; return self;
  778. case "!==": self.operator = "==="; return self;
  779. case "&&":
  780. self.operator = "||";
  781. self.left = self.left.negate(compressor);
  782. self.right = self.right.negate(compressor);
  783. return best_of(basic_negation(this), self);
  784. case "||":
  785. self.operator = "&&";
  786. self.left = self.left.negate(compressor);
  787. self.right = self.right.negate(compressor);
  788. return best_of(basic_negation(this), self);
  789. }
  790. return basic_negation(this);
  791. });
  792. })(function(node, func){
  793. node.DEFMETHOD("negate", function(compressor){
  794. return func.call(this, compressor);
  795. });
  796. });
  797. // determine if expression has side effects
  798. (function(def){
  799. def(AST_Node, function(compressor){ return true });
  800. def(AST_EmptyStatement, function(compressor){ return false });
  801. def(AST_Constant, function(compressor){ return false });
  802. def(AST_This, function(compressor){ return false });
  803. def(AST_Call, function(compressor){
  804. var pure = compressor.option("pure_funcs");
  805. if (!pure) return true;
  806. return pure.indexOf(this.expression.print_to_string()) < 0;
  807. });
  808. def(AST_Block, function(compressor){
  809. for (var i = this.body.length; --i >= 0;) {
  810. if (this.body[i].has_side_effects(compressor))
  811. return true;
  812. }
  813. return false;
  814. });
  815. def(AST_SimpleStatement, function(compressor){
  816. return this.body.has_side_effects(compressor);
  817. });
  818. def(AST_Defun, function(compressor){ return true });
  819. def(AST_Function, function(compressor){ return false });
  820. def(AST_Binary, function(compressor){
  821. return this.left.has_side_effects(compressor)
  822. || this.right.has_side_effects(compressor);
  823. });
  824. def(AST_Assign, function(compressor){ return true });
  825. def(AST_Conditional, function(compressor){
  826. return this.condition.has_side_effects(compressor)
  827. || this.consequent.has_side_effects(compressor)
  828. || this.alternative.has_side_effects(compressor);
  829. });
  830. def(AST_Unary, function(compressor){
  831. return this.operator == "delete"
  832. || this.operator == "++"
  833. || this.operator == "--"
  834. || this.expression.has_side_effects(compressor);
  835. });
  836. def(AST_SymbolRef, function(compressor){ return false });
  837. def(AST_Object, function(compressor){
  838. for (var i = this.properties.length; --i >= 0;)
  839. if (this.properties[i].has_side_effects(compressor))
  840. return true;
  841. return false;
  842. });
  843. def(AST_ObjectProperty, function(compressor){
  844. return this.value.has_side_effects(compressor);
  845. });
  846. def(AST_Array, function(compressor){
  847. for (var i = this.elements.length; --i >= 0;)
  848. if (this.elements[i].has_side_effects(compressor))
  849. return true;
  850. return false;
  851. });
  852. def(AST_Dot, function(compressor){
  853. if (!compressor.option("pure_getters")) return true;
  854. return this.expression.has_side_effects(compressor);
  855. });
  856. def(AST_Sub, function(compressor){
  857. if (!compressor.option("pure_getters")) return true;
  858. return this.expression.has_side_effects(compressor)
  859. || this.property.has_side_effects(compressor);
  860. });
  861. def(AST_PropAccess, function(compressor){
  862. return !compressor.option("pure_getters");
  863. });
  864. def(AST_Seq, function(compressor){
  865. return this.car.has_side_effects(compressor)
  866. || this.cdr.has_side_effects(compressor);
  867. });
  868. })(function(node, func){
  869. node.DEFMETHOD("has_side_effects", func);
  870. });
  871. // tell me if a statement aborts
  872. function aborts(thing) {
  873. return thing && thing.aborts();
  874. };
  875. (function(def){
  876. def(AST_Statement, function(){ return null });
  877. def(AST_Jump, function(){ return this });
  878. function block_aborts(){
  879. var n = this.body.length;
  880. return n > 0 && aborts(this.body[n - 1]);
  881. };
  882. def(AST_BlockStatement, block_aborts);
  883. def(AST_SwitchBranch, block_aborts);
  884. def(AST_If, function(){
  885. return this.alternative && aborts(this.body) && aborts(this.alternative);
  886. });
  887. })(function(node, func){
  888. node.DEFMETHOD("aborts", func);
  889. });
  890. /* -----[ optimizers ]----- */
  891. OPT(AST_Directive, function(self, compressor){
  892. if (self.scope.has_directive(self.value) !== self.scope) {
  893. return make_node(AST_EmptyStatement, self);
  894. }
  895. return self;
  896. });
  897. OPT(AST_Debugger, function(self, compressor){
  898. if (compressor.option("drop_debugger"))
  899. return make_node(AST_EmptyStatement, self);
  900. return self;
  901. });
  902. OPT(AST_LabeledStatement, function(self, compressor){
  903. if (self.body instanceof AST_Break
  904. && compressor.loopcontrol_target(self.body.label) === self.body) {
  905. return make_node(AST_EmptyStatement, self);
  906. }
  907. return self.label.references.length == 0 ? self.body : self;
  908. });
  909. OPT(AST_Block, function(self, compressor){
  910. self.body = tighten_body(self.body, compressor);
  911. return self;
  912. });
  913. OPT(AST_BlockStatement, function(self, compressor){
  914. self.body = tighten_body(self.body, compressor);
  915. switch (self.body.length) {
  916. case 1: return self.body[0];
  917. case 0: return make_node(AST_EmptyStatement, self);
  918. }
  919. return self;
  920. });
  921. AST_Scope.DEFMETHOD("drop_unused", function(compressor){
  922. var self = this;
  923. if (compressor.option("unused")
  924. && !(self instanceof AST_Toplevel)
  925. && !self.uses_eval
  926. ) {
  927. var in_use = [];
  928. var initializations = new Dictionary();
  929. // pass 1: find out which symbols are directly used in
  930. // this scope (not in nested scopes).
  931. var scope = this;
  932. var tw = new TreeWalker(function(node, descend){
  933. if (node !== self) {
  934. if (node instanceof AST_Defun) {
  935. initializations.add(node.name.name, node);
  936. return true; // don't go in nested scopes
  937. }
  938. if (node instanceof AST_Definitions && scope === self) {
  939. node.definitions.forEach(function(def){
  940. if (def.value) {
  941. initializations.add(def.name.name, def.value);
  942. if (def.value.has_side_effects(compressor)) {
  943. def.value.walk(tw);
  944. }
  945. }
  946. });
  947. return true;
  948. }
  949. if (node instanceof AST_SymbolRef) {
  950. push_uniq(in_use, node.definition());
  951. return true;
  952. }
  953. if (node instanceof AST_Scope) {
  954. var save_scope = scope;
  955. scope = node;
  956. descend();
  957. scope = save_scope;
  958. return true;
  959. }
  960. }
  961. });
  962. self.walk(tw);
  963. // pass 2: for every used symbol we need to walk its
  964. // initialization code to figure out if it uses other
  965. // symbols (that may not be in_use).
  966. for (var i = 0; i < in_use.length; ++i) {
  967. in_use[i].orig.forEach(function(decl){
  968. // undeclared globals will be instanceof AST_SymbolRef
  969. var init = initializations.get(decl.name);
  970. if (init) init.forEach(function(init){
  971. var tw = new TreeWalker(function(node){
  972. if (node instanceof AST_SymbolRef) {
  973. push_uniq(in_use, node.definition());
  974. }
  975. });
  976. init.walk(tw);
  977. });
  978. });
  979. }
  980. // pass 3: we should drop declarations not in_use
  981. var tt = new TreeTransformer(
  982. function before(node, descend, in_list) {
  983. if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) {
  984. for (var a = node.argnames, i = a.length; --i >= 0;) {
  985. var sym = a[i];
  986. if (sym.unreferenced()) {
  987. a.pop();
  988. compressor.warn("Dropping unused function argument {name} [{file}:{line},{col}]", {
  989. name : sym.name,
  990. file : sym.start.file,
  991. line : sym.start.line,
  992. col : sym.start.col
  993. });
  994. }
  995. else break;
  996. }
  997. }
  998. if (node instanceof AST_Defun && node !== self) {
  999. if (!member(node.name.definition(), in_use)) {
  1000. compressor.warn("Dropping unused function {name} [{file}:{line},{col}]", {
  1001. name : node.name.name,
  1002. file : node.name.start.file,
  1003. line : node.name.start.line,
  1004. col : node.name.start.col
  1005. });
  1006. return make_node(AST_EmptyStatement, node);
  1007. }
  1008. return node;
  1009. }
  1010. if (node instanceof AST_Definitions && !(tt.parent() instanceof AST_ForIn)) {
  1011. var def = node.definitions.filter(function(def){
  1012. if (member(def.name.definition(), in_use)) return true;
  1013. var w = {
  1014. name : def.name.name,
  1015. file : def.name.start.file,
  1016. line : def.name.start.line,
  1017. col : def.name.start.col
  1018. };
  1019. if (def.value && def.value.has_side_effects(compressor)) {
  1020. def._unused_side_effects = true;
  1021. compressor.warn("Side effects in initialization of unused variable {name} [{file}:{line},{col}]", w);
  1022. return true;
  1023. }
  1024. compressor.warn("Dropping unused variable {name} [{file}:{line},{col}]", w);
  1025. return false;
  1026. });
  1027. // place uninitialized names at the start
  1028. def = mergeSort(def, function(a, b){
  1029. if (!a.value && b.value) return -1;
  1030. if (!b.value && a.value) return 1;
  1031. return 0;
  1032. });
  1033. // for unused names whose initialization has
  1034. // side effects, we can cascade the init. code
  1035. // into the next one, or next statement.
  1036. var side_effects = [];
  1037. for (var i = 0; i < def.length;) {
  1038. var x = def[i];
  1039. if (x._unused_side_effects) {
  1040. side_effects.push(x.value);
  1041. def.splice(i, 1);
  1042. } else {
  1043. if (side_effects.length > 0) {
  1044. side_effects.push(x.value);
  1045. x.value = AST_Seq.from_array(side_effects);
  1046. side_effects = [];
  1047. }
  1048. ++i;
  1049. }
  1050. }
  1051. if (side_effects.length > 0) {
  1052. side_effects = make_node(AST_BlockStatement, node, {
  1053. body: [ make_node(AST_SimpleStatement, node, {
  1054. body: AST_Seq.from_array(side_effects)
  1055. }) ]
  1056. });
  1057. } else {
  1058. side_effects = null;
  1059. }
  1060. if (def.length == 0 && !side_effects) {
  1061. return make_node(AST_EmptyStatement, node);
  1062. }
  1063. if (def.length == 0) {
  1064. return side_effects;
  1065. }
  1066. node.definitions = def;
  1067. if (side_effects) {
  1068. side_effects.body.unshift(node);
  1069. node = side_effects;
  1070. }
  1071. return node;
  1072. }
  1073. if (node instanceof AST_For) {
  1074. descend(node, this);
  1075. if (node.init instanceof AST_BlockStatement) {
  1076. // certain combination of unused name + side effect leads to:
  1077. // https://github.com/mishoo/UglifyJS2/issues/44
  1078. // that's an invalid AST.
  1079. // We fix it at this stage by moving the `var` outside the `for`.
  1080. var body = node.init.body.slice(0, -1);
  1081. node.init = node.init.body.slice(-1)[0].body;
  1082. body.push(node);
  1083. return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, {
  1084. body: body
  1085. });
  1086. }
  1087. }
  1088. if (node instanceof AST_Scope && node !== self)
  1089. return node;
  1090. }
  1091. );
  1092. self.transform(tt);
  1093. }
  1094. });
  1095. AST_Scope.DEFMETHOD("hoist_declarations", function(compressor){
  1096. var hoist_funs = compressor.option("hoist_funs");
  1097. var hoist_vars = compressor.option("hoist_vars");
  1098. var self = this;
  1099. if (hoist_funs || hoist_vars) {
  1100. var dirs = [];
  1101. var hoisted = [];
  1102. var vars = new Dictionary(), vars_found = 0, var_decl = 0;
  1103. // let's count var_decl first, we seem to waste a lot of
  1104. // space if we hoist `var` when there's only one.
  1105. self.walk(new TreeWalker(function(node){
  1106. if (node instanceof AST_Scope && node !== self)
  1107. return true;
  1108. if (node instanceof AST_Var) {
  1109. ++var_decl;
  1110. return true;
  1111. }
  1112. }));
  1113. hoist_vars = hoist_vars && var_decl > 1;
  1114. var tt = new TreeTransformer(
  1115. function before(node) {
  1116. if (node !== self) {
  1117. if (node instanceof AST_Directive) {
  1118. dirs.push(node);
  1119. return make_node(AST_EmptyStatement, node);
  1120. }
  1121. if (node instanceof AST_Defun && hoist_funs) {
  1122. hoisted.push(node);
  1123. return make_node(AST_EmptyStatement, node);
  1124. }
  1125. if (node instanceof AST_Var && hoist_vars) {
  1126. node.definitions.forEach(function(def){
  1127. vars.set(def.name.name, def);
  1128. ++vars_found;
  1129. });
  1130. var seq = node.to_assignments();
  1131. var p = tt.parent();
  1132. if (p instanceof AST_ForIn && p.init === node) {
  1133. if (seq == null) return node.definitions[0].name;
  1134. return seq;
  1135. }
  1136. if (p instanceof AST_For && p.init === node) {
  1137. return seq;
  1138. }
  1139. if (!seq) return make_node(AST_EmptyStatement, node);
  1140. return make_node(AST_SimpleStatement, node, {
  1141. body: seq
  1142. });
  1143. }
  1144. if (node instanceof AST_Scope)
  1145. return node; // to avoid descending in nested scopes
  1146. }
  1147. }
  1148. );
  1149. self = self.transform(tt);
  1150. if (vars_found > 0) {
  1151. // collect only vars which don't show up in self's arguments list
  1152. var defs = [];
  1153. vars.each(function(def, name){
  1154. if (self instanceof AST_Lambda
  1155. && find_if(function(x){ return x.name == def.name.name },
  1156. self.argnames)) {
  1157. vars.del(name);
  1158. } else {
  1159. def = def.clone();
  1160. def.value = null;
  1161. defs.push(def);
  1162. vars.set(name, def);
  1163. }
  1164. });
  1165. if (defs.length > 0) {
  1166. // try to merge in assignments
  1167. for (var i = 0; i < self.body.length;) {
  1168. if (self.body[i] instanceof AST_SimpleStatement) {
  1169. var expr = self.body[i].body, sym, assign;
  1170. if (expr instanceof AST_Assign
  1171. && expr.operator == "="
  1172. && (sym = expr.left) instanceof AST_Symbol
  1173. && vars.has(sym.name))
  1174. {
  1175. var def = vars.get(sym.name);
  1176. if (def.value) break;
  1177. def.value = expr.right;
  1178. remove(defs, def);
  1179. defs.push(def);
  1180. self.body.splice(i, 1);
  1181. continue;
  1182. }
  1183. if (expr instanceof AST_Seq
  1184. && (assign = expr.car) instanceof AST_Assign
  1185. && assign.operator == "="
  1186. && (sym = assign.left) instanceof AST_Symbol
  1187. && vars.has(sym.name))
  1188. {
  1189. var def = vars.get(sym.name);
  1190. if (def.value) break;
  1191. def.value = assign.right;
  1192. remove(defs, def);
  1193. defs.push(def);
  1194. self.body[i].body = expr.cdr;
  1195. continue;
  1196. }
  1197. }
  1198. if (self.body[i] instanceof AST_EmptyStatement) {
  1199. self.body.splice(i, 1);
  1200. continue;
  1201. }
  1202. if (self.body[i] instanceof AST_BlockStatement) {
  1203. var tmp = [ i, 1 ].concat(self.body[i].body);
  1204. self.body.splice.apply(self.body, tmp);
  1205. continue;
  1206. }
  1207. break;
  1208. }
  1209. defs = make_node(AST_Var, self, {
  1210. definitions: defs
  1211. });
  1212. hoisted.push(defs);
  1213. };
  1214. }
  1215. self.body = dirs.concat(hoisted, self.body);
  1216. }
  1217. return self;
  1218. });
  1219. OPT(AST_SimpleStatement, function(self, compressor){
  1220. if (compressor.option("side_effects")) {
  1221. if (!self.body.has_side_effects(compressor)) {
  1222. compressor.warn("Dropping side-effect-free statement [{file}:{line},{col}]", self.start);
  1223. return make_node(AST_EmptyStatement, self);
  1224. }
  1225. }
  1226. return self;
  1227. });
  1228. OPT(AST_DWLoop, function(self, compressor){
  1229. var cond = self.condition.evaluate(compressor);
  1230. self.condition = cond[0];
  1231. if (!compressor.option("loops")) return self;
  1232. if (cond.length > 1) {
  1233. if (cond[1]) {
  1234. return make_node(AST_For, self, {
  1235. body: self.body
  1236. });
  1237. } else if (self instanceof AST_While) {
  1238. if (compressor.option("dead_code")) {
  1239. var a = [];
  1240. extract_declarations_from_unreachable_code(compressor, self.body, a);
  1241. return make_node(AST_BlockStatement, self, { body: a });
  1242. }
  1243. }
  1244. }
  1245. return self;
  1246. });
  1247. function if_break_in_loop(self, compressor) {
  1248. function drop_it(rest) {
  1249. rest = as_statement_array(rest);
  1250. if (self.body instanceof AST_BlockStatement) {
  1251. self.body = self.body.clone();
  1252. self.body.body = rest.concat(self.body.body.slice(1));
  1253. self.body = self.body.transform(compressor);
  1254. } else {
  1255. self.body = make_node(AST_BlockStatement, self.body, {
  1256. body: rest
  1257. }).transform(compressor);
  1258. }
  1259. if_break_in_loop(self, compressor);
  1260. }
  1261. var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body;
  1262. if (first instanceof AST_If) {
  1263. if (first.body instanceof AST_Break
  1264. && compressor.loopcontrol_target(first.body.label) === self) {
  1265. if (self.condition) {
  1266. self.condition = make_node(AST_Binary, self.condition, {
  1267. left: self.condition,
  1268. operator: "&&",
  1269. right: first.condition.negate(compressor),
  1270. });
  1271. } else {
  1272. self.condition = first.condition.negate(compressor);
  1273. }
  1274. drop_it(first.alternative);
  1275. }
  1276. else if (first.alternative instanceof AST_Break
  1277. && compressor.loopcontrol_target(first.alternative.label) === self) {
  1278. if (self.condition) {
  1279. self.condition = make_node(AST_Binary, self.condition, {
  1280. left: self.condition,
  1281. operator: "&&",
  1282. right: first.condition,
  1283. });
  1284. } else {
  1285. self.condition = first.condition;
  1286. }
  1287. drop_it(first.body);
  1288. }
  1289. }
  1290. };
  1291. OPT(AST_While, function(self, compressor) {
  1292. if (!compressor.option("loops")) return self;
  1293. self = AST_DWLoop.prototype.optimize.call(self, compressor);
  1294. if (self instanceof AST_While) {
  1295. if_break_in_loop(self, compressor);
  1296. self = make_node(AST_For, self, self).transform(compressor);
  1297. }
  1298. return self;
  1299. });
  1300. OPT(AST_For, function(self, compressor){
  1301. var cond = self.condition;
  1302. if (cond) {
  1303. cond = cond.evaluate(compressor);
  1304. self.condition = cond[0];
  1305. }
  1306. if (!compressor.option("loops")) return self;
  1307. if (cond) {
  1308. if (cond.length > 1 && !cond[1]) {
  1309. if (compressor.option("dead_code")) {
  1310. var a = [];
  1311. if (self.init instanceof AST_Statement) {
  1312. a.push(self.init);
  1313. }
  1314. else if (self.init) {
  1315. a.push(make_node(AST_SimpleStatement, self.init, {
  1316. body: self.init
  1317. }));
  1318. }
  1319. extract_declarations_from_unreachable_code(compressor, self.body, a);
  1320. return make_node(AST_BlockStatement, self, { body: a });
  1321. }
  1322. }
  1323. }
  1324. if_break_in_loop(self, compressor);
  1325. return self;
  1326. });
  1327. OPT(AST_If, function(self, compressor){
  1328. if (!compressor.option("conditionals")) return self;
  1329. // if condition can be statically determined, warn and drop
  1330. // one of the blocks. note, statically determined implies
  1331. // “has no side effects”; also it doesn't work for cases like
  1332. // `x && true`, though it probably should.
  1333. var cond = self.condition.evaluate(compressor);
  1334. self.condition = cond[0];
  1335. if (cond.length > 1) {
  1336. if (cond[1]) {
  1337. compressor.warn("Condition always true [{file}:{line},{col}]", self.condition.start);
  1338. if (compressor.option("dead_code")) {
  1339. var a = [];
  1340. if (self.alternative) {
  1341. extract_declarations_from_unreachable_code(compressor, self.alternative, a);
  1342. }
  1343. a.push(self.body);
  1344. return make_node(AST_BlockStatement, self, { body: a }).transform(compressor);
  1345. }
  1346. } else {
  1347. compressor.warn("Condition always false [{file}:{line},{col}]", self.condition.start);
  1348. if (compressor.option("dead_code")) {
  1349. var a = [];
  1350. extract_declarations_from_unreachable_code(compressor, self.body, a);
  1351. if (self.alternative) a.push(self.alternative);
  1352. return make_node(AST_BlockStatement, self, { body: a }).transform(compressor);
  1353. }
  1354. }
  1355. }
  1356. if (is_empty(self.alternative)) self.alternative = null;
  1357. var negated = self.condition.negate(compressor);
  1358. var negated_is_best = best_of(self.condition, negated) === negated;
  1359. if (self.alternative && negated_is_best) {
  1360. negated_is_best = false; // because we already do the switch here.
  1361. self.condition = negated;
  1362. var tmp = self.body;
  1363. self.body = self.alternative || make_node(AST_EmptyStatement);
  1364. self.alternative = tmp;
  1365. }
  1366. if (is_empty(self.body) && is_empty(self.alternative)) {
  1367. return make_node(AST_SimpleStatement, self.condition, {
  1368. body: self.condition
  1369. }).transform(compressor);
  1370. }
  1371. if (self.body instanceof AST_SimpleStatement
  1372. && self.alternative instanceof AST_SimpleStatement) {
  1373. return make_node(AST_SimpleStatement, self, {
  1374. body: make_node(AST_Conditional, self, {
  1375. condition : self.condition,
  1376. consequent : self.body.body,
  1377. alternative : self.alternative.body
  1378. })
  1379. }).transform(compressor);
  1380. }
  1381. if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) {
  1382. if (negated_is_best) return make_node(AST_SimpleStatement, self, {
  1383. body: make_node(AST_Binary, self, {
  1384. operator : "||",
  1385. left : negated,
  1386. right : self.body.body
  1387. })
  1388. }).transform(compressor);
  1389. return make_node(AST_SimpleStatement, self, {
  1390. body: make_node(AST_Binary, self, {
  1391. operator : "&&",
  1392. left : self.condition,
  1393. right : self.body.body
  1394. })
  1395. }).transform(compressor);
  1396. }
  1397. if (self.body instanceof AST_EmptyStatement
  1398. && self.alternative
  1399. && self.alternative instanceof AST_SimpleStatement) {
  1400. return make_node(AST_SimpleStatement, self, {
  1401. body: make_node(AST_Binary, self, {
  1402. operator : "||",
  1403. left : self.condition,
  1404. right : self.alternative.body
  1405. })
  1406. }).transform(compressor);
  1407. }
  1408. if (self.body instanceof AST_Exit
  1409. && self.alternative instanceof AST_Exit
  1410. && self.body.TYPE == self.alternative.TYPE) {
  1411. return make_node(self.body.CTOR, self, {
  1412. value: make_node(AST_Conditional, self, {
  1413. condition : self.condition,
  1414. consequent : self.body.value || make_node(AST_Undefined, self.body).optimize(compressor),
  1415. alternative : self.alternative.value || make_node(AST_Undefined, self.alternative).optimize(compressor)
  1416. })
  1417. }).transform(compressor);
  1418. }
  1419. if (self.body instanceof AST_If
  1420. && !self.body.alternative
  1421. && !self.alternative) {
  1422. self.condition = make_node(AST_Binary, self.condition, {
  1423. operator: "&&",
  1424. left: self.condition,
  1425. right: self.body.condition
  1426. }).transform(compressor);
  1427. self.body = self.body.body;
  1428. }
  1429. if (aborts(self.body)) {
  1430. if (self.alternative) {
  1431. var alt = self.alternative;
  1432. self.alternative = null;
  1433. return make_node(AST_BlockStatement, self, {
  1434. body: [ self, alt ]
  1435. }).transform(compressor);
  1436. }
  1437. }
  1438. if (aborts(self.alternative)) {
  1439. var body = self.body;
  1440. self.body = self.alternative;
  1441. self.condition = negated_is_best ? negated : self.condition.negate(compressor);
  1442. self.alternative = null;
  1443. return make_node(AST_BlockStatement, self, {
  1444. body: [ self, body ]
  1445. }).transform(compressor);
  1446. }
  1447. return self;
  1448. });
  1449. OPT(AST_Switch, function(self, compressor){
  1450. if (self.body.length == 0 && compressor.option("conditionals")) {
  1451. return make_node(AST_SimpleStatement, self, {
  1452. body: self.expression
  1453. }).transform(compressor);
  1454. }
  1455. for(;;) {
  1456. var last_branch = self.body[self.body.length - 1];
  1457. if (last_branch) {
  1458. var stat = last_branch.body[last_branch.body.length - 1]; // last statement
  1459. if (stat instanceof AST_Break && loop_body(compressor.loopcontrol_target(stat.label)) === self)
  1460. last_branch.body.pop();
  1461. if (last_branch instanceof AST_Default && last_branch.body.length == 0) {
  1462. self.body.pop();
  1463. continue;
  1464. }
  1465. }
  1466. break;
  1467. }
  1468. var exp = self.expression.evaluate(compressor);
  1469. out: if (exp.length == 2) try {
  1470. // constant expression
  1471. self.expression = exp[0];
  1472. if (!compressor.option("dead_code")) break out;
  1473. var value = exp[1];
  1474. var in_if = false;
  1475. var in_block = false;
  1476. var started = false;
  1477. var stopped = false;
  1478. var ruined = false;
  1479. var tt = new TreeTransformer(function(node, descend, in_list){
  1480. if (node instanceof AST_Lambda || node instanceof AST_SimpleStatement) {
  1481. // no need to descend these node types
  1482. return node;
  1483. }
  1484. else if (node instanceof AST_Switch && node === self) {
  1485. node = node.clone();
  1486. descend(node, this);
  1487. return ruined ? node : make_node(AST_BlockStatement, node, {
  1488. body: node.body.reduce(function(a, branch){
  1489. return a.concat(branch.body);
  1490. }, [])
  1491. }).transform(compressor);
  1492. }
  1493. else if (node instanceof AST_If || node instanceof AST_Try) {
  1494. var save = in_if;
  1495. in_if = !in_block;
  1496. descend(node, this);
  1497. in_if = save;
  1498. return node;
  1499. }
  1500. else if (node instanceof AST_StatementWithBody || node instanceof AST_Switch) {
  1501. var save = in_block;
  1502. in_block = true;
  1503. descend(node, this);
  1504. in_block = save;
  1505. return node;
  1506. }
  1507. else if (node instanceof AST_Break && this.loopcontrol_target(node.label) === self) {
  1508. if (in_if) {
  1509. ruined = true;
  1510. return node;
  1511. }
  1512. if (in_block) return node;
  1513. stopped = true;
  1514. return in_list ? MAP.skip : make_node(AST_EmptyStatement, node);
  1515. }
  1516. else if (node instanceof AST_SwitchBranch && this.parent() === self) {
  1517. if (stopped) return MAP.skip;
  1518. if (node instanceof AST_Case) {
  1519. var exp = node.expression.evaluate(compressor);
  1520. if (exp.length < 2) {
  1521. // got a case with non-constant expression, baling out
  1522. throw self;
  1523. }
  1524. if (exp[1] === value || started) {
  1525. started = true;
  1526. if (aborts(node)) stopped = true;
  1527. descend(node, this);
  1528. return node;
  1529. }
  1530. return MAP.skip;
  1531. }
  1532. descend(node, this);
  1533. return node;
  1534. }
  1535. });
  1536. tt.stack = compressor.stack.slice(); // so that's able to see parent nodes
  1537. self = self.transform(tt);
  1538. } catch(ex) {
  1539. if (ex !== self) throw ex;
  1540. }
  1541. return self;
  1542. });
  1543. OPT(AST_Case, function(self, compressor){
  1544. self.body = tighten_body(self.body, compressor);
  1545. return self;
  1546. });
  1547. OPT(AST_Try, function(self, compressor){
  1548. self.body = tighten_body(self.body, compressor);
  1549. return self;
  1550. });
  1551. AST_Definitions.DEFMETHOD("remove_initializers", function(){
  1552. this.definitions.forEach(function(def){ def.value = null });
  1553. });
  1554. AST_Definitions.DEFMETHOD("to_assignments", function(){
  1555. var assignments = this.definitions.reduce(function(a, def){
  1556. if (def.value) {
  1557. var name = make_node(AST_SymbolRef, def.name, def.name);
  1558. a.push(make_node(AST_Assign, def, {
  1559. operator : "=",
  1560. left : name,
  1561. right : def.value
  1562. }));
  1563. }
  1564. return a;
  1565. }, []);
  1566. if (assignments.length == 0) return null;
  1567. return AST_Seq.from_array(assignments);
  1568. });
  1569. OPT(AST_Definitions, function(self, compressor){
  1570. if (self.definitions.length == 0)
  1571. return make_node(AST_EmptyStatement, self);
  1572. return self;
  1573. });
  1574. OPT(AST_Function, function(self, compressor){
  1575. self = AST_Lambda.prototype.optimize.call(self, compressor);
  1576. if (compressor.option("unused")) {
  1577. if (self.name && self.name.unreferenced()) {
  1578. self.name = null;
  1579. }
  1580. }
  1581. return self;
  1582. });
  1583. OPT(AST_Call, function(self, compressor){
  1584. if (compressor.option("unsafe")) {
  1585. var exp = self.expression;
  1586. if (exp instanceof AST_SymbolRef && exp.undeclared()) {
  1587. switch (exp.name) {
  1588. case "Array":
  1589. if (self.args.length != 1) {
  1590. return make_node(AST_Array, self, {
  1591. elements: self.args
  1592. }).transform(compressor);
  1593. }
  1594. break;
  1595. case "Object":
  1596. if (self.args.length == 0) {
  1597. return make_node(AST_Object, self, {
  1598. properties: []
  1599. });
  1600. }
  1601. break;
  1602. case "String":
  1603. if (self.args.length == 0) return make_node(AST_String, self, {
  1604. value: ""
  1605. });
  1606. if (self.args.length <= 1) return make_node(AST_Binary, self, {
  1607. left: self.args[0],
  1608. operator: "+",
  1609. right: make_node(AST_String, self, { value: "" })
  1610. }).transform(compressor);
  1611. break;
  1612. case "Number":
  1613. if (self.args.length == 0) return make_node(AST_Number, self, {
  1614. value: 0
  1615. });
  1616. if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
  1617. expression: self.args[0],
  1618. operator: "+"
  1619. }).transform(compressor);
  1620. case "Boolean":
  1621. if (self.args.length == 0) return make_node(AST_False, self);
  1622. if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
  1623. expression: make_node(AST_UnaryPrefix, null, {
  1624. expression: self.args[0],
  1625. operator: "!"
  1626. }),
  1627. operator: "!"
  1628. }).transform(compressor);
  1629. break;
  1630. case "Function":
  1631. if (all(self.args, function(x){ return x instanceof AST_String })) {
  1632. // quite a corner-case, but we can handle it:
  1633. // https://github.com/mishoo/UglifyJS2/issues/203
  1634. // if the code argument is a constant, then we can minify it.
  1635. try {
  1636. var code = "(function(" + self.args.slice(0, -1).map(function(arg){
  1637. return arg.value;
  1638. }).join(",") + "){" + self.args[self.args.length - 1].value + "})()";
  1639. var ast = parse(code);
  1640. ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") });
  1641. var comp = new Compressor(compressor.options);
  1642. ast = ast.transform(comp);
  1643. ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") });
  1644. ast.mangle_names();
  1645. var fun;
  1646. try {
  1647. ast.walk(new TreeWalker(function(node){
  1648. if (node instanceof AST_Lambda) {
  1649. fun = node;
  1650. throw ast;
  1651. }
  1652. }));
  1653. } catch(ex) {
  1654. if (ex !== ast) throw ex;
  1655. };
  1656. var args = fun.argnames.map(function(arg, i){
  1657. return make_node(AST_String, self.args[i], {
  1658. value: arg.print_to_string()
  1659. });
  1660. });
  1661. var code = OutputStream();
  1662. AST_BlockStatement.prototype._codegen.call(fun, fun, code);
  1663. code = code.toString().replace(/^\{|\}$/g, "");
  1664. args.push(make_node(AST_String, self.args[self.args.length - 1], {
  1665. value: code
  1666. }));
  1667. self.args = args;
  1668. return self;
  1669. } catch(ex) {
  1670. if (ex instanceof JS_Parse_Error) {
  1671. compressor.warn("Error parsing code passed to new Function [{file}:{line},{col}]", self.args[self.args.length - 1].start);
  1672. compressor.warn(ex.toString());
  1673. } else {
  1674. console.log(ex);
  1675. throw ex;
  1676. }
  1677. }
  1678. }
  1679. break;
  1680. }
  1681. }
  1682. else if (exp instanceof AST_Dot && exp.property == "toString" && self.args.length == 0) {
  1683. return make_node(AST_Binary, self, {
  1684. left: make_node(AST_String, self, { value: "" }),
  1685. operator: "+",
  1686. right: exp.expression
  1687. }).transform(compressor);
  1688. }
  1689. else if (exp instanceof AST_Dot && exp.expression instanceof AST_Array && exp.property == "join") EXIT: {
  1690. var separator = self.args.length == 0 ? "," : self.args[0].evaluate(compressor)[1];
  1691. if (separator == null) break EXIT; // not a constant
  1692. var elements = exp.expression.elements.reduce(function(a, el){
  1693. el = el.evaluate(compressor);
  1694. if (a.length == 0 || el.length == 1) {
  1695. a.push(el);
  1696. } else {
  1697. var last = a[a.length - 1];
  1698. if (last.length == 2) {
  1699. // it's a constant
  1700. var val = "" + last[1] + separator + el[1];
  1701. a[a.length - 1] = [ make_node_from_constant(compressor, val, last[0]), val ];
  1702. } else {
  1703. a.push(el);
  1704. }
  1705. }
  1706. return a;
  1707. }, []);
  1708. if (elements.length == 0) return make_node(AST_String, self, { value: "" });
  1709. if (elements.length == 1) return elements[0][0];
  1710. if (separator == "") {
  1711. var first;
  1712. if (elements[0][0] instanceof AST_String
  1713. || elements[1][0] instanceof AST_String) {
  1714. first = elements.shift()[0];
  1715. } else {
  1716. first = make_node(AST_String, self, { value: "" });
  1717. }
  1718. return elements.reduce(function(prev, el){
  1719. return make_node(AST_Binary, el[0], {
  1720. operator : "+",
  1721. left : prev,
  1722. right : el[0],
  1723. });
  1724. }, first).transform(compressor);
  1725. }
  1726. // need this awkward cloning to not affect original element
  1727. // best_of will decide which one to get through.
  1728. var node = self.clone();
  1729. node.expression = node.expression.clone();
  1730. node.expression.expression = node.expression.expression.clone();
  1731. node.expression.expression.elements = elements.map(function(el){
  1732. return el[0];
  1733. });
  1734. return best_of(self, node);
  1735. }
  1736. }
  1737. if (compressor.option("side_effects")) {
  1738. if (self.expression instanceof AST_Function
  1739. && self.args.length == 0
  1740. && !AST_Block.prototype.has_side_effects.call(self.expression, compressor)) {
  1741. return make_node(AST_Undefined, self).transform(compressor);
  1742. }
  1743. }
  1744. if (compressor.option("drop_console")) {
  1745. if (self.expression instanceof AST_PropAccess &&
  1746. self.expression.expression instanceof AST_SymbolRef &&
  1747. self.expression.expression.name == "console" &&
  1748. self.expression.expression.undeclared()) {
  1749. return make_node(AST_Undefined, self).transform(compressor);
  1750. }
  1751. }
  1752. return self.evaluate(compressor)[0];
  1753. });
  1754. OPT(AST_New, function(self, compressor){
  1755. if (compressor.option("unsafe")) {
  1756. var exp = self.expression;
  1757. if (exp instanceof AST_SymbolRef && exp.undeclared()) {
  1758. switch (exp.name) {
  1759. case "Object":
  1760. case "RegExp":
  1761. case "Function":
  1762. case "Error":
  1763. case "Array":
  1764. return make_node(AST_Call, self, self).transform(compressor);
  1765. }
  1766. }
  1767. }
  1768. return self;
  1769. });
  1770. OPT(AST_Seq, function(self, compressor){
  1771. if (!compressor.option("side_effects"))
  1772. return self;
  1773. if (!self.car.has_side_effects(compressor)) {
  1774. // we shouldn't compress (1,eval)(something) to
  1775. // eval(something) because that changes the meaning of
  1776. // eval (becomes lexical instead of global).
  1777. var p;
  1778. if (!(self.cdr instanceof AST_SymbolRef
  1779. && self.cdr.name == "eval"
  1780. && self.cdr.undeclared()
  1781. && (p = compressor.parent()) instanceof AST_Call
  1782. && p.expression === self)) {
  1783. return self.cdr;
  1784. }
  1785. }
  1786. if (compressor.option("cascade")) {
  1787. if (self.car instanceof AST_Assign
  1788. && !self.car.left.has_side_effects(compressor)) {
  1789. if (self.car.left.equivalent_to(self.cdr)) {
  1790. return self.car;
  1791. }
  1792. if (self.cdr instanceof AST_Call
  1793. && self.cdr.expression.equivalent_to(self.car.left)) {
  1794. self.cdr.expression = self.car;
  1795. return self.cdr;
  1796. }
  1797. }
  1798. if (!self.car.has_side_effects(compressor)
  1799. && !self.cdr.has_side_effects(compressor)
  1800. && self.car.equivalent_to(self.cdr)) {
  1801. return self.car;
  1802. }
  1803. }
  1804. if (self.cdr instanceof AST_UnaryPrefix
  1805. && self.cdr.operator == "void"
  1806. && !self.cdr.expression.has_side_effects(compressor)) {
  1807. self.cdr.operator = self.car;
  1808. return self.cdr;
  1809. }
  1810. if (self.cdr instanceof AST_Undefined) {
  1811. return make_node(AST_UnaryPrefix, self, {
  1812. operator : "void",
  1813. expression : self.car
  1814. });
  1815. }
  1816. return self;
  1817. });
  1818. AST_Unary.DEFMETHOD("lift_sequences", function(compressor){
  1819. if (compressor.option("sequences")) {
  1820. if (this.expression instanceof AST_Seq) {
  1821. var seq = this.expression;
  1822. var x = seq.to_array();
  1823. this.expression = x.pop();
  1824. x.push(this);
  1825. seq = AST_Seq.from_array(x).transform(compressor);
  1826. return seq;
  1827. }
  1828. }
  1829. return this;
  1830. });
  1831. OPT(AST_UnaryPostfix, function(self, compressor){
  1832. return self.lift_sequences(compressor);
  1833. });
  1834. OPT(AST_UnaryPrefix, function(self, compressor){
  1835. self = self.lift_sequences(compressor);
  1836. var e = self.expression;
  1837. if (compressor.option("booleans") && compressor.in_boolean_context()) {
  1838. switch (self.operator) {
  1839. case "!":
  1840. if (e instanceof AST_UnaryPrefix && e.operator == "!") {
  1841. // !!foo ==> foo, if we're in boolean context
  1842. return e.expression;
  1843. }
  1844. break;
  1845. case "typeof":
  1846. // typeof always returns a non-empty string, thus it's
  1847. // always true in booleans
  1848. compressor.warn("Boolean expression always true [{file}:{line},{col}]", self.start);
  1849. return make_node(AST_True, self);
  1850. }
  1851. if (e instanceof AST_Binary && self.operator == "!") {
  1852. self = best_of(self, e.negate(compressor));
  1853. }
  1854. }
  1855. return self.evaluate(compressor)[0];
  1856. });
  1857. function has_side_effects_or_prop_access(node, compressor) {
  1858. var save_pure_getters = compressor.option("pure_getters");
  1859. compressor.options.pure_getters = false;
  1860. var ret = node.has_side_effects(compressor);
  1861. compressor.options.pure_getters = save_pure_getters;
  1862. return ret;
  1863. }
  1864. AST_Binary.DEFMETHOD("lift_sequences", function(compressor){
  1865. if (compressor.option("sequences")) {
  1866. if (this.left instanceof AST_Seq) {
  1867. var seq = this.left;
  1868. var x = seq.to_array();
  1869. this.left = x.pop();
  1870. x.push(this);
  1871. seq = AST_Seq.from_array(x).transform(compressor);
  1872. return seq;
  1873. }
  1874. if (this.right instanceof AST_Seq
  1875. && this instanceof AST_Assign
  1876. && !has_side_effects_or_prop_access(this.left, compressor)) {
  1877. var seq = this.right;
  1878. var x = seq.to_array();
  1879. this.right = x.pop();
  1880. x.push(this);
  1881. seq = AST_Seq.from_array(x).transform(compressor);
  1882. return seq;
  1883. }
  1884. }
  1885. return this;
  1886. });
  1887. var commutativeOperators = makePredicate("== === != !== * & | ^");
  1888. OPT(AST_Binary, function(self, compressor){
  1889. var reverse = compressor.has_directive("use asm") ? noop
  1890. : function(op, force) {
  1891. if (force || !(self.left.has_side_effects(compressor) || self.right.has_side_effects(compressor))) {
  1892. if (op) self.operator = op;
  1893. var tmp = self.left;
  1894. self.left = self.right;
  1895. self.right = tmp;
  1896. }
  1897. };
  1898. if (commutativeOperators(self.operator)) {
  1899. if (self.right instanceof AST_Constant
  1900. && !(self.left instanceof AST_Constant)) {
  1901. // if right is a constant, whatever side effects the
  1902. // left side might have could not influence the
  1903. // result. hence, force switch.
  1904. if (!(self.left instanceof AST_Binary
  1905. && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) {
  1906. reverse(null, true);
  1907. }
  1908. }
  1909. if (/^[!=]==?$/.test(self.operator)) {
  1910. if (self.left instanceof AST_SymbolRef && self.right instanceof AST_Conditional) {
  1911. if (self.right.consequent instanceof AST_SymbolRef
  1912. && self.right.consequent.definition() === self.left.definition()) {
  1913. if (/^==/.test(self.operator)) return self.right.condition;
  1914. if (/^!=/.test(self.operator)) return self.right.condition.negate(compressor);
  1915. }
  1916. if (self.right.alternative instanceof AST_SymbolRef
  1917. && self.right.alternative.definition() === self.left.definition()) {
  1918. if (/^==/.test(self.operator)) return self.right.condition.negate(compressor);
  1919. if (/^!=/.test(self.operator)) return self.right.condition;
  1920. }
  1921. }
  1922. if (self.right instanceof AST_SymbolRef && self.left instanceof AST_Conditional) {
  1923. if (self.left.consequent instanceof AST_SymbolRef
  1924. && self.left.consequent.definition() === self.right.definition()) {
  1925. if (/^==/.test(self.operator)) return self.left.condition;
  1926. if (/^!=/.test(self.operator)) return self.left.condition.negate(compressor);
  1927. }
  1928. if (self.left.alternative instanceof AST_SymbolRef
  1929. && self.left.alternative.definition() === self.right.definition()) {
  1930. if (/^==/.test(self.operator)) return self.left.condition.negate(compressor);
  1931. if (/^!=/.test(self.operator)) return self.left.condition;
  1932. }
  1933. }
  1934. }
  1935. }
  1936. self = self.lift_sequences(compressor);
  1937. if (compressor.option("comparisons")) switch (self.operator) {
  1938. case "===":
  1939. case "!==":
  1940. if ((self.left.is_string(compressor) && self.right.is_string(compressor)) ||
  1941. (self.left.is_boolean() && self.right.is_boolean())) {
  1942. self.operator = self.operator.substr(0, 2);
  1943. }
  1944. // XXX: intentionally falling down to the next case
  1945. case "==":
  1946. case "!=":
  1947. if (self.left instanceof AST_String
  1948. && self.left.value == "undefined"
  1949. && self.right instanceof AST_UnaryPrefix
  1950. && self.right.operator == "typeof"
  1951. && compressor.option("unsafe")) {
  1952. if (!(self.right.expression instanceof AST_SymbolRef)
  1953. || !self.right.expression.undeclared()) {
  1954. self.right = self.right.expression;
  1955. self.left = make_node(AST_Undefined, self.left).optimize(compressor);
  1956. if (self.operator.length == 2) self.operator += "=";
  1957. }
  1958. }
  1959. break;
  1960. }
  1961. if (compressor.option("booleans") && compressor.in_boolean_context()) switch (self.operator) {
  1962. case "&&":
  1963. var ll = self.left.evaluate(compressor);
  1964. var rr = self.right.evaluate(compressor);
  1965. if ((ll.length > 1 && !ll[1]) || (rr.length > 1 && !rr[1])) {
  1966. compressor.warn("Boolean && always false [{file}:{line},{col}]", self.start);
  1967. return make_node(AST_False, self);
  1968. }
  1969. if (ll.length > 1 && ll[1]) {
  1970. return rr[0];
  1971. }
  1972. if (rr.length > 1 && rr[1]) {
  1973. return ll[0];
  1974. }
  1975. break;
  1976. case "||":
  1977. var ll = self.left.evaluate(compressor);
  1978. var rr = self.right.evaluate(compressor);
  1979. if ((ll.length > 1 && ll[1]) || (rr.length > 1 && rr[1])) {
  1980. compressor.warn("Boolean || always true [{file}:{line},{col}]", self.start);
  1981. return make_node(AST_True, self);
  1982. }
  1983. if (ll.length > 1 && !ll[1]) {
  1984. return rr[0];
  1985. }
  1986. if (rr.length > 1 && !rr[1]) {
  1987. return ll[0];
  1988. }
  1989. break;
  1990. case "+":
  1991. var ll = self.left.evaluate(compressor);
  1992. var rr = self.right.evaluate(compressor);
  1993. if ((ll.length > 1 && ll[0] instanceof AST_String && ll[1]) ||
  1994. (rr.length > 1 && rr[0] instanceof AST_String && rr[1])) {
  1995. compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start);
  1996. return make_node(AST_True, self);
  1997. }
  1998. break;
  1999. }
  2000. if (compressor.option("comparisons")) {
  2001. if (!(compressor.parent() instanceof AST_Binary)
  2002. || compressor.parent() instanceof AST_Assign) {
  2003. var negated = make_node(AST_UnaryPrefix, self, {
  2004. operator: "!",
  2005. expression: self.negate(compressor)
  2006. });
  2007. self = best_of(self, negated);
  2008. }
  2009. switch (self.operator) {
  2010. case "<": reverse(">"); break;
  2011. case "<=": reverse(">="); break;
  2012. }
  2013. }
  2014. if (self.operator == "+" && self.right instanceof AST_String
  2015. && self.right.getValue() === "" && self.left instanceof AST_Binary
  2016. && self.left.operator == "+" && self.left.is_string(compressor)) {
  2017. return self.left;
  2018. }
  2019. if (compressor.option("evaluate")) {
  2020. if (self.operator == "+") {
  2021. if (self.left instanceof AST_Constant
  2022. && self.right instanceof AST_Binary
  2023. && self.right.operator == "+"
  2024. && self.right.left instanceof AST_Constant
  2025. && self.right.is_string(compressor)) {
  2026. self = make_node(AST_Binary, self, {
  2027. operator: "+",
  2028. left: make_node(AST_String, null, {
  2029. value: "" + self.left.getValue() + self.right.left.getValue(),
  2030. start: self.left.start,
  2031. end: self.right.left.end
  2032. }),
  2033. right: self.right.right
  2034. });
  2035. }
  2036. if (self.right instanceof AST_Constant
  2037. && self.left instanceof AST_Binary
  2038. && self.left.operator == "+"
  2039. && self.left.right instanceof AST_Constant
  2040. && self.left.is_string(compressor)) {
  2041. self = make_node(AST_Binary, self, {
  2042. operator: "+",
  2043. left: self.left.left,
  2044. right: make_node(AST_String, null, {
  2045. value: "" + self.left.right.getValue() + self.right.getValue(),
  2046. start: self.left.right.start,
  2047. end: self.right.end
  2048. })
  2049. });
  2050. }
  2051. if (self.left instanceof AST_Binary
  2052. && self.left.operator == "+"
  2053. && self.left.is_string(compressor)
  2054. && self.left.right instanceof AST_Constant
  2055. && self.right instanceof AST_Binary
  2056. && self.right.operator == "+"
  2057. && self.right.left instanceof AST_Constant
  2058. && self.right.is_string(compressor)) {
  2059. self = make_node(AST_Binary, self, {
  2060. operator: "+",
  2061. left: make_node(AST_Binary, self.left, {
  2062. operator: "+",
  2063. left: self.left.left,
  2064. right: make_node(AST_String, null, {
  2065. value: "" + self.left.right.getValue() + self.right.left.getValue(),
  2066. start: self.left.right.start,
  2067. end: self.right.left.end
  2068. })
  2069. }),
  2070. right: self.right.right
  2071. });
  2072. }
  2073. }
  2074. }
  2075. // x * (y * z) ==> x * y * z
  2076. if (self.right instanceof AST_Binary
  2077. && self.right.operator == self.operator
  2078. && (self.operator == "*" || self.operator == "&&" || self.operator == "||"))
  2079. {
  2080. self.left = make_node(AST_Binary, self.left, {
  2081. operator : self.operator,
  2082. left : self.left,
  2083. right : self.right.left
  2084. });
  2085. self.right = self.right.right;
  2086. return self.transform(compressor);
  2087. }
  2088. return self.evaluate(compressor)[0];
  2089. });
  2090. OPT(AST_SymbolRef, function(self, compressor){
  2091. if (self.undeclared()) {
  2092. var defines = compressor.option("global_defs");
  2093. if (defines && defines.hasOwnProperty(self.name)) {
  2094. return make_node_from_constant(compressor, defines[self.name], self);
  2095. }
  2096. switch (self.name) {
  2097. case "undefined":
  2098. return make_node(AST_Undefined, self);
  2099. case "NaN":
  2100. return make_node(AST_NaN, self);
  2101. case "Infinity":
  2102. return make_node(AST_Infinity, self);
  2103. }
  2104. }
  2105. return self;
  2106. });
  2107. OPT(AST_Undefined, function(self, compressor){
  2108. if (compressor.option("unsafe")) {
  2109. var scope = compressor.find_parent(AST_Scope);
  2110. var undef = scope.find_variable("undefined");
  2111. if (undef) {
  2112. var ref = make_node(AST_SymbolRef, self, {
  2113. name : "undefined",
  2114. scope : scope,
  2115. thedef : undef
  2116. });
  2117. ref.reference();
  2118. return ref;
  2119. }
  2120. }
  2121. return self;
  2122. });
  2123. var ASSIGN_OPS = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ];
  2124. OPT(AST_Assign, function(self, compressor){
  2125. self = self.lift_sequences(compressor);
  2126. if (self.operator == "="
  2127. && self.left instanceof AST_SymbolRef
  2128. && self.right instanceof AST_Binary
  2129. && self.right.left instanceof AST_SymbolRef
  2130. && self.right.left.name == self.left.name
  2131. && member(self.right.operator, ASSIGN_OPS)) {
  2132. self.operator = self.right.operator + "=";
  2133. self.right = self.right.right;
  2134. }
  2135. return self;
  2136. });
  2137. OPT(AST_Conditional, function(self, compressor){
  2138. if (!compressor.option("conditionals")) return self;
  2139. if (self.condition instanceof AST_Seq) {
  2140. var car = self.condition.car;
  2141. self.condition = self.condition.cdr;
  2142. return AST_Seq.cons(car, self);
  2143. }
  2144. var cond = self.condition.evaluate(compressor);
  2145. if (cond.length > 1) {
  2146. if (cond[1]) {
  2147. compressor.warn("Condition always true [{file}:{line},{col}]", self.start);
  2148. return self.consequent;
  2149. } else {
  2150. compressor.warn("Condition always false [{file}:{line},{col}]", self.start);
  2151. return self.alternative;
  2152. }
  2153. }
  2154. var negated = cond[0].negate(compressor);
  2155. if (best_of(cond[0], negated) === negated) {
  2156. self = make_node(AST_Conditional, self, {
  2157. condition: negated,
  2158. consequent: self.alternative,
  2159. alternative: self.consequent
  2160. });
  2161. }
  2162. var consequent = self.consequent;
  2163. var alternative = self.alternative;
  2164. if (consequent instanceof AST_Assign
  2165. && alternative instanceof AST_Assign
  2166. && consequent.operator == alternative.operator
  2167. && consequent.left.equivalent_to(alternative.left)
  2168. ) {
  2169. /*
  2170. * Stuff like this:
  2171. * if (foo) exp = something; else exp = something_else;
  2172. * ==>
  2173. * exp = foo ? something : something_else;
  2174. */
  2175. return make_node(AST_Assign, self, {
  2176. operator: consequent.operator,
  2177. left: consequent.left,
  2178. right: make_node(AST_Conditional, self, {
  2179. condition: self.condition,
  2180. consequent: consequent.right,
  2181. alternative: alternative.right
  2182. })
  2183. });
  2184. }
  2185. if (consequent instanceof AST_Call
  2186. && alternative.TYPE === consequent.TYPE
  2187. && consequent.args.length == alternative.args.length
  2188. && consequent.expression.equivalent_to(alternative.expression)) {
  2189. if (consequent.args.length == 0) {
  2190. return make_node(AST_Seq, self, {
  2191. car: self.condition,
  2192. cdr: consequent
  2193. });
  2194. }
  2195. if (consequent.args.length == 1) {
  2196. consequent.args[0] = make_node(AST_Conditional, self, {
  2197. condition: self.condition,
  2198. consequent: consequent.args[0],
  2199. alternative: alternative.args[0]
  2200. });
  2201. return consequent;
  2202. }
  2203. }
  2204. return self;
  2205. });
  2206. OPT(AST_Boolean, function(self, compressor){
  2207. if (compressor.option("booleans")) {
  2208. var p = compressor.parent();
  2209. if (p instanceof AST_Binary && (p.operator == "=="
  2210. || p.operator == "!=")) {
  2211. compressor.warn("Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]", {
  2212. operator : p.operator,
  2213. value : self.value,
  2214. file : p.start.file,
  2215. line : p.start.line,
  2216. col : p.start.col,
  2217. });
  2218. return make_node(AST_Number, self, {
  2219. value: +self.value
  2220. });
  2221. }
  2222. return make_node(AST_UnaryPrefix, self, {
  2223. operator: "!",
  2224. expression: make_node(AST_Number, self, {
  2225. value: 1 - self.value
  2226. })
  2227. });
  2228. }
  2229. return self;
  2230. });
  2231. OPT(AST_Sub, function(self, compressor){
  2232. var prop = self.property;
  2233. if (prop instanceof AST_String && compressor.option("properties")) {
  2234. prop = prop.getValue();
  2235. if (RESERVED_WORDS(prop) ? compressor.option("screw_ie8") : is_identifier_string(prop)) {
  2236. return make_node(AST_Dot, self, {
  2237. expression : self.expression,
  2238. property : prop
  2239. });
  2240. }
  2241. var v = parseFloat(prop);
  2242. if (!isNaN(v) && v.toString() == prop) {
  2243. self.property = make_node(AST_Number, self.property, {
  2244. value: v
  2245. });
  2246. }
  2247. }
  2248. return self;
  2249. });
  2250. function literals_in_boolean_context(self, compressor) {
  2251. if (compressor.option("booleans") && compressor.in_boolean_context()) {
  2252. return make_node(AST_True, self);
  2253. }
  2254. return self;
  2255. };
  2256. OPT(AST_Array, literals_in_boolean_context);
  2257. OPT(AST_Object, literals_in_boolean_context);
  2258. OPT(AST_RegExp, literals_in_boolean_context);
  2259. })();