scope.js 34 KB

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