react / wstein / node_modules / jest-cli / node_modules / istanbul / node_modules / handlebars / node_modules / uglify-js / lib / scope.js
80713 views/***********************************************************************12A JavaScript tokenizer / parser / beautifier / compressor.3https://github.com/mishoo/UglifyJS245-------------------------------- (C) ---------------------------------67Author: Mihai Bazon8<[email protected]>9http://mihai.bazon.net/blog1011Distributed under the BSD license:1213Copyright 2012 (c) Mihai Bazon <[email protected]>1415Redistribution and use in source and binary forms, with or without16modification, are permitted provided that the following conditions17are met:1819* Redistributions of source code must retain the above20copyright notice, this list of conditions and the following21disclaimer.2223* Redistributions in binary form must reproduce the above24copyright notice, this list of conditions and the following25disclaimer in the documentation and/or other materials26provided with the distribution.2728THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY29EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE30IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR31PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE32LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,33OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,34PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR35PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY36THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR37TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF38THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF39SUCH DAMAGE.4041***********************************************************************/4243"use strict";4445function SymbolDef(scope, index, orig) {46this.name = orig.name;47this.orig = [ orig ];48this.scope = scope;49this.references = [];50this.global = false;51this.mangled_name = null;52this.undeclared = false;53this.constant = false;54this.index = index;55};5657SymbolDef.prototype = {58unmangleable: function(options) {59return (this.global && !(options && options.toplevel))60|| this.undeclared61|| (!(options && options.eval) && (this.scope.uses_eval || this.scope.uses_with));62},63mangle: function(options) {64if (!this.mangled_name && !this.unmangleable(options)) {65var s = this.scope;66if (this.orig[0] instanceof AST_SymbolLambda && !options.screw_ie8)67s = s.parent_scope;68this.mangled_name = s.next_mangled(options);69}70}71};7273AST_Toplevel.DEFMETHOD("figure_out_scope", function(){74// This does what ast_add_scope did in UglifyJS v1.75//76// Part of it could be done at parse time, but it would complicate77// the parser (and it's already kinda complex). It's also worth78// having it separated because we might need to call it multiple79// times on the same tree.8081// pass 1: setup scope chaining and handle definitions82var self = this;83var scope = self.parent_scope = null;84var labels = new Dictionary();85var nesting = 0;86var tw = new TreeWalker(function(node, descend){87if (node instanceof AST_Scope) {88node.init_scope_vars(nesting);89var save_scope = node.parent_scope = scope;90var save_labels = labels;91++nesting;92scope = node;93labels = new Dictionary();94descend();95labels = save_labels;96scope = save_scope;97--nesting;98return true; // don't descend again in TreeWalker99}100if (node instanceof AST_Directive) {101node.scope = scope;102push_uniq(scope.directives, node.value);103return true;104}105if (node instanceof AST_With) {106for (var s = scope; s; s = s.parent_scope)107s.uses_with = true;108return;109}110if (node instanceof AST_LabeledStatement) {111var l = node.label;112if (labels.has(l.name))113throw new Error(string_template("Label {name} defined twice", l));114labels.set(l.name, l);115descend();116labels.del(l.name);117return true; // no descend again118}119if (node instanceof AST_Symbol) {120node.scope = scope;121}122if (node instanceof AST_Label) {123node.thedef = node;124node.init_scope_vars();125}126if (node instanceof AST_SymbolLambda) {127scope.def_function(node);128}129else if (node instanceof AST_SymbolDefun) {130// Careful here, the scope where this should be defined is131// the parent scope. The reason is that we enter a new132// scope when we encounter the AST_Defun node (which is133// instanceof AST_Scope) but we get to the symbol a bit134// later.135(node.scope = scope.parent_scope).def_function(node);136}137else if (node instanceof AST_SymbolVar138|| node instanceof AST_SymbolConst) {139var def = scope.def_variable(node);140def.constant = node instanceof AST_SymbolConst;141def.init = tw.parent().value;142}143else if (node instanceof AST_SymbolCatch) {144// XXX: this is wrong according to ECMA-262 (12.4). the145// `catch` argument name should be visible only inside the146// catch block. For a quick fix AST_Catch should inherit147// from AST_Scope. Keeping it this way because of IE,148// which doesn't obey the standard. (it introduces the149// identifier in the enclosing scope)150scope.def_variable(node);151}152if (node instanceof AST_LabelRef) {153var sym = labels.get(node.name);154if (!sym) throw new Error(string_template("Undefined label {name} [{line},{col}]", {155name: node.name,156line: node.start.line,157col: node.start.col158}));159node.thedef = sym;160}161});162self.walk(tw);163164// pass 2: find back references and eval165var func = null;166var globals = self.globals = new Dictionary();167var tw = new TreeWalker(function(node, descend){168if (node instanceof AST_Lambda) {169var prev_func = func;170func = node;171descend();172func = prev_func;173return true;174}175if (node instanceof AST_LabelRef) {176node.reference();177return true;178}179if (node instanceof AST_SymbolRef) {180var name = node.name;181var sym = node.scope.find_variable(name);182if (!sym) {183var g;184if (globals.has(name)) {185g = globals.get(name);186} else {187g = new SymbolDef(self, globals.size(), node);188g.undeclared = true;189g.global = true;190globals.set(name, g);191}192node.thedef = g;193if (name == "eval" && tw.parent() instanceof AST_Call) {194for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope)195s.uses_eval = true;196}197if (name == "arguments") {198func.uses_arguments = true;199}200} else {201node.thedef = sym;202}203node.reference();204return true;205}206});207self.walk(tw);208});209210AST_Scope.DEFMETHOD("init_scope_vars", function(nesting){211this.directives = []; // contains the directives defined in this scope, i.e. "use strict"212this.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions)213this.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope)214this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement215this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval`216this.parent_scope = null; // the parent scope217this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes218this.cname = -1; // the current index for mangling functions/variables219this.nesting = nesting; // the nesting level of this scope (0 means toplevel)220});221222AST_Scope.DEFMETHOD("strict", function(){223return this.has_directive("use strict");224});225226AST_Lambda.DEFMETHOD("init_scope_vars", function(){227AST_Scope.prototype.init_scope_vars.apply(this, arguments);228this.uses_arguments = false;229});230231AST_SymbolRef.DEFMETHOD("reference", function() {232var def = this.definition();233def.references.push(this);234var s = this.scope;235while (s) {236push_uniq(s.enclosed, def);237if (s === def.scope) break;238s = s.parent_scope;239}240this.frame = this.scope.nesting - def.scope.nesting;241});242243AST_Label.DEFMETHOD("init_scope_vars", function(){244this.references = [];245});246247AST_LabelRef.DEFMETHOD("reference", function(){248this.thedef.references.push(this);249});250251AST_Scope.DEFMETHOD("find_variable", function(name){252if (name instanceof AST_Symbol) name = name.name;253return this.variables.get(name)254|| (this.parent_scope && this.parent_scope.find_variable(name));255});256257AST_Scope.DEFMETHOD("has_directive", function(value){258return this.parent_scope && this.parent_scope.has_directive(value)259|| (this.directives.indexOf(value) >= 0 ? this : null);260});261262AST_Scope.DEFMETHOD("def_function", function(symbol){263this.functions.set(symbol.name, this.def_variable(symbol));264});265266AST_Scope.DEFMETHOD("def_variable", function(symbol){267var def;268if (!this.variables.has(symbol.name)) {269def = new SymbolDef(this, this.variables.size(), symbol);270this.variables.set(symbol.name, def);271def.global = !this.parent_scope;272} else {273def = this.variables.get(symbol.name);274def.orig.push(symbol);275}276return symbol.thedef = def;277});278279AST_Scope.DEFMETHOD("next_mangled", function(options){280var ext = this.enclosed;281out: while (true) {282var m = base54(++this.cname);283if (!is_identifier(m)) continue; // skip over "do"284// we must ensure that the mangled name does not shadow a name285// from some parent scope that is referenced in this or in286// inner scopes.287for (var i = ext.length; --i >= 0;) {288var sym = ext[i];289var name = sym.mangled_name || (sym.unmangleable(options) && sym.name);290if (m == name) continue out;291}292return m;293}294});295296AST_Scope.DEFMETHOD("references", function(sym){297if (sym instanceof AST_Symbol) sym = sym.definition();298return this.enclosed.indexOf(sym) < 0 ? null : sym;299});300301AST_Symbol.DEFMETHOD("unmangleable", function(options){302return this.definition().unmangleable(options);303});304305// property accessors are not mangleable306AST_SymbolAccessor.DEFMETHOD("unmangleable", function(){307return true;308});309310// labels are always mangleable311AST_Label.DEFMETHOD("unmangleable", function(){312return false;313});314315AST_Symbol.DEFMETHOD("unreferenced", function(){316return this.definition().references.length == 0317&& !(this.scope.uses_eval || this.scope.uses_with);318});319320AST_Symbol.DEFMETHOD("undeclared", function(){321return this.definition().undeclared;322});323324AST_LabelRef.DEFMETHOD("undeclared", function(){325return false;326});327328AST_Label.DEFMETHOD("undeclared", function(){329return false;330});331332AST_Symbol.DEFMETHOD("definition", function(){333return this.thedef;334});335336AST_Symbol.DEFMETHOD("global", function(){337return this.definition().global;338});339340AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options){341return defaults(options, {342except : [],343eval : false,344sort : false,345toplevel : false,346screw_ie8 : false347});348});349350AST_Toplevel.DEFMETHOD("mangle_names", function(options){351options = this._default_mangler_options(options);352// We only need to mangle declaration nodes. Special logic wired353// into the code generator will display the mangled name if it's354// present (and for AST_SymbolRef-s it'll use the mangled name of355// the AST_SymbolDeclaration that it points to).356var lname = -1;357var to_mangle = [];358var tw = new TreeWalker(function(node, descend){359if (node instanceof AST_LabeledStatement) {360// lname is incremented when we get to the AST_Label361var save_nesting = lname;362descend();363lname = save_nesting;364return true; // don't descend again in TreeWalker365}366if (node instanceof AST_Scope) {367var p = tw.parent(), a = [];368node.variables.each(function(symbol){369if (options.except.indexOf(symbol.name) < 0) {370a.push(symbol);371}372});373if (options.sort) a.sort(function(a, b){374return b.references.length - a.references.length;375});376to_mangle.push.apply(to_mangle, a);377return;378}379if (node instanceof AST_Label) {380var name;381do name = base54(++lname); while (!is_identifier(name));382node.mangled_name = name;383return true;384}385});386this.walk(tw);387to_mangle.forEach(function(def){ def.mangle(options) });388});389390AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options){391options = this._default_mangler_options(options);392var tw = new TreeWalker(function(node){393if (node instanceof AST_Constant)394base54.consider(node.print_to_string());395else if (node instanceof AST_Return)396base54.consider("return");397else if (node instanceof AST_Throw)398base54.consider("throw");399else if (node instanceof AST_Continue)400base54.consider("continue");401else if (node instanceof AST_Break)402base54.consider("break");403else if (node instanceof AST_Debugger)404base54.consider("debugger");405else if (node instanceof AST_Directive)406base54.consider(node.value);407else if (node instanceof AST_While)408base54.consider("while");409else if (node instanceof AST_Do)410base54.consider("do while");411else if (node instanceof AST_If) {412base54.consider("if");413if (node.alternative) base54.consider("else");414}415else if (node instanceof AST_Var)416base54.consider("var");417else if (node instanceof AST_Const)418base54.consider("const");419else if (node instanceof AST_Lambda)420base54.consider("function");421else if (node instanceof AST_For)422base54.consider("for");423else if (node instanceof AST_ForIn)424base54.consider("for in");425else if (node instanceof AST_Switch)426base54.consider("switch");427else if (node instanceof AST_Case)428base54.consider("case");429else if (node instanceof AST_Default)430base54.consider("default");431else if (node instanceof AST_With)432base54.consider("with");433else if (node instanceof AST_ObjectSetter)434base54.consider("set" + node.key);435else if (node instanceof AST_ObjectGetter)436base54.consider("get" + node.key);437else if (node instanceof AST_ObjectKeyVal)438base54.consider(node.key);439else if (node instanceof AST_New)440base54.consider("new");441else if (node instanceof AST_This)442base54.consider("this");443else if (node instanceof AST_Try)444base54.consider("try");445else if (node instanceof AST_Catch)446base54.consider("catch");447else if (node instanceof AST_Finally)448base54.consider("finally");449else if (node instanceof AST_Symbol && node.unmangleable(options))450base54.consider(node.name);451else if (node instanceof AST_Unary || node instanceof AST_Binary)452base54.consider(node.operator);453else if (node instanceof AST_Dot)454base54.consider(node.property);455});456this.walk(tw);457base54.sort();458});459460var base54 = (function() {461var string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";462var chars, frequency;463function reset() {464frequency = Object.create(null);465chars = string.split("").map(function(ch){ return ch.charCodeAt(0) });466chars.forEach(function(ch){ frequency[ch] = 0 });467}468base54.consider = function(str){469for (var i = str.length; --i >= 0;) {470var code = str.charCodeAt(i);471if (code in frequency) ++frequency[code];472}473};474base54.sort = function() {475chars = mergeSort(chars, function(a, b){476if (is_digit(a) && !is_digit(b)) return 1;477if (is_digit(b) && !is_digit(a)) return -1;478return frequency[b] - frequency[a];479});480};481base54.reset = reset;482reset();483base54.get = function(){ return chars };484base54.freq = function(){ return frequency };485function base54(num) {486var ret = "", base = 54;487do {488ret += String.fromCharCode(chars[num % base]);489num = Math.floor(num / base);490base = 64;491} while (num > 0);492return ret;493};494return base54;495})();496497AST_Toplevel.DEFMETHOD("scope_warnings", function(options){498options = defaults(options, {499undeclared : false, // this makes a lot of noise500unreferenced : true,501assign_to_global : true,502func_arguments : true,503nested_defuns : true,504eval : true505});506var tw = new TreeWalker(function(node){507if (options.undeclared508&& node instanceof AST_SymbolRef509&& node.undeclared())510{511// XXX: this also warns about JS standard names,512// i.e. Object, Array, parseInt etc. Should add a list of513// exceptions.514AST_Node.warn("Undeclared symbol: {name} [{file}:{line},{col}]", {515name: node.name,516file: node.start.file,517line: node.start.line,518col: node.start.col519});520}521if (options.assign_to_global)522{523var sym = null;524if (node instanceof AST_Assign && node.left instanceof AST_SymbolRef)525sym = node.left;526else if (node instanceof AST_ForIn && node.init instanceof AST_SymbolRef)527sym = node.init;528if (sym529&& (sym.undeclared()530|| (sym.global() && sym.scope !== sym.definition().scope))) {531AST_Node.warn("{msg}: {name} [{file}:{line},{col}]", {532msg: sym.undeclared() ? "Accidental global?" : "Assignment to global",533name: sym.name,534file: sym.start.file,535line: sym.start.line,536col: sym.start.col537});538}539}540if (options.eval541&& node instanceof AST_SymbolRef542&& node.undeclared()543&& node.name == "eval") {544AST_Node.warn("Eval is used [{file}:{line},{col}]", node.start);545}546if (options.unreferenced547&& (node instanceof AST_SymbolDeclaration || node instanceof AST_Label)548&& node.unreferenced()) {549AST_Node.warn("{type} {name} is declared but not referenced [{file}:{line},{col}]", {550type: node instanceof AST_Label ? "Label" : "Symbol",551name: node.name,552file: node.start.file,553line: node.start.line,554col: node.start.col555});556}557if (options.func_arguments558&& node instanceof AST_Lambda559&& node.uses_arguments) {560AST_Node.warn("arguments used in function {name} [{file}:{line},{col}]", {561name: node.name ? node.name.name : "anonymous",562file: node.start.file,563line: node.start.line,564col: node.start.col565});566}567if (options.nested_defuns568&& node instanceof AST_Defun569&& !(tw.parent() instanceof AST_Scope)) {570AST_Node.warn("Function {name} declared in nested statement \"{type}\" [{file}:{line},{col}]", {571name: node.name.name,572type: tw.parent().TYPE,573file: node.start.file,574line: node.start.line,575col: node.start.col576});577}578});579this.walk(tw);580});581582583