inline.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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_Array,
  35. AST_Assign,
  36. AST_Block,
  37. AST_Call,
  38. AST_Catch,
  39. AST_Class,
  40. AST_ClassExpression,
  41. AST_DefaultAssign,
  42. AST_DefClass,
  43. AST_Defun,
  44. AST_Destructuring,
  45. AST_EmptyStatement,
  46. AST_Expansion,
  47. AST_Export,
  48. AST_Function,
  49. AST_IterationStatement,
  50. AST_Lambda,
  51. AST_Node,
  52. AST_Number,
  53. AST_Object,
  54. AST_ObjectKeyVal,
  55. AST_PropAccess,
  56. AST_Return,
  57. AST_Scope,
  58. AST_SimpleStatement,
  59. AST_Statement,
  60. AST_SymbolDefun,
  61. AST_SymbolFunarg,
  62. AST_SymbolLambda,
  63. AST_SymbolRef,
  64. AST_SymbolVar,
  65. AST_This,
  66. AST_Toplevel,
  67. AST_UnaryPrefix,
  68. AST_Undefined,
  69. AST_Var,
  70. AST_VarDef,
  71. walk,
  72. _INLINE,
  73. _NOINLINE,
  74. _PURE
  75. } from "../ast.js";
  76. import { make_node, has_annotation } from "../utils/index.js";
  77. import "../size.js";
  78. import "./evaluate.js";
  79. import "./drop-side-effect-free.js";
  80. import "./reduce-vars.js";
  81. import { is_lhs } from "./inference.js";
  82. import {
  83. SQUEEZED,
  84. INLINED,
  85. UNUSED,
  86. has_flag,
  87. set_flag,
  88. } from "./compressor-flags.js";
  89. import {
  90. make_sequence,
  91. best_of,
  92. make_node_from_constant,
  93. identifier_atom,
  94. is_empty,
  95. is_func_expr,
  96. is_iife_call,
  97. is_reachable,
  98. is_recursive_ref,
  99. retain_top_func,
  100. } from "./common.js";
  101. function within_array_or_object_literal(compressor) {
  102. var node, level = 0;
  103. while (node = compressor.parent(level++)) {
  104. if (node instanceof AST_Statement) return false;
  105. if (node instanceof AST_Array
  106. || node instanceof AST_ObjectKeyVal
  107. || node instanceof AST_Object) {
  108. return true;
  109. }
  110. }
  111. return false;
  112. }
  113. function scope_encloses_variables_in_this_scope(scope, pulled_scope) {
  114. for (const enclosed of pulled_scope.enclosed) {
  115. if (pulled_scope.variables.has(enclosed.name)) {
  116. continue;
  117. }
  118. const looked_up = scope.find_variable(enclosed.name);
  119. if (looked_up) {
  120. if (looked_up === enclosed) continue;
  121. return true;
  122. }
  123. }
  124. return false;
  125. }
  126. export function inline_into_symbolref(self, compressor) {
  127. const parent = compressor.parent();
  128. if (compressor.option("reduce_vars") && is_lhs(self, parent) !== self) {
  129. const def = self.definition();
  130. const nearest_scope = compressor.find_scope();
  131. if (compressor.top_retain && def.global && compressor.top_retain(def)) {
  132. def.fixed = false;
  133. def.single_use = false;
  134. return self;
  135. }
  136. let fixed = self.fixed_value();
  137. let single_use = def.single_use
  138. && !(parent instanceof AST_Call
  139. && (parent.is_callee_pure(compressor))
  140. || has_annotation(parent, _NOINLINE))
  141. && !(parent instanceof AST_Export
  142. && fixed instanceof AST_Lambda
  143. && fixed.name);
  144. if (single_use && fixed instanceof AST_Node) {
  145. single_use =
  146. !fixed.has_side_effects(compressor)
  147. && !fixed.may_throw(compressor);
  148. }
  149. if (single_use && (fixed instanceof AST_Lambda || fixed instanceof AST_Class)) {
  150. if (retain_top_func(fixed, compressor)) {
  151. single_use = false;
  152. } else if (def.scope !== self.scope
  153. && (def.escaped == 1
  154. || has_flag(fixed, INLINED)
  155. || within_array_or_object_literal(compressor)
  156. || !compressor.option("reduce_funcs"))) {
  157. single_use = false;
  158. } else if (is_recursive_ref(compressor, def)) {
  159. single_use = false;
  160. } else if (def.scope !== self.scope || def.orig[0] instanceof AST_SymbolFunarg) {
  161. single_use = fixed.is_constant_expression(self.scope);
  162. if (single_use == "f") {
  163. var scope = self.scope;
  164. do {
  165. if (scope instanceof AST_Defun || is_func_expr(scope)) {
  166. set_flag(scope, INLINED);
  167. }
  168. } while (scope = scope.parent_scope);
  169. }
  170. }
  171. }
  172. if (single_use && (fixed instanceof AST_Lambda || fixed instanceof AST_Class)) {
  173. single_use =
  174. def.scope === self.scope
  175. && !scope_encloses_variables_in_this_scope(nearest_scope, fixed)
  176. || parent instanceof AST_Call
  177. && parent.expression === self
  178. && !scope_encloses_variables_in_this_scope(nearest_scope, fixed)
  179. && !(fixed.name && fixed.name.definition().recursive_refs > 0);
  180. }
  181. if (single_use && fixed) {
  182. if (fixed instanceof AST_DefClass) {
  183. set_flag(fixed, SQUEEZED);
  184. fixed = make_node(AST_ClassExpression, fixed, fixed);
  185. }
  186. if (fixed instanceof AST_Defun) {
  187. set_flag(fixed, SQUEEZED);
  188. fixed = make_node(AST_Function, fixed, fixed);
  189. }
  190. if (def.recursive_refs > 0 && fixed.name instanceof AST_SymbolDefun) {
  191. const defun_def = fixed.name.definition();
  192. let lambda_def = fixed.variables.get(fixed.name.name);
  193. let name = lambda_def && lambda_def.orig[0];
  194. if (!(name instanceof AST_SymbolLambda)) {
  195. name = make_node(AST_SymbolLambda, fixed.name, fixed.name);
  196. name.scope = fixed;
  197. fixed.name = name;
  198. lambda_def = fixed.def_function(name);
  199. }
  200. walk(fixed, node => {
  201. if (node instanceof AST_SymbolRef && node.definition() === defun_def) {
  202. node.thedef = lambda_def;
  203. lambda_def.references.push(node);
  204. }
  205. });
  206. }
  207. if (
  208. (fixed instanceof AST_Lambda || fixed instanceof AST_Class)
  209. && fixed.parent_scope !== nearest_scope
  210. ) {
  211. fixed = fixed.clone(true, compressor.get_toplevel());
  212. nearest_scope.add_child_scope(fixed);
  213. }
  214. return fixed.optimize(compressor);
  215. }
  216. // multiple uses
  217. if (fixed) {
  218. let replace;
  219. if (fixed instanceof AST_This) {
  220. if (!(def.orig[0] instanceof AST_SymbolFunarg)
  221. && def.references.every((ref) =>
  222. def.scope === ref.scope
  223. )) {
  224. replace = fixed;
  225. }
  226. } else {
  227. var ev = fixed.evaluate(compressor);
  228. if (
  229. ev !== fixed
  230. && (compressor.option("unsafe_regexp") || !(ev instanceof RegExp))
  231. ) {
  232. replace = make_node_from_constant(ev, fixed);
  233. }
  234. }
  235. if (replace) {
  236. const name_length = self.size(compressor);
  237. const replace_size = replace.size(compressor);
  238. let overhead = 0;
  239. if (compressor.option("unused") && !compressor.exposed(def)) {
  240. overhead =
  241. (name_length + 2 + replace_size) /
  242. (def.references.length - def.assignments);
  243. }
  244. if (replace_size <= name_length + overhead) {
  245. return replace;
  246. }
  247. }
  248. }
  249. }
  250. return self;
  251. }
  252. export function inline_into_call(self, fn, compressor) {
  253. var exp = self.expression;
  254. var simple_args = self.args.every((arg) => !(arg instanceof AST_Expansion));
  255. if (compressor.option("reduce_vars")
  256. && fn instanceof AST_SymbolRef
  257. && !has_annotation(self, _NOINLINE)
  258. ) {
  259. const fixed = fn.fixed_value();
  260. if (!retain_top_func(fixed, compressor)) {
  261. fn = fixed;
  262. }
  263. }
  264. var is_func = fn instanceof AST_Lambda;
  265. var stat = is_func && fn.body[0];
  266. var is_regular_func = is_func && !fn.is_generator && !fn.async;
  267. var can_inline = is_regular_func && compressor.option("inline") && !self.is_callee_pure(compressor);
  268. if (can_inline && stat instanceof AST_Return) {
  269. let returned = stat.value;
  270. if (!returned || returned.is_constant_expression()) {
  271. if (returned) {
  272. returned = returned.clone(true);
  273. } else {
  274. returned = make_node(AST_Undefined, self);
  275. }
  276. const args = self.args.concat(returned);
  277. return make_sequence(self, args).optimize(compressor);
  278. }
  279. // optimize identity function
  280. if (
  281. fn.argnames.length === 1
  282. && (fn.argnames[0] instanceof AST_SymbolFunarg)
  283. && self.args.length < 2
  284. && !(self.args[0] instanceof AST_Expansion)
  285. && returned instanceof AST_SymbolRef
  286. && returned.name === fn.argnames[0].name
  287. ) {
  288. const replacement =
  289. (self.args[0] || make_node(AST_Undefined)).optimize(compressor);
  290. let parent;
  291. if (
  292. replacement instanceof AST_PropAccess
  293. && (parent = compressor.parent()) instanceof AST_Call
  294. && parent.expression === self
  295. ) {
  296. // identity function was being used to remove `this`, like in
  297. //
  298. // id(bag.no_this)(...)
  299. //
  300. // Replace with a larger but more effish (0, bag.no_this) wrapper.
  301. return make_sequence(self, [
  302. make_node(AST_Number, self, { value: 0 }),
  303. replacement
  304. ]);
  305. }
  306. // replace call with first argument or undefined if none passed
  307. return replacement;
  308. }
  309. }
  310. if (can_inline) {
  311. var scope, in_loop, level = -1;
  312. let def;
  313. let returned_value;
  314. let nearest_scope;
  315. if (simple_args
  316. && !fn.uses_arguments
  317. && !(compressor.parent() instanceof AST_Class)
  318. && !(fn.name && fn instanceof AST_Function)
  319. && (returned_value = can_flatten_body(stat))
  320. && (exp === fn
  321. || has_annotation(self, _INLINE)
  322. || compressor.option("unused")
  323. && (def = exp.definition()).references.length == 1
  324. && !is_recursive_ref(compressor, def)
  325. && fn.is_constant_expression(exp.scope))
  326. && !has_annotation(self, _PURE | _NOINLINE)
  327. && !fn.contains_this()
  328. && can_inject_symbols()
  329. && (nearest_scope = compressor.find_scope())
  330. && !scope_encloses_variables_in_this_scope(nearest_scope, fn)
  331. && !(function in_default_assign() {
  332. // Due to the fact function parameters have their own scope
  333. // which can't use `var something` in the function body within,
  334. // we simply don't inline into DefaultAssign.
  335. let i = 0;
  336. let p;
  337. while ((p = compressor.parent(i++))) {
  338. if (p instanceof AST_DefaultAssign) return true;
  339. if (p instanceof AST_Block) break;
  340. }
  341. return false;
  342. })()
  343. && !(scope instanceof AST_Class)
  344. ) {
  345. set_flag(fn, SQUEEZED);
  346. nearest_scope.add_child_scope(fn);
  347. return make_sequence(self, flatten_fn(returned_value)).optimize(compressor);
  348. }
  349. }
  350. if (can_inline && has_annotation(self, _INLINE)) {
  351. set_flag(fn, SQUEEZED);
  352. fn = make_node(fn.CTOR === AST_Defun ? AST_Function : fn.CTOR, fn, fn);
  353. fn = fn.clone(true);
  354. fn.figure_out_scope({}, {
  355. parent_scope: compressor.find_scope(),
  356. toplevel: compressor.get_toplevel()
  357. });
  358. return make_node(AST_Call, self, {
  359. expression: fn,
  360. args: self.args,
  361. }).optimize(compressor);
  362. }
  363. const can_drop_this_call = is_regular_func && compressor.option("side_effects") && fn.body.every(is_empty);
  364. if (can_drop_this_call) {
  365. var args = self.args.concat(make_node(AST_Undefined, self));
  366. return make_sequence(self, args).optimize(compressor);
  367. }
  368. if (compressor.option("negate_iife")
  369. && compressor.parent() instanceof AST_SimpleStatement
  370. && is_iife_call(self)) {
  371. return self.negate(compressor, true);
  372. }
  373. var ev = self.evaluate(compressor);
  374. if (ev !== self) {
  375. ev = make_node_from_constant(ev, self).optimize(compressor);
  376. return best_of(compressor, ev, self);
  377. }
  378. return self;
  379. function return_value(stat) {
  380. if (!stat) return make_node(AST_Undefined, self);
  381. if (stat instanceof AST_Return) {
  382. if (!stat.value) return make_node(AST_Undefined, self);
  383. return stat.value.clone(true);
  384. }
  385. if (stat instanceof AST_SimpleStatement) {
  386. return make_node(AST_UnaryPrefix, stat, {
  387. operator: "void",
  388. expression: stat.body.clone(true)
  389. });
  390. }
  391. }
  392. function can_flatten_body(stat) {
  393. var body = fn.body;
  394. var len = body.length;
  395. if (compressor.option("inline") < 3) {
  396. return len == 1 && return_value(stat);
  397. }
  398. stat = null;
  399. for (var i = 0; i < len; i++) {
  400. var line = body[i];
  401. if (line instanceof AST_Var) {
  402. if (stat && !line.definitions.every((var_def) =>
  403. !var_def.value
  404. )) {
  405. return false;
  406. }
  407. } else if (stat) {
  408. return false;
  409. } else if (!(line instanceof AST_EmptyStatement)) {
  410. stat = line;
  411. }
  412. }
  413. return return_value(stat);
  414. }
  415. function can_inject_args(block_scoped, safe_to_inject) {
  416. for (var i = 0, len = fn.argnames.length; i < len; i++) {
  417. var arg = fn.argnames[i];
  418. if (arg instanceof AST_DefaultAssign) {
  419. if (has_flag(arg.left, UNUSED)) continue;
  420. return false;
  421. }
  422. if (arg instanceof AST_Destructuring) return false;
  423. if (arg instanceof AST_Expansion) {
  424. if (has_flag(arg.expression, UNUSED)) continue;
  425. return false;
  426. }
  427. if (has_flag(arg, UNUSED)) continue;
  428. if (!safe_to_inject
  429. || block_scoped.has(arg.name)
  430. || identifier_atom.has(arg.name)
  431. || scope.conflicting_def(arg.name)) {
  432. return false;
  433. }
  434. if (in_loop) in_loop.push(arg.definition());
  435. }
  436. return true;
  437. }
  438. function can_inject_vars(block_scoped, safe_to_inject) {
  439. var len = fn.body.length;
  440. for (var i = 0; i < len; i++) {
  441. var stat = fn.body[i];
  442. if (!(stat instanceof AST_Var)) continue;
  443. if (!safe_to_inject) return false;
  444. for (var j = stat.definitions.length; --j >= 0;) {
  445. var name = stat.definitions[j].name;
  446. if (name instanceof AST_Destructuring
  447. || block_scoped.has(name.name)
  448. || identifier_atom.has(name.name)
  449. || scope.conflicting_def(name.name)) {
  450. return false;
  451. }
  452. if (in_loop) in_loop.push(name.definition());
  453. }
  454. }
  455. return true;
  456. }
  457. function can_inject_symbols() {
  458. var block_scoped = new Set();
  459. do {
  460. scope = compressor.parent(++level);
  461. if (scope.is_block_scope() && scope.block_scope) {
  462. // TODO this is sometimes undefined during compression.
  463. // But it should always have a value!
  464. scope.block_scope.variables.forEach(function (variable) {
  465. block_scoped.add(variable.name);
  466. });
  467. }
  468. if (scope instanceof AST_Catch) {
  469. // TODO can we delete? AST_Catch is a block scope.
  470. if (scope.argname) {
  471. block_scoped.add(scope.argname.name);
  472. }
  473. } else if (scope instanceof AST_IterationStatement) {
  474. in_loop = [];
  475. } else if (scope instanceof AST_SymbolRef) {
  476. if (scope.fixed_value() instanceof AST_Scope) return false;
  477. }
  478. } while (!(scope instanceof AST_Scope));
  479. var safe_to_inject = !(scope instanceof AST_Toplevel) || compressor.toplevel.vars;
  480. var inline = compressor.option("inline");
  481. if (!can_inject_vars(block_scoped, inline >= 3 && safe_to_inject)) return false;
  482. if (!can_inject_args(block_scoped, inline >= 2 && safe_to_inject)) return false;
  483. return !in_loop || in_loop.length == 0 || !is_reachable(fn, in_loop);
  484. }
  485. function append_var(decls, expressions, name, value) {
  486. var def = name.definition();
  487. // Name already exists, only when a function argument had the same name
  488. const already_appended = scope.variables.has(name.name);
  489. if (!already_appended) {
  490. scope.variables.set(name.name, def);
  491. scope.enclosed.push(def);
  492. decls.push(make_node(AST_VarDef, name, {
  493. name: name,
  494. value: null
  495. }));
  496. }
  497. var sym = make_node(AST_SymbolRef, name, name);
  498. def.references.push(sym);
  499. if (value) expressions.push(make_node(AST_Assign, self, {
  500. operator: "=",
  501. logical: false,
  502. left: sym,
  503. right: value.clone()
  504. }));
  505. }
  506. function flatten_args(decls, expressions) {
  507. var len = fn.argnames.length;
  508. for (var i = self.args.length; --i >= len;) {
  509. expressions.push(self.args[i]);
  510. }
  511. for (i = len; --i >= 0;) {
  512. var name = fn.argnames[i];
  513. var value = self.args[i];
  514. if (has_flag(name, UNUSED) || !name.name || scope.conflicting_def(name.name)) {
  515. if (value) expressions.push(value);
  516. } else {
  517. var symbol = make_node(AST_SymbolVar, name, name);
  518. name.definition().orig.push(symbol);
  519. if (!value && in_loop) value = make_node(AST_Undefined, self);
  520. append_var(decls, expressions, symbol, value);
  521. }
  522. }
  523. decls.reverse();
  524. expressions.reverse();
  525. }
  526. function flatten_vars(decls, expressions) {
  527. var pos = expressions.length;
  528. for (var i = 0, lines = fn.body.length; i < lines; i++) {
  529. var stat = fn.body[i];
  530. if (!(stat instanceof AST_Var)) continue;
  531. for (var j = 0, defs = stat.definitions.length; j < defs; j++) {
  532. var var_def = stat.definitions[j];
  533. var name = var_def.name;
  534. append_var(decls, expressions, name, var_def.value);
  535. if (in_loop && fn.argnames.every((argname) =>
  536. argname.name != name.name
  537. )) {
  538. var def = fn.variables.get(name.name);
  539. var sym = make_node(AST_SymbolRef, name, name);
  540. def.references.push(sym);
  541. expressions.splice(pos++, 0, make_node(AST_Assign, var_def, {
  542. operator: "=",
  543. logical: false,
  544. left: sym,
  545. right: make_node(AST_Undefined, name)
  546. }));
  547. }
  548. }
  549. }
  550. }
  551. function flatten_fn(returned_value) {
  552. var decls = [];
  553. var expressions = [];
  554. flatten_args(decls, expressions);
  555. flatten_vars(decls, expressions);
  556. expressions.push(returned_value);
  557. if (decls.length) {
  558. const i = scope.body.indexOf(compressor.parent(level - 1)) + 1;
  559. scope.body.splice(i, 0, make_node(AST_Var, fn, {
  560. definitions: decls
  561. }));
  562. }
  563. return expressions.map(exp => exp.clone(true));
  564. }
  565. }