drop-unused.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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_Assign,
  36. AST_BlockStatement,
  37. AST_Class,
  38. AST_ClassExpression,
  39. AST_ClassStaticBlock,
  40. AST_DefaultAssign,
  41. AST_DefClass,
  42. AST_Definitions,
  43. AST_Defun,
  44. AST_Destructuring,
  45. AST_EmptyStatement,
  46. AST_Expansion,
  47. AST_Export,
  48. AST_For,
  49. AST_ForIn,
  50. AST_Function,
  51. AST_LabeledStatement,
  52. AST_Lambda,
  53. AST_Number,
  54. AST_Scope,
  55. AST_SimpleStatement,
  56. AST_SymbolBlockDeclaration,
  57. AST_SymbolCatch,
  58. AST_SymbolDeclaration,
  59. AST_SymbolFunarg,
  60. AST_SymbolRef,
  61. AST_SymbolVar,
  62. AST_Toplevel,
  63. AST_Unary,
  64. AST_Var,
  65. TreeTransformer,
  66. TreeWalker,
  67. walk,
  68. _INLINE,
  69. _NOINLINE,
  70. _PURE
  71. } from "../ast.js";
  72. import {
  73. keep_name,
  74. make_node,
  75. map_add,
  76. MAP,
  77. remove,
  78. return_false,
  79. } from "../utils/index.js";
  80. import { SymbolDef } from "../scope.js";
  81. import {
  82. WRITE_ONLY,
  83. UNUSED,
  84. has_flag,
  85. set_flag,
  86. } from "./compressor-flags.js";
  87. import {
  88. make_sequence,
  89. maintain_this_binding,
  90. is_empty,
  91. is_ref_of,
  92. can_be_evicted_from_block,
  93. } from "./common.js";
  94. const r_keep_assign = /keep_assign/;
  95. /** Drop unused variables from this scope */
  96. AST_Scope.DEFMETHOD("drop_unused", function(compressor) {
  97. if (!compressor.option("unused")) return;
  98. if (compressor.has_directive("use asm")) return;
  99. var self = this;
  100. if (self.pinned()) return;
  101. var drop_funcs = !(self instanceof AST_Toplevel) || compressor.toplevel.funcs;
  102. var drop_vars = !(self instanceof AST_Toplevel) || compressor.toplevel.vars;
  103. const assign_as_unused = r_keep_assign.test(compressor.option("unused")) ? return_false : function(node) {
  104. if (node instanceof AST_Assign
  105. && !node.logical
  106. && (has_flag(node, WRITE_ONLY) || node.operator == "=")
  107. ) {
  108. return node.left;
  109. }
  110. if (node instanceof AST_Unary && has_flag(node, WRITE_ONLY)) {
  111. return node.expression;
  112. }
  113. };
  114. var in_use_ids = new Map();
  115. var fixed_ids = new Map();
  116. if (self instanceof AST_Toplevel && compressor.top_retain) {
  117. self.variables.forEach(function(def) {
  118. if (compressor.top_retain(def) && !in_use_ids.has(def.id)) {
  119. in_use_ids.set(def.id, def);
  120. }
  121. });
  122. }
  123. var var_defs_by_id = new Map();
  124. var initializations = new Map();
  125. // pass 1: find out which symbols are directly used in
  126. // this scope (not in nested scopes).
  127. var scope = this;
  128. var tw = new TreeWalker(function(node, descend) {
  129. if (node instanceof AST_Lambda && node.uses_arguments && !tw.has_directive("use strict")) {
  130. node.argnames.forEach(function(argname) {
  131. if (!(argname instanceof AST_SymbolDeclaration)) return;
  132. var def = argname.definition();
  133. if (!in_use_ids.has(def.id)) {
  134. in_use_ids.set(def.id, def);
  135. }
  136. });
  137. }
  138. if (node === self) return;
  139. if (node instanceof AST_Class) {
  140. if (node.has_side_effects(compressor)) {
  141. node.visit_nondeferred_class_parts(tw);
  142. }
  143. }
  144. if (node instanceof AST_Defun || node instanceof AST_DefClass) {
  145. var node_def = node.name.definition();
  146. const in_export = tw.parent() instanceof AST_Export;
  147. if (in_export || !drop_funcs && scope === self) {
  148. if (node_def.global && !in_use_ids.has(node_def.id)) {
  149. in_use_ids.set(node_def.id, node_def);
  150. }
  151. }
  152. map_add(initializations, node_def.id, node);
  153. return true; // don't go in nested scopes
  154. }
  155. if (node instanceof AST_SymbolFunarg && scope === self) {
  156. map_add(var_defs_by_id, node.definition().id, node);
  157. }
  158. if (node instanceof AST_Definitions && scope === self) {
  159. const in_export = tw.parent() instanceof AST_Export;
  160. node.definitions.forEach(function(def) {
  161. if (def.name instanceof AST_SymbolVar) {
  162. map_add(var_defs_by_id, def.name.definition().id, def);
  163. }
  164. if (in_export || !drop_vars) {
  165. walk(def.name, node => {
  166. if (node instanceof AST_SymbolDeclaration) {
  167. const def = node.definition();
  168. if (def.global && !in_use_ids.has(def.id)) {
  169. in_use_ids.set(def.id, def);
  170. }
  171. }
  172. });
  173. }
  174. if (def.name instanceof AST_Destructuring) {
  175. def.walk(tw);
  176. }
  177. if (def.name instanceof AST_SymbolDeclaration && def.value) {
  178. var node_def = def.name.definition();
  179. map_add(initializations, node_def.id, def.value);
  180. if (!node_def.chained && def.name.fixed_value() === def.value) {
  181. fixed_ids.set(node_def.id, def);
  182. }
  183. if (def.value.has_side_effects(compressor)) {
  184. def.value.walk(tw);
  185. }
  186. }
  187. });
  188. return true;
  189. }
  190. return scan_ref_scoped(node, descend);
  191. });
  192. self.walk(tw);
  193. // pass 2: for every used symbol we need to walk its
  194. // initialization code to figure out if it uses other
  195. // symbols (that may not be in_use).
  196. tw = new TreeWalker(scan_ref_scoped);
  197. in_use_ids.forEach(function (def) {
  198. var init = initializations.get(def.id);
  199. if (init) init.forEach(function(init) {
  200. init.walk(tw);
  201. });
  202. });
  203. // pass 3: we should drop declarations not in_use
  204. var tt = new TreeTransformer(
  205. function before(node, descend, in_list) {
  206. var parent = tt.parent();
  207. if (drop_vars) {
  208. const sym = assign_as_unused(node);
  209. if (sym instanceof AST_SymbolRef) {
  210. var def = sym.definition();
  211. var in_use = in_use_ids.has(def.id);
  212. if (node instanceof AST_Assign) {
  213. if (!in_use || fixed_ids.has(def.id) && fixed_ids.get(def.id) !== node) {
  214. return maintain_this_binding(parent, node, node.right.transform(tt));
  215. }
  216. } else if (!in_use) {
  217. return in_list ? MAP.skip : make_node(AST_Number, node, { value: 0 });
  218. }
  219. }
  220. }
  221. if (scope !== self) return;
  222. var def;
  223. if (node.name
  224. && (node instanceof AST_ClassExpression
  225. && !keep_name(compressor.option("keep_classnames"), (def = node.name.definition()).name)
  226. || node instanceof AST_Function
  227. && !keep_name(compressor.option("keep_fnames"), (def = node.name.definition()).name))) {
  228. // any declarations with same name will overshadow
  229. // name of this anonymous function and can therefore
  230. // never be used anywhere
  231. if (!in_use_ids.has(def.id) || def.orig.length > 1) node.name = null;
  232. }
  233. if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) {
  234. var trim = !compressor.option("keep_fargs");
  235. for (var a = node.argnames, i = a.length; --i >= 0;) {
  236. var sym = a[i];
  237. if (sym instanceof AST_Expansion) {
  238. sym = sym.expression;
  239. }
  240. if (sym instanceof AST_DefaultAssign) {
  241. sym = sym.left;
  242. }
  243. // Do not drop destructuring arguments.
  244. // They constitute a type assertion of sorts
  245. if (
  246. !(sym instanceof AST_Destructuring)
  247. && !in_use_ids.has(sym.definition().id)
  248. ) {
  249. set_flag(sym, UNUSED);
  250. if (trim) {
  251. a.pop();
  252. }
  253. } else {
  254. trim = false;
  255. }
  256. }
  257. }
  258. if (node instanceof AST_DefClass && node !== self) {
  259. const def = node.name.definition();
  260. descend(node, this);
  261. const keep_class = def.global && !drop_funcs || in_use_ids.has(def.id);
  262. if (!keep_class) {
  263. const kept = node.drop_side_effect_free(compressor);
  264. if (kept == null) {
  265. def.eliminated++;
  266. return in_list ? MAP.skip : make_node(AST_EmptyStatement, node);
  267. }
  268. return kept;
  269. }
  270. return node;
  271. }
  272. if (node instanceof AST_Defun && node !== self) {
  273. const def = node.name.definition();
  274. const keep = def.global && !drop_funcs || in_use_ids.has(def.id);
  275. if (!keep) {
  276. def.eliminated++;
  277. return in_list ? MAP.skip : make_node(AST_EmptyStatement, node);
  278. }
  279. }
  280. if (node instanceof AST_Definitions && !(parent instanceof AST_ForIn && parent.init === node)) {
  281. var drop_block = !(parent instanceof AST_Toplevel) && !(node instanceof AST_Var);
  282. // place uninitialized names at the start
  283. var body = [], head = [], tail = [];
  284. // for unused names whose initialization has
  285. // side effects, we can cascade the init. code
  286. // into the next one, or next statement.
  287. var side_effects = [];
  288. node.definitions.forEach(function(def) {
  289. if (def.value) def.value = def.value.transform(tt);
  290. var is_destructure = def.name instanceof AST_Destructuring;
  291. var sym = is_destructure
  292. ? new SymbolDef(null, { name: "<destructure>" }) /* fake SymbolDef */
  293. : def.name.definition();
  294. if (drop_block && sym.global) return tail.push(def);
  295. if (!(drop_vars || drop_block)
  296. || is_destructure
  297. && (def.name.names.length
  298. || def.name.is_array
  299. || compressor.option("pure_getters") != true)
  300. || in_use_ids.has(sym.id)
  301. ) {
  302. if (def.value && fixed_ids.has(sym.id) && fixed_ids.get(sym.id) !== def) {
  303. def.value = def.value.drop_side_effect_free(compressor);
  304. }
  305. if (def.name instanceof AST_SymbolVar) {
  306. var var_defs = var_defs_by_id.get(sym.id);
  307. if (var_defs.length > 1 && (!def.value || sym.orig.indexOf(def.name) > sym.eliminated)) {
  308. if (def.value) {
  309. var ref = make_node(AST_SymbolRef, def.name, def.name);
  310. sym.references.push(ref);
  311. var assign = make_node(AST_Assign, def, {
  312. operator: "=",
  313. logical: false,
  314. left: ref,
  315. right: def.value
  316. });
  317. if (fixed_ids.get(sym.id) === def) {
  318. fixed_ids.set(sym.id, assign);
  319. }
  320. side_effects.push(assign.transform(tt));
  321. }
  322. remove(var_defs, def);
  323. sym.eliminated++;
  324. return;
  325. }
  326. }
  327. if (def.value) {
  328. if (side_effects.length > 0) {
  329. if (tail.length > 0) {
  330. side_effects.push(def.value);
  331. def.value = make_sequence(def.value, side_effects);
  332. } else {
  333. body.push(make_node(AST_SimpleStatement, node, {
  334. body: make_sequence(node, side_effects)
  335. }));
  336. }
  337. side_effects = [];
  338. }
  339. tail.push(def);
  340. } else {
  341. head.push(def);
  342. }
  343. } else if (sym.orig[0] instanceof AST_SymbolCatch) {
  344. var value = def.value && def.value.drop_side_effect_free(compressor);
  345. if (value) side_effects.push(value);
  346. def.value = null;
  347. head.push(def);
  348. } else {
  349. var value = def.value && def.value.drop_side_effect_free(compressor);
  350. if (value) {
  351. side_effects.push(value);
  352. }
  353. sym.eliminated++;
  354. }
  355. });
  356. if (head.length > 0 || tail.length > 0) {
  357. node.definitions = head.concat(tail);
  358. body.push(node);
  359. }
  360. if (side_effects.length > 0) {
  361. body.push(make_node(AST_SimpleStatement, node, {
  362. body: make_sequence(node, side_effects)
  363. }));
  364. }
  365. switch (body.length) {
  366. case 0:
  367. return in_list ? MAP.skip : make_node(AST_EmptyStatement, node);
  368. case 1:
  369. return body[0];
  370. default:
  371. return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, { body });
  372. }
  373. }
  374. // certain combination of unused name + side effect leads to:
  375. // https://github.com/mishoo/UglifyJS2/issues/44
  376. // https://github.com/mishoo/UglifyJS2/issues/1830
  377. // https://github.com/mishoo/UglifyJS2/issues/1838
  378. // that's an invalid AST.
  379. // We fix it at this stage by moving the `var` outside the `for`.
  380. if (node instanceof AST_For) {
  381. descend(node, this);
  382. var block;
  383. if (node.init instanceof AST_BlockStatement) {
  384. block = node.init;
  385. node.init = block.body.pop();
  386. block.body.push(node);
  387. }
  388. if (node.init instanceof AST_SimpleStatement) {
  389. node.init = node.init.body;
  390. } else if (is_empty(node.init)) {
  391. node.init = null;
  392. }
  393. return !block ? node : in_list ? MAP.splice(block.body) : block;
  394. }
  395. if (node instanceof AST_LabeledStatement
  396. && node.body instanceof AST_For
  397. ) {
  398. descend(node, this);
  399. if (node.body instanceof AST_BlockStatement) {
  400. var block = node.body;
  401. node.body = block.body.pop();
  402. block.body.push(node);
  403. return in_list ? MAP.splice(block.body) : block;
  404. }
  405. return node;
  406. }
  407. if (node instanceof AST_BlockStatement) {
  408. descend(node, this);
  409. if (in_list && node.body.every(can_be_evicted_from_block)) {
  410. return MAP.splice(node.body);
  411. }
  412. return node;
  413. }
  414. if (node instanceof AST_Scope && !(node instanceof AST_ClassStaticBlock)) {
  415. const save_scope = scope;
  416. scope = node;
  417. descend(node, this);
  418. scope = save_scope;
  419. return node;
  420. }
  421. }
  422. );
  423. self.transform(tt);
  424. function scan_ref_scoped(node, descend) {
  425. var node_def;
  426. const sym = assign_as_unused(node);
  427. if (sym instanceof AST_SymbolRef
  428. && !is_ref_of(node.left, AST_SymbolBlockDeclaration)
  429. && self.variables.get(sym.name) === (node_def = sym.definition())
  430. ) {
  431. if (node instanceof AST_Assign) {
  432. node.right.walk(tw);
  433. if (!node_def.chained && node.left.fixed_value() === node.right) {
  434. fixed_ids.set(node_def.id, node);
  435. }
  436. }
  437. return true;
  438. }
  439. if (node instanceof AST_SymbolRef) {
  440. node_def = node.definition();
  441. if (!in_use_ids.has(node_def.id)) {
  442. in_use_ids.set(node_def.id, node_def);
  443. if (node_def.orig[0] instanceof AST_SymbolCatch) {
  444. const redef = node_def.scope.is_block_scope()
  445. && node_def.scope.get_defun_scope().variables.get(node_def.name);
  446. if (redef) in_use_ids.set(redef.id, redef);
  447. }
  448. }
  449. return true;
  450. }
  451. if (node instanceof AST_Class) {
  452. descend();
  453. return true;
  454. }
  455. if (node instanceof AST_Scope && !(node instanceof AST_ClassStaticBlock)) {
  456. var save_scope = scope;
  457. scope = node;
  458. descend();
  459. scope = save_scope;
  460. return true;
  461. }
  462. }
  463. });