You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

scope.js 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. /***********************************************************************
  2. A JavaScript tokenizer / parser / beautifier / compressor.
  3. https://github.com/mishoo/UglifyJS
  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. function SymbolDef(id, scope, orig, init) {
  35. this.eliminated = 0;
  36. this.global = false;
  37. this.id = id;
  38. this.init = init;
  39. this.lambda = orig instanceof AST_SymbolLambda;
  40. this.mangled_name = null;
  41. this.name = orig.name;
  42. this.orig = [ orig ];
  43. this.references = [];
  44. this.replaced = 0;
  45. this.scope = scope;
  46. this.undeclared = false;
  47. }
  48. SymbolDef.prototype = {
  49. unmangleable: function(options) {
  50. return this.global && !options.toplevel
  51. || this.undeclared
  52. || !options.eval && this.scope.pinned()
  53. || options.keep_fnames
  54. && (this.orig[0] instanceof AST_SymbolLambda
  55. || this.orig[0] instanceof AST_SymbolDefun);
  56. },
  57. mangle: function(options) {
  58. var cache = options.cache && options.cache.props;
  59. if (this.global && cache && cache.has(this.name)) {
  60. this.mangled_name = cache.get(this.name);
  61. } else if (!this.mangled_name && !this.unmangleable(options)) {
  62. var def;
  63. if (def = this.redefined()) {
  64. this.mangled_name = def.mangled_name || def.name;
  65. } else {
  66. this.mangled_name = next_mangled_name(this.scope, options, this);
  67. }
  68. if (this.global && cache) {
  69. cache.set(this.name, this.mangled_name);
  70. }
  71. }
  72. },
  73. redefined: function() {
  74. return this.defun && this.defun.variables.get(this.name);
  75. }
  76. };
  77. AST_Toplevel.DEFMETHOD("figure_out_scope", function(options) {
  78. options = defaults(options, {
  79. cache: null,
  80. ie8: false,
  81. });
  82. // pass 1: setup scope chaining and handle definitions
  83. var self = this;
  84. var scope = self.parent_scope = null;
  85. var defun = null;
  86. var tw = new TreeWalker(function(node, descend) {
  87. if (node instanceof AST_Catch) {
  88. var save_scope = scope;
  89. scope = new AST_Scope(node);
  90. scope.init_scope_vars(save_scope);
  91. descend();
  92. scope = save_scope;
  93. return true;
  94. }
  95. if (node instanceof AST_Scope) {
  96. node.init_scope_vars(scope);
  97. var save_scope = scope;
  98. var save_defun = defun;
  99. defun = scope = node;
  100. descend();
  101. scope = save_scope;
  102. defun = save_defun;
  103. return true;
  104. }
  105. if (node instanceof AST_With) {
  106. for (var s = scope; s; s = s.parent_scope) s.uses_with = true;
  107. return;
  108. }
  109. if (node instanceof AST_Symbol) {
  110. node.scope = scope;
  111. }
  112. if (node instanceof AST_Label) {
  113. node.thedef = node;
  114. node.references = [];
  115. }
  116. if (node instanceof AST_SymbolDefun) {
  117. // This should be defined in the parent scope, as we encounter the
  118. // AST_Defun node before getting to its AST_Symbol.
  119. (node.scope = defun.parent_scope.resolve()).def_function(node, defun);
  120. } else if (node instanceof AST_SymbolLambda) {
  121. var def = defun.def_function(node, node.name == "arguments" ? undefined : defun);
  122. if (options.ie8) def.defun = defun.parent_scope.resolve();
  123. } else if (node instanceof AST_SymbolVar) {
  124. defun.def_variable(node, node.TYPE == "SymbolVar" ? null : undefined);
  125. if (defun !== scope) {
  126. node.mark_enclosed(options);
  127. var def = scope.find_variable(node);
  128. if (node.thedef !== def) {
  129. node.thedef = def;
  130. }
  131. node.reference(options);
  132. }
  133. } else if (node instanceof AST_SymbolCatch) {
  134. scope.def_variable(node).defun = defun;
  135. }
  136. });
  137. self.next_def_id = 0;
  138. self.walk(tw);
  139. // pass 2: find back references and eval
  140. self.globals = new Dictionary();
  141. var tw = new TreeWalker(function(node) {
  142. if (node instanceof AST_LoopControl) {
  143. if (node.label) node.label.thedef.references.push(node);
  144. return true;
  145. }
  146. if (node instanceof AST_SymbolRef) {
  147. var name = node.name;
  148. var sym = node.scope.find_variable(name);
  149. if (!sym) {
  150. sym = self.def_global(node);
  151. } else if (sym.scope instanceof AST_Lambda && name == "arguments") {
  152. sym.scope.uses_arguments = true;
  153. }
  154. if (name == "eval") {
  155. var parent = tw.parent();
  156. if (parent.TYPE == "Call" && parent.expression === node) {
  157. for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope) {
  158. s.uses_eval = true;
  159. }
  160. } else if (sym.undeclared) {
  161. self.uses_eval = true;
  162. }
  163. }
  164. node.thedef = sym;
  165. node.reference(options);
  166. return true;
  167. }
  168. // ensure mangling works if catch reuses a scope variable
  169. if (node instanceof AST_SymbolCatch) {
  170. var def = node.definition().redefined();
  171. if (def) for (var s = node.scope; s; s = s.parent_scope) {
  172. push_uniq(s.enclosed, def);
  173. if (s === def.scope) break;
  174. }
  175. return true;
  176. }
  177. });
  178. self.walk(tw);
  179. // pass 3: fix up any scoping issue with IE8
  180. if (options.ie8) self.walk(new TreeWalker(function(node) {
  181. if (node instanceof AST_SymbolCatch) {
  182. var scope = node.thedef.defun;
  183. if (scope.name instanceof AST_SymbolLambda && scope.name.name == node.name) {
  184. scope = scope.parent_scope.resolve();
  185. }
  186. redefine(node, scope);
  187. return true;
  188. }
  189. if (node instanceof AST_SymbolLambda) {
  190. var def = node.thedef;
  191. redefine(node, node.scope.parent_scope.resolve());
  192. if (typeof node.thedef.init !== "undefined") {
  193. node.thedef.init = false;
  194. } else if (def.init) {
  195. node.thedef.init = def.init;
  196. }
  197. return true;
  198. }
  199. }));
  200. function redefine(node, scope) {
  201. var name = node.name;
  202. var old_def = node.thedef;
  203. var new_def = scope.find_variable(name);
  204. if (new_def) {
  205. var redef;
  206. while (redef = new_def.redefined()) new_def = redef;
  207. } else {
  208. new_def = self.globals.get(name);
  209. }
  210. if (new_def) {
  211. new_def.orig.push(node);
  212. } else {
  213. new_def = scope.def_variable(node);
  214. }
  215. old_def.orig.concat(old_def.references).forEach(function(node) {
  216. node.thedef = new_def;
  217. node.reference(options);
  218. });
  219. if (old_def.lambda) new_def.lambda = true;
  220. if (new_def.undeclared) self.variables.set(name, new_def);
  221. }
  222. });
  223. AST_Scope.DEFMETHOD("make_def", function(orig, init) {
  224. var top = this;
  225. while (top.parent_scope) top = top.parent_scope;
  226. return new SymbolDef(++top.next_def_id, this, orig, init);
  227. });
  228. AST_Toplevel.DEFMETHOD("def_global", function(node) {
  229. var globals = this.globals, name = node.name;
  230. if (globals.has(name)) {
  231. return globals.get(name);
  232. } else {
  233. var g = this.make_def(node);
  234. g.undeclared = true;
  235. g.global = true;
  236. globals.set(name, g);
  237. return g;
  238. }
  239. });
  240. AST_Scope.DEFMETHOD("init_scope_vars", function(parent_scope) {
  241. this.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions)
  242. this.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope)
  243. this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement
  244. this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval`
  245. this.parent_scope = parent_scope; // the parent scope
  246. this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes
  247. this.cname = -1; // the current index for mangling functions/variables
  248. });
  249. AST_Lambda.DEFMETHOD("init_scope_vars", function() {
  250. AST_Scope.prototype.init_scope_vars.apply(this, arguments);
  251. this.uses_arguments = false;
  252. this.def_variable(new AST_SymbolFunarg({
  253. name: "arguments",
  254. start: this.start,
  255. end: this.end
  256. }));
  257. });
  258. AST_Symbol.DEFMETHOD("mark_enclosed", function(options) {
  259. var def = this.definition();
  260. for (var s = this.scope; s; s = s.parent_scope) {
  261. push_uniq(s.enclosed, def);
  262. if (options.keep_fnames) {
  263. s.functions.each(function(d) {
  264. push_uniq(def.scope.enclosed, d);
  265. });
  266. }
  267. if (s === def.scope) break;
  268. }
  269. });
  270. AST_Symbol.DEFMETHOD("reference", function(options) {
  271. this.definition().references.push(this);
  272. this.mark_enclosed(options);
  273. });
  274. AST_Scope.DEFMETHOD("find_variable", function(name) {
  275. if (name instanceof AST_Symbol) name = name.name;
  276. return this.variables.get(name)
  277. || (this.parent_scope && this.parent_scope.find_variable(name));
  278. });
  279. AST_Scope.DEFMETHOD("def_function", function(symbol, init) {
  280. var def = this.def_variable(symbol, init);
  281. if (!def.init || def.init instanceof AST_Defun) def.init = init;
  282. this.functions.set(symbol.name, def);
  283. return def;
  284. });
  285. AST_Scope.DEFMETHOD("def_variable", function(symbol, init) {
  286. var def = this.variables.get(symbol.name);
  287. if (def) {
  288. def.orig.push(symbol);
  289. if (def.init instanceof AST_Function) def.init = init;
  290. } else {
  291. def = this.make_def(symbol, init);
  292. this.variables.set(symbol.name, def);
  293. def.global = !this.parent_scope;
  294. }
  295. return symbol.thedef = def;
  296. });
  297. AST_Lambda.DEFMETHOD("resolve", return_this);
  298. AST_Scope.DEFMETHOD("resolve", function() {
  299. return this.parent_scope.resolve();
  300. });
  301. AST_Toplevel.DEFMETHOD("resolve", return_this);
  302. function names_in_use(scope, options) {
  303. var names = scope.names_in_use;
  304. if (!names) {
  305. scope.names_in_use = names = Object.create(scope.mangled_names || null);
  306. scope.cname_holes = [];
  307. var cache = options.cache && options.cache.props;
  308. scope.enclosed.forEach(function(def) {
  309. if (def.unmangleable(options)) names[def.name] = true;
  310. if (def.global && cache && cache.has(def.name)) {
  311. names[cache.get(def.name)] = true;
  312. }
  313. });
  314. }
  315. return names;
  316. }
  317. function next_mangled_name(scope, options, def) {
  318. var in_use = names_in_use(scope, options);
  319. var holes = scope.cname_holes;
  320. var names = Object.create(null);
  321. var scopes = [ scope ];
  322. def.references.forEach(function(sym) {
  323. var scope = sym.scope;
  324. do {
  325. if (scopes.indexOf(scope) < 0) {
  326. for (var name in names_in_use(scope, options)) {
  327. names[name] = true;
  328. }
  329. scopes.push(scope);
  330. } else break;
  331. } while (scope = scope.parent_scope);
  332. });
  333. var name;
  334. for (var i = 0; i < holes.length; i++) {
  335. name = base54(holes[i]);
  336. if (names[name]) continue;
  337. holes.splice(i, 1);
  338. scope.names_in_use[name] = true;
  339. return name;
  340. }
  341. while (true) {
  342. name = base54(++scope.cname);
  343. if (in_use[name] || RESERVED_WORDS[name] || options.reserved.has[name]) continue;
  344. if (!names[name]) break;
  345. holes.push(scope.cname);
  346. }
  347. scope.names_in_use[name] = true;
  348. return name;
  349. }
  350. AST_Symbol.DEFMETHOD("unmangleable", function(options) {
  351. var def = this.definition();
  352. return !def || def.unmangleable(options);
  353. });
  354. // labels are always mangleable
  355. AST_Label.DEFMETHOD("unmangleable", return_false);
  356. AST_Symbol.DEFMETHOD("unreferenced", function() {
  357. return !this.definition().references.length && !this.scope.pinned();
  358. });
  359. AST_Symbol.DEFMETHOD("definition", function() {
  360. return this.thedef;
  361. });
  362. AST_Symbol.DEFMETHOD("global", function() {
  363. return this.definition().global;
  364. });
  365. function _default_mangler_options(options) {
  366. options = defaults(options, {
  367. eval : false,
  368. ie8 : false,
  369. keep_fnames : false,
  370. reserved : [],
  371. toplevel : false,
  372. });
  373. if (!Array.isArray(options.reserved)) options.reserved = [];
  374. // Never mangle arguments
  375. push_uniq(options.reserved, "arguments");
  376. options.reserved.has = makePredicate(options.reserved);
  377. return options;
  378. }
  379. AST_Toplevel.DEFMETHOD("mangle_names", function(options) {
  380. options = _default_mangler_options(options);
  381. // We only need to mangle declaration nodes. Special logic wired
  382. // into the code generator will display the mangled name if it's
  383. // present (and for AST_SymbolRef-s it'll use the mangled name of
  384. // the AST_SymbolDeclaration that it points to).
  385. var lname = -1;
  386. if (options.cache && options.cache.props) {
  387. var mangled_names = this.mangled_names = Object.create(null);
  388. options.cache.props.each(function(mangled_name) {
  389. mangled_names[mangled_name] = true;
  390. });
  391. }
  392. var redefined = [];
  393. var tw = new TreeWalker(function(node, descend) {
  394. if (node instanceof AST_LabeledStatement) {
  395. // lname is incremented when we get to the AST_Label
  396. var save_nesting = lname;
  397. descend();
  398. lname = save_nesting;
  399. return true;
  400. }
  401. if (node instanceof AST_Scope) {
  402. descend();
  403. if (options.cache && node instanceof AST_Toplevel) {
  404. node.globals.each(mangle);
  405. }
  406. if (node instanceof AST_Defun && tw.has_directive("use asm")) {
  407. var sym = new AST_SymbolRef(node.name);
  408. sym.scope = node;
  409. sym.reference(options);
  410. }
  411. node.variables.each(function(def) {
  412. if (!defer_redef(def)) mangle(def);
  413. });
  414. return true;
  415. }
  416. if (node instanceof AST_Label) {
  417. var name;
  418. do {
  419. name = base54(++lname);
  420. } while (RESERVED_WORDS[name]);
  421. node.mangled_name = name;
  422. return true;
  423. }
  424. if (!options.ie8 && node instanceof AST_Catch) {
  425. var def = node.argname.definition();
  426. var redef = defer_redef(def, node.argname);
  427. descend();
  428. if (!redef) mangle(def);
  429. return true;
  430. }
  431. });
  432. this.walk(tw);
  433. redefined.forEach(mangle);
  434. function mangle(def) {
  435. if (options.reserved.has[def.name]) return;
  436. def.mangle(options);
  437. }
  438. function defer_redef(def, node) {
  439. var redef = def.redefined();
  440. if (!redef) return false;
  441. redefined.push(def);
  442. def.references.forEach(reference);
  443. if (node) reference(node);
  444. return true;
  445. function reference(sym) {
  446. sym.thedef = redef;
  447. sym.reference(options);
  448. sym.thedef = def;
  449. }
  450. }
  451. });
  452. AST_Toplevel.DEFMETHOD("find_colliding_names", function(options) {
  453. var cache = options.cache && options.cache.props;
  454. var avoid = Object.create(null);
  455. options.reserved.forEach(to_avoid);
  456. this.globals.each(add_def);
  457. this.walk(new TreeWalker(function(node) {
  458. if (node instanceof AST_Scope) node.variables.each(add_def);
  459. if (node instanceof AST_SymbolCatch) add_def(node.definition());
  460. }));
  461. return avoid;
  462. function to_avoid(name) {
  463. avoid[name] = true;
  464. }
  465. function add_def(def) {
  466. var name = def.name;
  467. if (def.global && cache && cache.has(name)) name = cache.get(name);
  468. else if (!def.unmangleable(options)) return;
  469. to_avoid(name);
  470. }
  471. });
  472. AST_Toplevel.DEFMETHOD("expand_names", function(options) {
  473. base54.reset();
  474. base54.sort();
  475. options = _default_mangler_options(options);
  476. var avoid = this.find_colliding_names(options);
  477. var cname = 0;
  478. this.globals.each(rename);
  479. this.walk(new TreeWalker(function(node) {
  480. if (node instanceof AST_Scope) node.variables.each(rename);
  481. if (node instanceof AST_SymbolCatch) rename(node.definition());
  482. }));
  483. function next_name() {
  484. var name;
  485. do {
  486. name = base54(cname++);
  487. } while (avoid[name] || RESERVED_WORDS[name]);
  488. return name;
  489. }
  490. function rename(def) {
  491. if (def.global && options.cache) return;
  492. if (def.unmangleable(options)) return;
  493. if (options.reserved.has[def.name]) return;
  494. var redef = def.redefined();
  495. var name = redef ? redef.rename || redef.name : next_name();
  496. def.rename = name;
  497. def.orig.forEach(function(sym) {
  498. sym.name = name;
  499. });
  500. def.references.forEach(function(sym) {
  501. sym.name = name;
  502. });
  503. }
  504. });
  505. AST_Node.DEFMETHOD("tail_node", return_this);
  506. AST_Sequence.DEFMETHOD("tail_node", function() {
  507. return this.expressions[this.expressions.length - 1];
  508. });
  509. AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options) {
  510. options = _default_mangler_options(options);
  511. base54.reset();
  512. try {
  513. AST_Node.prototype.print = function(stream, force_parens) {
  514. this._print(stream, force_parens);
  515. if (this instanceof AST_Symbol && !this.unmangleable(options)) {
  516. base54.consider(this.name, -1);
  517. } else if (options.properties) {
  518. if (this instanceof AST_Dot) {
  519. base54.consider(this.property, -1);
  520. } else if (this instanceof AST_Sub) {
  521. skip_string(this.property);
  522. }
  523. }
  524. };
  525. base54.consider(this.print_to_string(), 1);
  526. } finally {
  527. AST_Node.prototype.print = AST_Node.prototype._print;
  528. }
  529. base54.sort();
  530. function skip_string(node) {
  531. if (node instanceof AST_String) {
  532. base54.consider(node.value, -1);
  533. } else if (node instanceof AST_Conditional) {
  534. skip_string(node.consequent);
  535. skip_string(node.alternative);
  536. } else if (node instanceof AST_Sequence) {
  537. skip_string(node.tail_node());
  538. }
  539. }
  540. });
  541. var base54 = (function() {
  542. var freq = Object.create(null);
  543. function init(chars) {
  544. var array = [];
  545. for (var i = 0; i < chars.length; i++) {
  546. var ch = chars[i];
  547. array.push(ch);
  548. freq[ch] = -1e-2 * i;
  549. }
  550. return array;
  551. }
  552. var digits = init("0123456789");
  553. var leading = init("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_");
  554. var chars, frequency;
  555. function reset() {
  556. frequency = Object.create(freq);
  557. }
  558. base54.consider = function(str, delta) {
  559. for (var i = str.length; --i >= 0;) {
  560. frequency[str[i]] += delta;
  561. }
  562. };
  563. function compare(a, b) {
  564. return frequency[b] - frequency[a];
  565. }
  566. base54.sort = function() {
  567. chars = leading.sort(compare).concat(digits.sort(compare));
  568. };
  569. base54.reset = reset;
  570. reset();
  571. function base54(num) {
  572. var ret = "", base = 54;
  573. num++;
  574. do {
  575. num--;
  576. ret += chars[num % base];
  577. num = Math.floor(num / base);
  578. base = 64;
  579. } while (num > 0);
  580. return ret;
  581. }
  582. return base54;
  583. })();