scope.js 20 KB

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