scope.js 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  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. import {
  35. defaults,
  36. keep_name,
  37. mergeSort,
  38. push_uniq,
  39. make_node,
  40. return_false,
  41. return_this,
  42. return_true,
  43. string_template,
  44. } from "./utils/index.js";
  45. import {
  46. AST_Arrow,
  47. AST_Block,
  48. AST_Call,
  49. AST_Catch,
  50. AST_Class,
  51. AST_Conditional,
  52. AST_DefClass,
  53. AST_Defun,
  54. AST_Destructuring,
  55. AST_Dot,
  56. AST_DotHash,
  57. AST_Export,
  58. AST_For,
  59. AST_ForIn,
  60. AST_Function,
  61. AST_Import,
  62. AST_IterationStatement,
  63. AST_Label,
  64. AST_LabeledStatement,
  65. AST_LabelRef,
  66. AST_Lambda,
  67. AST_LoopControl,
  68. AST_NameMapping,
  69. AST_Node,
  70. AST_Scope,
  71. AST_Sequence,
  72. AST_String,
  73. AST_Sub,
  74. AST_Switch,
  75. AST_SwitchBranch,
  76. AST_Symbol,
  77. AST_SymbolBlockDeclaration,
  78. AST_SymbolCatch,
  79. AST_SymbolClass,
  80. AST_SymbolConst,
  81. AST_SymbolDefClass,
  82. AST_SymbolDefun,
  83. AST_SymbolExport,
  84. AST_SymbolFunarg,
  85. AST_SymbolImport,
  86. AST_SymbolLambda,
  87. AST_SymbolLet,
  88. AST_SymbolMethod,
  89. AST_SymbolRef,
  90. AST_SymbolVar,
  91. AST_Toplevel,
  92. AST_VarDef,
  93. AST_With,
  94. TreeWalker,
  95. walk
  96. } from "./ast.js";
  97. import {
  98. ALL_RESERVED_WORDS,
  99. js_error,
  100. } from "./parse.js";
  101. const MASK_EXPORT_DONT_MANGLE = 1 << 0;
  102. const MASK_EXPORT_WANT_MANGLE = 1 << 1;
  103. let function_defs = null;
  104. let unmangleable_names = null;
  105. /**
  106. * When defined, there is a function declaration somewhere that's inside of a block.
  107. * See https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-block-level-function-declarations-web-legacy-compatibility-semantics
  108. */
  109. let scopes_with_block_defuns = null;
  110. class SymbolDef {
  111. constructor(scope, orig, init) {
  112. this.name = orig.name;
  113. this.orig = [ orig ];
  114. this.init = init;
  115. this.eliminated = 0;
  116. this.assignments = 0;
  117. this.scope = scope;
  118. this.replaced = 0;
  119. this.global = false;
  120. this.export = 0;
  121. this.mangled_name = null;
  122. this.undeclared = false;
  123. this.id = SymbolDef.next_id++;
  124. this.chained = false;
  125. this.direct_access = false;
  126. this.escaped = 0;
  127. this.recursive_refs = 0;
  128. this.references = [];
  129. this.should_replace = undefined;
  130. this.single_use = false;
  131. this.fixed = false;
  132. Object.seal(this);
  133. }
  134. fixed_value() {
  135. if (!this.fixed || this.fixed instanceof AST_Node) return this.fixed;
  136. return this.fixed();
  137. }
  138. unmangleable(options) {
  139. if (!options) options = {};
  140. if (
  141. function_defs &&
  142. function_defs.has(this.id) &&
  143. keep_name(options.keep_fnames, this.orig[0].name)
  144. ) return true;
  145. return this.global && !options.toplevel
  146. || (this.export & MASK_EXPORT_DONT_MANGLE)
  147. || this.undeclared
  148. || !options.eval && this.scope.pinned()
  149. || (this.orig[0] instanceof AST_SymbolLambda
  150. || this.orig[0] instanceof AST_SymbolDefun) && keep_name(options.keep_fnames, this.orig[0].name)
  151. || this.orig[0] instanceof AST_SymbolMethod
  152. || (this.orig[0] instanceof AST_SymbolClass
  153. || this.orig[0] instanceof AST_SymbolDefClass) && keep_name(options.keep_classnames, this.orig[0].name);
  154. }
  155. mangle(options) {
  156. const cache = options.cache && options.cache.props;
  157. if (this.global && cache && cache.has(this.name)) {
  158. this.mangled_name = cache.get(this.name);
  159. } else if (!this.mangled_name && !this.unmangleable(options)) {
  160. var s = this.scope;
  161. var sym = this.orig[0];
  162. if (options.ie8 && sym instanceof AST_SymbolLambda)
  163. s = s.parent_scope;
  164. const redefinition = redefined_catch_def(this);
  165. this.mangled_name = redefinition
  166. ? redefinition.mangled_name || redefinition.name
  167. : s.next_mangled(options, this);
  168. if (this.global && cache) {
  169. cache.set(this.name, this.mangled_name);
  170. }
  171. }
  172. }
  173. }
  174. SymbolDef.next_id = 1;
  175. function redefined_catch_def(def) {
  176. if (def.orig[0] instanceof AST_SymbolCatch
  177. && def.scope.is_block_scope()
  178. ) {
  179. return def.scope.get_defun_scope().variables.get(def.name);
  180. }
  181. }
  182. AST_Scope.DEFMETHOD("figure_out_scope", function(options, { parent_scope = null, toplevel = this } = {}) {
  183. options = defaults(options, {
  184. cache: null,
  185. ie8: false,
  186. safari10: false,
  187. });
  188. if (!(toplevel instanceof AST_Toplevel)) {
  189. throw new Error("Invalid toplevel scope");
  190. }
  191. // pass 1: setup scope chaining and handle definitions
  192. var scope = this.parent_scope = parent_scope;
  193. var labels = new Map();
  194. var defun = null;
  195. var in_destructuring = null;
  196. var for_scopes = [];
  197. var tw = new TreeWalker((node, descend) => {
  198. if (node.is_block_scope()) {
  199. const save_scope = scope;
  200. node.block_scope = scope = new AST_Scope(node);
  201. scope._block_scope = true;
  202. // AST_Try in the AST sadly *is* (not has) a body itself,
  203. // and its catch and finally branches are children of the AST_Try itself
  204. const parent_scope = node instanceof AST_Catch
  205. ? save_scope.parent_scope
  206. : save_scope;
  207. scope.init_scope_vars(parent_scope);
  208. scope.uses_with = save_scope.uses_with;
  209. scope.uses_eval = save_scope.uses_eval;
  210. if (options.safari10) {
  211. if (node instanceof AST_For || node instanceof AST_ForIn) {
  212. for_scopes.push(scope);
  213. }
  214. }
  215. if (node instanceof AST_Switch) {
  216. // XXX: HACK! Ensure the switch expression gets the correct scope (the parent scope) and the body gets the contained scope
  217. // AST_Switch has a scope within the body, but it itself "is a block scope"
  218. // This means the switched expression has to belong to the outer scope
  219. // while the body inside belongs to the switch itself.
  220. // This is pretty nasty and warrants an AST change similar to AST_Try (read above)
  221. const the_block_scope = scope;
  222. scope = save_scope;
  223. node.expression.walk(tw);
  224. scope = the_block_scope;
  225. for (let i = 0; i < node.body.length; i++) {
  226. node.body[i].walk(tw);
  227. }
  228. } else {
  229. descend();
  230. }
  231. scope = save_scope;
  232. return true;
  233. }
  234. if (node instanceof AST_Destructuring) {
  235. const save_destructuring = in_destructuring;
  236. in_destructuring = node;
  237. descend();
  238. in_destructuring = save_destructuring;
  239. return true;
  240. }
  241. if (node instanceof AST_Scope) {
  242. node.init_scope_vars(scope);
  243. var save_scope = scope;
  244. var save_defun = defun;
  245. var save_labels = labels;
  246. defun = scope = node;
  247. labels = new Map();
  248. descend();
  249. scope = save_scope;
  250. defun = save_defun;
  251. labels = save_labels;
  252. return true; // don't descend again in TreeWalker
  253. }
  254. if (node instanceof AST_LabeledStatement) {
  255. var l = node.label;
  256. if (labels.has(l.name)) {
  257. throw new Error(string_template("Label {name} defined twice", l));
  258. }
  259. labels.set(l.name, l);
  260. descend();
  261. labels.delete(l.name);
  262. return true; // no descend again
  263. }
  264. if (node instanceof AST_With) {
  265. for (var s = scope; s; s = s.parent_scope)
  266. s.uses_with = true;
  267. return;
  268. }
  269. if (node instanceof AST_Symbol) {
  270. node.scope = scope;
  271. }
  272. if (node instanceof AST_Label) {
  273. node.thedef = node;
  274. node.references = [];
  275. }
  276. if (node instanceof AST_SymbolLambda) {
  277. defun.def_function(node, node.name == "arguments" ? undefined : defun);
  278. } else if (node instanceof AST_SymbolDefun) {
  279. // Careful here, the scope where this should be defined is
  280. // the parent scope. The reason is that we enter a new
  281. // scope when we encounter the AST_Defun node (which is
  282. // instanceof AST_Scope) but we get to the symbol a bit
  283. // later.
  284. const closest_scope = defun.parent_scope;
  285. // In strict mode, function definitions are block-scoped
  286. node.scope = tw.directives["use strict"]
  287. ? closest_scope
  288. : closest_scope.get_defun_scope();
  289. mark_export(node.scope.def_function(node, defun), 1);
  290. } else if (node instanceof AST_SymbolClass) {
  291. mark_export(defun.def_variable(node, defun), 1);
  292. } else if (node instanceof AST_SymbolImport) {
  293. scope.def_variable(node);
  294. } else if (node instanceof AST_SymbolDefClass) {
  295. // This deals with the name of the class being available
  296. // inside the class.
  297. mark_export((node.scope = defun.parent_scope).def_function(node, defun), 1);
  298. } else if (
  299. node instanceof AST_SymbolVar
  300. || node instanceof AST_SymbolLet
  301. || node instanceof AST_SymbolConst
  302. || node instanceof AST_SymbolCatch
  303. ) {
  304. var def;
  305. if (node instanceof AST_SymbolBlockDeclaration) {
  306. def = scope.def_variable(node, null);
  307. } else {
  308. def = defun.def_variable(node, node.TYPE == "SymbolVar" ? null : undefined);
  309. }
  310. if (!def.orig.every((sym) => {
  311. if (sym === node) return true;
  312. if (node instanceof AST_SymbolBlockDeclaration) {
  313. return sym instanceof AST_SymbolLambda;
  314. }
  315. return !(sym instanceof AST_SymbolLet || sym instanceof AST_SymbolConst);
  316. })) {
  317. js_error(
  318. `"${node.name}" is redeclared`,
  319. node.start.file,
  320. node.start.line,
  321. node.start.col,
  322. node.start.pos
  323. );
  324. }
  325. if (!(node instanceof AST_SymbolFunarg)) mark_export(def, 2);
  326. if (defun !== scope) {
  327. node.mark_enclosed();
  328. var def = scope.find_variable(node);
  329. if (node.thedef !== def) {
  330. node.thedef = def;
  331. node.reference();
  332. }
  333. }
  334. } else if (node instanceof AST_LabelRef) {
  335. var sym = labels.get(node.name);
  336. if (!sym) throw new Error(string_template("Undefined label {name} [{line},{col}]", {
  337. name: node.name,
  338. line: node.start.line,
  339. col: node.start.col
  340. }));
  341. node.thedef = sym;
  342. }
  343. if (!(scope instanceof AST_Toplevel) && (node instanceof AST_Export || node instanceof AST_Import)) {
  344. js_error(
  345. `"${node.TYPE}" statement may only appear at the top level`,
  346. node.start.file,
  347. node.start.line,
  348. node.start.col,
  349. node.start.pos
  350. );
  351. }
  352. });
  353. this.walk(tw);
  354. function mark_export(def, level) {
  355. if (in_destructuring) {
  356. var i = 0;
  357. do {
  358. level++;
  359. } while (tw.parent(i++) !== in_destructuring);
  360. }
  361. var node = tw.parent(level);
  362. if (def.export = node instanceof AST_Export ? MASK_EXPORT_DONT_MANGLE : 0) {
  363. var exported = node.exported_definition;
  364. if ((exported instanceof AST_Defun || exported instanceof AST_DefClass) && node.is_default) {
  365. def.export = MASK_EXPORT_WANT_MANGLE;
  366. }
  367. }
  368. }
  369. // pass 2: find back references and eval
  370. const is_toplevel = this instanceof AST_Toplevel;
  371. if (is_toplevel) {
  372. this.globals = new Map();
  373. }
  374. var tw = new TreeWalker(node => {
  375. if (node instanceof AST_LoopControl && node.label) {
  376. node.label.thedef.references.push(node);
  377. return true;
  378. }
  379. if (node instanceof AST_SymbolRef) {
  380. var name = node.name;
  381. if (name == "eval" && tw.parent() instanceof AST_Call) {
  382. for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope) {
  383. s.uses_eval = true;
  384. }
  385. }
  386. var sym;
  387. if (tw.parent() instanceof AST_NameMapping && tw.parent(1).module_name
  388. || !(sym = node.scope.find_variable(name))) {
  389. sym = toplevel.def_global(node);
  390. if (node instanceof AST_SymbolExport) sym.export = MASK_EXPORT_DONT_MANGLE;
  391. } else if (sym.scope instanceof AST_Lambda && name == "arguments") {
  392. sym.scope.uses_arguments = true;
  393. }
  394. node.thedef = sym;
  395. node.reference();
  396. if (node.scope.is_block_scope()
  397. && !(sym.orig[0] instanceof AST_SymbolBlockDeclaration)) {
  398. node.scope = node.scope.get_defun_scope();
  399. }
  400. return true;
  401. }
  402. // ensure mangling works if catch reuses a scope variable
  403. var def;
  404. if (node instanceof AST_SymbolCatch && (def = redefined_catch_def(node.definition()))) {
  405. var s = node.scope;
  406. while (s) {
  407. push_uniq(s.enclosed, def);
  408. if (s === def.scope) break;
  409. s = s.parent_scope;
  410. }
  411. }
  412. });
  413. this.walk(tw);
  414. // pass 3: work around IE8 and Safari catch scope bugs
  415. if (options.ie8 || options.safari10) {
  416. walk(this, node => {
  417. if (node instanceof AST_SymbolCatch) {
  418. var name = node.name;
  419. var refs = node.thedef.references;
  420. var scope = node.scope.get_defun_scope();
  421. var def = scope.find_variable(name)
  422. || toplevel.globals.get(name)
  423. || scope.def_variable(node);
  424. refs.forEach(function(ref) {
  425. ref.thedef = def;
  426. ref.reference();
  427. });
  428. node.thedef = def;
  429. node.reference();
  430. return true;
  431. }
  432. });
  433. }
  434. // pass 4: add symbol definitions to loop scopes
  435. // Safari/Webkit bug workaround - loop init let variable shadowing argument.
  436. // https://github.com/mishoo/UglifyJS2/issues/1753
  437. // https://bugs.webkit.org/show_bug.cgi?id=171041
  438. if (options.safari10) {
  439. for (const scope of for_scopes) {
  440. scope.parent_scope.variables.forEach(function(def) {
  441. push_uniq(scope.enclosed, def);
  442. });
  443. }
  444. }
  445. });
  446. AST_Toplevel.DEFMETHOD("def_global", function(node) {
  447. var globals = this.globals, name = node.name;
  448. if (globals.has(name)) {
  449. return globals.get(name);
  450. } else {
  451. var g = new SymbolDef(this, node);
  452. g.undeclared = true;
  453. g.global = true;
  454. globals.set(name, g);
  455. return g;
  456. }
  457. });
  458. AST_Scope.DEFMETHOD("init_scope_vars", function(parent_scope) {
  459. this.variables = new Map(); // map name to AST_SymbolVar (variables defined in this scope; includes functions)
  460. this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement
  461. this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval`
  462. this.parent_scope = parent_scope; // the parent scope
  463. this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes
  464. this.cname = -1; // the current index for mangling functions/variables
  465. });
  466. AST_Scope.DEFMETHOD("conflicting_def", function (name) {
  467. return (
  468. this.enclosed.find(def => def.name === name)
  469. || this.variables.has(name)
  470. || (this.parent_scope && this.parent_scope.conflicting_def(name))
  471. );
  472. });
  473. AST_Scope.DEFMETHOD("conflicting_def_shallow", function (name) {
  474. return (
  475. this.enclosed.find(def => def.name === name)
  476. || this.variables.has(name)
  477. );
  478. });
  479. AST_Scope.DEFMETHOD("add_child_scope", function (scope) {
  480. // `scope` is going to be moved into `this` right now.
  481. // Update the required scopes' information
  482. if (scope.parent_scope === this) return;
  483. scope.parent_scope = this;
  484. // TODO uses_with, uses_eval, etc
  485. const scope_ancestry = (() => {
  486. const ancestry = [];
  487. let cur = this;
  488. do {
  489. ancestry.push(cur);
  490. } while ((cur = cur.parent_scope));
  491. ancestry.reverse();
  492. return ancestry;
  493. })();
  494. const new_scope_enclosed_set = new Set(scope.enclosed);
  495. const to_enclose = [];
  496. for (const scope_topdown of scope_ancestry) {
  497. to_enclose.forEach(e => push_uniq(scope_topdown.enclosed, e));
  498. for (const def of scope_topdown.variables.values()) {
  499. if (new_scope_enclosed_set.has(def)) {
  500. push_uniq(to_enclose, def);
  501. push_uniq(scope_topdown.enclosed, def);
  502. }
  503. }
  504. }
  505. });
  506. function find_scopes_visible_from(scopes) {
  507. const found_scopes = new Set();
  508. for (const scope of new Set(scopes)) {
  509. (function bubble_up(scope) {
  510. if (scope == null || found_scopes.has(scope)) return;
  511. found_scopes.add(scope);
  512. bubble_up(scope.parent_scope);
  513. })(scope);
  514. }
  515. return [...found_scopes];
  516. }
  517. // Creates a symbol during compression
  518. AST_Scope.DEFMETHOD("create_symbol", function(SymClass, {
  519. source,
  520. tentative_name,
  521. scope,
  522. conflict_scopes = [scope],
  523. init = null
  524. } = {}) {
  525. let symbol_name;
  526. conflict_scopes = find_scopes_visible_from(conflict_scopes);
  527. if (tentative_name) {
  528. // Implement hygiene (no new names are conflicting with existing names)
  529. tentative_name =
  530. symbol_name =
  531. tentative_name.replace(/(?:^[^a-z_$]|[^a-z0-9_$])/ig, "_");
  532. let i = 0;
  533. while (conflict_scopes.find(s => s.conflicting_def_shallow(symbol_name))) {
  534. symbol_name = tentative_name + "$" + i++;
  535. }
  536. }
  537. if (!symbol_name) {
  538. throw new Error("No symbol name could be generated in create_symbol()");
  539. }
  540. const symbol = make_node(SymClass, source, {
  541. name: symbol_name,
  542. scope
  543. });
  544. this.def_variable(symbol, init || null);
  545. symbol.mark_enclosed();
  546. return symbol;
  547. });
  548. AST_Node.DEFMETHOD("is_block_scope", return_false);
  549. AST_Class.DEFMETHOD("is_block_scope", return_false);
  550. AST_Lambda.DEFMETHOD("is_block_scope", return_false);
  551. AST_Toplevel.DEFMETHOD("is_block_scope", return_false);
  552. AST_SwitchBranch.DEFMETHOD("is_block_scope", return_false);
  553. AST_Block.DEFMETHOD("is_block_scope", return_true);
  554. AST_Scope.DEFMETHOD("is_block_scope", function () {
  555. return this._block_scope || false;
  556. });
  557. AST_IterationStatement.DEFMETHOD("is_block_scope", return_true);
  558. AST_Lambda.DEFMETHOD("init_scope_vars", function() {
  559. AST_Scope.prototype.init_scope_vars.apply(this, arguments);
  560. this.uses_arguments = false;
  561. this.def_variable(new AST_SymbolFunarg({
  562. name: "arguments",
  563. start: this.start,
  564. end: this.end
  565. }));
  566. });
  567. AST_Arrow.DEFMETHOD("init_scope_vars", function() {
  568. AST_Scope.prototype.init_scope_vars.apply(this, arguments);
  569. this.uses_arguments = false;
  570. });
  571. AST_Symbol.DEFMETHOD("mark_enclosed", function() {
  572. var def = this.definition();
  573. var s = this.scope;
  574. while (s) {
  575. push_uniq(s.enclosed, def);
  576. if (s === def.scope) break;
  577. s = s.parent_scope;
  578. }
  579. });
  580. AST_Symbol.DEFMETHOD("reference", function() {
  581. this.definition().references.push(this);
  582. this.mark_enclosed();
  583. });
  584. AST_Scope.DEFMETHOD("find_variable", function(name) {
  585. if (name instanceof AST_Symbol) name = name.name;
  586. return this.variables.get(name)
  587. || (this.parent_scope && this.parent_scope.find_variable(name));
  588. });
  589. AST_Scope.DEFMETHOD("def_function", function(symbol, init) {
  590. var def = this.def_variable(symbol, init);
  591. if (!def.init || def.init instanceof AST_Defun) def.init = init;
  592. return def;
  593. });
  594. AST_Scope.DEFMETHOD("def_variable", function(symbol, init) {
  595. var def = this.variables.get(symbol.name);
  596. if (def) {
  597. def.orig.push(symbol);
  598. if (def.init && (def.scope !== symbol.scope || def.init instanceof AST_Function)) {
  599. def.init = init;
  600. }
  601. } else {
  602. def = new SymbolDef(this, symbol, init);
  603. this.variables.set(symbol.name, def);
  604. def.global = !this.parent_scope;
  605. }
  606. return symbol.thedef = def;
  607. });
  608. function next_mangled(scope, options) {
  609. let defun_scope;
  610. if (
  611. scopes_with_block_defuns
  612. && (defun_scope = scope.get_defun_scope())
  613. && scopes_with_block_defuns.has(defun_scope)
  614. ) {
  615. scope = defun_scope;
  616. }
  617. var ext = scope.enclosed;
  618. var nth_identifier = options.nth_identifier;
  619. out: while (true) {
  620. var m = nth_identifier.get(++scope.cname);
  621. if (ALL_RESERVED_WORDS.has(m)) continue; // skip over "do"
  622. // https://github.com/mishoo/UglifyJS2/issues/242 -- do not
  623. // shadow a name reserved from mangling.
  624. if (options.reserved.has(m)) continue;
  625. // Functions with short names might collide with base54 output
  626. // and therefore cause collisions when keep_fnames is true.
  627. if (unmangleable_names && unmangleable_names.has(m)) continue out;
  628. // we must ensure that the mangled name does not shadow a name
  629. // from some parent scope that is referenced in this or in
  630. // inner scopes.
  631. for (let i = ext.length; --i >= 0;) {
  632. const def = ext[i];
  633. const name = def.mangled_name || (def.unmangleable(options) && def.name);
  634. if (m == name) continue out;
  635. }
  636. return m;
  637. }
  638. }
  639. AST_Scope.DEFMETHOD("next_mangled", function(options) {
  640. return next_mangled(this, options);
  641. });
  642. AST_Toplevel.DEFMETHOD("next_mangled", function(options) {
  643. let name;
  644. const mangled_names = this.mangled_names;
  645. do {
  646. name = next_mangled(this, options);
  647. } while (mangled_names.has(name));
  648. return name;
  649. });
  650. AST_Function.DEFMETHOD("next_mangled", function(options, def) {
  651. // #179, #326
  652. // in Safari strict mode, something like (function x(x){...}) is a syntax error;
  653. // a function expression's argument cannot shadow the function expression's name
  654. var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition();
  655. // the function's mangled_name is null when keep_fnames is true
  656. var tricky_name = tricky_def ? tricky_def.mangled_name || tricky_def.name : null;
  657. while (true) {
  658. var name = next_mangled(this, options);
  659. if (!tricky_name || tricky_name != name)
  660. return name;
  661. }
  662. });
  663. AST_Symbol.DEFMETHOD("unmangleable", function(options) {
  664. var def = this.definition();
  665. return !def || def.unmangleable(options);
  666. });
  667. // labels are always mangleable
  668. AST_Label.DEFMETHOD("unmangleable", return_false);
  669. AST_Symbol.DEFMETHOD("unreferenced", function() {
  670. return !this.definition().references.length && !this.scope.pinned();
  671. });
  672. AST_Symbol.DEFMETHOD("definition", function() {
  673. return this.thedef;
  674. });
  675. AST_Symbol.DEFMETHOD("global", function() {
  676. return this.thedef.global;
  677. });
  678. AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options) {
  679. options = defaults(options, {
  680. eval : false,
  681. nth_identifier : base54,
  682. ie8 : false,
  683. keep_classnames: false,
  684. keep_fnames : false,
  685. module : false,
  686. reserved : [],
  687. toplevel : false,
  688. });
  689. if (options.module) options.toplevel = true;
  690. if (!Array.isArray(options.reserved)
  691. && !(options.reserved instanceof Set)
  692. ) {
  693. options.reserved = [];
  694. }
  695. options.reserved = new Set(options.reserved);
  696. // Never mangle arguments
  697. options.reserved.add("arguments");
  698. return options;
  699. });
  700. AST_Toplevel.DEFMETHOD("mangle_names", function(options) {
  701. options = this._default_mangler_options(options);
  702. var nth_identifier = options.nth_identifier;
  703. // We only need to mangle declaration nodes. Special logic wired
  704. // into the code generator will display the mangled name if it's
  705. // present (and for AST_SymbolRef-s it'll use the mangled name of
  706. // the AST_SymbolDeclaration that it points to).
  707. var lname = -1;
  708. var to_mangle = [];
  709. if (options.keep_fnames) {
  710. function_defs = new Set();
  711. }
  712. const mangled_names = this.mangled_names = new Set();
  713. unmangleable_names = new Set();
  714. if (options.cache) {
  715. this.globals.forEach(collect);
  716. if (options.cache.props) {
  717. options.cache.props.forEach(function(mangled_name) {
  718. mangled_names.add(mangled_name);
  719. });
  720. }
  721. }
  722. var tw = new TreeWalker(function(node, descend) {
  723. if (node instanceof AST_LabeledStatement) {
  724. // lname is incremented when we get to the AST_Label
  725. var save_nesting = lname;
  726. descend();
  727. lname = save_nesting;
  728. return true; // don't descend again in TreeWalker
  729. }
  730. if (
  731. node instanceof AST_Defun
  732. && !(tw.parent() instanceof AST_Scope)
  733. ) {
  734. scopes_with_block_defuns = scopes_with_block_defuns || new Set();
  735. scopes_with_block_defuns.add(node.parent_scope.get_defun_scope());
  736. }
  737. if (node instanceof AST_Scope) {
  738. node.variables.forEach(collect);
  739. return;
  740. }
  741. if (node.is_block_scope()) {
  742. node.block_scope.variables.forEach(collect);
  743. return;
  744. }
  745. if (
  746. function_defs
  747. && node instanceof AST_VarDef
  748. && node.value instanceof AST_Lambda
  749. && !node.value.name
  750. && keep_name(options.keep_fnames, node.name.name)
  751. ) {
  752. function_defs.add(node.name.definition().id);
  753. return;
  754. }
  755. if (node instanceof AST_Label) {
  756. let name;
  757. do {
  758. name = nth_identifier.get(++lname);
  759. } while (ALL_RESERVED_WORDS.has(name));
  760. node.mangled_name = name;
  761. return true;
  762. }
  763. if (!(options.ie8 || options.safari10) && node instanceof AST_SymbolCatch) {
  764. to_mangle.push(node.definition());
  765. return;
  766. }
  767. });
  768. this.walk(tw);
  769. if (options.keep_fnames || options.keep_classnames) {
  770. // Collect a set of short names which are unmangleable,
  771. // for use in avoiding collisions in next_mangled.
  772. to_mangle.forEach(def => {
  773. if (def.name.length < 6 && def.unmangleable(options)) {
  774. unmangleable_names.add(def.name);
  775. }
  776. });
  777. }
  778. to_mangle.forEach(def => { def.mangle(options); });
  779. function_defs = null;
  780. unmangleable_names = null;
  781. scopes_with_block_defuns = null;
  782. function collect(symbol) {
  783. if (symbol.export & MASK_EXPORT_DONT_MANGLE) {
  784. unmangleable_names.add(symbol.name);
  785. } else if (!options.reserved.has(symbol.name)) {
  786. to_mangle.push(symbol);
  787. }
  788. }
  789. });
  790. AST_Toplevel.DEFMETHOD("find_colliding_names", function(options) {
  791. const cache = options.cache && options.cache.props;
  792. const avoid = new Set();
  793. options.reserved.forEach(to_avoid);
  794. this.globals.forEach(add_def);
  795. this.walk(new TreeWalker(function(node) {
  796. if (node instanceof AST_Scope) node.variables.forEach(add_def);
  797. if (node instanceof AST_SymbolCatch) add_def(node.definition());
  798. }));
  799. return avoid;
  800. function to_avoid(name) {
  801. avoid.add(name);
  802. }
  803. function add_def(def) {
  804. var name = def.name;
  805. if (def.global && cache && cache.has(name)) name = cache.get(name);
  806. else if (!def.unmangleable(options)) return;
  807. to_avoid(name);
  808. }
  809. });
  810. AST_Toplevel.DEFMETHOD("expand_names", function(options) {
  811. options = this._default_mangler_options(options);
  812. var nth_identifier = options.nth_identifier;
  813. if (nth_identifier.reset && nth_identifier.sort) {
  814. nth_identifier.reset();
  815. nth_identifier.sort();
  816. }
  817. var avoid = this.find_colliding_names(options);
  818. var cname = 0;
  819. this.globals.forEach(rename);
  820. this.walk(new TreeWalker(function(node) {
  821. if (node instanceof AST_Scope) node.variables.forEach(rename);
  822. if (node instanceof AST_SymbolCatch) rename(node.definition());
  823. }));
  824. function next_name() {
  825. var name;
  826. do {
  827. name = nth_identifier.get(cname++);
  828. } while (avoid.has(name) || ALL_RESERVED_WORDS.has(name));
  829. return name;
  830. }
  831. function rename(def) {
  832. if (def.global && options.cache) return;
  833. if (def.unmangleable(options)) return;
  834. if (options.reserved.has(def.name)) return;
  835. const redefinition = redefined_catch_def(def);
  836. const name = def.name = redefinition ? redefinition.name : next_name();
  837. def.orig.forEach(function(sym) {
  838. sym.name = name;
  839. });
  840. def.references.forEach(function(sym) {
  841. sym.name = name;
  842. });
  843. }
  844. });
  845. AST_Node.DEFMETHOD("tail_node", return_this);
  846. AST_Sequence.DEFMETHOD("tail_node", function() {
  847. return this.expressions[this.expressions.length - 1];
  848. });
  849. AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options) {
  850. options = this._default_mangler_options(options);
  851. var nth_identifier = options.nth_identifier;
  852. if (!nth_identifier.reset || !nth_identifier.consider || !nth_identifier.sort) {
  853. // If the identifier mangler is invariant, skip computing character frequency.
  854. return;
  855. }
  856. nth_identifier.reset();
  857. try {
  858. AST_Node.prototype.print = function(stream, force_parens) {
  859. this._print(stream, force_parens);
  860. if (this instanceof AST_Symbol && !this.unmangleable(options)) {
  861. nth_identifier.consider(this.name, -1);
  862. } else if (options.properties) {
  863. if (this instanceof AST_DotHash) {
  864. nth_identifier.consider("#" + this.property, -1);
  865. } else if (this instanceof AST_Dot) {
  866. nth_identifier.consider(this.property, -1);
  867. } else if (this instanceof AST_Sub) {
  868. skip_string(this.property);
  869. }
  870. }
  871. };
  872. nth_identifier.consider(this.print_to_string(), 1);
  873. } finally {
  874. AST_Node.prototype.print = AST_Node.prototype._print;
  875. }
  876. nth_identifier.sort();
  877. function skip_string(node) {
  878. if (node instanceof AST_String) {
  879. nth_identifier.consider(node.value, -1);
  880. } else if (node instanceof AST_Conditional) {
  881. skip_string(node.consequent);
  882. skip_string(node.alternative);
  883. } else if (node instanceof AST_Sequence) {
  884. skip_string(node.tail_node());
  885. }
  886. }
  887. });
  888. const base54 = (() => {
  889. const leading = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_".split("");
  890. const digits = "0123456789".split("");
  891. let chars;
  892. let frequency;
  893. function reset() {
  894. frequency = new Map();
  895. leading.forEach(function(ch) {
  896. frequency.set(ch, 0);
  897. });
  898. digits.forEach(function(ch) {
  899. frequency.set(ch, 0);
  900. });
  901. }
  902. function consider(str, delta) {
  903. for (var i = str.length; --i >= 0;) {
  904. frequency.set(str[i], frequency.get(str[i]) + delta);
  905. }
  906. }
  907. function compare(a, b) {
  908. return frequency.get(b) - frequency.get(a);
  909. }
  910. function sort() {
  911. chars = mergeSort(leading, compare).concat(mergeSort(digits, compare));
  912. }
  913. // Ensure this is in a usable initial state.
  914. reset();
  915. sort();
  916. function base54(num) {
  917. var ret = "", base = 54;
  918. num++;
  919. do {
  920. num--;
  921. ret += chars[num % base];
  922. num = Math.floor(num / base);
  923. base = 64;
  924. } while (num > 0);
  925. return ret;
  926. }
  927. return {
  928. get: base54,
  929. consider,
  930. reset,
  931. sort
  932. };
  933. })();
  934. export {
  935. base54,
  936. SymbolDef,
  937. };