scope.js 21 KB

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