scope.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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.constant = false;
  43. this.index = index;
  44. };
  45. SymbolDef.prototype = {
  46. unmangleable: function(options) {
  47. if (!options) options = {};
  48. return (this.global && !options.toplevel)
  49. || this.undeclared
  50. || (!options.eval && (this.scope.uses_eval || this.scope.uses_with))
  51. || (options.keep_fnames
  52. && (this.orig[0] instanceof AST_SymbolLambda
  53. || this.orig[0] instanceof AST_SymbolDefun));
  54. },
  55. mangle: function(options) {
  56. var cache = options.cache && options.cache.props;
  57. if (this.global && cache && cache.has(this.name)) {
  58. this.mangled_name = cache.get(this.name);
  59. }
  60. else if (!this.mangled_name && !this.unmangleable(options)) {
  61. var s = this.scope;
  62. if (!options.screw_ie8 && this.orig[0] instanceof AST_SymbolLambda)
  63. s = s.parent_scope;
  64. this.mangled_name = s.next_mangled(options, this);
  65. if (this.global && cache) {
  66. cache.set(this.name, this.mangled_name);
  67. }
  68. }
  69. }
  70. };
  71. AST_Toplevel.DEFMETHOD("figure_out_scope", function(options){
  72. options = defaults(options, {
  73. screw_ie8: false,
  74. cache: null
  75. });
  76. // pass 1: setup scope chaining and handle definitions
  77. var self = this;
  78. var scope = self.parent_scope = null;
  79. var defun = null;
  80. var nesting = 0;
  81. var tw = new TreeWalker(function(node, descend){
  82. if (options.screw_ie8 && node instanceof AST_Catch) {
  83. var save_scope = scope;
  84. scope = new AST_Scope(node);
  85. scope.init_scope_vars(nesting);
  86. scope.parent_scope = save_scope;
  87. descend();
  88. scope = save_scope;
  89. return true;
  90. }
  91. if (node instanceof AST_Scope) {
  92. node.init_scope_vars(nesting);
  93. var save_scope = node.parent_scope = scope;
  94. var save_defun = defun;
  95. defun = scope = node;
  96. ++nesting; descend(); --nesting;
  97. scope = save_scope;
  98. defun = save_defun;
  99. return true; // don't descend again in TreeWalker
  100. }
  101. if (node instanceof AST_Directive) {
  102. node.scope = scope;
  103. push_uniq(scope.directives, node.value);
  104. return true;
  105. }
  106. if (node instanceof AST_With) {
  107. for (var s = scope; s; s = s.parent_scope)
  108. s.uses_with = true;
  109. return;
  110. }
  111. if (node instanceof AST_Symbol) {
  112. node.scope = scope;
  113. }
  114. if (node instanceof AST_SymbolLambda) {
  115. defun.def_function(node);
  116. }
  117. else if (node instanceof AST_SymbolDefun) {
  118. // Careful here, the scope where this should be defined is
  119. // the parent scope. The reason is that we enter a new
  120. // scope when we encounter the AST_Defun node (which is
  121. // instanceof AST_Scope) but we get to the symbol a bit
  122. // later.
  123. (node.scope = defun.parent_scope).def_function(node);
  124. }
  125. else if (node instanceof AST_SymbolVar
  126. || node instanceof AST_SymbolConst) {
  127. var def = defun.def_variable(node);
  128. def.constant = node instanceof AST_SymbolConst;
  129. def.init = tw.parent().value;
  130. }
  131. else if (node instanceof AST_SymbolCatch) {
  132. (options.screw_ie8 ? scope : defun)
  133. .def_variable(node);
  134. }
  135. });
  136. self.walk(tw);
  137. // pass 2: find back references and eval
  138. var func = null;
  139. var globals = self.globals = new Dictionary();
  140. var tw = new TreeWalker(function(node, descend){
  141. if (node instanceof AST_Lambda) {
  142. var prev_func = func;
  143. func = node;
  144. descend();
  145. func = prev_func;
  146. return true;
  147. }
  148. if (node instanceof AST_SymbolRef) {
  149. var name = node.name;
  150. var sym = node.scope.find_variable(name);
  151. if (!sym) {
  152. var g;
  153. if (globals.has(name)) {
  154. g = globals.get(name);
  155. } else {
  156. g = new SymbolDef(self, globals.size(), node);
  157. g.undeclared = true;
  158. g.global = true;
  159. globals.set(name, g);
  160. }
  161. node.thedef = g;
  162. if (name == "eval" && tw.parent() instanceof AST_Call) {
  163. for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope)
  164. s.uses_eval = true;
  165. }
  166. if (func && name == "arguments") {
  167. func.uses_arguments = true;
  168. }
  169. } else {
  170. node.thedef = sym;
  171. }
  172. node.reference();
  173. return true;
  174. }
  175. });
  176. self.walk(tw);
  177. if (options.cache) {
  178. this.cname = options.cache.cname;
  179. }
  180. });
  181. AST_Scope.DEFMETHOD("init_scope_vars", function(nesting){
  182. this.directives = []; // contains the directives defined in this scope, i.e. "use strict"
  183. this.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions)
  184. this.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope)
  185. this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement
  186. this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval`
  187. this.parent_scope = null; // the parent scope
  188. this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes
  189. this.cname = -1; // the current index for mangling functions/variables
  190. this.nesting = nesting; // the nesting level of this scope (0 means toplevel)
  191. });
  192. AST_Scope.DEFMETHOD("strict", function(){
  193. return this.has_directive("use strict");
  194. });
  195. AST_Lambda.DEFMETHOD("init_scope_vars", function(){
  196. AST_Scope.prototype.init_scope_vars.apply(this, arguments);
  197. this.uses_arguments = false;
  198. });
  199. AST_SymbolRef.DEFMETHOD("reference", function() {
  200. var def = this.definition();
  201. def.references.push(this);
  202. var s = this.scope;
  203. while (s) {
  204. push_uniq(s.enclosed, def);
  205. if (s === def.scope) break;
  206. s = s.parent_scope;
  207. }
  208. this.frame = this.scope.nesting - def.scope.nesting;
  209. });
  210. AST_Scope.DEFMETHOD("find_variable", function(name){
  211. if (name instanceof AST_Symbol) name = name.name;
  212. return this.variables.get(name)
  213. || (this.parent_scope && this.parent_scope.find_variable(name));
  214. });
  215. AST_Scope.DEFMETHOD("has_directive", function(value){
  216. return this.parent_scope && this.parent_scope.has_directive(value)
  217. || (this.directives.indexOf(value) >= 0 ? this : null);
  218. });
  219. AST_Scope.DEFMETHOD("def_function", function(symbol){
  220. this.functions.set(symbol.name, this.def_variable(symbol));
  221. });
  222. AST_Scope.DEFMETHOD("def_variable", function(symbol){
  223. var def;
  224. if (!this.variables.has(symbol.name)) {
  225. def = new SymbolDef(this, this.variables.size(), symbol);
  226. this.variables.set(symbol.name, def);
  227. def.global = !this.parent_scope;
  228. } else {
  229. def = this.variables.get(symbol.name);
  230. def.orig.push(symbol);
  231. }
  232. return symbol.thedef = def;
  233. });
  234. AST_Scope.DEFMETHOD("next_mangled", function(options){
  235. var ext = this.enclosed;
  236. out: while (true) {
  237. var m = base54(++this.cname);
  238. if (!is_identifier(m)) continue; // skip over "do"
  239. // https://github.com/mishoo/UglifyJS2/issues/242 -- do not
  240. // shadow a name excepted from mangling.
  241. if (options.except.indexOf(m) >= 0) continue;
  242. // we must ensure that the mangled name does not shadow a name
  243. // from some parent scope that is referenced in this or in
  244. // inner scopes.
  245. for (var i = ext.length; --i >= 0;) {
  246. var sym = ext[i];
  247. var name = sym.mangled_name || (sym.unmangleable(options) && sym.name);
  248. if (m == name) continue out;
  249. }
  250. return m;
  251. }
  252. });
  253. AST_Function.DEFMETHOD("next_mangled", function(options, def){
  254. // #179, #326
  255. // in Safari strict mode, something like (function x(x){...}) is a syntax error;
  256. // a function expression's argument cannot shadow the function expression's name
  257. var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition();
  258. while (true) {
  259. var name = AST_Lambda.prototype.next_mangled.call(this, options, def);
  260. if (!(tricky_def && tricky_def.mangled_name == name))
  261. return name;
  262. }
  263. });
  264. AST_Scope.DEFMETHOD("references", function(sym){
  265. if (sym instanceof AST_Symbol) sym = sym.definition();
  266. return this.enclosed.indexOf(sym) < 0 ? null : sym;
  267. });
  268. AST_Symbol.DEFMETHOD("unmangleable", function(options){
  269. return this.definition().unmangleable(options);
  270. });
  271. // property accessors are not mangleable
  272. AST_SymbolAccessor.DEFMETHOD("unmangleable", function(){
  273. return true;
  274. });
  275. // labels are always mangleable
  276. AST_Label.DEFMETHOD("unmangleable", function(){
  277. return false;
  278. });
  279. AST_Symbol.DEFMETHOD("unreferenced", function(){
  280. return this.definition().references.length == 0
  281. && !(this.scope.uses_eval || this.scope.uses_with);
  282. });
  283. AST_Symbol.DEFMETHOD("undeclared", function(){
  284. return this.definition().undeclared;
  285. });
  286. AST_LabelRef.DEFMETHOD("undeclared", function(){
  287. return false;
  288. });
  289. AST_Label.DEFMETHOD("undeclared", function(){
  290. return false;
  291. });
  292. AST_Symbol.DEFMETHOD("definition", function(){
  293. return this.thedef;
  294. });
  295. AST_Symbol.DEFMETHOD("global", function(){
  296. return this.definition().global;
  297. });
  298. AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options){
  299. return defaults(options, {
  300. except : [],
  301. eval : false,
  302. sort : false,
  303. toplevel : false,
  304. screw_ie8 : false,
  305. keep_fnames : false
  306. });
  307. });
  308. AST_Toplevel.DEFMETHOD("mangle_names", function(options){
  309. options = this._default_mangler_options(options);
  310. // We only need to mangle declaration nodes. Special logic wired
  311. // into the code generator will display the mangled name if it's
  312. // present (and for AST_SymbolRef-s it'll use the mangled name of
  313. // the AST_SymbolDeclaration that it points to).
  314. var lname = -1;
  315. var to_mangle = [];
  316. if (options.cache) {
  317. this.globals.each(function(symbol){
  318. if (options.except.indexOf(symbol.name) < 0) {
  319. to_mangle.push(symbol);
  320. }
  321. });
  322. }
  323. var tw = new TreeWalker(function(node, descend){
  324. if (node instanceof AST_LabeledStatement) {
  325. // lname is incremented when we get to the AST_Label
  326. var save_nesting = lname;
  327. descend();
  328. lname = save_nesting;
  329. return true; // don't descend again in TreeWalker
  330. }
  331. if (node instanceof AST_Scope) {
  332. var p = tw.parent(), a = [];
  333. node.variables.each(function(symbol){
  334. if (options.except.indexOf(symbol.name) < 0) {
  335. a.push(symbol);
  336. }
  337. });
  338. if (options.sort) a.sort(function(a, b){
  339. return b.references.length - a.references.length;
  340. });
  341. to_mangle.push.apply(to_mangle, a);
  342. return;
  343. }
  344. if (node instanceof AST_Label) {
  345. var name;
  346. do name = base54(++lname); while (!is_identifier(name));
  347. node.mangled_name = name;
  348. return true;
  349. }
  350. if (options.screw_ie8 && node instanceof AST_SymbolCatch) {
  351. to_mangle.push(node.definition());
  352. return;
  353. }
  354. });
  355. this.walk(tw);
  356. to_mangle.forEach(function(def){ def.mangle(options) });
  357. if (options.cache) {
  358. options.cache.cname = this.cname;
  359. }
  360. });
  361. AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options){
  362. options = this._default_mangler_options(options);
  363. var tw = new TreeWalker(function(node){
  364. if (node instanceof AST_Constant)
  365. base54.consider(node.print_to_string());
  366. else if (node instanceof AST_Return)
  367. base54.consider("return");
  368. else if (node instanceof AST_Throw)
  369. base54.consider("throw");
  370. else if (node instanceof AST_Continue)
  371. base54.consider("continue");
  372. else if (node instanceof AST_Break)
  373. base54.consider("break");
  374. else if (node instanceof AST_Debugger)
  375. base54.consider("debugger");
  376. else if (node instanceof AST_Directive)
  377. base54.consider(node.value);
  378. else if (node instanceof AST_While)
  379. base54.consider("while");
  380. else if (node instanceof AST_Do)
  381. base54.consider("do while");
  382. else if (node instanceof AST_If) {
  383. base54.consider("if");
  384. if (node.alternative) base54.consider("else");
  385. }
  386. else if (node instanceof AST_Var)
  387. base54.consider("var");
  388. else if (node instanceof AST_Const)
  389. base54.consider("const");
  390. else if (node instanceof AST_Lambda)
  391. base54.consider("function");
  392. else if (node instanceof AST_For)
  393. base54.consider("for");
  394. else if (node instanceof AST_ForIn)
  395. base54.consider("for in");
  396. else if (node instanceof AST_Switch)
  397. base54.consider("switch");
  398. else if (node instanceof AST_Case)
  399. base54.consider("case");
  400. else if (node instanceof AST_Default)
  401. base54.consider("default");
  402. else if (node instanceof AST_With)
  403. base54.consider("with");
  404. else if (node instanceof AST_ObjectSetter)
  405. base54.consider("set" + node.key);
  406. else if (node instanceof AST_ObjectGetter)
  407. base54.consider("get" + node.key);
  408. else if (node instanceof AST_ObjectKeyVal)
  409. base54.consider(node.key);
  410. else if (node instanceof AST_New)
  411. base54.consider("new");
  412. else if (node instanceof AST_This)
  413. base54.consider("this");
  414. else if (node instanceof AST_Try)
  415. base54.consider("try");
  416. else if (node instanceof AST_Catch)
  417. base54.consider("catch");
  418. else if (node instanceof AST_Finally)
  419. base54.consider("finally");
  420. else if (node instanceof AST_Symbol && node.unmangleable(options))
  421. base54.consider(node.name);
  422. else if (node instanceof AST_Unary || node instanceof AST_Binary)
  423. base54.consider(node.operator);
  424. else if (node instanceof AST_Dot)
  425. base54.consider(node.property);
  426. });
  427. this.walk(tw);
  428. base54.sort();
  429. });
  430. var base54 = (function() {
  431. var string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";
  432. var chars, frequency;
  433. function reset() {
  434. frequency = Object.create(null);
  435. chars = string.split("").map(function(ch){ return ch.charCodeAt(0) });
  436. chars.forEach(function(ch){ frequency[ch] = 0 });
  437. }
  438. base54.consider = function(str){
  439. for (var i = str.length; --i >= 0;) {
  440. var code = str.charCodeAt(i);
  441. if (code in frequency) ++frequency[code];
  442. }
  443. };
  444. base54.sort = function() {
  445. chars = mergeSort(chars, function(a, b){
  446. if (is_digit(a) && !is_digit(b)) return 1;
  447. if (is_digit(b) && !is_digit(a)) return -1;
  448. return frequency[b] - frequency[a];
  449. });
  450. };
  451. base54.reset = reset;
  452. reset();
  453. base54.get = function(){ return chars };
  454. base54.freq = function(){ return frequency };
  455. function base54(num) {
  456. var ret = "", base = 54;
  457. num++;
  458. do {
  459. num--;
  460. ret += String.fromCharCode(chars[num % base]);
  461. num = Math.floor(num / base);
  462. base = 64;
  463. } while (num > 0);
  464. return ret;
  465. };
  466. return base54;
  467. })();
  468. AST_Toplevel.DEFMETHOD("scope_warnings", function(options){
  469. options = defaults(options, {
  470. undeclared : false, // this makes a lot of noise
  471. unreferenced : true,
  472. assign_to_global : true,
  473. func_arguments : true,
  474. nested_defuns : true,
  475. eval : true
  476. });
  477. var tw = new TreeWalker(function(node){
  478. if (options.undeclared
  479. && node instanceof AST_SymbolRef
  480. && node.undeclared())
  481. {
  482. // XXX: this also warns about JS standard names,
  483. // i.e. Object, Array, parseInt etc. Should add a list of
  484. // exceptions.
  485. AST_Node.warn("Undeclared symbol: {name} [{file}:{line},{col}]", {
  486. name: node.name,
  487. file: node.start.file,
  488. line: node.start.line,
  489. col: node.start.col
  490. });
  491. }
  492. if (options.assign_to_global)
  493. {
  494. var sym = null;
  495. if (node instanceof AST_Assign && node.left instanceof AST_SymbolRef)
  496. sym = node.left;
  497. else if (node instanceof AST_ForIn && node.init instanceof AST_SymbolRef)
  498. sym = node.init;
  499. if (sym
  500. && (sym.undeclared()
  501. || (sym.global() && sym.scope !== sym.definition().scope))) {
  502. AST_Node.warn("{msg}: {name} [{file}:{line},{col}]", {
  503. msg: sym.undeclared() ? "Accidental global?" : "Assignment to global",
  504. name: sym.name,
  505. file: sym.start.file,
  506. line: sym.start.line,
  507. col: sym.start.col
  508. });
  509. }
  510. }
  511. if (options.eval
  512. && node instanceof AST_SymbolRef
  513. && node.undeclared()
  514. && node.name == "eval") {
  515. AST_Node.warn("Eval is used [{file}:{line},{col}]", node.start);
  516. }
  517. if (options.unreferenced
  518. && (node instanceof AST_SymbolDeclaration || node instanceof AST_Label)
  519. && !(node instanceof AST_SymbolCatch)
  520. && node.unreferenced()) {
  521. AST_Node.warn("{type} {name} is declared but not referenced [{file}:{line},{col}]", {
  522. type: node instanceof AST_Label ? "Label" : "Symbol",
  523. name: node.name,
  524. file: node.start.file,
  525. line: node.start.line,
  526. col: node.start.col
  527. });
  528. }
  529. if (options.func_arguments
  530. && node instanceof AST_Lambda
  531. && node.uses_arguments) {
  532. AST_Node.warn("arguments used in function {name} [{file}:{line},{col}]", {
  533. name: node.name ? node.name.name : "anonymous",
  534. file: node.start.file,
  535. line: node.start.line,
  536. col: node.start.col
  537. });
  538. }
  539. if (options.nested_defuns
  540. && node instanceof AST_Defun
  541. && !(tw.parent() instanceof AST_Scope)) {
  542. AST_Node.warn("Function {name} declared in nested statement \"{type}\" [{file}:{line},{col}]", {
  543. name: node.name.name,
  544. type: tw.parent().TYPE,
  545. file: node.start.file,
  546. line: node.start.line,
  547. col: node.start.col
  548. });
  549. }
  550. });
  551. this.walk(tw);
  552. });