scope.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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, index, orig) {
  35. this.name = orig.name;
  36. this.orig = [ orig ];
  37. this.scope = scope;
  38. this.references = [];
  39. this.global = false;
  40. this.mangled_name = null;
  41. this.undeclared = false;
  42. this.index = index;
  43. this.id = SymbolDef.next_id++;
  44. };
  45. SymbolDef.next_id = 1;
  46. SymbolDef.prototype = {
  47. unmangleable: function(options) {
  48. if (!options) options = {};
  49. return (this.global && !options.toplevel)
  50. || this.undeclared
  51. || (!options.eval && (this.scope.uses_eval || this.scope.uses_with))
  52. || (options.keep_fnames
  53. && (this.orig[0] instanceof AST_SymbolLambda
  54. || this.orig[0] instanceof AST_SymbolDefun));
  55. },
  56. mangle: function(options) {
  57. var cache = options.cache && options.cache.props;
  58. if (this.global && cache && cache.has(this.name)) {
  59. this.mangled_name = cache.get(this.name);
  60. }
  61. else if (!this.mangled_name && !this.unmangleable(options)) {
  62. var s = this.scope;
  63. var sym = this.orig[0];
  64. if (options.ie8 && sym instanceof AST_SymbolLambda)
  65. s = s.parent_scope;
  66. var def;
  67. if (def = this.redefined()) {
  68. this.mangled_name = def.mangled_name || def.name;
  69. } else
  70. this.mangled_name = s.next_mangled(options, this);
  71. if (this.global && cache) {
  72. cache.set(this.name, this.mangled_name);
  73. }
  74. }
  75. },
  76. redefined: function() {
  77. return this.defun && this.defun.variables.get(this.name);
  78. }
  79. };
  80. AST_Toplevel.DEFMETHOD("figure_out_scope", function(options){
  81. options = defaults(options, {
  82. cache: null,
  83. ie8: false,
  84. });
  85. // pass 1: setup scope chaining and handle definitions
  86. var self = this;
  87. var scope = self.parent_scope = null;
  88. var labels = new Dictionary();
  89. var defun = null;
  90. var tw = new TreeWalker(function(node, descend){
  91. if (node instanceof AST_Catch) {
  92. var save_scope = scope;
  93. scope = new AST_Scope(node);
  94. scope.init_scope_vars(save_scope);
  95. descend();
  96. scope = save_scope;
  97. return true;
  98. }
  99. if (node instanceof AST_Scope) {
  100. node.init_scope_vars(scope);
  101. var save_scope = scope;
  102. var save_defun = defun;
  103. var save_labels = labels;
  104. defun = scope = node;
  105. labels = new Dictionary();
  106. descend();
  107. scope = save_scope;
  108. defun = save_defun;
  109. labels = save_labels;
  110. return true; // don't descend again in TreeWalker
  111. }
  112. if (node instanceof AST_LabeledStatement) {
  113. var l = node.label;
  114. if (labels.has(l.name)) {
  115. throw new Error(string_template("Label {name} defined twice", l));
  116. }
  117. labels.set(l.name, l);
  118. descend();
  119. labels.del(l.name);
  120. return true; // no descend again
  121. }
  122. if (node instanceof AST_With) {
  123. for (var s = scope; s; s = s.parent_scope)
  124. s.uses_with = true;
  125. return;
  126. }
  127. if (node instanceof AST_Symbol) {
  128. node.scope = scope;
  129. }
  130. if (node instanceof AST_Label) {
  131. node.thedef = node;
  132. node.references = [];
  133. }
  134. if (node instanceof AST_SymbolLambda) {
  135. defun.def_function(node);
  136. }
  137. else if (node instanceof AST_SymbolDefun) {
  138. // Careful here, the scope where this should be defined is
  139. // the parent scope. The reason is that we enter a new
  140. // scope when we encounter the AST_Defun node (which is
  141. // instanceof AST_Scope) but we get to the symbol a bit
  142. // later.
  143. (node.scope = defun.parent_scope).def_function(node);
  144. }
  145. else if (node instanceof AST_SymbolVar) {
  146. defun.def_variable(node);
  147. if (defun !== scope) {
  148. node.mark_enclosed(options);
  149. var def = scope.find_variable(node);
  150. if (node.thedef !== def) {
  151. node.thedef = def;
  152. node.reference(options);
  153. }
  154. }
  155. }
  156. else if (node instanceof AST_SymbolCatch) {
  157. scope.def_variable(node).defun = defun;
  158. }
  159. else if (node instanceof AST_LabelRef) {
  160. var sym = labels.get(node.name);
  161. if (!sym) throw new Error(string_template("Undefined label {name} [{line},{col}]", {
  162. name: node.name,
  163. line: node.start.line,
  164. col: node.start.col
  165. }));
  166. node.thedef = sym;
  167. }
  168. });
  169. self.walk(tw);
  170. // pass 2: find back references and eval
  171. self.globals = new Dictionary();
  172. var tw = new TreeWalker(function(node, descend){
  173. if (node instanceof AST_LoopControl && node.label) {
  174. node.label.thedef.references.push(node);
  175. return true;
  176. }
  177. if (node instanceof AST_SymbolRef) {
  178. var name = node.name;
  179. if (name == "eval" && tw.parent() instanceof AST_Call) {
  180. for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope) {
  181. s.uses_eval = true;
  182. }
  183. }
  184. var sym = node.scope.find_variable(name);
  185. if (!sym) {
  186. sym = self.def_global(node);
  187. } else if (sym.scope instanceof AST_Lambda && name == "arguments") {
  188. sym.scope.uses_arguments = true;
  189. }
  190. node.thedef = sym;
  191. node.reference(options);
  192. return true;
  193. }
  194. // ensure mangling works if catch reuses a scope variable
  195. var def;
  196. if (node instanceof AST_SymbolCatch && (def = node.definition().redefined())) {
  197. var s = node.scope;
  198. while (s) {
  199. push_uniq(s.enclosed, def);
  200. if (s === def.scope) break;
  201. s = s.parent_scope;
  202. }
  203. }
  204. });
  205. self.walk(tw);
  206. // pass 3: fix up any scoping issue with IE8
  207. if (options.ie8) {
  208. self.walk(new TreeWalker(function(node, descend) {
  209. if (node instanceof AST_SymbolCatch) {
  210. var name = node.name;
  211. var refs = node.thedef.references;
  212. var scope = node.thedef.defun;
  213. var def = scope.find_variable(name) || self.globals.get(name) || scope.def_variable(node);
  214. refs.forEach(function(ref) {
  215. ref.thedef = def;
  216. ref.reference(options);
  217. });
  218. node.thedef = def;
  219. return true;
  220. }
  221. }));
  222. }
  223. if (options.cache) {
  224. this.cname = options.cache.cname;
  225. }
  226. });
  227. AST_Toplevel.DEFMETHOD("def_global", function(node){
  228. var globals = this.globals, name = node.name;
  229. if (globals.has(name)) {
  230. return globals.get(name);
  231. } else {
  232. var g = new SymbolDef(this, globals.size(), node);
  233. g.undeclared = true;
  234. g.global = true;
  235. globals.set(name, g);
  236. return g;
  237. }
  238. });
  239. AST_Scope.DEFMETHOD("init_scope_vars", function(parent_scope){
  240. this.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions)
  241. this.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope)
  242. this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement
  243. this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval`
  244. this.parent_scope = parent_scope; // the parent scope
  245. this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes
  246. this.cname = -1; // the current index for mangling functions/variables
  247. });
  248. AST_Lambda.DEFMETHOD("init_scope_vars", function(){
  249. AST_Scope.prototype.init_scope_vars.apply(this, arguments);
  250. this.uses_arguments = false;
  251. this.def_variable(new AST_SymbolFunarg({
  252. name: "arguments",
  253. start: this.start,
  254. end: this.end
  255. }));
  256. });
  257. AST_Symbol.DEFMETHOD("mark_enclosed", function(options) {
  258. var def = this.definition();
  259. var s = this.scope;
  260. while (s) {
  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. s = s.parent_scope;
  269. }
  270. });
  271. AST_Symbol.DEFMETHOD("reference", function(options) {
  272. this.definition().references.push(this);
  273. this.mark_enclosed(options);
  274. });
  275. AST_Scope.DEFMETHOD("find_variable", function(name){
  276. if (name instanceof AST_Symbol) name = name.name;
  277. return this.variables.get(name)
  278. || (this.parent_scope && this.parent_scope.find_variable(name));
  279. });
  280. AST_Scope.DEFMETHOD("def_function", function(symbol){
  281. this.functions.set(symbol.name, this.def_variable(symbol));
  282. });
  283. AST_Scope.DEFMETHOD("def_variable", function(symbol){
  284. var def;
  285. if (!this.variables.has(symbol.name)) {
  286. def = new SymbolDef(this, this.variables.size(), symbol);
  287. this.variables.set(symbol.name, def);
  288. def.global = !this.parent_scope;
  289. } else {
  290. def = this.variables.get(symbol.name);
  291. def.orig.push(symbol);
  292. }
  293. return symbol.thedef = def;
  294. });
  295. AST_Scope.DEFMETHOD("next_mangled", function(options){
  296. var ext = this.enclosed;
  297. out: while (true) {
  298. var m = base54(++this.cname);
  299. if (!is_identifier(m)) continue; // skip over "do"
  300. // https://github.com/mishoo/UglifyJS2/issues/242 -- do not
  301. // shadow a name reserved from mangling.
  302. if (options.reserved.indexOf(m) >= 0) continue;
  303. // we must ensure that the mangled name does not shadow a name
  304. // from some parent scope that is referenced in this or in
  305. // inner scopes.
  306. for (var i = ext.length; --i >= 0;) {
  307. var sym = ext[i];
  308. var name = sym.mangled_name || (sym.unmangleable(options) && sym.name);
  309. if (m == name) continue out;
  310. }
  311. return m;
  312. }
  313. });
  314. AST_Function.DEFMETHOD("next_mangled", function(options, def){
  315. // #179, #326
  316. // in Safari strict mode, something like (function x(x){...}) is a syntax error;
  317. // a function expression's argument cannot shadow the function expression's name
  318. var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition();
  319. // the function's mangled_name is null when keep_fnames is true
  320. var tricky_name = tricky_def ? tricky_def.mangled_name || tricky_def.name : null;
  321. while (true) {
  322. var name = AST_Lambda.prototype.next_mangled.call(this, options, def);
  323. if (!tricky_name || tricky_name != name)
  324. return name;
  325. }
  326. });
  327. AST_Symbol.DEFMETHOD("unmangleable", function(options){
  328. var def = this.definition();
  329. return !def || def.unmangleable(options);
  330. });
  331. // labels are always mangleable
  332. AST_Label.DEFMETHOD("unmangleable", return_false);
  333. AST_Symbol.DEFMETHOD("unreferenced", function(){
  334. return this.definition().references.length == 0
  335. && !(this.scope.uses_eval || this.scope.uses_with);
  336. });
  337. AST_Symbol.DEFMETHOD("definition", function(){
  338. return this.thedef;
  339. });
  340. AST_Symbol.DEFMETHOD("global", function(){
  341. return this.definition().global;
  342. });
  343. AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options){
  344. options = defaults(options, {
  345. eval : false,
  346. ie8 : false,
  347. keep_fnames : false,
  348. reserved : [],
  349. toplevel : false,
  350. });
  351. if (!Array.isArray(options.reserved)) options.reserved = [];
  352. return options;
  353. });
  354. AST_Toplevel.DEFMETHOD("mangle_names", function(options){
  355. options = this._default_mangler_options(options);
  356. // Never mangle arguments
  357. options.reserved.push('arguments');
  358. // We only need to mangle declaration nodes. Special logic wired
  359. // into the code generator will display the mangled name if it's
  360. // present (and for AST_SymbolRef-s it'll use the mangled name of
  361. // the AST_SymbolDeclaration that it points to).
  362. var lname = -1;
  363. var to_mangle = [];
  364. if (options.cache) {
  365. this.globals.each(function(symbol){
  366. if (options.reserved.indexOf(symbol.name) < 0) {
  367. to_mangle.push(symbol);
  368. }
  369. });
  370. }
  371. var tw = new TreeWalker(function(node, descend){
  372. if (node instanceof AST_LabeledStatement) {
  373. // lname is incremented when we get to the AST_Label
  374. var save_nesting = lname;
  375. descend();
  376. lname = save_nesting;
  377. return true; // don't descend again in TreeWalker
  378. }
  379. if (node instanceof AST_Scope) {
  380. var p = tw.parent(), a = [];
  381. node.variables.each(function(symbol){
  382. if (options.reserved.indexOf(symbol.name) < 0) {
  383. a.push(symbol);
  384. }
  385. });
  386. to_mangle.push.apply(to_mangle, a);
  387. return;
  388. }
  389. if (node instanceof AST_Label) {
  390. var name;
  391. do name = base54(++lname); while (!is_identifier(name));
  392. node.mangled_name = name;
  393. return true;
  394. }
  395. if (!options.ie8 && node instanceof AST_SymbolCatch) {
  396. to_mangle.push(node.definition());
  397. return;
  398. }
  399. });
  400. this.walk(tw);
  401. to_mangle.forEach(function(def){ def.mangle(options) });
  402. if (options.cache) {
  403. options.cache.cname = this.cname;
  404. }
  405. });
  406. AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options){
  407. options = this._default_mangler_options(options);
  408. try {
  409. AST_Node.prototype.print = function(stream, force_parens) {
  410. this._print(stream, force_parens);
  411. if (this instanceof AST_Symbol && !this.unmangleable(options)) {
  412. base54.consider(this.name, -1);
  413. } else if (options.properties) {
  414. if (this instanceof AST_Dot) {
  415. base54.consider(this.property, -1);
  416. } else if (this instanceof AST_Sub) {
  417. skip_string(this.property);
  418. }
  419. }
  420. };
  421. base54.consider(this.print_to_string(), 1);
  422. } finally {
  423. AST_Node.prototype.print = AST_Node.prototype._print;
  424. }
  425. base54.sort();
  426. function skip_string(node) {
  427. if (node instanceof AST_String) {
  428. base54.consider(node.value, -1);
  429. } else if (node instanceof AST_Conditional) {
  430. skip_string(node.consequent);
  431. skip_string(node.alternative);
  432. } else if (node instanceof AST_Sequence) {
  433. skip_string(node.expressions[node.expressions.length - 1]);
  434. }
  435. }
  436. });
  437. var base54 = (function() {
  438. var leading = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_".split("");
  439. var digits = "0123456789".split("");
  440. var chars, frequency;
  441. function reset() {
  442. frequency = Object.create(null);
  443. leading.forEach(function(ch) {
  444. frequency[ch] = 0;
  445. });
  446. digits.forEach(function(ch) {
  447. frequency[ch] = 0;
  448. });
  449. }
  450. base54.consider = function(str, delta) {
  451. for (var i = str.length; --i >= 0;) {
  452. frequency[str[i]] += delta;
  453. }
  454. };
  455. function compare(a, b) {
  456. return frequency[b] - frequency[a];
  457. }
  458. base54.sort = function() {
  459. chars = mergeSort(leading, compare).concat(mergeSort(digits, compare));
  460. };
  461. base54.reset = reset;
  462. reset();
  463. function base54(num) {
  464. var ret = "", base = 54;
  465. num++;
  466. do {
  467. num--;
  468. ret += chars[num % base];
  469. num = Math.floor(num / base);
  470. base = 64;
  471. } while (num > 0);
  472. return ret;
  473. };
  474. return base54;
  475. })();