scope.js 20 KB

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