reduce-vars.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  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. import {
  34. AST_Accessor,
  35. AST_Array,
  36. AST_Assign,
  37. AST_Await,
  38. AST_Binary,
  39. AST_Block,
  40. AST_Call,
  41. AST_Case,
  42. AST_Chain,
  43. AST_Class,
  44. AST_ClassStaticBlock,
  45. AST_ClassExpression,
  46. AST_Conditional,
  47. AST_Default,
  48. AST_Defun,
  49. AST_Destructuring,
  50. AST_Do,
  51. AST_Exit,
  52. AST_Expansion,
  53. AST_For,
  54. AST_ForIn,
  55. AST_If,
  56. AST_LabeledStatement,
  57. AST_Lambda,
  58. AST_New,
  59. AST_Node,
  60. AST_Number,
  61. AST_ObjectKeyVal,
  62. AST_PropAccess,
  63. AST_Sequence,
  64. AST_SimpleStatement,
  65. AST_Symbol,
  66. AST_SymbolCatch,
  67. AST_SymbolConst,
  68. AST_SymbolDefun,
  69. AST_SymbolFunarg,
  70. AST_SymbolLambda,
  71. AST_SymbolRef,
  72. AST_This,
  73. AST_Toplevel,
  74. AST_Try,
  75. AST_Unary,
  76. AST_UnaryPrefix,
  77. AST_Undefined,
  78. AST_VarDef,
  79. AST_While,
  80. AST_Yield,
  81. walk,
  82. walk_body,
  83. _INLINE,
  84. _NOINLINE,
  85. _PURE
  86. } from "../ast.js";
  87. import { HOP, make_node, noop } from "../utils/index.js";
  88. import { lazy_op, is_modified } from "./inference.js";
  89. import { INLINED, clear_flag } from "./compressor-flags.js";
  90. import { read_property, has_break_or_continue, is_recursive_ref } from "./common.js";
  91. // Define the method AST_Node#reduce_vars, which goes through the AST in
  92. // execution order to perform basic flow analysis
  93. function def_reduce_vars(node, func) {
  94. node.DEFMETHOD("reduce_vars", func);
  95. }
  96. def_reduce_vars(AST_Node, noop);
  97. function reset_def(compressor, def) {
  98. def.assignments = 0;
  99. def.chained = false;
  100. def.direct_access = false;
  101. def.escaped = 0;
  102. def.recursive_refs = 0;
  103. def.references = [];
  104. def.single_use = undefined;
  105. if (def.scope.pinned()) {
  106. def.fixed = false;
  107. } else if (def.orig[0] instanceof AST_SymbolConst || !compressor.exposed(def)) {
  108. def.fixed = def.init;
  109. } else {
  110. def.fixed = false;
  111. }
  112. }
  113. function reset_variables(tw, compressor, node) {
  114. node.variables.forEach(function(def) {
  115. reset_def(compressor, def);
  116. if (def.fixed === null) {
  117. tw.defs_to_safe_ids.set(def.id, tw.safe_ids);
  118. mark(tw, def, true);
  119. } else if (def.fixed) {
  120. tw.loop_ids.set(def.id, tw.in_loop);
  121. mark(tw, def, true);
  122. }
  123. });
  124. }
  125. function reset_block_variables(compressor, node) {
  126. if (node.block_scope) node.block_scope.variables.forEach((def) => {
  127. reset_def(compressor, def);
  128. });
  129. }
  130. function push(tw) {
  131. tw.safe_ids = Object.create(tw.safe_ids);
  132. }
  133. function pop(tw) {
  134. tw.safe_ids = Object.getPrototypeOf(tw.safe_ids);
  135. }
  136. function mark(tw, def, safe) {
  137. tw.safe_ids[def.id] = safe;
  138. }
  139. function safe_to_read(tw, def) {
  140. if (def.single_use == "m") return false;
  141. if (tw.safe_ids[def.id]) {
  142. if (def.fixed == null) {
  143. var orig = def.orig[0];
  144. if (orig instanceof AST_SymbolFunarg || orig.name == "arguments") return false;
  145. def.fixed = make_node(AST_Undefined, orig);
  146. }
  147. return true;
  148. }
  149. return def.fixed instanceof AST_Defun;
  150. }
  151. function safe_to_assign(tw, def, scope, value) {
  152. if (def.fixed === undefined) return true;
  153. let def_safe_ids;
  154. if (def.fixed === null
  155. && (def_safe_ids = tw.defs_to_safe_ids.get(def.id))
  156. ) {
  157. def_safe_ids[def.id] = false;
  158. tw.defs_to_safe_ids.delete(def.id);
  159. return true;
  160. }
  161. if (!HOP(tw.safe_ids, def.id)) return false;
  162. if (!safe_to_read(tw, def)) return false;
  163. if (def.fixed === false) return false;
  164. if (def.fixed != null && (!value || def.references.length > def.assignments)) return false;
  165. if (def.fixed instanceof AST_Defun) {
  166. return value instanceof AST_Node && def.fixed.parent_scope === scope;
  167. }
  168. return def.orig.every((sym) => {
  169. return !(sym instanceof AST_SymbolConst
  170. || sym instanceof AST_SymbolDefun
  171. || sym instanceof AST_SymbolLambda);
  172. });
  173. }
  174. function ref_once(tw, compressor, def) {
  175. return compressor.option("unused")
  176. && !def.scope.pinned()
  177. && def.references.length - def.recursive_refs == 1
  178. && tw.loop_ids.get(def.id) === tw.in_loop;
  179. }
  180. function is_immutable(value) {
  181. if (!value) return false;
  182. return value.is_constant()
  183. || value instanceof AST_Lambda
  184. || value instanceof AST_This;
  185. }
  186. // A definition "escapes" when its value can leave the point of use.
  187. // Example: `a = b || c`
  188. // In this example, "b" and "c" are escaping, because they're going into "a"
  189. //
  190. // def.escaped is != 0 when it escapes.
  191. //
  192. // When greater than 1, it means that N chained properties will be read off
  193. // of that def before an escape occurs. This is useful for evaluating
  194. // property accesses, where you need to know when to stop.
  195. function mark_escaped(tw, d, scope, node, value, level = 0, depth = 1) {
  196. var parent = tw.parent(level);
  197. if (value) {
  198. if (value.is_constant()) return;
  199. if (value instanceof AST_ClassExpression) return;
  200. }
  201. if (
  202. parent instanceof AST_Assign && (parent.operator === "=" || parent.logical) && node === parent.right
  203. || parent instanceof AST_Call && (node !== parent.expression || parent instanceof AST_New)
  204. || parent instanceof AST_Exit && node === parent.value && node.scope !== d.scope
  205. || parent instanceof AST_VarDef && node === parent.value
  206. || parent instanceof AST_Yield && node === parent.value && node.scope !== d.scope
  207. ) {
  208. if (depth > 1 && !(value && value.is_constant_expression(scope))) depth = 1;
  209. if (!d.escaped || d.escaped > depth) d.escaped = depth;
  210. return;
  211. } else if (
  212. parent instanceof AST_Array
  213. || parent instanceof AST_Await
  214. || parent instanceof AST_Binary && lazy_op.has(parent.operator)
  215. || parent instanceof AST_Conditional && node !== parent.condition
  216. || parent instanceof AST_Expansion
  217. || parent instanceof AST_Sequence && node === parent.tail_node()
  218. ) {
  219. mark_escaped(tw, d, scope, parent, parent, level + 1, depth);
  220. } else if (parent instanceof AST_ObjectKeyVal && node === parent.value) {
  221. var obj = tw.parent(level + 1);
  222. mark_escaped(tw, d, scope, obj, obj, level + 2, depth);
  223. } else if (parent instanceof AST_PropAccess && node === parent.expression) {
  224. value = read_property(value, parent.property);
  225. mark_escaped(tw, d, scope, parent, value, level + 1, depth + 1);
  226. if (value) return;
  227. }
  228. if (level > 0) return;
  229. if (parent instanceof AST_Sequence && node !== parent.tail_node()) return;
  230. if (parent instanceof AST_SimpleStatement) return;
  231. d.direct_access = true;
  232. }
  233. const suppress = node => walk(node, node => {
  234. if (!(node instanceof AST_Symbol)) return;
  235. var d = node.definition();
  236. if (!d) return;
  237. if (node instanceof AST_SymbolRef) d.references.push(node);
  238. d.fixed = false;
  239. });
  240. def_reduce_vars(AST_Accessor, function(tw, descend, compressor) {
  241. push(tw);
  242. reset_variables(tw, compressor, this);
  243. descend();
  244. pop(tw);
  245. return true;
  246. });
  247. def_reduce_vars(AST_Assign, function(tw, descend, compressor) {
  248. var node = this;
  249. if (node.left instanceof AST_Destructuring) {
  250. suppress(node.left);
  251. return;
  252. }
  253. const finish_walk = () => {
  254. if (node.logical) {
  255. node.left.walk(tw);
  256. push(tw);
  257. node.right.walk(tw);
  258. pop(tw);
  259. return true;
  260. }
  261. };
  262. var sym = node.left;
  263. if (!(sym instanceof AST_SymbolRef)) return finish_walk();
  264. var def = sym.definition();
  265. var safe = safe_to_assign(tw, def, sym.scope, node.right);
  266. def.assignments++;
  267. if (!safe) return finish_walk();
  268. var fixed = def.fixed;
  269. if (!fixed && node.operator != "=" && !node.logical) return finish_walk();
  270. var eq = node.operator == "=";
  271. var value = eq ? node.right : node;
  272. if (is_modified(compressor, tw, node, value, 0)) return finish_walk();
  273. def.references.push(sym);
  274. if (!node.logical) {
  275. if (!eq) def.chained = true;
  276. def.fixed = eq ? function() {
  277. return node.right;
  278. } : function() {
  279. return make_node(AST_Binary, node, {
  280. operator: node.operator.slice(0, -1),
  281. left: fixed instanceof AST_Node ? fixed : fixed(),
  282. right: node.right
  283. });
  284. };
  285. }
  286. if (node.logical) {
  287. mark(tw, def, false);
  288. push(tw);
  289. node.right.walk(tw);
  290. pop(tw);
  291. return true;
  292. }
  293. mark(tw, def, false);
  294. node.right.walk(tw);
  295. mark(tw, def, true);
  296. mark_escaped(tw, def, sym.scope, node, value, 0, 1);
  297. return true;
  298. });
  299. def_reduce_vars(AST_Binary, function(tw) {
  300. if (!lazy_op.has(this.operator)) return;
  301. this.left.walk(tw);
  302. push(tw);
  303. this.right.walk(tw);
  304. pop(tw);
  305. return true;
  306. });
  307. def_reduce_vars(AST_Block, function(tw, descend, compressor) {
  308. reset_block_variables(compressor, this);
  309. });
  310. def_reduce_vars(AST_Case, function(tw) {
  311. push(tw);
  312. this.expression.walk(tw);
  313. pop(tw);
  314. push(tw);
  315. walk_body(this, tw);
  316. pop(tw);
  317. return true;
  318. });
  319. def_reduce_vars(AST_Class, function(tw, descend) {
  320. clear_flag(this, INLINED);
  321. push(tw);
  322. descend();
  323. pop(tw);
  324. return true;
  325. });
  326. def_reduce_vars(AST_ClassStaticBlock, function(tw, descend, compressor) {
  327. reset_block_variables(compressor, this);
  328. });
  329. def_reduce_vars(AST_Conditional, function(tw) {
  330. this.condition.walk(tw);
  331. push(tw);
  332. this.consequent.walk(tw);
  333. pop(tw);
  334. push(tw);
  335. this.alternative.walk(tw);
  336. pop(tw);
  337. return true;
  338. });
  339. def_reduce_vars(AST_Chain, function(tw, descend) {
  340. // Chains' conditions apply left-to-right, cumulatively.
  341. // If we walk normally we don't go in that order because we would pop before pushing again
  342. // Solution: AST_PropAccess and AST_Call push when they are optional, and never pop.
  343. // Then we pop everything when they are done being walked.
  344. const safe_ids = tw.safe_ids;
  345. descend();
  346. // Unroll back to start
  347. tw.safe_ids = safe_ids;
  348. return true;
  349. });
  350. def_reduce_vars(AST_Call, function (tw) {
  351. this.expression.walk(tw);
  352. if (this.optional) {
  353. // Never pop -- it's popped at AST_Chain above
  354. push(tw);
  355. }
  356. for (const arg of this.args) arg.walk(tw);
  357. return true;
  358. });
  359. def_reduce_vars(AST_PropAccess, function (tw) {
  360. if (!this.optional) return;
  361. this.expression.walk(tw);
  362. // Never pop -- it's popped at AST_Chain above
  363. push(tw);
  364. if (this.property instanceof AST_Node) this.property.walk(tw);
  365. return true;
  366. });
  367. def_reduce_vars(AST_Default, function(tw, descend) {
  368. push(tw);
  369. descend();
  370. pop(tw);
  371. return true;
  372. });
  373. function mark_lambda(tw, descend, compressor) {
  374. clear_flag(this, INLINED);
  375. push(tw);
  376. reset_variables(tw, compressor, this);
  377. if (this.uses_arguments) {
  378. descend();
  379. pop(tw);
  380. return;
  381. }
  382. var iife;
  383. if (!this.name
  384. && (iife = tw.parent()) instanceof AST_Call
  385. && iife.expression === this
  386. && !iife.args.some(arg => arg instanceof AST_Expansion)
  387. && this.argnames.every(arg_name => arg_name instanceof AST_Symbol)
  388. ) {
  389. // Virtually turn IIFE parameters into variable definitions:
  390. // (function(a,b) {...})(c,d) => (function() {var a=c,b=d; ...})()
  391. // So existing transformation rules can work on them.
  392. this.argnames.forEach((arg, i) => {
  393. if (!arg.definition) return;
  394. var d = arg.definition();
  395. // Avoid setting fixed when there's more than one origin for a variable value
  396. if (d.orig.length > 1) return;
  397. if (d.fixed === undefined && (!this.uses_arguments || tw.has_directive("use strict"))) {
  398. d.fixed = function() {
  399. return iife.args[i] || make_node(AST_Undefined, iife);
  400. };
  401. tw.loop_ids.set(d.id, tw.in_loop);
  402. mark(tw, d, true);
  403. } else {
  404. d.fixed = false;
  405. }
  406. });
  407. }
  408. descend();
  409. pop(tw);
  410. return true;
  411. }
  412. def_reduce_vars(AST_Lambda, mark_lambda);
  413. def_reduce_vars(AST_Do, function(tw, descend, compressor) {
  414. reset_block_variables(compressor, this);
  415. const saved_loop = tw.in_loop;
  416. tw.in_loop = this;
  417. push(tw);
  418. this.body.walk(tw);
  419. if (has_break_or_continue(this)) {
  420. pop(tw);
  421. push(tw);
  422. }
  423. this.condition.walk(tw);
  424. pop(tw);
  425. tw.in_loop = saved_loop;
  426. return true;
  427. });
  428. def_reduce_vars(AST_For, function(tw, descend, compressor) {
  429. reset_block_variables(compressor, this);
  430. if (this.init) this.init.walk(tw);
  431. const saved_loop = tw.in_loop;
  432. tw.in_loop = this;
  433. push(tw);
  434. if (this.condition) this.condition.walk(tw);
  435. this.body.walk(tw);
  436. if (this.step) {
  437. if (has_break_or_continue(this)) {
  438. pop(tw);
  439. push(tw);
  440. }
  441. this.step.walk(tw);
  442. }
  443. pop(tw);
  444. tw.in_loop = saved_loop;
  445. return true;
  446. });
  447. def_reduce_vars(AST_ForIn, function(tw, descend, compressor) {
  448. reset_block_variables(compressor, this);
  449. suppress(this.init);
  450. this.object.walk(tw);
  451. const saved_loop = tw.in_loop;
  452. tw.in_loop = this;
  453. push(tw);
  454. this.body.walk(tw);
  455. pop(tw);
  456. tw.in_loop = saved_loop;
  457. return true;
  458. });
  459. def_reduce_vars(AST_If, function(tw) {
  460. this.condition.walk(tw);
  461. push(tw);
  462. this.body.walk(tw);
  463. pop(tw);
  464. if (this.alternative) {
  465. push(tw);
  466. this.alternative.walk(tw);
  467. pop(tw);
  468. }
  469. return true;
  470. });
  471. def_reduce_vars(AST_LabeledStatement, function(tw) {
  472. push(tw);
  473. this.body.walk(tw);
  474. pop(tw);
  475. return true;
  476. });
  477. def_reduce_vars(AST_SymbolCatch, function() {
  478. this.definition().fixed = false;
  479. });
  480. def_reduce_vars(AST_SymbolRef, function(tw, descend, compressor) {
  481. var d = this.definition();
  482. d.references.push(this);
  483. if (d.references.length == 1
  484. && !d.fixed
  485. && d.orig[0] instanceof AST_SymbolDefun) {
  486. tw.loop_ids.set(d.id, tw.in_loop);
  487. }
  488. var fixed_value;
  489. if (d.fixed === undefined || !safe_to_read(tw, d)) {
  490. d.fixed = false;
  491. } else if (d.fixed) {
  492. fixed_value = this.fixed_value();
  493. if (
  494. fixed_value instanceof AST_Lambda
  495. && is_recursive_ref(tw, d)
  496. ) {
  497. d.recursive_refs++;
  498. } else if (fixed_value
  499. && !compressor.exposed(d)
  500. && ref_once(tw, compressor, d)
  501. ) {
  502. d.single_use =
  503. fixed_value instanceof AST_Lambda && !fixed_value.pinned()
  504. || fixed_value instanceof AST_Class
  505. || d.scope === this.scope && fixed_value.is_constant_expression();
  506. } else {
  507. d.single_use = false;
  508. }
  509. if (is_modified(compressor, tw, this, fixed_value, 0, is_immutable(fixed_value))) {
  510. if (d.single_use) {
  511. d.single_use = "m";
  512. } else {
  513. d.fixed = false;
  514. }
  515. }
  516. }
  517. mark_escaped(tw, d, this.scope, this, fixed_value, 0, 1);
  518. });
  519. def_reduce_vars(AST_Toplevel, function(tw, descend, compressor) {
  520. this.globals.forEach(function(def) {
  521. reset_def(compressor, def);
  522. });
  523. reset_variables(tw, compressor, this);
  524. });
  525. def_reduce_vars(AST_Try, function(tw, descend, compressor) {
  526. reset_block_variables(compressor, this);
  527. push(tw);
  528. walk_body(this, tw);
  529. pop(tw);
  530. if (this.bcatch) {
  531. push(tw);
  532. this.bcatch.walk(tw);
  533. pop(tw);
  534. }
  535. if (this.bfinally) this.bfinally.walk(tw);
  536. return true;
  537. });
  538. def_reduce_vars(AST_Unary, function(tw) {
  539. var node = this;
  540. if (node.operator !== "++" && node.operator !== "--") return;
  541. var exp = node.expression;
  542. if (!(exp instanceof AST_SymbolRef)) return;
  543. var def = exp.definition();
  544. var safe = safe_to_assign(tw, def, exp.scope, true);
  545. def.assignments++;
  546. if (!safe) return;
  547. var fixed = def.fixed;
  548. if (!fixed) return;
  549. def.references.push(exp);
  550. def.chained = true;
  551. def.fixed = function() {
  552. return make_node(AST_Binary, node, {
  553. operator: node.operator.slice(0, -1),
  554. left: make_node(AST_UnaryPrefix, node, {
  555. operator: "+",
  556. expression: fixed instanceof AST_Node ? fixed : fixed()
  557. }),
  558. right: make_node(AST_Number, node, {
  559. value: 1
  560. })
  561. });
  562. };
  563. mark(tw, def, true);
  564. return true;
  565. });
  566. def_reduce_vars(AST_VarDef, function(tw, descend) {
  567. var node = this;
  568. if (node.name instanceof AST_Destructuring) {
  569. suppress(node.name);
  570. return;
  571. }
  572. var d = node.name.definition();
  573. if (node.value) {
  574. if (safe_to_assign(tw, d, node.name.scope, node.value)) {
  575. d.fixed = function() {
  576. return node.value;
  577. };
  578. tw.loop_ids.set(d.id, tw.in_loop);
  579. mark(tw, d, false);
  580. descend();
  581. mark(tw, d, true);
  582. return true;
  583. } else {
  584. d.fixed = false;
  585. }
  586. }
  587. });
  588. def_reduce_vars(AST_While, function(tw, descend, compressor) {
  589. reset_block_variables(compressor, this);
  590. const saved_loop = tw.in_loop;
  591. tw.in_loop = this;
  592. push(tw);
  593. descend();
  594. pop(tw);
  595. tw.in_loop = saved_loop;
  596. return true;
  597. });