drop-unused.js 19 KB

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