scope.js 35 KB

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