pax_global_header00006660000000000000000000000064123572545240014523gustar00rootroot0000000000000052 comment=83e0939088a26ad8c28bd2c1719f92bdcf17d045 UglifyJS2-2.4.15/000077500000000000000000000000001235725452400133725ustar00rootroot00000000000000UglifyJS2-2.4.15/.gitignore000066400000000000000000000000231235725452400153550ustar00rootroot00000000000000tmp/ node_modules/ UglifyJS2-2.4.15/.travis.yml000066400000000000000000000001011235725452400154730ustar00rootroot00000000000000language: node_js node_js: - "0.8" - "0.10" - "0.11" UglifyJS2-2.4.15/LICENSE000066400000000000000000000025041235725452400144000ustar00rootroot00000000000000UglifyJS is released under the BSD license: Copyright 2012-2013 (c) Mihai Bazon Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. UglifyJS2-2.4.15/README.md000066400000000000000000000634721235725452400146650ustar00rootroot00000000000000UglifyJS 2 ========== [![Build Status](https://travis-ci.org/mishoo/UglifyJS2.png)](https://travis-ci.org/mishoo/UglifyJS2) UglifyJS is a JavaScript parser, minifier, compressor or beautifier toolkit. This page documents the command line utility. For [API and internals documentation see my website](http://lisperator.net/uglifyjs/). There's also an [in-browser online demo](http://lisperator.net/uglifyjs/#demo) (for Firefox, Chrome and probably Safari). Install ------- First make sure you have installed the latest version of [node.js](http://nodejs.org/) (You may need to restart your computer after this step). From NPM for use as a command line app: npm install uglify-js -g From NPM for programmatic use: npm install uglify-js From Git: git clone git://github.com/mishoo/UglifyJS2.git cd UglifyJS2 npm link . Usage ----- uglifyjs [input files] [options] UglifyJS2 can take multiple input files. It's recommended that you pass the input files first, then pass the options. UglifyJS will parse input files in sequence and apply any compression options. The files are parsed in the same global scope, that is, a reference from a file to some variable/function declared in another file will be matched properly. If you want to read from STDIN instead, pass a single dash instead of input files. The available options are: ``` --source-map Specify an output file where to generate source map. [string] --source-map-root The path to the original source to be included in the source map. [string] --source-map-url The path to the source map to be added in //# sourceMappingURL. Defaults to the value passed with --source-map. [string] --source-map-include-sources Pass this flag if you want to include the content of source files in the source map as sourcesContent property. [boolean] --in-source-map Input source map, useful if you're compressing JS that was generated from some other original code. --screw-ie8 Pass this flag if you don't care about full compliance with Internet Explorer 6-8 quirks (by default UglifyJS will try to be IE-proof). [boolean] --expr Parse a single expression, rather than a program (for parsing JSON) [boolean] -p, --prefix Skip prefix for original filenames that appear in source maps. For example -p 3 will drop 3 directories from file names and ensure they are relative paths. You can also specify -p relative, which will make UglifyJS figure out itself the relative paths between original sources, the source map and the output file. [string] -o, --output Output file (default STDOUT). -b, --beautify Beautify output/specify output options. [string] -m, --mangle Mangle names/pass mangler options. [string] -r, --reserved Reserved names to exclude from mangling. -c, --compress Enable compressor/pass compressor options. Pass options like -c hoist_vars=false,if_return=false. Use -c with no argument to use the default compression options. [string] -d, --define Global definitions [string] -e, --enclose Embed everything in a big function, with a configurable parameter/argument list. [string] --comments Preserve copyright comments in the output. By default this works like Google Closure, keeping JSDoc-style comments that contain "@license" or "@preserve". You can optionally pass one of the following arguments to this flag: - "all" to keep all comments - a valid JS regexp (needs to start with a slash) to keep only comments that match. Note that currently not *all* comments can be kept when compression is on, because of dead code removal or cascading statements into sequences. [string] --preamble Preamble to prepend to the output. You can use this to insert a comment, for example for licensing information. This will not be parsed, but the source map will adjust for its presence. --stats Display operations run time on STDERR. [boolean] --acorn Use Acorn for parsing. [boolean] --spidermonkey Assume input files are SpiderMonkey AST format (as JSON). [boolean] --self Build itself (UglifyJS2) as a library (implies --wrap=UglifyJS --export-all) [boolean] --wrap Embed everything in a big function, making the “exports” and “global” variables available. You need to pass an argument to this option to specify the name that your module will take when included in, say, a browser. [string] --export-all Only used when --wrap, this tells UglifyJS to add code to automatically export all globals. [boolean] --lint Display some scope warnings [boolean] -v, --verbose Verbose [boolean] -V, --version Print version number and exit. [boolean] ``` Specify `--output` (`-o`) to declare the output file. Otherwise the output goes to STDOUT. ## Source map options UglifyJS2 can generate a source map file, which is highly useful for debugging your compressed JavaScript. To get a source map, pass `--source-map output.js.map` (full path to the file where you want the source map dumped). Additionally you might need `--source-map-root` to pass the URL where the original files can be found. In case you are passing full paths to input files to UglifyJS, you can use `--prefix` (`-p`) to specify the number of directories to drop from the path prefix when declaring files in the source map. For example: uglifyjs /home/doe/work/foo/src/js/file1.js \ /home/doe/work/foo/src/js/file2.js \ -o foo.min.js \ --source-map foo.min.js.map \ --source-map-root http://foo.com/src \ -p 5 -c -m The above will compress and mangle `file1.js` and `file2.js`, will drop the output in `foo.min.js` and the source map in `foo.min.js.map`. The source mapping will refer to `http://foo.com/src/js/file1.js` and `http://foo.com/src/js/file2.js` (in fact it will list `http://foo.com/src` as the source map root, and the original files as `js/file1.js` and `js/file2.js`). ### Composed source map When you're compressing JS code that was output by a compiler such as CoffeeScript, mapping to the JS code won't be too helpful. Instead, you'd like to map back to the original code (i.e. CoffeeScript). UglifyJS has an option to take an input source map. Assuming you have a mapping from CoffeeScript → compiled JS, UglifyJS can generate a map from CoffeeScript → compressed JS by mapping every token in the compiled JS to its original location. To use this feature you need to pass `--in-source-map /path/to/input/source.map`. Normally the input source map should also point to the file containing the generated JS, so if that's correct you can omit input files from the command line. ## Mangler options To enable the mangler you need to pass `--mangle` (`-m`). The following (comma-separated) options are supported: - `sort` — to assign shorter names to most frequently used variables. This saves a few hundred bytes on jQuery before gzip, but the output is _bigger_ after gzip (and seems to happen for other libraries I tried it on) therefore it's not enabled by default. - `toplevel` — mangle names declared in the toplevel scope (disabled by default). - `eval` — mangle names visible in scopes where `eval` or `with` are used (disabled by default). When mangling is enabled but you want to prevent certain names from being mangled, you can declare those names with `--reserved` (`-r`) — pass a comma-separated list of names. For example: uglifyjs ... -m -r '$,require,exports' to prevent the `require`, `exports` and `$` names from being changed. ## Compressor options You need to pass `--compress` (`-c`) to enable the compressor. Optionally you can pass a comma-separated list of options. Options are in the form `foo=bar`, or just `foo` (the latter implies a boolean option that you want to set `true`; it's effectively a shortcut for `foo=true`). - `sequences` -- join consecutive simple statements using the comma operator - `properties` -- rewrite property access using the dot notation, for example `foo["bar"] → foo.bar` - `dead_code` -- remove unreachable code - `drop_debugger` -- remove `debugger;` statements - `unsafe` (default: false) -- apply "unsafe" transformations (discussion below) - `conditionals` -- apply optimizations for `if`-s and conditional expressions - `comparisons` -- apply certain optimizations to binary nodes, for example: `!(a <= b) → a > b` (only when `unsafe`), attempts to negate binary nodes, e.g. `a = !b && !c && !d && !e → a=!(b||c||d||e)` etc. - `evaluate` -- attempt to evaluate constant expressions - `booleans` -- various optimizations for boolean context, for example `!!a ? b : c → a ? b : c` - `loops` -- optimizations for `do`, `while` and `for` loops when we can statically determine the condition - `unused` -- drop unreferenced functions and variables - `hoist_funs` -- hoist function declarations - `hoist_vars` (default: false) -- hoist `var` declarations (this is `false` by default because it seems to increase the size of the output in general) - `if_return` -- optimizations for if/return and if/continue - `join_vars` -- join consecutive `var` statements - `cascade` -- small optimization for sequences, transform `x, x` into `x` and `x = something(), x` into `x = something()` - `warnings` -- display warnings when dropping unreachable code or unused declarations etc. - `negate_iife` -- negate "Immediately-Called Function Expressions" where the return value is discarded, to avoid the parens that the code generator would insert. - `pure_getters` -- the default is `false`. If you pass `true` for this, UglifyJS will assume that object property access (e.g. `foo.bar` or `foo["bar"]`) doesn't have any side effects. - `pure_funcs` -- default `null`. You can pass an array of names and UglifyJS will assume that those functions do not produce side effects. DANGER: will not check if the name is redefined in scope. An example case here, for instance `var q = Math.floor(a/b)`. If variable `q` is not used elsewhere, UglifyJS will drop it, but will still keep the `Math.floor(a/b)`, not knowing what it does. You can pass `pure_funcs: [ 'Math.floor' ]` to let it know that this function won't produce any side effect, in which case the whole statement would get discarded. The current implementation adds some overhead (compression will be slower). - `drop_console` -- default `false`. Pass `true` to discard calls to `console.*` functions. ### The `unsafe` option It enables some transformations that *might* break code logic in certain contrived cases, but should be fine for most code. You might want to try it on your own code, it should reduce the minified size. Here's what happens when this flag is on: - `new Array(1, 2, 3)` or `Array(1, 2, 3)` → `[1, 2, 3 ]` - `new Object()` → `{}` - `String(exp)` or `exp.toString()` → `"" + exp` - `new Object/RegExp/Function/Error/Array (...)` → we discard the `new` - `typeof foo == "undefined"` → `foo === void 0` - `void 0` → `undefined` (if there is a variable named "undefined" in scope; we do it because the variable name will be mangled, typically reduced to a single character). ### Conditional compilation You can use the `--define` (`-d`) switch in order to declare global variables that UglifyJS will assume to be constants (unless defined in scope). For example if you pass `--define DEBUG=false` then, coupled with dead code removal UglifyJS will discard the following from the output: ```javascript if (DEBUG) { console.log("debug stuff"); } ``` UglifyJS will warn about the condition being always false and about dropping unreachable code; for now there is no option to turn off only this specific warning, you can pass `warnings=false` to turn off *all* warnings. Another way of doing that is to declare your globals as constants in a separate file and include it into the build. For example you can have a `build/defines.js` file with the following: ```javascript const DEBUG = false; const PRODUCTION = true; // etc. ``` and build your code like this: uglifyjs build/defines.js js/foo.js js/bar.js... -c UglifyJS will notice the constants and, since they cannot be altered, it will evaluate references to them to the value itself and drop unreachable code as usual. The possible downside of this approach is that the build will contain the `const` declarations. ## Beautifier options The code generator tries to output shortest code possible by default. In case you want beautified output, pass `--beautify` (`-b`). Optionally you can pass additional arguments that control the code output: - `beautify` (default `true`) -- whether to actually beautify the output. Passing `-b` will set this to true, but you might need to pass `-b` even when you want to generate minified code, in order to specify additional arguments, so you can use `-b beautify=false` to override it. - `indent-level` (default 4) - `indent-start` (default 0) -- prefix all lines by that many spaces - `quote-keys` (default `false`) -- pass `true` to quote all keys in literal objects - `space-colon` (default `true`) -- insert a space after the colon signs - `ascii-only` (default `false`) -- escape Unicode characters in strings and regexps - `inline-script` (default `false`) -- escape the slash in occurrences of ` 0) { sys.error("WARN: Ignoring input files since --self was passed"); } files = UglifyJS.FILES; if (!ARGS.wrap) ARGS.wrap = "UglifyJS"; ARGS.export_all = true; } var ORIG_MAP = ARGS.in_source_map; if (ORIG_MAP) { ORIG_MAP = JSON.parse(fs.readFileSync(ORIG_MAP)); if (files.length == 0) { sys.error("INFO: Using file from the input source map: " + ORIG_MAP.file); files = [ ORIG_MAP.file ]; } if (ARGS.source_map_root == null) { ARGS.source_map_root = ORIG_MAP.sourceRoot; } } if (files.length == 0) { files = [ "-" ]; } if (files.indexOf("-") >= 0 && ARGS.source_map) { sys.error("ERROR: Source map doesn't work with input from STDIN"); process.exit(1); } if (files.filter(function(el){ return el == "-" }).length > 1) { sys.error("ERROR: Can read a single file from STDIN (two or more dashes specified)"); process.exit(1); } var STATS = {}; var OUTPUT_FILE = ARGS.o; var TOPLEVEL = null; var P_RELATIVE = ARGS.p && ARGS.p == "relative"; var SOURCES_CONTENT = {}; var SOURCE_MAP = ARGS.source_map ? UglifyJS.SourceMap({ file: P_RELATIVE ? path.relative(path.dirname(ARGS.source_map), OUTPUT_FILE) : OUTPUT_FILE, root: ARGS.source_map_root, orig: ORIG_MAP, }) : null; OUTPUT_OPTIONS.source_map = SOURCE_MAP; try { var output = UglifyJS.OutputStream(OUTPUT_OPTIONS); var compressor = COMPRESS && UglifyJS.Compressor(COMPRESS); } catch(ex) { if (ex instanceof UglifyJS.DefaultsError) { sys.error(ex.msg); sys.error("Supported options:"); sys.error(sys.inspect(ex.defs)); process.exit(1); } } async.eachLimit(files, 1, function (file, cb) { read_whole_file(file, function (err, code) { if (err) { sys.error("ERROR: can't read file: " + file); process.exit(1); } if (ARGS.p != null) { if (P_RELATIVE) { file = path.relative(path.dirname(ARGS.source_map), file); } else { var p = parseInt(ARGS.p, 10); if (!isNaN(p)) { file = file.replace(/^\/+/, "").split(/\/+/).slice(ARGS.p).join("/"); } } } SOURCES_CONTENT[file] = code; time_it("parse", function(){ if (ARGS.spidermonkey) { var program = JSON.parse(code); if (!TOPLEVEL) TOPLEVEL = program; else TOPLEVEL.body = TOPLEVEL.body.concat(program.body); } else if (ARGS.acorn) { TOPLEVEL = acorn.parse(code, { locations : true, sourceFile : file, program : TOPLEVEL }); } else { try { TOPLEVEL = UglifyJS.parse(code, { filename : file, toplevel : TOPLEVEL, expression : ARGS.expr, }); } catch(ex) { if (ex instanceof UglifyJS.JS_Parse_Error) { sys.error("Parse error at " + file + ":" + ex.line + "," + ex.col); sys.error(ex.message); sys.error(ex.stack); process.exit(1); } throw ex; } }; }); cb(); }); }, function () { if (ARGS.acorn || ARGS.spidermonkey) time_it("convert_ast", function(){ TOPLEVEL = UglifyJS.AST_Node.from_mozilla_ast(TOPLEVEL); }); if (ARGS.wrap) { TOPLEVEL = TOPLEVEL.wrap_commonjs(ARGS.wrap, ARGS.export_all); } if (ARGS.enclose) { var arg_parameter_list = ARGS.enclose; if (arg_parameter_list === true) { arg_parameter_list = []; } else if (!(arg_parameter_list instanceof Array)) { arg_parameter_list = [arg_parameter_list]; } TOPLEVEL = TOPLEVEL.wrap_enclose(arg_parameter_list); } var SCOPE_IS_NEEDED = COMPRESS || MANGLE || ARGS.lint; if (SCOPE_IS_NEEDED) { time_it("scope", function(){ TOPLEVEL.figure_out_scope({ screw_ie8: ARGS.screw_ie8 }); if (ARGS.lint) { TOPLEVEL.scope_warnings(); } }); } if (COMPRESS) { time_it("squeeze", function(){ TOPLEVEL = TOPLEVEL.transform(compressor); }); } if (SCOPE_IS_NEEDED) { time_it("scope", function(){ TOPLEVEL.figure_out_scope({ screw_ie8: ARGS.screw_ie8 }); if (MANGLE) { TOPLEVEL.compute_char_frequency(MANGLE); } }); } if (MANGLE) time_it("mangle", function(){ TOPLEVEL.mangle_names(MANGLE); }); if (ARGS.source_map_include_sources) { for (var file in SOURCES_CONTENT) { if (SOURCES_CONTENT.hasOwnProperty(file)) { SOURCE_MAP.get().setSourceContent(file, SOURCES_CONTENT[file]); } } } time_it("generate", function(){ TOPLEVEL.print(output); }); output = output.get(); if (SOURCE_MAP) { fs.writeFileSync(ARGS.source_map, SOURCE_MAP, "utf8"); var source_map_url = ARGS.source_map_url || ( P_RELATIVE ? path.relative(path.dirname(OUTPUT_FILE), ARGS.source_map) : ARGS.source_map ); output += "\n//# sourceMappingURL=" + source_map_url; } if (OUTPUT_FILE) { fs.writeFileSync(OUTPUT_FILE, output, "utf8"); } else { sys.print(output); } if (ARGS.stats) { sys.error(UglifyJS.string_template("Timing information (compressed {count} files):", { count: files.length })); for (var i in STATS) if (STATS.hasOwnProperty(i)) { sys.error(UglifyJS.string_template("- {name}: {time}s", { name: i, time: (STATS[i] / 1000).toFixed(3) })); } } }); /* -----[ functions ]----- */ function normalize(o) { for (var i in o) if (o.hasOwnProperty(i) && /-/.test(i)) { o[i.replace(/-/g, "_")] = o[i]; delete o[i]; } } function getOptions(x, constants) { x = ARGS[x]; if (!x) return null; var ret = {}; if (x !== true) { var ast; try { ast = UglifyJS.parse(x, { expression: true }); } catch(ex) { if (ex instanceof UglifyJS.JS_Parse_Error) { sys.error("Error parsing arguments in: " + x); process.exit(1); } } ast.walk(new UglifyJS.TreeWalker(function(node){ if (node instanceof UglifyJS.AST_Seq) return; // descend if (node instanceof UglifyJS.AST_Assign) { var name = node.left.print_to_string({ beautify: false }).replace(/-/g, "_"); var value = node.right; if (constants) value = new Function("return (" + value.print_to_string() + ")")(); ret[name] = value; return true; // no descend } if (node instanceof UglifyJS.AST_Symbol || node instanceof UglifyJS.AST_Binary) { var name = node.print_to_string({ beautify: false }).replace(/-/g, "_"); ret[name] = true; return true; // no descend } sys.error(node.TYPE) sys.error("Error parsing arguments in: " + x); process.exit(1); })); } return ret; } function read_whole_file(filename, cb) { if (filename == "-") { var chunks = []; process.stdin.setEncoding('utf-8'); process.stdin.on('data', function (chunk) { chunks.push(chunk); }).on('end', function () { cb(null, chunks.join("")); }); process.openStdin(); } else { fs.readFile(filename, "utf-8", cb); } } function time_it(name, cont) { var t1 = new Date().getTime(); var ret = cont(); if (ARGS.stats) { var spent = new Date().getTime() - t1; if (STATS[name]) STATS[name] += spent; else STATS[name] = spent; } return ret; } UglifyJS2-2.4.15/lib/000077500000000000000000000000001235725452400141405ustar00rootroot00000000000000UglifyJS2-2.4.15/lib/ast.js000066400000000000000000000772101235725452400152740ustar00rootroot00000000000000/*********************************************************************** A JavaScript tokenizer / parser / beautifier / compressor. https://github.com/mishoo/UglifyJS2 -------------------------------- (C) --------------------------------- Author: Mihai Bazon http://mihai.bazon.net/blog Distributed under the BSD license: Copyright 2012 (c) Mihai Bazon Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ "use strict"; function DEFNODE(type, props, methods, base) { if (arguments.length < 4) base = AST_Node; if (!props) props = []; else props = props.split(/\s+/); var self_props = props; if (base && base.PROPS) props = props.concat(base.PROPS); var code = "return function AST_" + type + "(props){ if (props) { "; for (var i = props.length; --i >= 0;) { code += "this." + props[i] + " = props." + props[i] + ";"; } var proto = base && new base; if (proto && proto.initialize || (methods && methods.initialize)) code += "this.initialize();"; code += "}}"; var ctor = new Function(code)(); if (proto) { ctor.prototype = proto; ctor.BASE = base; } if (base) base.SUBCLASSES.push(ctor); ctor.prototype.CTOR = ctor; ctor.PROPS = props || null; ctor.SELF_PROPS = self_props; ctor.SUBCLASSES = []; if (type) { ctor.prototype.TYPE = ctor.TYPE = type; } if (methods) for (i in methods) if (methods.hasOwnProperty(i)) { if (/^\$/.test(i)) { ctor[i.substr(1)] = methods[i]; } else { ctor.prototype[i] = methods[i]; } } ctor.DEFMETHOD = function(name, method) { this.prototype[name] = method; }; return ctor; }; var AST_Token = DEFNODE("Token", "type value line col pos endpos nlb comments_before file", { }, null); var AST_Node = DEFNODE("Node", "start end", { clone: function() { return new this.CTOR(this); }, $documentation: "Base class of all AST nodes", $propdoc: { start: "[AST_Token] The first token of this node", end: "[AST_Token] The last token of this node" }, _walk: function(visitor) { return visitor._visit(this); }, walk: function(visitor) { return this._walk(visitor); // not sure the indirection will be any help } }, null); AST_Node.warn_function = null; AST_Node.warn = function(txt, props) { if (AST_Node.warn_function) AST_Node.warn_function(string_template(txt, props)); }; /* -----[ statements ]----- */ var AST_Statement = DEFNODE("Statement", null, { $documentation: "Base class of all statements", }); var AST_Debugger = DEFNODE("Debugger", null, { $documentation: "Represents a debugger statement", }, AST_Statement); var AST_Directive = DEFNODE("Directive", "value scope", { $documentation: "Represents a directive, like \"use strict\";", $propdoc: { value: "[string] The value of this directive as a plain string (it's not an AST_String!)", scope: "[AST_Scope/S] The scope that this directive affects" }, }, AST_Statement); var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", { $documentation: "A statement consisting of an expression, i.e. a = 1 + 2", $propdoc: { body: "[AST_Node] an expression node (should not be instanceof AST_Statement)" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.body._walk(visitor); }); } }, AST_Statement); function walk_body(node, visitor) { if (node.body instanceof AST_Statement) { node.body._walk(visitor); } else node.body.forEach(function(stat){ stat._walk(visitor); }); }; var AST_Block = DEFNODE("Block", "body", { $documentation: "A body of statements (usually bracketed)", $propdoc: { body: "[AST_Statement*] an array of statements" }, _walk: function(visitor) { return visitor._visit(this, function(){ walk_body(this, visitor); }); } }, AST_Statement); var AST_BlockStatement = DEFNODE("BlockStatement", null, { $documentation: "A block statement", }, AST_Block); var AST_EmptyStatement = DEFNODE("EmptyStatement", null, { $documentation: "The empty statement (empty block or simply a semicolon)", _walk: function(visitor) { return visitor._visit(this); } }, AST_Statement); var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", { $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`", $propdoc: { body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.body._walk(visitor); }); } }, AST_Statement); var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", { $documentation: "Statement with a label", $propdoc: { label: "[AST_Label] a label definition" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.label._walk(visitor); this.body._walk(visitor); }); } }, AST_StatementWithBody); var AST_IterationStatement = DEFNODE("IterationStatement", null, { $documentation: "Internal class. All loops inherit from it." }, AST_StatementWithBody); var AST_DWLoop = DEFNODE("DWLoop", "condition", { $documentation: "Base class for do/while statements", $propdoc: { condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.condition._walk(visitor); this.body._walk(visitor); }); } }, AST_IterationStatement); var AST_Do = DEFNODE("Do", null, { $documentation: "A `do` statement", }, AST_DWLoop); var AST_While = DEFNODE("While", null, { $documentation: "A `while` statement", }, AST_DWLoop); var AST_For = DEFNODE("For", "init condition step", { $documentation: "A `for` statement", $propdoc: { init: "[AST_Node?] the `for` initialization code, or null if empty", condition: "[AST_Node?] the `for` termination clause, or null if empty", step: "[AST_Node?] the `for` update clause, or null if empty" }, _walk: function(visitor) { return visitor._visit(this, function(){ if (this.init) this.init._walk(visitor); if (this.condition) this.condition._walk(visitor); if (this.step) this.step._walk(visitor); this.body._walk(visitor); }); } }, AST_IterationStatement); var AST_ForIn = DEFNODE("ForIn", "init name object", { $documentation: "A `for ... in` statement", $propdoc: { init: "[AST_Node] the `for/in` initialization code", name: "[AST_SymbolRef?] the loop variable, only if `init` is AST_Var", object: "[AST_Node] the object that we're looping through" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.init._walk(visitor); this.object._walk(visitor); this.body._walk(visitor); }); } }, AST_IterationStatement); var AST_With = DEFNODE("With", "expression", { $documentation: "A `with` statement", $propdoc: { expression: "[AST_Node] the `with` expression" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.expression._walk(visitor); this.body._walk(visitor); }); } }, AST_StatementWithBody); /* -----[ scope and functions ]----- */ var AST_Scope = DEFNODE("Scope", "directives variables functions uses_with uses_eval parent_scope enclosed cname", { $documentation: "Base class for all statements introducing a lexical scope", $propdoc: { directives: "[string*/S] an array of directives declared in this scope", variables: "[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope", functions: "[Object/S] like `variables`, but only lists function declarations", uses_with: "[boolean/S] tells whether this scope uses the `with` statement", uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`", parent_scope: "[AST_Scope?/S] link to the parent scope", enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes", cname: "[integer/S] current index for mangling variables (used internally by the mangler)", }, }, AST_Block); var AST_Toplevel = DEFNODE("Toplevel", "globals", { $documentation: "The toplevel scope", $propdoc: { globals: "[Object/S] a map of name -> SymbolDef for all undeclared names", }, wrap_enclose: function(arg_parameter_pairs) { var self = this; var args = []; var parameters = []; arg_parameter_pairs.forEach(function(pair) { var splitAt = pair.lastIndexOf(":"); args.push(pair.substr(0, splitAt)); parameters.push(pair.substr(splitAt + 1)); }); var wrapped_tl = "(function(" + parameters.join(",") + "){ '$ORIG'; })(" + args.join(",") + ")"; wrapped_tl = parse(wrapped_tl); wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){ if (node instanceof AST_Directive && node.value == "$ORIG") { return MAP.splice(self.body); } })); return wrapped_tl; }, wrap_commonjs: function(name, export_all) { var self = this; var to_export = []; if (export_all) { self.figure_out_scope(); self.walk(new TreeWalker(function(node){ if (node instanceof AST_SymbolDeclaration && node.definition().global) { if (!find_if(function(n){ return n.name == node.name }, to_export)) to_export.push(node); } })); } var wrapped_tl = "(function(exports, global){ global['" + name + "'] = exports; '$ORIG'; '$EXPORTS'; }({}, (function(){return this}())))"; wrapped_tl = parse(wrapped_tl); wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){ if (node instanceof AST_SimpleStatement) { node = node.body; if (node instanceof AST_String) switch (node.getValue()) { case "$ORIG": return MAP.splice(self.body); case "$EXPORTS": var body = []; to_export.forEach(function(sym){ body.push(new AST_SimpleStatement({ body: new AST_Assign({ left: new AST_Sub({ expression: new AST_SymbolRef({ name: "exports" }), property: new AST_String({ value: sym.name }), }), operator: "=", right: new AST_SymbolRef(sym), }), })); }); return MAP.splice(body); } } })); return wrapped_tl; } }, AST_Scope); var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments", { $documentation: "Base class for functions", $propdoc: { name: "[AST_SymbolDeclaration?] the name of this function", argnames: "[AST_SymbolFunarg*] array of function arguments", uses_arguments: "[boolean/S] tells whether this function accesses the arguments array" }, _walk: function(visitor) { return visitor._visit(this, function(){ if (this.name) this.name._walk(visitor); this.argnames.forEach(function(arg){ arg._walk(visitor); }); walk_body(this, visitor); }); } }, AST_Scope); var AST_Accessor = DEFNODE("Accessor", null, { $documentation: "A setter/getter function. The `name` property is always null." }, AST_Lambda); var AST_Function = DEFNODE("Function", null, { $documentation: "A function expression" }, AST_Lambda); var AST_Defun = DEFNODE("Defun", null, { $documentation: "A function definition" }, AST_Lambda); /* -----[ JUMPS ]----- */ var AST_Jump = DEFNODE("Jump", null, { $documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)" }, AST_Statement); var AST_Exit = DEFNODE("Exit", "value", { $documentation: "Base class for “exits” (`return` and `throw`)", $propdoc: { value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return" }, _walk: function(visitor) { return visitor._visit(this, this.value && function(){ this.value._walk(visitor); }); } }, AST_Jump); var AST_Return = DEFNODE("Return", null, { $documentation: "A `return` statement" }, AST_Exit); var AST_Throw = DEFNODE("Throw", null, { $documentation: "A `throw` statement" }, AST_Exit); var AST_LoopControl = DEFNODE("LoopControl", "label", { $documentation: "Base class for loop control statements (`break` and `continue`)", $propdoc: { label: "[AST_LabelRef?] the label, or null if none", }, _walk: function(visitor) { return visitor._visit(this, this.label && function(){ this.label._walk(visitor); }); } }, AST_Jump); var AST_Break = DEFNODE("Break", null, { $documentation: "A `break` statement" }, AST_LoopControl); var AST_Continue = DEFNODE("Continue", null, { $documentation: "A `continue` statement" }, AST_LoopControl); /* -----[ IF ]----- */ var AST_If = DEFNODE("If", "condition alternative", { $documentation: "A `if` statement", $propdoc: { condition: "[AST_Node] the `if` condition", alternative: "[AST_Statement?] the `else` part, or null if not present" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.condition._walk(visitor); this.body._walk(visitor); if (this.alternative) this.alternative._walk(visitor); }); } }, AST_StatementWithBody); /* -----[ SWITCH ]----- */ var AST_Switch = DEFNODE("Switch", "expression", { $documentation: "A `switch` statement", $propdoc: { expression: "[AST_Node] the `switch` “discriminant”" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.expression._walk(visitor); walk_body(this, visitor); }); } }, AST_Block); var AST_SwitchBranch = DEFNODE("SwitchBranch", null, { $documentation: "Base class for `switch` branches", }, AST_Block); var AST_Default = DEFNODE("Default", null, { $documentation: "A `default` switch branch", }, AST_SwitchBranch); var AST_Case = DEFNODE("Case", "expression", { $documentation: "A `case` switch branch", $propdoc: { expression: "[AST_Node] the `case` expression" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.expression._walk(visitor); walk_body(this, visitor); }); } }, AST_SwitchBranch); /* -----[ EXCEPTIONS ]----- */ var AST_Try = DEFNODE("Try", "bcatch bfinally", { $documentation: "A `try` statement", $propdoc: { bcatch: "[AST_Catch?] the catch block, or null if not present", bfinally: "[AST_Finally?] the finally block, or null if not present" }, _walk: function(visitor) { return visitor._visit(this, function(){ walk_body(this, visitor); if (this.bcatch) this.bcatch._walk(visitor); if (this.bfinally) this.bfinally._walk(visitor); }); } }, AST_Block); var AST_Catch = DEFNODE("Catch", "argname", { $documentation: "A `catch` node; only makes sense as part of a `try` statement", $propdoc: { argname: "[AST_SymbolCatch] symbol for the exception" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.argname._walk(visitor); walk_body(this, visitor); }); } }, AST_Block); var AST_Finally = DEFNODE("Finally", null, { $documentation: "A `finally` node; only makes sense as part of a `try` statement" }, AST_Block); /* -----[ VAR/CONST ]----- */ var AST_Definitions = DEFNODE("Definitions", "definitions", { $documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)", $propdoc: { definitions: "[AST_VarDef*] array of variable definitions" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.definitions.forEach(function(def){ def._walk(visitor); }); }); } }, AST_Statement); var AST_Var = DEFNODE("Var", null, { $documentation: "A `var` statement" }, AST_Definitions); var AST_Const = DEFNODE("Const", null, { $documentation: "A `const` statement" }, AST_Definitions); var AST_VarDef = DEFNODE("VarDef", "name value", { $documentation: "A variable declaration; only appears in a AST_Definitions node", $propdoc: { name: "[AST_SymbolVar|AST_SymbolConst] name of the variable", value: "[AST_Node?] initializer, or null of there's no initializer" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.name._walk(visitor); if (this.value) this.value._walk(visitor); }); } }); /* -----[ OTHER ]----- */ var AST_Call = DEFNODE("Call", "expression args", { $documentation: "A function call expression", $propdoc: { expression: "[AST_Node] expression to invoke as function", args: "[AST_Node*] array of arguments" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.expression._walk(visitor); this.args.forEach(function(arg){ arg._walk(visitor); }); }); } }); var AST_New = DEFNODE("New", null, { $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties" }, AST_Call); var AST_Seq = DEFNODE("Seq", "car cdr", { $documentation: "A sequence expression (two comma-separated expressions)", $propdoc: { car: "[AST_Node] first element in sequence", cdr: "[AST_Node] second element in sequence" }, $cons: function(x, y) { var seq = new AST_Seq(x); seq.car = x; seq.cdr = y; return seq; }, $from_array: function(array) { if (array.length == 0) return null; if (array.length == 1) return array[0].clone(); var list = null; for (var i = array.length; --i >= 0;) { list = AST_Seq.cons(array[i], list); } var p = list; while (p) { if (p.cdr && !p.cdr.cdr) { p.cdr = p.cdr.car; break; } p = p.cdr; } return list; }, to_array: function() { var p = this, a = []; while (p) { a.push(p.car); if (p.cdr && !(p.cdr instanceof AST_Seq)) { a.push(p.cdr); break; } p = p.cdr; } return a; }, add: function(node) { var p = this; while (p) { if (!(p.cdr instanceof AST_Seq)) { var cell = AST_Seq.cons(p.cdr, node); return p.cdr = cell; } p = p.cdr; } }, _walk: function(visitor) { return visitor._visit(this, function(){ this.car._walk(visitor); if (this.cdr) this.cdr._walk(visitor); }); } }); var AST_PropAccess = DEFNODE("PropAccess", "expression property", { $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`", $propdoc: { expression: "[AST_Node] the “container” expression", property: "[AST_Node|string] the property to access. For AST_Dot this is always a plain string, while for AST_Sub it's an arbitrary AST_Node" } }); var AST_Dot = DEFNODE("Dot", null, { $documentation: "A dotted property access expression", _walk: function(visitor) { return visitor._visit(this, function(){ this.expression._walk(visitor); }); } }, AST_PropAccess); var AST_Sub = DEFNODE("Sub", null, { $documentation: "Index-style property access, i.e. `a[\"foo\"]`", _walk: function(visitor) { return visitor._visit(this, function(){ this.expression._walk(visitor); this.property._walk(visitor); }); } }, AST_PropAccess); var AST_Unary = DEFNODE("Unary", "operator expression", { $documentation: "Base class for unary expressions", $propdoc: { operator: "[string] the operator", expression: "[AST_Node] expression that this unary operator applies to" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.expression._walk(visitor); }); } }); var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, { $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`" }, AST_Unary); var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, { $documentation: "Unary postfix expression, i.e. `i++`" }, AST_Unary); var AST_Binary = DEFNODE("Binary", "left operator right", { $documentation: "Binary expression, i.e. `a + b`", $propdoc: { left: "[AST_Node] left-hand side expression", operator: "[string] the operator", right: "[AST_Node] right-hand side expression" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.left._walk(visitor); this.right._walk(visitor); }); } }); var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", { $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`", $propdoc: { condition: "[AST_Node]", consequent: "[AST_Node]", alternative: "[AST_Node]" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.condition._walk(visitor); this.consequent._walk(visitor); this.alternative._walk(visitor); }); } }); var AST_Assign = DEFNODE("Assign", null, { $documentation: "An assignment expression — `a = b + 5`", }, AST_Binary); /* -----[ LITERALS ]----- */ var AST_Array = DEFNODE("Array", "elements", { $documentation: "An array literal", $propdoc: { elements: "[AST_Node*] array of elements" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.elements.forEach(function(el){ el._walk(visitor); }); }); } }); var AST_Object = DEFNODE("Object", "properties", { $documentation: "An object literal", $propdoc: { properties: "[AST_ObjectProperty*] array of properties" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.properties.forEach(function(prop){ prop._walk(visitor); }); }); } }); var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", { $documentation: "Base class for literal object properties", $propdoc: { key: "[string] the property name converted to a string for ObjectKeyVal. For setters and getters this is an arbitrary AST_Node.", value: "[AST_Node] property value. For setters and getters this is an AST_Function." }, _walk: function(visitor) { return visitor._visit(this, function(){ this.value._walk(visitor); }); } }); var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", null, { $documentation: "A key: value object property", }, AST_ObjectProperty); var AST_ObjectSetter = DEFNODE("ObjectSetter", null, { $documentation: "An object setter property", }, AST_ObjectProperty); var AST_ObjectGetter = DEFNODE("ObjectGetter", null, { $documentation: "An object getter property", }, AST_ObjectProperty); var AST_Symbol = DEFNODE("Symbol", "scope name thedef", { $propdoc: { name: "[string] name of this symbol", scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)", thedef: "[SymbolDef/S] the definition of this symbol" }, $documentation: "Base class for all symbols", }); var AST_SymbolAccessor = DEFNODE("SymbolAccessor", null, { $documentation: "The name of a property accessor (setter/getter function)" }, AST_Symbol); var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", { $documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)", $propdoc: { init: "[AST_Node*/S] array of initializers for this declaration." } }, AST_Symbol); var AST_SymbolVar = DEFNODE("SymbolVar", null, { $documentation: "Symbol defining a variable", }, AST_SymbolDeclaration); var AST_SymbolConst = DEFNODE("SymbolConst", null, { $documentation: "A constant declaration" }, AST_SymbolDeclaration); var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, { $documentation: "Symbol naming a function argument", }, AST_SymbolVar); var AST_SymbolDefun = DEFNODE("SymbolDefun", null, { $documentation: "Symbol defining a function", }, AST_SymbolDeclaration); var AST_SymbolLambda = DEFNODE("SymbolLambda", null, { $documentation: "Symbol naming a function expression", }, AST_SymbolDeclaration); var AST_SymbolCatch = DEFNODE("SymbolCatch", null, { $documentation: "Symbol naming the exception in catch", }, AST_SymbolDeclaration); var AST_Label = DEFNODE("Label", "references", { $documentation: "Symbol naming a label (declaration)", $propdoc: { references: "[AST_LoopControl*] a list of nodes referring to this label" }, initialize: function() { this.references = []; this.thedef = this; } }, AST_Symbol); var AST_SymbolRef = DEFNODE("SymbolRef", null, { $documentation: "Reference to some symbol (not definition/declaration)", }, AST_Symbol); var AST_LabelRef = DEFNODE("LabelRef", null, { $documentation: "Reference to a label symbol", }, AST_Symbol); var AST_This = DEFNODE("This", null, { $documentation: "The `this` symbol", }, AST_Symbol); var AST_Constant = DEFNODE("Constant", null, { $documentation: "Base class for all constants", getValue: function() { return this.value; } }); var AST_String = DEFNODE("String", "value", { $documentation: "A string literal", $propdoc: { value: "[string] the contents of this string" } }, AST_Constant); var AST_Number = DEFNODE("Number", "value", { $documentation: "A number literal", $propdoc: { value: "[number] the numeric value" } }, AST_Constant); var AST_RegExp = DEFNODE("RegExp", "value", { $documentation: "A regexp literal", $propdoc: { value: "[RegExp] the actual regexp" } }, AST_Constant); var AST_Atom = DEFNODE("Atom", null, { $documentation: "Base class for atoms", }, AST_Constant); var AST_Null = DEFNODE("Null", null, { $documentation: "The `null` atom", value: null }, AST_Atom); var AST_NaN = DEFNODE("NaN", null, { $documentation: "The impossible value", value: 0/0 }, AST_Atom); var AST_Undefined = DEFNODE("Undefined", null, { $documentation: "The `undefined` value", value: (function(){}()) }, AST_Atom); var AST_Hole = DEFNODE("Hole", null, { $documentation: "A hole in an array", value: (function(){}()) }, AST_Atom); var AST_Infinity = DEFNODE("Infinity", null, { $documentation: "The `Infinity` value", value: 1/0 }, AST_Atom); var AST_Boolean = DEFNODE("Boolean", null, { $documentation: "Base class for booleans", }, AST_Atom); var AST_False = DEFNODE("False", null, { $documentation: "The `false` atom", value: false }, AST_Boolean); var AST_True = DEFNODE("True", null, { $documentation: "The `true` atom", value: true }, AST_Boolean); /* -----[ TreeWalker ]----- */ function TreeWalker(callback) { this.visit = callback; this.stack = []; }; TreeWalker.prototype = { _visit: function(node, descend) { this.stack.push(node); var ret = this.visit(node, descend ? function(){ descend.call(node); } : noop); if (!ret && descend) { descend.call(node); } this.stack.pop(); return ret; }, parent: function(n) { return this.stack[this.stack.length - 2 - (n || 0)]; }, push: function (node) { this.stack.push(node); }, pop: function() { return this.stack.pop(); }, self: function() { return this.stack[this.stack.length - 1]; }, find_parent: function(type) { var stack = this.stack; for (var i = stack.length; --i >= 0;) { var x = stack[i]; if (x instanceof type) return x; } }, has_directive: function(type) { return this.find_parent(AST_Scope).has_directive(type); }, in_boolean_context: function() { var stack = this.stack; var i = stack.length, self = stack[--i]; while (i > 0) { var p = stack[--i]; if ((p instanceof AST_If && p.condition === self) || (p instanceof AST_Conditional && p.condition === self) || (p instanceof AST_DWLoop && p.condition === self) || (p instanceof AST_For && p.condition === self) || (p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self)) { return true; } if (!(p instanceof AST_Binary && (p.operator == "&&" || p.operator == "||"))) return false; self = p; } }, loopcontrol_target: function(label) { var stack = this.stack; if (label) for (var i = stack.length; --i >= 0;) { var x = stack[i]; if (x instanceof AST_LabeledStatement && x.label.name == label.name) { return x.body; } } else for (var i = stack.length; --i >= 0;) { var x = stack[i]; if (x instanceof AST_Switch || x instanceof AST_IterationStatement) return x; } } }; UglifyJS2-2.4.15/lib/compress.js000066400000000000000000003123371235725452400163420ustar00rootroot00000000000000/*********************************************************************** A JavaScript tokenizer / parser / beautifier / compressor. https://github.com/mishoo/UglifyJS2 -------------------------------- (C) --------------------------------- Author: Mihai Bazon http://mihai.bazon.net/blog Distributed under the BSD license: Copyright 2012 (c) Mihai Bazon Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ "use strict"; function Compressor(options, false_by_default) { if (!(this instanceof Compressor)) return new Compressor(options, false_by_default); TreeTransformer.call(this, this.before, this.after); this.options = defaults(options, { sequences : !false_by_default, properties : !false_by_default, dead_code : !false_by_default, drop_debugger : !false_by_default, unsafe : false, unsafe_comps : false, conditionals : !false_by_default, comparisons : !false_by_default, evaluate : !false_by_default, booleans : !false_by_default, loops : !false_by_default, unused : !false_by_default, hoist_funs : !false_by_default, keep_fargs : false, hoist_vars : false, if_return : !false_by_default, join_vars : !false_by_default, cascade : !false_by_default, side_effects : !false_by_default, pure_getters : false, pure_funcs : null, negate_iife : !false_by_default, screw_ie8 : false, drop_console : false, angular : false, warnings : true, global_defs : {} }, true); }; Compressor.prototype = new TreeTransformer; merge(Compressor.prototype, { option: function(key) { return this.options[key] }, warn: function() { if (this.options.warnings) AST_Node.warn.apply(AST_Node, arguments); }, before: function(node, descend, in_list) { if (node._squeezed) return node; var was_scope = false; if (node instanceof AST_Scope) { node = node.hoist_declarations(this); was_scope = true; } descend(node, this); node = node.optimize(this); if (was_scope && node instanceof AST_Scope) { node.drop_unused(this); descend(node, this); } node._squeezed = true; return node; } }); (function(){ function OPT(node, optimizer) { node.DEFMETHOD("optimize", function(compressor){ var self = this; if (self._optimized) return self; var opt = optimizer(self, compressor); opt._optimized = true; if (opt === self) return opt; return opt.transform(compressor); }); }; OPT(AST_Node, function(self, compressor){ return self; }); AST_Node.DEFMETHOD("equivalent_to", function(node){ // XXX: this is a rather expensive way to test two node's equivalence: return this.print_to_string() == node.print_to_string(); }); function make_node(ctor, orig, props) { if (!props) props = {}; if (orig) { if (!props.start) props.start = orig.start; if (!props.end) props.end = orig.end; } return new ctor(props); }; function make_node_from_constant(compressor, val, orig) { // XXX: WIP. // if (val instanceof AST_Node) return val.transform(new TreeTransformer(null, function(node){ // if (node instanceof AST_SymbolRef) { // var scope = compressor.find_parent(AST_Scope); // var def = scope.find_variable(node); // node.thedef = def; // return node; // } // })).transform(compressor); if (val instanceof AST_Node) return val.transform(compressor); switch (typeof val) { case "string": return make_node(AST_String, orig, { value: val }).optimize(compressor); case "number": return make_node(isNaN(val) ? AST_NaN : AST_Number, orig, { value: val }).optimize(compressor); case "boolean": return make_node(val ? AST_True : AST_False, orig).optimize(compressor); case "undefined": return make_node(AST_Undefined, orig).optimize(compressor); default: if (val === null) { return make_node(AST_Null, orig).optimize(compressor); } if (val instanceof RegExp) { return make_node(AST_RegExp, orig).optimize(compressor); } throw new Error(string_template("Can't handle constant of type: {type}", { type: typeof val })); } }; function as_statement_array(thing) { if (thing === null) return []; if (thing instanceof AST_BlockStatement) return thing.body; if (thing instanceof AST_EmptyStatement) return []; if (thing instanceof AST_Statement) return [ thing ]; throw new Error("Can't convert thing to statement array"); }; function is_empty(thing) { if (thing === null) return true; if (thing instanceof AST_EmptyStatement) return true; if (thing instanceof AST_BlockStatement) return thing.body.length == 0; return false; }; function loop_body(x) { if (x instanceof AST_Switch) return x; if (x instanceof AST_For || x instanceof AST_ForIn || x instanceof AST_DWLoop) { return (x.body instanceof AST_BlockStatement ? x.body : x); } return x; }; function tighten_body(statements, compressor) { var CHANGED; do { CHANGED = false; if (compressor.option("angular")) { statements = process_for_angular(statements); } statements = eliminate_spurious_blocks(statements); if (compressor.option("dead_code")) { statements = eliminate_dead_code(statements, compressor); } if (compressor.option("if_return")) { statements = handle_if_return(statements, compressor); } if (compressor.option("sequences")) { statements = sequencesize(statements, compressor); } if (compressor.option("join_vars")) { statements = join_consecutive_vars(statements, compressor); } } while (CHANGED); if (compressor.option("negate_iife")) { negate_iifes(statements, compressor); } return statements; function process_for_angular(statements) { function make_injector(func, name) { return make_node(AST_SimpleStatement, func, { body: make_node(AST_Assign, func, { operator: "=", left: make_node(AST_Dot, name, { expression: make_node(AST_SymbolRef, name, name), property: "$inject" }), right: make_node(AST_Array, func, { elements: func.argnames.map(function(sym){ return make_node(AST_String, sym, { value: sym.name }); }) }) }) }); } return statements.reduce(function(a, stat){ a.push(stat); var token = stat.start; var comments = token.comments_before; if (comments && comments.length > 0) { var last = comments.pop(); if (/@ngInject/.test(last.value)) { // case 1: defun if (stat instanceof AST_Defun) { a.push(make_injector(stat, stat.name)); } else if (stat instanceof AST_Definitions) { stat.definitions.forEach(function(def){ if (def.value && def.value instanceof AST_Lambda) { a.push(make_injector(def.value, def.name)); } }); } else { compressor.warn("Unknown statement marked with @ngInject [{file}:{line},{col}]", token); } } } return a; }, []); } function eliminate_spurious_blocks(statements) { var seen_dirs = []; return statements.reduce(function(a, stat){ if (stat instanceof AST_BlockStatement) { CHANGED = true; a.push.apply(a, eliminate_spurious_blocks(stat.body)); } else if (stat instanceof AST_EmptyStatement) { CHANGED = true; } else if (stat instanceof AST_Directive) { if (seen_dirs.indexOf(stat.value) < 0) { a.push(stat); seen_dirs.push(stat.value); } else { CHANGED = true; } } else { a.push(stat); } return a; }, []); }; function handle_if_return(statements, compressor) { var self = compressor.self(); var in_lambda = self instanceof AST_Lambda; var ret = []; loop: for (var i = statements.length; --i >= 0;) { var stat = statements[i]; switch (true) { case (in_lambda && stat instanceof AST_Return && !stat.value && ret.length == 0): CHANGED = true; // note, ret.length is probably always zero // because we drop unreachable code before this // step. nevertheless, it's good to check. continue loop; case stat instanceof AST_If: if (stat.body instanceof AST_Return) { //--- // pretty silly case, but: // if (foo()) return; return; ==> foo(); return; if (((in_lambda && ret.length == 0) || (ret[0] instanceof AST_Return && !ret[0].value)) && !stat.body.value && !stat.alternative) { CHANGED = true; var cond = make_node(AST_SimpleStatement, stat.condition, { body: stat.condition }); ret.unshift(cond); continue loop; } //--- // if (foo()) return x; return y; ==> return foo() ? x : y; if (ret[0] instanceof AST_Return && stat.body.value && ret[0].value && !stat.alternative) { CHANGED = true; stat = stat.clone(); stat.alternative = ret[0]; ret[0] = stat.transform(compressor); continue loop; } //--- // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined; if ((ret.length == 0 || ret[0] instanceof AST_Return) && stat.body.value && !stat.alternative && in_lambda) { CHANGED = true; stat = stat.clone(); stat.alternative = ret[0] || make_node(AST_Return, stat, { value: make_node(AST_Undefined, stat) }); ret[0] = stat.transform(compressor); continue loop; } //--- // if (foo()) return; [ else x... ]; y... ==> if (!foo()) { x...; y... } if (!stat.body.value && in_lambda) { CHANGED = true; stat = stat.clone(); stat.condition = stat.condition.negate(compressor); stat.body = make_node(AST_BlockStatement, stat, { body: as_statement_array(stat.alternative).concat(ret) }); stat.alternative = null; ret = [ stat.transform(compressor) ]; continue loop; } //--- if (ret.length == 1 && in_lambda && ret[0] instanceof AST_SimpleStatement && (!stat.alternative || stat.alternative instanceof AST_SimpleStatement)) { CHANGED = true; ret.push(make_node(AST_Return, ret[0], { value: make_node(AST_Undefined, ret[0]) }).transform(compressor)); ret = as_statement_array(stat.alternative).concat(ret); ret.unshift(stat); continue loop; } } var ab = aborts(stat.body); var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null; if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda) || (ab instanceof AST_Continue && self === loop_body(lct)) || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) { if (ab.label) { remove(ab.label.thedef.references, ab); } CHANGED = true; var body = as_statement_array(stat.body).slice(0, -1); stat = stat.clone(); stat.condition = stat.condition.negate(compressor); stat.body = make_node(AST_BlockStatement, stat, { body: as_statement_array(stat.alternative).concat(ret) }); stat.alternative = make_node(AST_BlockStatement, stat, { body: body }); ret = [ stat.transform(compressor) ]; continue loop; } var ab = aborts(stat.alternative); var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null; if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda) || (ab instanceof AST_Continue && self === loop_body(lct)) || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) { if (ab.label) { remove(ab.label.thedef.references, ab); } CHANGED = true; stat = stat.clone(); stat.body = make_node(AST_BlockStatement, stat.body, { body: as_statement_array(stat.body).concat(ret) }); stat.alternative = make_node(AST_BlockStatement, stat.alternative, { body: as_statement_array(stat.alternative).slice(0, -1) }); ret = [ stat.transform(compressor) ]; continue loop; } ret.unshift(stat); break; default: ret.unshift(stat); break; } } return ret; }; function eliminate_dead_code(statements, compressor) { var has_quit = false; var orig = statements.length; var self = compressor.self(); statements = statements.reduce(function(a, stat){ if (has_quit) { extract_declarations_from_unreachable_code(compressor, stat, a); } else { if (stat instanceof AST_LoopControl) { var lct = compressor.loopcontrol_target(stat.label); if ((stat instanceof AST_Break && lct instanceof AST_BlockStatement && loop_body(lct) === self) || (stat instanceof AST_Continue && loop_body(lct) === self)) { if (stat.label) { remove(stat.label.thedef.references, stat); } } else { a.push(stat); } } else { a.push(stat); } if (aborts(stat)) has_quit = true; } return a; }, []); CHANGED = statements.length != orig; return statements; }; function sequencesize(statements, compressor) { if (statements.length < 2) return statements; var seq = [], ret = []; function push_seq() { seq = AST_Seq.from_array(seq); if (seq) ret.push(make_node(AST_SimpleStatement, seq, { body: seq })); seq = []; }; statements.forEach(function(stat){ if (stat instanceof AST_SimpleStatement) seq.push(stat.body); else push_seq(), ret.push(stat); }); push_seq(); ret = sequencesize_2(ret, compressor); CHANGED = ret.length != statements.length; return ret; }; function sequencesize_2(statements, compressor) { function cons_seq(right) { ret.pop(); var left = prev.body; if (left instanceof AST_Seq) { left.add(right); } else { left = AST_Seq.cons(left, right); } return left.transform(compressor); }; var ret = [], prev = null; statements.forEach(function(stat){ if (prev) { if (stat instanceof AST_For) { var opera = {}; try { prev.body.walk(new TreeWalker(function(node){ if (node instanceof AST_Binary && node.operator == "in") throw opera; })); if (stat.init && !(stat.init instanceof AST_Definitions)) { stat.init = cons_seq(stat.init); } else if (!stat.init) { stat.init = prev.body; ret.pop(); } } catch(ex) { if (ex !== opera) throw ex; } } else if (stat instanceof AST_If) { stat.condition = cons_seq(stat.condition); } else if (stat instanceof AST_With) { stat.expression = cons_seq(stat.expression); } else if (stat instanceof AST_Exit && stat.value) { stat.value = cons_seq(stat.value); } else if (stat instanceof AST_Exit) { stat.value = cons_seq(make_node(AST_Undefined, stat)); } else if (stat instanceof AST_Switch) { stat.expression = cons_seq(stat.expression); } } ret.push(stat); prev = stat instanceof AST_SimpleStatement ? stat : null; }); return ret; }; function join_consecutive_vars(statements, compressor) { var prev = null; return statements.reduce(function(a, stat){ if (stat instanceof AST_Definitions && prev && prev.TYPE == stat.TYPE) { prev.definitions = prev.definitions.concat(stat.definitions); CHANGED = true; } else if (stat instanceof AST_For && prev instanceof AST_Definitions && (!stat.init || stat.init.TYPE == prev.TYPE)) { CHANGED = true; a.pop(); if (stat.init) { stat.init.definitions = prev.definitions.concat(stat.init.definitions); } else { stat.init = prev; } a.push(stat); prev = stat; } else { prev = stat; a.push(stat); } return a; }, []); }; function negate_iifes(statements, compressor) { statements.forEach(function(stat){ if (stat instanceof AST_SimpleStatement) { stat.body = (function transform(thing) { return thing.transform(new TreeTransformer(function(node){ if (node instanceof AST_Call && node.expression instanceof AST_Function) { return make_node(AST_UnaryPrefix, node, { operator: "!", expression: node }); } else if (node instanceof AST_Call) { node.expression = transform(node.expression); } else if (node instanceof AST_Seq) { node.car = transform(node.car); } else if (node instanceof AST_Conditional) { var expr = transform(node.condition); if (expr !== node.condition) { // it has been negated, reverse node.condition = expr; var tmp = node.consequent; node.consequent = node.alternative; node.alternative = tmp; } } return node; })); })(stat.body); } }); }; }; function extract_declarations_from_unreachable_code(compressor, stat, target) { compressor.warn("Dropping unreachable code [{file}:{line},{col}]", stat.start); stat.walk(new TreeWalker(function(node){ if (node instanceof AST_Definitions) { compressor.warn("Declarations in unreachable code! [{file}:{line},{col}]", node.start); node.remove_initializers(); target.push(node); return true; } if (node instanceof AST_Defun) { target.push(node); return true; } if (node instanceof AST_Scope) { return true; } })); }; /* -----[ boolean/negation helpers ]----- */ // methods to determine whether an expression has a boolean result type (function (def){ var unary_bool = [ "!", "delete" ]; var binary_bool = [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ]; def(AST_Node, function(){ return false }); def(AST_UnaryPrefix, function(){ return member(this.operator, unary_bool); }); def(AST_Binary, function(){ return member(this.operator, binary_bool) || ( (this.operator == "&&" || this.operator == "||") && this.left.is_boolean() && this.right.is_boolean() ); }); def(AST_Conditional, function(){ return this.consequent.is_boolean() && this.alternative.is_boolean(); }); def(AST_Assign, function(){ return this.operator == "=" && this.right.is_boolean(); }); def(AST_Seq, function(){ return this.cdr.is_boolean(); }); def(AST_True, function(){ return true }); def(AST_False, function(){ return true }); })(function(node, func){ node.DEFMETHOD("is_boolean", func); }); // methods to determine if an expression has a string result type (function (def){ def(AST_Node, function(){ return false }); def(AST_String, function(){ return true }); def(AST_UnaryPrefix, function(){ return this.operator == "typeof"; }); def(AST_Binary, function(compressor){ return this.operator == "+" && (this.left.is_string(compressor) || this.right.is_string(compressor)); }); def(AST_Assign, function(compressor){ return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor); }); def(AST_Seq, function(compressor){ return this.cdr.is_string(compressor); }); def(AST_Conditional, function(compressor){ return this.consequent.is_string(compressor) && this.alternative.is_string(compressor); }); def(AST_Call, function(compressor){ return compressor.option("unsafe") && this.expression instanceof AST_SymbolRef && this.expression.name == "String" && this.expression.undeclared(); }); })(function(node, func){ node.DEFMETHOD("is_string", func); }); function best_of(ast1, ast2) { return ast1.print_to_string().length > ast2.print_to_string().length ? ast2 : ast1; }; // methods to evaluate a constant expression (function (def){ // The evaluate method returns an array with one or two // elements. If the node has been successfully reduced to a // constant, then the second element tells us the value; // otherwise the second element is missing. The first element // of the array is always an AST_Node descendant; if // evaluation was successful it's a node that represents the // constant; otherwise it's the original or a replacement node. AST_Node.DEFMETHOD("evaluate", function(compressor){ if (!compressor.option("evaluate")) return [ this ]; try { var val = this._eval(compressor); return [ best_of(make_node_from_constant(compressor, val, this), this), val ]; } catch(ex) { if (ex !== def) throw ex; return [ this ]; } }); def(AST_Statement, function(){ throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start)); }); def(AST_Function, function(){ // XXX: AST_Function inherits from AST_Scope, which itself // inherits from AST_Statement; however, an AST_Function // isn't really a statement. This could byte in other // places too. :-( Wish JS had multiple inheritance. throw def; }); function ev(node, compressor) { if (!compressor) throw new Error("Compressor must be passed"); return node._eval(compressor); }; def(AST_Node, function(){ throw def; // not constant }); def(AST_Constant, function(){ return this.getValue(); }); def(AST_UnaryPrefix, function(compressor){ var e = this.expression; switch (this.operator) { case "!": return !ev(e, compressor); case "typeof": // Function would be evaluated to an array and so typeof would // incorrectly return 'object'. Hence making is a special case. if (e instanceof AST_Function) return typeof function(){}; e = ev(e, compressor); // typeof returns "object" or "function" on different platforms // so cannot evaluate reliably if (e instanceof RegExp) throw def; return typeof e; case "void": return void ev(e, compressor); case "~": return ~ev(e, compressor); case "-": e = ev(e, compressor); if (e === 0) throw def; return -e; case "+": return +ev(e, compressor); } throw def; }); def(AST_Binary, function(c){ var left = this.left, right = this.right; switch (this.operator) { case "&&" : return ev(left, c) && ev(right, c); case "||" : return ev(left, c) || ev(right, c); case "|" : return ev(left, c) | ev(right, c); case "&" : return ev(left, c) & ev(right, c); case "^" : return ev(left, c) ^ ev(right, c); case "+" : return ev(left, c) + ev(right, c); case "*" : return ev(left, c) * ev(right, c); case "/" : return ev(left, c) / ev(right, c); case "%" : return ev(left, c) % ev(right, c); case "-" : return ev(left, c) - ev(right, c); case "<<" : return ev(left, c) << ev(right, c); case ">>" : return ev(left, c) >> ev(right, c); case ">>>" : return ev(left, c) >>> ev(right, c); case "==" : return ev(left, c) == ev(right, c); case "===" : return ev(left, c) === ev(right, c); case "!=" : return ev(left, c) != ev(right, c); case "!==" : return ev(left, c) !== ev(right, c); case "<" : return ev(left, c) < ev(right, c); case "<=" : return ev(left, c) <= ev(right, c); case ">" : return ev(left, c) > ev(right, c); case ">=" : return ev(left, c) >= ev(right, c); case "in" : return ev(left, c) in ev(right, c); case "instanceof" : return ev(left, c) instanceof ev(right, c); } throw def; }); def(AST_Conditional, function(compressor){ return ev(this.condition, compressor) ? ev(this.consequent, compressor) : ev(this.alternative, compressor); }); def(AST_SymbolRef, function(compressor){ var d = this.definition(); if (d && d.constant && d.init) return ev(d.init, compressor); throw def; }); def(AST_Dot, function(compressor){ if (compressor.option("unsafe") && this.property == "length") { var str = ev(this.expression, compressor); if (typeof str == "string") return str.length; } throw def; }); })(function(node, func){ node.DEFMETHOD("_eval", func); }); // method to negate an expression (function(def){ function basic_negation(exp) { return make_node(AST_UnaryPrefix, exp, { operator: "!", expression: exp }); }; def(AST_Node, function(){ return basic_negation(this); }); def(AST_Statement, function(){ throw new Error("Cannot negate a statement"); }); def(AST_Function, function(){ return basic_negation(this); }); def(AST_UnaryPrefix, function(){ if (this.operator == "!") return this.expression; return basic_negation(this); }); def(AST_Seq, function(compressor){ var self = this.clone(); self.cdr = self.cdr.negate(compressor); return self; }); def(AST_Conditional, function(compressor){ var self = this.clone(); self.consequent = self.consequent.negate(compressor); self.alternative = self.alternative.negate(compressor); return best_of(basic_negation(this), self); }); def(AST_Binary, function(compressor){ var self = this.clone(), op = this.operator; if (compressor.option("unsafe_comps")) { switch (op) { case "<=" : self.operator = ">" ; return self; case "<" : self.operator = ">=" ; return self; case ">=" : self.operator = "<" ; return self; case ">" : self.operator = "<=" ; return self; } } switch (op) { case "==" : self.operator = "!="; return self; case "!=" : self.operator = "=="; return self; case "===": self.operator = "!=="; return self; case "!==": self.operator = "==="; return self; case "&&": self.operator = "||"; self.left = self.left.negate(compressor); self.right = self.right.negate(compressor); return best_of(basic_negation(this), self); case "||": self.operator = "&&"; self.left = self.left.negate(compressor); self.right = self.right.negate(compressor); return best_of(basic_negation(this), self); } return basic_negation(this); }); })(function(node, func){ node.DEFMETHOD("negate", function(compressor){ return func.call(this, compressor); }); }); // determine if expression has side effects (function(def){ def(AST_Node, function(compressor){ return true }); def(AST_EmptyStatement, function(compressor){ return false }); def(AST_Constant, function(compressor){ return false }); def(AST_This, function(compressor){ return false }); def(AST_Call, function(compressor){ var pure = compressor.option("pure_funcs"); if (!pure) return true; return pure.indexOf(this.expression.print_to_string()) < 0; }); def(AST_Block, function(compressor){ for (var i = this.body.length; --i >= 0;) { if (this.body[i].has_side_effects(compressor)) return true; } return false; }); def(AST_SimpleStatement, function(compressor){ return this.body.has_side_effects(compressor); }); def(AST_Defun, function(compressor){ return true }); def(AST_Function, function(compressor){ return false }); def(AST_Binary, function(compressor){ return this.left.has_side_effects(compressor) || this.right.has_side_effects(compressor); }); def(AST_Assign, function(compressor){ return true }); def(AST_Conditional, function(compressor){ return this.condition.has_side_effects(compressor) || this.consequent.has_side_effects(compressor) || this.alternative.has_side_effects(compressor); }); def(AST_Unary, function(compressor){ return this.operator == "delete" || this.operator == "++" || this.operator == "--" || this.expression.has_side_effects(compressor); }); def(AST_SymbolRef, function(compressor){ return false }); def(AST_Object, function(compressor){ for (var i = this.properties.length; --i >= 0;) if (this.properties[i].has_side_effects(compressor)) return true; return false; }); def(AST_ObjectProperty, function(compressor){ return this.value.has_side_effects(compressor); }); def(AST_Array, function(compressor){ for (var i = this.elements.length; --i >= 0;) if (this.elements[i].has_side_effects(compressor)) return true; return false; }); def(AST_Dot, function(compressor){ if (!compressor.option("pure_getters")) return true; return this.expression.has_side_effects(compressor); }); def(AST_Sub, function(compressor){ if (!compressor.option("pure_getters")) return true; return this.expression.has_side_effects(compressor) || this.property.has_side_effects(compressor); }); def(AST_PropAccess, function(compressor){ return !compressor.option("pure_getters"); }); def(AST_Seq, function(compressor){ return this.car.has_side_effects(compressor) || this.cdr.has_side_effects(compressor); }); })(function(node, func){ node.DEFMETHOD("has_side_effects", func); }); // tell me if a statement aborts function aborts(thing) { return thing && thing.aborts(); }; (function(def){ def(AST_Statement, function(){ return null }); def(AST_Jump, function(){ return this }); function block_aborts(){ var n = this.body.length; return n > 0 && aborts(this.body[n - 1]); }; def(AST_BlockStatement, block_aborts); def(AST_SwitchBranch, block_aborts); def(AST_If, function(){ return this.alternative && aborts(this.body) && aborts(this.alternative); }); })(function(node, func){ node.DEFMETHOD("aborts", func); }); /* -----[ optimizers ]----- */ OPT(AST_Directive, function(self, compressor){ if (self.scope.has_directive(self.value) !== self.scope) { return make_node(AST_EmptyStatement, self); } return self; }); OPT(AST_Debugger, function(self, compressor){ if (compressor.option("drop_debugger")) return make_node(AST_EmptyStatement, self); return self; }); OPT(AST_LabeledStatement, function(self, compressor){ if (self.body instanceof AST_Break && compressor.loopcontrol_target(self.body.label) === self.body) { return make_node(AST_EmptyStatement, self); } return self.label.references.length == 0 ? self.body : self; }); OPT(AST_Block, function(self, compressor){ self.body = tighten_body(self.body, compressor); return self; }); OPT(AST_BlockStatement, function(self, compressor){ self.body = tighten_body(self.body, compressor); switch (self.body.length) { case 1: return self.body[0]; case 0: return make_node(AST_EmptyStatement, self); } return self; }); AST_Scope.DEFMETHOD("drop_unused", function(compressor){ var self = this; if (compressor.option("unused") && !(self instanceof AST_Toplevel) && !self.uses_eval ) { var in_use = []; var initializations = new Dictionary(); // pass 1: find out which symbols are directly used in // this scope (not in nested scopes). var scope = this; var tw = new TreeWalker(function(node, descend){ if (node !== self) { if (node instanceof AST_Defun) { initializations.add(node.name.name, node); return true; // don't go in nested scopes } if (node instanceof AST_Definitions && scope === self) { node.definitions.forEach(function(def){ if (def.value) { initializations.add(def.name.name, def.value); if (def.value.has_side_effects(compressor)) { def.value.walk(tw); } } }); return true; } if (node instanceof AST_SymbolRef) { push_uniq(in_use, node.definition()); return true; } if (node instanceof AST_Scope) { var save_scope = scope; scope = node; descend(); scope = save_scope; return true; } } }); self.walk(tw); // pass 2: for every used symbol we need to walk its // initialization code to figure out if it uses other // symbols (that may not be in_use). for (var i = 0; i < in_use.length; ++i) { in_use[i].orig.forEach(function(decl){ // undeclared globals will be instanceof AST_SymbolRef var init = initializations.get(decl.name); if (init) init.forEach(function(init){ var tw = new TreeWalker(function(node){ if (node instanceof AST_SymbolRef) { push_uniq(in_use, node.definition()); } }); init.walk(tw); }); }); } // pass 3: we should drop declarations not in_use var tt = new TreeTransformer( function before(node, descend, in_list) { if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) { if (!compressor.option("keep_fargs")) { for (var a = node.argnames, i = a.length; --i >= 0;) { var sym = a[i]; if (sym.unreferenced()) { a.pop(); compressor.warn("Dropping unused function argument {name} [{file}:{line},{col}]", { name : sym.name, file : sym.start.file, line : sym.start.line, col : sym.start.col }); } else break; } } } if (node instanceof AST_Defun && node !== self) { if (!member(node.name.definition(), in_use)) { compressor.warn("Dropping unused function {name} [{file}:{line},{col}]", { name : node.name.name, file : node.name.start.file, line : node.name.start.line, col : node.name.start.col }); return make_node(AST_EmptyStatement, node); } return node; } if (node instanceof AST_Definitions && !(tt.parent() instanceof AST_ForIn)) { var def = node.definitions.filter(function(def){ if (member(def.name.definition(), in_use)) return true; var w = { name : def.name.name, file : def.name.start.file, line : def.name.start.line, col : def.name.start.col }; if (def.value && def.value.has_side_effects(compressor)) { def._unused_side_effects = true; compressor.warn("Side effects in initialization of unused variable {name} [{file}:{line},{col}]", w); return true; } compressor.warn("Dropping unused variable {name} [{file}:{line},{col}]", w); return false; }); // place uninitialized names at the start def = mergeSort(def, function(a, b){ if (!a.value && b.value) return -1; if (!b.value && a.value) return 1; return 0; }); // for unused names whose initialization has // side effects, we can cascade the init. code // into the next one, or next statement. var side_effects = []; for (var i = 0; i < def.length;) { var x = def[i]; if (x._unused_side_effects) { side_effects.push(x.value); def.splice(i, 1); } else { if (side_effects.length > 0) { side_effects.push(x.value); x.value = AST_Seq.from_array(side_effects); side_effects = []; } ++i; } } if (side_effects.length > 0) { side_effects = make_node(AST_BlockStatement, node, { body: [ make_node(AST_SimpleStatement, node, { body: AST_Seq.from_array(side_effects) }) ] }); } else { side_effects = null; } if (def.length == 0 && !side_effects) { return make_node(AST_EmptyStatement, node); } if (def.length == 0) { return side_effects; } node.definitions = def; if (side_effects) { side_effects.body.unshift(node); node = side_effects; } return node; } if (node instanceof AST_For) { descend(node, this); if (node.init instanceof AST_BlockStatement) { // certain combination of unused name + side effect leads to: // https://github.com/mishoo/UglifyJS2/issues/44 // that's an invalid AST. // We fix it at this stage by moving the `var` outside the `for`. var body = node.init.body.slice(0, -1); node.init = node.init.body.slice(-1)[0].body; body.push(node); return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, { body: body }); } } if (node instanceof AST_Scope && node !== self) return node; } ); self.transform(tt); } }); AST_Scope.DEFMETHOD("hoist_declarations", function(compressor){ var hoist_funs = compressor.option("hoist_funs"); var hoist_vars = compressor.option("hoist_vars"); var self = this; if (hoist_funs || hoist_vars) { var dirs = []; var hoisted = []; var vars = new Dictionary(), vars_found = 0, var_decl = 0; // let's count var_decl first, we seem to waste a lot of // space if we hoist `var` when there's only one. self.walk(new TreeWalker(function(node){ if (node instanceof AST_Scope && node !== self) return true; if (node instanceof AST_Var) { ++var_decl; return true; } })); hoist_vars = hoist_vars && var_decl > 1; var tt = new TreeTransformer( function before(node) { if (node !== self) { if (node instanceof AST_Directive) { dirs.push(node); return make_node(AST_EmptyStatement, node); } if (node instanceof AST_Defun && hoist_funs) { hoisted.push(node); return make_node(AST_EmptyStatement, node); } if (node instanceof AST_Var && hoist_vars) { node.definitions.forEach(function(def){ vars.set(def.name.name, def); ++vars_found; }); var seq = node.to_assignments(); var p = tt.parent(); if (p instanceof AST_ForIn && p.init === node) { if (seq == null) return node.definitions[0].name; return seq; } if (p instanceof AST_For && p.init === node) { return seq; } if (!seq) return make_node(AST_EmptyStatement, node); return make_node(AST_SimpleStatement, node, { body: seq }); } if (node instanceof AST_Scope) return node; // to avoid descending in nested scopes } } ); self = self.transform(tt); if (vars_found > 0) { // collect only vars which don't show up in self's arguments list var defs = []; vars.each(function(def, name){ if (self instanceof AST_Lambda && find_if(function(x){ return x.name == def.name.name }, self.argnames)) { vars.del(name); } else { def = def.clone(); def.value = null; defs.push(def); vars.set(name, def); } }); if (defs.length > 0) { // try to merge in assignments for (var i = 0; i < self.body.length;) { if (self.body[i] instanceof AST_SimpleStatement) { var expr = self.body[i].body, sym, assign; if (expr instanceof AST_Assign && expr.operator == "=" && (sym = expr.left) instanceof AST_Symbol && vars.has(sym.name)) { var def = vars.get(sym.name); if (def.value) break; def.value = expr.right; remove(defs, def); defs.push(def); self.body.splice(i, 1); continue; } if (expr instanceof AST_Seq && (assign = expr.car) instanceof AST_Assign && assign.operator == "=" && (sym = assign.left) instanceof AST_Symbol && vars.has(sym.name)) { var def = vars.get(sym.name); if (def.value) break; def.value = assign.right; remove(defs, def); defs.push(def); self.body[i].body = expr.cdr; continue; } } if (self.body[i] instanceof AST_EmptyStatement) { self.body.splice(i, 1); continue; } if (self.body[i] instanceof AST_BlockStatement) { var tmp = [ i, 1 ].concat(self.body[i].body); self.body.splice.apply(self.body, tmp); continue; } break; } defs = make_node(AST_Var, self, { definitions: defs }); hoisted.push(defs); }; } self.body = dirs.concat(hoisted, self.body); } return self; }); OPT(AST_SimpleStatement, function(self, compressor){ if (compressor.option("side_effects")) { if (!self.body.has_side_effects(compressor)) { compressor.warn("Dropping side-effect-free statement [{file}:{line},{col}]", self.start); return make_node(AST_EmptyStatement, self); } } return self; }); OPT(AST_DWLoop, function(self, compressor){ var cond = self.condition.evaluate(compressor); self.condition = cond[0]; if (!compressor.option("loops")) return self; if (cond.length > 1) { if (cond[1]) { return make_node(AST_For, self, { body: self.body }); } else if (self instanceof AST_While) { if (compressor.option("dead_code")) { var a = []; extract_declarations_from_unreachable_code(compressor, self.body, a); return make_node(AST_BlockStatement, self, { body: a }); } } } return self; }); function if_break_in_loop(self, compressor) { function drop_it(rest) { rest = as_statement_array(rest); if (self.body instanceof AST_BlockStatement) { self.body = self.body.clone(); self.body.body = rest.concat(self.body.body.slice(1)); self.body = self.body.transform(compressor); } else { self.body = make_node(AST_BlockStatement, self.body, { body: rest }).transform(compressor); } if_break_in_loop(self, compressor); } var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body; if (first instanceof AST_If) { if (first.body instanceof AST_Break && compressor.loopcontrol_target(first.body.label) === self) { if (self.condition) { self.condition = make_node(AST_Binary, self.condition, { left: self.condition, operator: "&&", right: first.condition.negate(compressor), }); } else { self.condition = first.condition.negate(compressor); } drop_it(first.alternative); } else if (first.alternative instanceof AST_Break && compressor.loopcontrol_target(first.alternative.label) === self) { if (self.condition) { self.condition = make_node(AST_Binary, self.condition, { left: self.condition, operator: "&&", right: first.condition, }); } else { self.condition = first.condition; } drop_it(first.body); } } }; OPT(AST_While, function(self, compressor) { if (!compressor.option("loops")) return self; self = AST_DWLoop.prototype.optimize.call(self, compressor); if (self instanceof AST_While) { if_break_in_loop(self, compressor); self = make_node(AST_For, self, self).transform(compressor); } return self; }); OPT(AST_For, function(self, compressor){ var cond = self.condition; if (cond) { cond = cond.evaluate(compressor); self.condition = cond[0]; } if (!compressor.option("loops")) return self; if (cond) { if (cond.length > 1 && !cond[1]) { if (compressor.option("dead_code")) { var a = []; if (self.init instanceof AST_Statement) { a.push(self.init); } else if (self.init) { a.push(make_node(AST_SimpleStatement, self.init, { body: self.init })); } extract_declarations_from_unreachable_code(compressor, self.body, a); return make_node(AST_BlockStatement, self, { body: a }); } } } if_break_in_loop(self, compressor); return self; }); OPT(AST_If, function(self, compressor){ if (!compressor.option("conditionals")) return self; // if condition can be statically determined, warn and drop // one of the blocks. note, statically determined implies // “has no side effects”; also it doesn't work for cases like // `x && true`, though it probably should. var cond = self.condition.evaluate(compressor); self.condition = cond[0]; if (cond.length > 1) { if (cond[1]) { compressor.warn("Condition always true [{file}:{line},{col}]", self.condition.start); if (compressor.option("dead_code")) { var a = []; if (self.alternative) { extract_declarations_from_unreachable_code(compressor, self.alternative, a); } a.push(self.body); return make_node(AST_BlockStatement, self, { body: a }).transform(compressor); } } else { compressor.warn("Condition always false [{file}:{line},{col}]", self.condition.start); if (compressor.option("dead_code")) { var a = []; extract_declarations_from_unreachable_code(compressor, self.body, a); if (self.alternative) a.push(self.alternative); return make_node(AST_BlockStatement, self, { body: a }).transform(compressor); } } } if (is_empty(self.alternative)) self.alternative = null; var negated = self.condition.negate(compressor); var negated_is_best = best_of(self.condition, negated) === negated; if (self.alternative && negated_is_best) { negated_is_best = false; // because we already do the switch here. self.condition = negated; var tmp = self.body; self.body = self.alternative || make_node(AST_EmptyStatement); self.alternative = tmp; } if (is_empty(self.body) && is_empty(self.alternative)) { return make_node(AST_SimpleStatement, self.condition, { body: self.condition }).transform(compressor); } if (self.body instanceof AST_SimpleStatement && self.alternative instanceof AST_SimpleStatement) { return make_node(AST_SimpleStatement, self, { body: make_node(AST_Conditional, self, { condition : self.condition, consequent : self.body.body, alternative : self.alternative.body }) }).transform(compressor); } if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) { if (negated_is_best) return make_node(AST_SimpleStatement, self, { body: make_node(AST_Binary, self, { operator : "||", left : negated, right : self.body.body }) }).transform(compressor); return make_node(AST_SimpleStatement, self, { body: make_node(AST_Binary, self, { operator : "&&", left : self.condition, right : self.body.body }) }).transform(compressor); } if (self.body instanceof AST_EmptyStatement && self.alternative && self.alternative instanceof AST_SimpleStatement) { return make_node(AST_SimpleStatement, self, { body: make_node(AST_Binary, self, { operator : "||", left : self.condition, right : self.alternative.body }) }).transform(compressor); } if (self.body instanceof AST_Exit && self.alternative instanceof AST_Exit && self.body.TYPE == self.alternative.TYPE) { return make_node(self.body.CTOR, self, { value: make_node(AST_Conditional, self, { condition : self.condition, consequent : self.body.value || make_node(AST_Undefined, self.body).optimize(compressor), alternative : self.alternative.value || make_node(AST_Undefined, self.alternative).optimize(compressor) }) }).transform(compressor); } if (self.body instanceof AST_If && !self.body.alternative && !self.alternative) { self.condition = make_node(AST_Binary, self.condition, { operator: "&&", left: self.condition, right: self.body.condition }).transform(compressor); self.body = self.body.body; } if (aborts(self.body)) { if (self.alternative) { var alt = self.alternative; self.alternative = null; return make_node(AST_BlockStatement, self, { body: [ self, alt ] }).transform(compressor); } } if (aborts(self.alternative)) { var body = self.body; self.body = self.alternative; self.condition = negated_is_best ? negated : self.condition.negate(compressor); self.alternative = null; return make_node(AST_BlockStatement, self, { body: [ self, body ] }).transform(compressor); } return self; }); OPT(AST_Switch, function(self, compressor){ if (self.body.length == 0 && compressor.option("conditionals")) { return make_node(AST_SimpleStatement, self, { body: self.expression }).transform(compressor); } for(;;) { var last_branch = self.body[self.body.length - 1]; if (last_branch) { var stat = last_branch.body[last_branch.body.length - 1]; // last statement if (stat instanceof AST_Break && loop_body(compressor.loopcontrol_target(stat.label)) === self) last_branch.body.pop(); if (last_branch instanceof AST_Default && last_branch.body.length == 0) { self.body.pop(); continue; } } break; } var exp = self.expression.evaluate(compressor); out: if (exp.length == 2) try { // constant expression self.expression = exp[0]; if (!compressor.option("dead_code")) break out; var value = exp[1]; var in_if = false; var in_block = false; var started = false; var stopped = false; var ruined = false; var tt = new TreeTransformer(function(node, descend, in_list){ if (node instanceof AST_Lambda || node instanceof AST_SimpleStatement) { // no need to descend these node types return node; } else if (node instanceof AST_Switch && node === self) { node = node.clone(); descend(node, this); return ruined ? node : make_node(AST_BlockStatement, node, { body: node.body.reduce(function(a, branch){ return a.concat(branch.body); }, []) }).transform(compressor); } else if (node instanceof AST_If || node instanceof AST_Try) { var save = in_if; in_if = !in_block; descend(node, this); in_if = save; return node; } else if (node instanceof AST_StatementWithBody || node instanceof AST_Switch) { var save = in_block; in_block = true; descend(node, this); in_block = save; return node; } else if (node instanceof AST_Break && this.loopcontrol_target(node.label) === self) { if (in_if) { ruined = true; return node; } if (in_block) return node; stopped = true; return in_list ? MAP.skip : make_node(AST_EmptyStatement, node); } else if (node instanceof AST_SwitchBranch && this.parent() === self) { if (stopped) return MAP.skip; if (node instanceof AST_Case) { var exp = node.expression.evaluate(compressor); if (exp.length < 2) { // got a case with non-constant expression, baling out throw self; } if (exp[1] === value || started) { started = true; if (aborts(node)) stopped = true; descend(node, this); return node; } return MAP.skip; } descend(node, this); return node; } }); tt.stack = compressor.stack.slice(); // so that's able to see parent nodes self = self.transform(tt); } catch(ex) { if (ex !== self) throw ex; } return self; }); OPT(AST_Case, function(self, compressor){ self.body = tighten_body(self.body, compressor); return self; }); OPT(AST_Try, function(self, compressor){ self.body = tighten_body(self.body, compressor); return self; }); AST_Definitions.DEFMETHOD("remove_initializers", function(){ this.definitions.forEach(function(def){ def.value = null }); }); AST_Definitions.DEFMETHOD("to_assignments", function(){ var assignments = this.definitions.reduce(function(a, def){ if (def.value) { var name = make_node(AST_SymbolRef, def.name, def.name); a.push(make_node(AST_Assign, def, { operator : "=", left : name, right : def.value })); } return a; }, []); if (assignments.length == 0) return null; return AST_Seq.from_array(assignments); }); OPT(AST_Definitions, function(self, compressor){ if (self.definitions.length == 0) return make_node(AST_EmptyStatement, self); return self; }); OPT(AST_Function, function(self, compressor){ self = AST_Lambda.prototype.optimize.call(self, compressor); if (compressor.option("unused")) { if (self.name && self.name.unreferenced()) { self.name = null; } } return self; }); OPT(AST_Call, function(self, compressor){ if (compressor.option("unsafe")) { var exp = self.expression; if (exp instanceof AST_SymbolRef && exp.undeclared()) { switch (exp.name) { case "Array": if (self.args.length != 1) { return make_node(AST_Array, self, { elements: self.args }).transform(compressor); } break; case "Object": if (self.args.length == 0) { return make_node(AST_Object, self, { properties: [] }); } break; case "String": if (self.args.length == 0) return make_node(AST_String, self, { value: "" }); if (self.args.length <= 1) return make_node(AST_Binary, self, { left: self.args[0], operator: "+", right: make_node(AST_String, self, { value: "" }) }).transform(compressor); break; case "Number": if (self.args.length == 0) return make_node(AST_Number, self, { value: 0 }); if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, { expression: self.args[0], operator: "+" }).transform(compressor); case "Boolean": if (self.args.length == 0) return make_node(AST_False, self); if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, { expression: make_node(AST_UnaryPrefix, null, { expression: self.args[0], operator: "!" }), operator: "!" }).transform(compressor); break; case "Function": if (all(self.args, function(x){ return x instanceof AST_String })) { // quite a corner-case, but we can handle it: // https://github.com/mishoo/UglifyJS2/issues/203 // if the code argument is a constant, then we can minify it. try { var code = "(function(" + self.args.slice(0, -1).map(function(arg){ return arg.value; }).join(",") + "){" + self.args[self.args.length - 1].value + "})()"; var ast = parse(code); ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") }); var comp = new Compressor(compressor.options); ast = ast.transform(comp); ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") }); ast.mangle_names(); var fun; try { ast.walk(new TreeWalker(function(node){ if (node instanceof AST_Lambda) { fun = node; throw ast; } })); } catch(ex) { if (ex !== ast) throw ex; }; var args = fun.argnames.map(function(arg, i){ return make_node(AST_String, self.args[i], { value: arg.print_to_string() }); }); var code = OutputStream(); AST_BlockStatement.prototype._codegen.call(fun, fun, code); code = code.toString().replace(/^\{|\}$/g, ""); args.push(make_node(AST_String, self.args[self.args.length - 1], { value: code })); self.args = args; return self; } catch(ex) { if (ex instanceof JS_Parse_Error) { compressor.warn("Error parsing code passed to new Function [{file}:{line},{col}]", self.args[self.args.length - 1].start); compressor.warn(ex.toString()); } else { console.log(ex); throw ex; } } } break; } } else if (exp instanceof AST_Dot && exp.property == "toString" && self.args.length == 0) { return make_node(AST_Binary, self, { left: make_node(AST_String, self, { value: "" }), operator: "+", right: exp.expression }).transform(compressor); } else if (exp instanceof AST_Dot && exp.expression instanceof AST_Array && exp.property == "join") EXIT: { var separator = self.args.length == 0 ? "," : self.args[0].evaluate(compressor)[1]; if (separator == null) break EXIT; // not a constant var elements = exp.expression.elements.reduce(function(a, el){ el = el.evaluate(compressor); if (a.length == 0 || el.length == 1) { a.push(el); } else { var last = a[a.length - 1]; if (last.length == 2) { // it's a constant var val = "" + last[1] + separator + el[1]; a[a.length - 1] = [ make_node_from_constant(compressor, val, last[0]), val ]; } else { a.push(el); } } return a; }, []); if (elements.length == 0) return make_node(AST_String, self, { value: "" }); if (elements.length == 1) return elements[0][0]; if (separator == "") { var first; if (elements[0][0] instanceof AST_String || elements[1][0] instanceof AST_String) { first = elements.shift()[0]; } else { first = make_node(AST_String, self, { value: "" }); } return elements.reduce(function(prev, el){ return make_node(AST_Binary, el[0], { operator : "+", left : prev, right : el[0], }); }, first).transform(compressor); } // need this awkward cloning to not affect original element // best_of will decide which one to get through. var node = self.clone(); node.expression = node.expression.clone(); node.expression.expression = node.expression.expression.clone(); node.expression.expression.elements = elements.map(function(el){ return el[0]; }); return best_of(self, node); } } if (compressor.option("side_effects")) { if (self.expression instanceof AST_Function && self.args.length == 0 && !AST_Block.prototype.has_side_effects.call(self.expression, compressor)) { return make_node(AST_Undefined, self).transform(compressor); } } if (compressor.option("drop_console")) { if (self.expression instanceof AST_PropAccess && self.expression.expression instanceof AST_SymbolRef && self.expression.expression.name == "console" && self.expression.expression.undeclared()) { return make_node(AST_Undefined, self).transform(compressor); } } return self.evaluate(compressor)[0]; }); OPT(AST_New, function(self, compressor){ if (compressor.option("unsafe")) { var exp = self.expression; if (exp instanceof AST_SymbolRef && exp.undeclared()) { switch (exp.name) { case "Object": case "RegExp": case "Function": case "Error": case "Array": return make_node(AST_Call, self, self).transform(compressor); } } } return self; }); OPT(AST_Seq, function(self, compressor){ if (!compressor.option("side_effects")) return self; if (!self.car.has_side_effects(compressor)) { // we shouldn't compress (1,eval)(something) to // eval(something) because that changes the meaning of // eval (becomes lexical instead of global). var p; if (!(self.cdr instanceof AST_SymbolRef && self.cdr.name == "eval" && self.cdr.undeclared() && (p = compressor.parent()) instanceof AST_Call && p.expression === self)) { return self.cdr; } } if (compressor.option("cascade")) { if (self.car instanceof AST_Assign && !self.car.left.has_side_effects(compressor)) { if (self.car.left.equivalent_to(self.cdr)) { return self.car; } if (self.cdr instanceof AST_Call && self.cdr.expression.equivalent_to(self.car.left)) { self.cdr.expression = self.car; return self.cdr; } } if (!self.car.has_side_effects(compressor) && !self.cdr.has_side_effects(compressor) && self.car.equivalent_to(self.cdr)) { return self.car; } } if (self.cdr instanceof AST_UnaryPrefix && self.cdr.operator == "void" && !self.cdr.expression.has_side_effects(compressor)) { self.cdr.operator = self.car; return self.cdr; } if (self.cdr instanceof AST_Undefined) { return make_node(AST_UnaryPrefix, self, { operator : "void", expression : self.car }); } return self; }); AST_Unary.DEFMETHOD("lift_sequences", function(compressor){ if (compressor.option("sequences")) { if (this.expression instanceof AST_Seq) { var seq = this.expression; var x = seq.to_array(); this.expression = x.pop(); x.push(this); seq = AST_Seq.from_array(x).transform(compressor); return seq; } } return this; }); OPT(AST_UnaryPostfix, function(self, compressor){ return self.lift_sequences(compressor); }); OPT(AST_UnaryPrefix, function(self, compressor){ self = self.lift_sequences(compressor); var e = self.expression; if (compressor.option("booleans") && compressor.in_boolean_context()) { switch (self.operator) { case "!": if (e instanceof AST_UnaryPrefix && e.operator == "!") { // !!foo ==> foo, if we're in boolean context return e.expression; } break; case "typeof": // typeof always returns a non-empty string, thus it's // always true in booleans compressor.warn("Boolean expression always true [{file}:{line},{col}]", self.start); return make_node(AST_True, self); } if (e instanceof AST_Binary && self.operator == "!") { self = best_of(self, e.negate(compressor)); } } return self.evaluate(compressor)[0]; }); function has_side_effects_or_prop_access(node, compressor) { var save_pure_getters = compressor.option("pure_getters"); compressor.options.pure_getters = false; var ret = node.has_side_effects(compressor); compressor.options.pure_getters = save_pure_getters; return ret; } AST_Binary.DEFMETHOD("lift_sequences", function(compressor){ if (compressor.option("sequences")) { if (this.left instanceof AST_Seq) { var seq = this.left; var x = seq.to_array(); this.left = x.pop(); x.push(this); seq = AST_Seq.from_array(x).transform(compressor); return seq; } if (this.right instanceof AST_Seq && this instanceof AST_Assign && !has_side_effects_or_prop_access(this.left, compressor)) { var seq = this.right; var x = seq.to_array(); this.right = x.pop(); x.push(this); seq = AST_Seq.from_array(x).transform(compressor); return seq; } } return this; }); var commutativeOperators = makePredicate("== === != !== * & | ^"); OPT(AST_Binary, function(self, compressor){ var reverse = compressor.has_directive("use asm") ? noop : function(op, force) { if (force || !(self.left.has_side_effects(compressor) || self.right.has_side_effects(compressor))) { if (op) self.operator = op; var tmp = self.left; self.left = self.right; self.right = tmp; } }; if (commutativeOperators(self.operator)) { if (self.right instanceof AST_Constant && !(self.left instanceof AST_Constant)) { // if right is a constant, whatever side effects the // left side might have could not influence the // result. hence, force switch. if (!(self.left instanceof AST_Binary && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) { reverse(null, true); } } if (/^[!=]==?$/.test(self.operator)) { if (self.left instanceof AST_SymbolRef && self.right instanceof AST_Conditional) { if (self.right.consequent instanceof AST_SymbolRef && self.right.consequent.definition() === self.left.definition()) { if (/^==/.test(self.operator)) return self.right.condition; if (/^!=/.test(self.operator)) return self.right.condition.negate(compressor); } if (self.right.alternative instanceof AST_SymbolRef && self.right.alternative.definition() === self.left.definition()) { if (/^==/.test(self.operator)) return self.right.condition.negate(compressor); if (/^!=/.test(self.operator)) return self.right.condition; } } if (self.right instanceof AST_SymbolRef && self.left instanceof AST_Conditional) { if (self.left.consequent instanceof AST_SymbolRef && self.left.consequent.definition() === self.right.definition()) { if (/^==/.test(self.operator)) return self.left.condition; if (/^!=/.test(self.operator)) return self.left.condition.negate(compressor); } if (self.left.alternative instanceof AST_SymbolRef && self.left.alternative.definition() === self.right.definition()) { if (/^==/.test(self.operator)) return self.left.condition.negate(compressor); if (/^!=/.test(self.operator)) return self.left.condition; } } } } self = self.lift_sequences(compressor); if (compressor.option("comparisons")) switch (self.operator) { case "===": case "!==": if ((self.left.is_string(compressor) && self.right.is_string(compressor)) || (self.left.is_boolean() && self.right.is_boolean())) { self.operator = self.operator.substr(0, 2); } // XXX: intentionally falling down to the next case case "==": case "!=": if (self.left instanceof AST_String && self.left.value == "undefined" && self.right instanceof AST_UnaryPrefix && self.right.operator == "typeof" && compressor.option("unsafe")) { if (!(self.right.expression instanceof AST_SymbolRef) || !self.right.expression.undeclared()) { self.right = self.right.expression; self.left = make_node(AST_Undefined, self.left).optimize(compressor); if (self.operator.length == 2) self.operator += "="; } } break; } if (compressor.option("booleans") && compressor.in_boolean_context()) switch (self.operator) { case "&&": var ll = self.left.evaluate(compressor); var rr = self.right.evaluate(compressor); if ((ll.length > 1 && !ll[1]) || (rr.length > 1 && !rr[1])) { compressor.warn("Boolean && always false [{file}:{line},{col}]", self.start); return make_node(AST_False, self); } if (ll.length > 1 && ll[1]) { return rr[0]; } if (rr.length > 1 && rr[1]) { return ll[0]; } break; case "||": var ll = self.left.evaluate(compressor); var rr = self.right.evaluate(compressor); if ((ll.length > 1 && ll[1]) || (rr.length > 1 && rr[1])) { compressor.warn("Boolean || always true [{file}:{line},{col}]", self.start); return make_node(AST_True, self); } if (ll.length > 1 && !ll[1]) { return rr[0]; } if (rr.length > 1 && !rr[1]) { return ll[0]; } break; case "+": var ll = self.left.evaluate(compressor); var rr = self.right.evaluate(compressor); if ((ll.length > 1 && ll[0] instanceof AST_String && ll[1]) || (rr.length > 1 && rr[0] instanceof AST_String && rr[1])) { compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start); return make_node(AST_True, self); } break; } if (compressor.option("comparisons")) { if (!(compressor.parent() instanceof AST_Binary) || compressor.parent() instanceof AST_Assign) { var negated = make_node(AST_UnaryPrefix, self, { operator: "!", expression: self.negate(compressor) }); self = best_of(self, negated); } switch (self.operator) { case "<": reverse(">"); break; case "<=": reverse(">="); break; } } if (self.operator == "+" && self.right instanceof AST_String && self.right.getValue() === "" && self.left instanceof AST_Binary && self.left.operator == "+" && self.left.is_string(compressor)) { return self.left; } if (compressor.option("evaluate")) { if (self.operator == "+") { if (self.left instanceof AST_Constant && self.right instanceof AST_Binary && self.right.operator == "+" && self.right.left instanceof AST_Constant && self.right.is_string(compressor)) { self = make_node(AST_Binary, self, { operator: "+", left: make_node(AST_String, null, { value: "" + self.left.getValue() + self.right.left.getValue(), start: self.left.start, end: self.right.left.end }), right: self.right.right }); } if (self.right instanceof AST_Constant && self.left instanceof AST_Binary && self.left.operator == "+" && self.left.right instanceof AST_Constant && self.left.is_string(compressor)) { self = make_node(AST_Binary, self, { operator: "+", left: self.left.left, right: make_node(AST_String, null, { value: "" + self.left.right.getValue() + self.right.getValue(), start: self.left.right.start, end: self.right.end }) }); } if (self.left instanceof AST_Binary && self.left.operator == "+" && self.left.is_string(compressor) && self.left.right instanceof AST_Constant && self.right instanceof AST_Binary && self.right.operator == "+" && self.right.left instanceof AST_Constant && self.right.is_string(compressor)) { self = make_node(AST_Binary, self, { operator: "+", left: make_node(AST_Binary, self.left, { operator: "+", left: self.left.left, right: make_node(AST_String, null, { value: "" + self.left.right.getValue() + self.right.left.getValue(), start: self.left.right.start, end: self.right.left.end }) }), right: self.right.right }); } } } // x * (y * z) ==> x * y * z if (self.right instanceof AST_Binary && self.right.operator == self.operator && (self.operator == "*" || self.operator == "&&" || self.operator == "||")) { self.left = make_node(AST_Binary, self.left, { operator : self.operator, left : self.left, right : self.right.left }); self.right = self.right.right; return self.transform(compressor); } return self.evaluate(compressor)[0]; }); OPT(AST_SymbolRef, function(self, compressor){ if (self.undeclared()) { var defines = compressor.option("global_defs"); if (defines && defines.hasOwnProperty(self.name)) { return make_node_from_constant(compressor, defines[self.name], self); } switch (self.name) { case "undefined": return make_node(AST_Undefined, self); case "NaN": return make_node(AST_NaN, self); case "Infinity": return make_node(AST_Infinity, self); } } return self; }); OPT(AST_Undefined, function(self, compressor){ if (compressor.option("unsafe")) { var scope = compressor.find_parent(AST_Scope); var undef = scope.find_variable("undefined"); if (undef) { var ref = make_node(AST_SymbolRef, self, { name : "undefined", scope : scope, thedef : undef }); ref.reference(); return ref; } } return self; }); var ASSIGN_OPS = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ]; OPT(AST_Assign, function(self, compressor){ self = self.lift_sequences(compressor); if (self.operator == "=" && self.left instanceof AST_SymbolRef && self.right instanceof AST_Binary && self.right.left instanceof AST_SymbolRef && self.right.left.name == self.left.name && member(self.right.operator, ASSIGN_OPS)) { self.operator = self.right.operator + "="; self.right = self.right.right; } return self; }); OPT(AST_Conditional, function(self, compressor){ if (!compressor.option("conditionals")) return self; if (self.condition instanceof AST_Seq) { var car = self.condition.car; self.condition = self.condition.cdr; return AST_Seq.cons(car, self); } var cond = self.condition.evaluate(compressor); if (cond.length > 1) { if (cond[1]) { compressor.warn("Condition always true [{file}:{line},{col}]", self.start); return self.consequent; } else { compressor.warn("Condition always false [{file}:{line},{col}]", self.start); return self.alternative; } } var negated = cond[0].negate(compressor); if (best_of(cond[0], negated) === negated) { self = make_node(AST_Conditional, self, { condition: negated, consequent: self.alternative, alternative: self.consequent }); } var consequent = self.consequent; var alternative = self.alternative; if (consequent instanceof AST_Assign && alternative instanceof AST_Assign && consequent.operator == alternative.operator && consequent.left.equivalent_to(alternative.left) ) { /* * Stuff like this: * if (foo) exp = something; else exp = something_else; * ==> * exp = foo ? something : something_else; */ return make_node(AST_Assign, self, { operator: consequent.operator, left: consequent.left, right: make_node(AST_Conditional, self, { condition: self.condition, consequent: consequent.right, alternative: alternative.right }) }); } if (consequent instanceof AST_Call && alternative.TYPE === consequent.TYPE && consequent.args.length == alternative.args.length && consequent.expression.equivalent_to(alternative.expression)) { if (consequent.args.length == 0) { return make_node(AST_Seq, self, { car: self.condition, cdr: consequent }); } if (consequent.args.length == 1) { consequent.args[0] = make_node(AST_Conditional, self, { condition: self.condition, consequent: consequent.args[0], alternative: alternative.args[0] }); return consequent; } } // x?y?z:a:a --> x&&y?z:a if (consequent instanceof AST_Conditional && consequent.alternative.equivalent_to(alternative)) { return make_node(AST_Conditional, self, { condition: make_node(AST_Binary, self, { left: self.condition, operator: "&&", right: consequent.condition }), consequent: consequent.consequent, alternative: alternative }); } return self; }); OPT(AST_Boolean, function(self, compressor){ if (compressor.option("booleans")) { var p = compressor.parent(); if (p instanceof AST_Binary && (p.operator == "==" || p.operator == "!=")) { compressor.warn("Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]", { operator : p.operator, value : self.value, file : p.start.file, line : p.start.line, col : p.start.col, }); return make_node(AST_Number, self, { value: +self.value }); } return make_node(AST_UnaryPrefix, self, { operator: "!", expression: make_node(AST_Number, self, { value: 1 - self.value }) }); } return self; }); OPT(AST_Sub, function(self, compressor){ var prop = self.property; if (prop instanceof AST_String && compressor.option("properties")) { prop = prop.getValue(); if (RESERVED_WORDS(prop) ? compressor.option("screw_ie8") : is_identifier_string(prop)) { return make_node(AST_Dot, self, { expression : self.expression, property : prop }).optimize(compressor); } var v = parseFloat(prop); if (!isNaN(v) && v.toString() == prop) { self.property = make_node(AST_Number, self.property, { value: v }); } } return self; }); OPT(AST_Dot, function(self, compressor){ return self.evaluate(compressor)[0]; }); function literals_in_boolean_context(self, compressor) { if (compressor.option("booleans") && compressor.in_boolean_context()) { return make_node(AST_True, self); } return self; }; OPT(AST_Array, literals_in_boolean_context); OPT(AST_Object, literals_in_boolean_context); OPT(AST_RegExp, literals_in_boolean_context); })(); UglifyJS2-2.4.15/lib/mozilla-ast.js000066400000000000000000000261701235725452400167400ustar00rootroot00000000000000/*********************************************************************** A JavaScript tokenizer / parser / beautifier / compressor. https://github.com/mishoo/UglifyJS2 -------------------------------- (C) --------------------------------- Author: Mihai Bazon http://mihai.bazon.net/blog Distributed under the BSD license: Copyright 2012 (c) Mihai Bazon Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ "use strict"; (function(){ var MOZ_TO_ME = { TryStatement : function(M) { return new AST_Try({ start : my_start_token(M), end : my_end_token(M), body : from_moz(M.block).body, bcatch : from_moz(M.handlers ? M.handlers[0] : M.handler), bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null }); }, CatchClause : function(M) { return new AST_Catch({ start : my_start_token(M), end : my_end_token(M), argname : from_moz(M.param), body : from_moz(M.body).body }); }, ObjectExpression : function(M) { return new AST_Object({ start : my_start_token(M), end : my_end_token(M), properties : M.properties.map(function(prop){ var key = prop.key; var name = key.type == "Identifier" ? key.name : key.value; var args = { start : my_start_token(key), end : my_end_token(prop.value), key : name, value : from_moz(prop.value) }; switch (prop.kind) { case "init": return new AST_ObjectKeyVal(args); case "set": args.value.name = from_moz(key); return new AST_ObjectSetter(args); case "get": args.value.name = from_moz(key); return new AST_ObjectGetter(args); } }) }); }, SequenceExpression : function(M) { return AST_Seq.from_array(M.expressions.map(from_moz)); }, MemberExpression : function(M) { return new (M.computed ? AST_Sub : AST_Dot)({ start : my_start_token(M), end : my_end_token(M), property : M.computed ? from_moz(M.property) : M.property.name, expression : from_moz(M.object) }); }, SwitchCase : function(M) { return new (M.test ? AST_Case : AST_Default)({ start : my_start_token(M), end : my_end_token(M), expression : from_moz(M.test), body : M.consequent.map(from_moz) }); }, Literal : function(M) { var val = M.value, args = { start : my_start_token(M), end : my_end_token(M) }; if (val === null) return new AST_Null(args); switch (typeof val) { case "string": args.value = val; return new AST_String(args); case "number": args.value = val; return new AST_Number(args); case "boolean": return new (val ? AST_True : AST_False)(args); default: args.value = val; return new AST_RegExp(args); } }, UnaryExpression: From_Moz_Unary, UpdateExpression: From_Moz_Unary, Identifier: function(M) { var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2]; return new (M.name == "this" ? AST_This : p.type == "LabeledStatement" ? AST_Label : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : AST_SymbolVar) : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg) : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg) : p.type == "CatchClause" ? AST_SymbolCatch : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef : AST_SymbolRef)({ start : my_start_token(M), end : my_end_token(M), name : M.name }); } }; function From_Moz_Unary(M) { var prefix = "prefix" in M ? M.prefix : M.type == "UnaryExpression" ? true : false; return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({ start : my_start_token(M), end : my_end_token(M), operator : M.operator, expression : from_moz(M.argument) }); }; var ME_TO_MOZ = {}; map("Node", AST_Node); map("Program", AST_Toplevel, "body@body"); map("Function", AST_Function, "id>name, params@argnames, body%body"); map("EmptyStatement", AST_EmptyStatement); map("BlockStatement", AST_BlockStatement, "body@body"); map("ExpressionStatement", AST_SimpleStatement, "expression>body"); map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative"); map("LabeledStatement", AST_LabeledStatement, "label>label, body>body"); map("BreakStatement", AST_Break, "label>label"); map("ContinueStatement", AST_Continue, "label>label"); map("WithStatement", AST_With, "object>expression, body>body"); map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body"); map("ReturnStatement", AST_Return, "argument>value"); map("ThrowStatement", AST_Throw, "argument>value"); map("WhileStatement", AST_While, "test>condition, body>body"); map("DoWhileStatement", AST_Do, "test>condition, body>body"); map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body"); map("ForInStatement", AST_ForIn, "left>init, right>object, body>body"); map("DebuggerStatement", AST_Debugger); map("FunctionDeclaration", AST_Defun, "id>name, params@argnames, body%body"); map("VariableDeclaration", AST_Var, "declarations@definitions"); map("VariableDeclarator", AST_VarDef, "id>name, init>value"); map("ThisExpression", AST_This); map("ArrayExpression", AST_Array, "elements@elements"); map("FunctionExpression", AST_Function, "id>name, params@argnames, body%body"); map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right"); map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right"); map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right"); map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative"); map("NewExpression", AST_New, "callee>expression, arguments@args"); map("CallExpression", AST_Call, "callee>expression, arguments@args"); /* -----[ tools ]----- */ function my_start_token(moznode) { return new AST_Token({ file : moznode.loc && moznode.loc.source, line : moznode.loc && moznode.loc.start.line, col : moznode.loc && moznode.loc.start.column, pos : moznode.start, endpos : moznode.start }); }; function my_end_token(moznode) { return new AST_Token({ file : moznode.loc && moznode.loc.source, line : moznode.loc && moznode.loc.end.line, col : moznode.loc && moznode.loc.end.column, pos : moznode.end, endpos : moznode.end }); }; function map(moztype, mytype, propmap) { var moz_to_me = "function From_Moz_" + moztype + "(M){\n"; moz_to_me += "return new mytype({\n" + "start: my_start_token(M),\n" + "end: my_end_token(M)"; if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop){ var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop); if (!m) throw new Error("Can't understand property map: " + prop); var moz = "M." + m[1], how = m[2], my = m[3]; moz_to_me += ",\n" + my + ": "; if (how == "@") { moz_to_me += moz + ".map(from_moz)"; } else if (how == ">") { moz_to_me += "from_moz(" + moz + ")"; } else if (how == "=") { moz_to_me += moz; } else if (how == "%") { moz_to_me += "from_moz(" + moz + ").body"; } else throw new Error("Can't understand operator in propmap: " + prop); }); moz_to_me += "\n})}"; // moz_to_me = parse(moz_to_me).print_to_string({ beautify: true }); // console.log(moz_to_me); moz_to_me = new Function("mytype", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")( mytype, my_start_token, my_end_token, from_moz ); return MOZ_TO_ME[moztype] = moz_to_me; }; var FROM_MOZ_STACK = null; function from_moz(node) { FROM_MOZ_STACK.push(node); var ret = node != null ? MOZ_TO_ME[node.type](node) : null; FROM_MOZ_STACK.pop(); return ret; }; AST_Node.from_mozilla_ast = function(node){ var save_stack = FROM_MOZ_STACK; FROM_MOZ_STACK = []; var ast = from_moz(node); FROM_MOZ_STACK = save_stack; return ast; }; })(); UglifyJS2-2.4.15/lib/output.js000066400000000000000000001251061235725452400160430ustar00rootroot00000000000000/*********************************************************************** A JavaScript tokenizer / parser / beautifier / compressor. https://github.com/mishoo/UglifyJS2 -------------------------------- (C) --------------------------------- Author: Mihai Bazon http://mihai.bazon.net/blog Distributed under the BSD license: Copyright 2012 (c) Mihai Bazon Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ "use strict"; function OutputStream(options) { options = defaults(options, { indent_start : 0, indent_level : 4, quote_keys : false, space_colon : true, ascii_only : false, unescape_regexps : false, inline_script : false, width : 80, max_line_len : 32000, beautify : false, source_map : null, bracketize : false, semicolons : true, comments : false, preserve_line : false, screw_ie8 : false, preamble : null, }, true); var indentation = 0; var current_col = 0; var current_line = 1; var current_pos = 0; var OUTPUT = ""; function to_ascii(str, identifier) { return str.replace(/[\u0080-\uffff]/g, function(ch) { var code = ch.charCodeAt(0).toString(16); if (code.length <= 2 && !identifier) { while (code.length < 2) code = "0" + code; return "\\x" + code; } else { while (code.length < 4) code = "0" + code; return "\\u" + code; } }); }; function make_string(str) { var dq = 0, sq = 0; str = str.replace(/[\\\b\f\n\r\t\x22\x27\u2028\u2029\0]/g, function(s){ switch (s) { case "\\": return "\\\\"; case "\b": return "\\b"; case "\f": return "\\f"; case "\n": return "\\n"; case "\r": return "\\r"; case "\u2028": return "\\u2028"; case "\u2029": return "\\u2029"; case '"': ++dq; return '"'; case "'": ++sq; return "'"; case "\0": return "\\x00"; } return s; }); if (options.ascii_only) str = to_ascii(str); if (dq > sq) return "'" + str.replace(/\x27/g, "\\'") + "'"; else return '"' + str.replace(/\x22/g, '\\"') + '"'; }; function encode_string(str) { var ret = make_string(str); if (options.inline_script) ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1"); return ret; }; function make_name(name) { name = name.toString(); if (options.ascii_only) name = to_ascii(name, true); return name; }; function make_indent(back) { return repeat_string(" ", options.indent_start + indentation - back * options.indent_level); }; /* -----[ beautification/minification ]----- */ var might_need_space = false; var might_need_semicolon = false; var last = null; function last_char() { return last.charAt(last.length - 1); }; function maybe_newline() { if (options.max_line_len && current_col > options.max_line_len) print("\n"); }; var requireSemicolonChars = makePredicate("( [ + * / - , ."); function print(str) { str = String(str); var ch = str.charAt(0); if (might_need_semicolon) { if ((!ch || ";}".indexOf(ch) < 0) && !/[;]$/.test(last)) { if (options.semicolons || requireSemicolonChars(ch)) { OUTPUT += ";"; current_col++; current_pos++; } else { OUTPUT += "\n"; current_pos++; current_line++; current_col = 0; } if (!options.beautify) might_need_space = false; } might_need_semicolon = false; maybe_newline(); } if (!options.beautify && options.preserve_line && stack[stack.length - 1]) { var target_line = stack[stack.length - 1].start.line; while (current_line < target_line) { OUTPUT += "\n"; current_pos++; current_line++; current_col = 0; might_need_space = false; } } if (might_need_space) { var prev = last_char(); if ((is_identifier_char(prev) && (is_identifier_char(ch) || ch == "\\")) || (/^[\+\-\/]$/.test(ch) && ch == prev)) { OUTPUT += " "; current_col++; current_pos++; } might_need_space = false; } var a = str.split(/\r?\n/), n = a.length - 1; current_line += n; if (n == 0) { current_col += a[n].length; } else { current_col = a[n].length; } current_pos += str.length; last = str; OUTPUT += str; }; var space = options.beautify ? function() { print(" "); } : function() { might_need_space = true; }; var indent = options.beautify ? function(half) { if (options.beautify) { print(make_indent(half ? 0.5 : 0)); } } : noop; var with_indent = options.beautify ? function(col, cont) { if (col === true) col = next_indent(); var save_indentation = indentation; indentation = col; var ret = cont(); indentation = save_indentation; return ret; } : function(col, cont) { return cont() }; var newline = options.beautify ? function() { print("\n"); } : noop; var semicolon = options.beautify ? function() { print(";"); } : function() { might_need_semicolon = true; }; function force_semicolon() { might_need_semicolon = false; print(";"); }; function next_indent() { return indentation + options.indent_level; }; function with_block(cont) { var ret; print("{"); newline(); with_indent(next_indent(), function(){ ret = cont(); }); indent(); print("}"); return ret; }; function with_parens(cont) { print("("); //XXX: still nice to have that for argument lists //var ret = with_indent(current_col, cont); var ret = cont(); print(")"); return ret; }; function with_square(cont) { print("["); //var ret = with_indent(current_col, cont); var ret = cont(); print("]"); return ret; }; function comma() { print(","); space(); }; function colon() { print(":"); if (options.space_colon) space(); }; var add_mapping = options.source_map ? function(token, name) { try { if (token) options.source_map.add( token.file || "?", current_line, current_col, token.line, token.col, (!name && token.type == "name") ? token.value : name ); } catch(ex) { AST_Node.warn("Couldn't figure out mapping for {file}:{line},{col} → {cline},{ccol} [{name}]", { file: token.file, line: token.line, col: token.col, cline: current_line, ccol: current_col, name: name || "" }) } } : noop; function get() { return OUTPUT; }; if (options.preamble) { print(options.preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g, "\n")); } var stack = []; return { get : get, toString : get, indent : indent, indentation : function() { return indentation }, current_width : function() { return current_col - indentation }, should_break : function() { return options.width && this.current_width() >= options.width }, newline : newline, print : print, space : space, comma : comma, colon : colon, last : function() { return last }, semicolon : semicolon, force_semicolon : force_semicolon, to_ascii : to_ascii, print_name : function(name) { print(make_name(name)) }, print_string : function(str) { print(encode_string(str)) }, next_indent : next_indent, with_indent : with_indent, with_block : with_block, with_parens : with_parens, with_square : with_square, add_mapping : add_mapping, option : function(opt) { return options[opt] }, line : function() { return current_line }, col : function() { return current_col }, pos : function() { return current_pos }, push_node : function(node) { stack.push(node) }, pop_node : function() { return stack.pop() }, stack : function() { return stack }, parent : function(n) { return stack[stack.length - 2 - (n || 0)]; } }; }; /* -----[ code generators ]----- */ (function(){ /* -----[ utils ]----- */ function DEFPRINT(nodetype, generator) { nodetype.DEFMETHOD("_codegen", generator); }; AST_Node.DEFMETHOD("print", function(stream, force_parens){ var self = this, generator = self._codegen; function doit() { self.add_comments(stream); self.add_source_map(stream); generator(self, stream); } stream.push_node(self); if (force_parens || self.needs_parens(stream)) { stream.with_parens(doit); } else { doit(); } stream.pop_node(); }); AST_Node.DEFMETHOD("print_to_string", function(options){ var s = OutputStream(options); this.print(s); return s.get(); }); /* -----[ comments ]----- */ AST_Node.DEFMETHOD("add_comments", function(output){ var c = output.option("comments"), self = this; if (c) { var start = self.start; if (start && !start._comments_dumped) { start._comments_dumped = true; var comments = start.comments_before || []; // XXX: ugly fix for https://github.com/mishoo/UglifyJS2/issues/112 // and https://github.com/mishoo/UglifyJS2/issues/372 if (self instanceof AST_Exit && self.value) { self.value.walk(new TreeWalker(function(node){ if (node.start && node.start.comments_before) { comments = comments.concat(node.start.comments_before); node.start.comments_before = []; } if (node instanceof AST_Function || node instanceof AST_Array || node instanceof AST_Object) { return true; // don't go inside. } })); } if (c.test) { comments = comments.filter(function(comment){ return c.test(comment.value); }); } else if (typeof c == "function") { comments = comments.filter(function(comment){ return c(self, comment); }); } comments.forEach(function(c){ if (/comment[134]/.test(c.type)) { output.print("//" + c.value + "\n"); output.indent(); } else if (c.type == "comment2") { output.print("/*" + c.value + "*/"); if (start.nlb) { output.print("\n"); output.indent(); } else { output.space(); } } }); } } }); /* -----[ PARENTHESES ]----- */ function PARENS(nodetype, func) { nodetype.DEFMETHOD("needs_parens", func); }; PARENS(AST_Node, function(){ return false; }); // a function expression needs parens around it when it's provably // the first token to appear in a statement. PARENS(AST_Function, function(output){ return first_in_statement(output); }); // same goes for an object literal, because otherwise it would be // interpreted as a block of code. PARENS(AST_Object, function(output){ return first_in_statement(output); }); PARENS(AST_Unary, function(output){ var p = output.parent(); return p instanceof AST_PropAccess && p.expression === this; }); PARENS(AST_Seq, function(output){ var p = output.parent(); return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4) || p instanceof AST_Unary // !(foo, bar, baz) || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8 || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4 || p instanceof AST_PropAccess // (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2 || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ] || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2 || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30) * ==> 20 (side effect, set a := 10 and b := 20) */ ; }); PARENS(AST_Binary, function(output){ var p = output.parent(); // (foo && bar)() if (p instanceof AST_Call && p.expression === this) return true; // typeof (foo && bar) if (p instanceof AST_Unary) return true; // (foo && bar)["prop"], (foo && bar).prop if (p instanceof AST_PropAccess && p.expression === this) return true; // this deals with precedence: 3 * (2 + 1) if (p instanceof AST_Binary) { var po = p.operator, pp = PRECEDENCE[po]; var so = this.operator, sp = PRECEDENCE[so]; if (pp > sp || (pp == sp && this === p.right)) { return true; } } }); PARENS(AST_PropAccess, function(output){ var p = output.parent(); if (p instanceof AST_New && p.expression === this) { // i.e. new (foo.bar().baz) // // if there's one call into this subtree, then we need // parens around it too, otherwise the call will be // interpreted as passing the arguments to the upper New // expression. try { this.walk(new TreeWalker(function(node){ if (node instanceof AST_Call) throw p; })); } catch(ex) { if (ex !== p) throw ex; return true; } } }); PARENS(AST_Call, function(output){ var p = output.parent(), p1; if (p instanceof AST_New && p.expression === this) return true; // workaround for Safari bug. // https://bugs.webkit.org/show_bug.cgi?id=123506 return this.expression instanceof AST_Function && p instanceof AST_PropAccess && p.expression === this && (p1 = output.parent(1)) instanceof AST_Assign && p1.left === p; }); PARENS(AST_New, function(output){ var p = output.parent(); if (no_constructor_parens(this, output) && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]() || p instanceof AST_Call && p.expression === this)) // (new foo)(bar) return true; }); PARENS(AST_Number, function(output){ var p = output.parent(); if (this.getValue() < 0 && p instanceof AST_PropAccess && p.expression === this) return true; }); PARENS(AST_NaN, function(output){ var p = output.parent(); if (p instanceof AST_PropAccess && p.expression === this) return true; }); function assign_and_conditional_paren_rules(output) { var p = output.parent(); // !(a = false) → true if (p instanceof AST_Unary) return true; // 1 + (a = 2) + 3 → 6, side effect setting a = 2 if (p instanceof AST_Binary && !(p instanceof AST_Assign)) return true; // (a = func)() —or— new (a = Object)() if (p instanceof AST_Call && p.expression === this) return true; // (a = foo) ? bar : baz if (p instanceof AST_Conditional && p.condition === this) return true; // (a = foo)["prop"] —or— (a = foo).prop if (p instanceof AST_PropAccess && p.expression === this) return true; }; PARENS(AST_Assign, assign_and_conditional_paren_rules); PARENS(AST_Conditional, assign_and_conditional_paren_rules); /* -----[ PRINTERS ]----- */ DEFPRINT(AST_Directive, function(self, output){ output.print_string(self.value); output.semicolon(); }); DEFPRINT(AST_Debugger, function(self, output){ output.print("debugger"); output.semicolon(); }); /* -----[ statements ]----- */ function display_body(body, is_toplevel, output) { var last = body.length - 1; body.forEach(function(stmt, i){ if (!(stmt instanceof AST_EmptyStatement)) { output.indent(); stmt.print(output); if (!(i == last && is_toplevel)) { output.newline(); if (is_toplevel) output.newline(); } } }); }; AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output){ force_statement(this.body, output); }); DEFPRINT(AST_Statement, function(self, output){ self.body.print(output); output.semicolon(); }); DEFPRINT(AST_Toplevel, function(self, output){ display_body(self.body, true, output); output.print(""); }); DEFPRINT(AST_LabeledStatement, function(self, output){ self.label.print(output); output.colon(); self.body.print(output); }); DEFPRINT(AST_SimpleStatement, function(self, output){ self.body.print(output); output.semicolon(); }); function print_bracketed(body, output) { if (body.length > 0) output.with_block(function(){ display_body(body, false, output); }); else output.print("{}"); }; DEFPRINT(AST_BlockStatement, function(self, output){ print_bracketed(self.body, output); }); DEFPRINT(AST_EmptyStatement, function(self, output){ output.semicolon(); }); DEFPRINT(AST_Do, function(self, output){ output.print("do"); output.space(); self._do_print_body(output); output.space(); output.print("while"); output.space(); output.with_parens(function(){ self.condition.print(output); }); output.semicolon(); }); DEFPRINT(AST_While, function(self, output){ output.print("while"); output.space(); output.with_parens(function(){ self.condition.print(output); }); output.space(); self._do_print_body(output); }); DEFPRINT(AST_For, function(self, output){ output.print("for"); output.space(); output.with_parens(function(){ if (self.init && !(self.init instanceof AST_EmptyStatement)) { if (self.init instanceof AST_Definitions) { self.init.print(output); } else { parenthesize_for_noin(self.init, output, true); } output.print(";"); output.space(); } else { output.print(";"); } if (self.condition) { self.condition.print(output); output.print(";"); output.space(); } else { output.print(";"); } if (self.step) { self.step.print(output); } }); output.space(); self._do_print_body(output); }); DEFPRINT(AST_ForIn, function(self, output){ output.print("for"); output.space(); output.with_parens(function(){ self.init.print(output); output.space(); output.print("in"); output.space(); self.object.print(output); }); output.space(); self._do_print_body(output); }); DEFPRINT(AST_With, function(self, output){ output.print("with"); output.space(); output.with_parens(function(){ self.expression.print(output); }); output.space(); self._do_print_body(output); }); /* -----[ functions ]----- */ AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword){ var self = this; if (!nokeyword) { output.print("function"); } if (self.name) { output.space(); self.name.print(output); } output.with_parens(function(){ self.argnames.forEach(function(arg, i){ if (i) output.comma(); arg.print(output); }); }); output.space(); print_bracketed(self.body, output); }); DEFPRINT(AST_Lambda, function(self, output){ self._do_print(output); }); /* -----[ exits ]----- */ AST_Exit.DEFMETHOD("_do_print", function(output, kind){ output.print(kind); if (this.value) { output.space(); this.value.print(output); } output.semicolon(); }); DEFPRINT(AST_Return, function(self, output){ self._do_print(output, "return"); }); DEFPRINT(AST_Throw, function(self, output){ self._do_print(output, "throw"); }); /* -----[ loop control ]----- */ AST_LoopControl.DEFMETHOD("_do_print", function(output, kind){ output.print(kind); if (this.label) { output.space(); this.label.print(output); } output.semicolon(); }); DEFPRINT(AST_Break, function(self, output){ self._do_print(output, "break"); }); DEFPRINT(AST_Continue, function(self, output){ self._do_print(output, "continue"); }); /* -----[ if ]----- */ function make_then(self, output) { if (output.option("bracketize")) { make_block(self.body, output); return; } // The squeezer replaces "block"-s that contain only a single // statement with the statement itself; technically, the AST // is correct, but this can create problems when we output an // IF having an ELSE clause where the THEN clause ends in an // IF *without* an ELSE block (then the outer ELSE would refer // to the inner IF). This function checks for this case and // adds the block brackets if needed. if (!self.body) return output.force_semicolon(); if (self.body instanceof AST_Do && !output.option("screw_ie8")) { // https://github.com/mishoo/UglifyJS/issues/#issue/57 IE // croaks with "syntax error" on code like this: if (foo) // do ... while(cond); else ... we need block brackets // around do/while make_block(self.body, output); return; } var b = self.body; while (true) { if (b instanceof AST_If) { if (!b.alternative) { make_block(self.body, output); return; } b = b.alternative; } else if (b instanceof AST_StatementWithBody) { b = b.body; } else break; } force_statement(self.body, output); }; DEFPRINT(AST_If, function(self, output){ output.print("if"); output.space(); output.with_parens(function(){ self.condition.print(output); }); output.space(); if (self.alternative) { make_then(self, output); output.space(); output.print("else"); output.space(); force_statement(self.alternative, output); } else { self._do_print_body(output); } }); /* -----[ switch ]----- */ DEFPRINT(AST_Switch, function(self, output){ output.print("switch"); output.space(); output.with_parens(function(){ self.expression.print(output); }); output.space(); if (self.body.length > 0) output.with_block(function(){ self.body.forEach(function(stmt, i){ if (i) output.newline(); output.indent(true); stmt.print(output); }); }); else output.print("{}"); }); AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output){ if (this.body.length > 0) { output.newline(); this.body.forEach(function(stmt){ output.indent(); stmt.print(output); output.newline(); }); } }); DEFPRINT(AST_Default, function(self, output){ output.print("default:"); self._do_print_body(output); }); DEFPRINT(AST_Case, function(self, output){ output.print("case"); output.space(); self.expression.print(output); output.print(":"); self._do_print_body(output); }); /* -----[ exceptions ]----- */ DEFPRINT(AST_Try, function(self, output){ output.print("try"); output.space(); print_bracketed(self.body, output); if (self.bcatch) { output.space(); self.bcatch.print(output); } if (self.bfinally) { output.space(); self.bfinally.print(output); } }); DEFPRINT(AST_Catch, function(self, output){ output.print("catch"); output.space(); output.with_parens(function(){ self.argname.print(output); }); output.space(); print_bracketed(self.body, output); }); DEFPRINT(AST_Finally, function(self, output){ output.print("finally"); output.space(); print_bracketed(self.body, output); }); /* -----[ var/const ]----- */ AST_Definitions.DEFMETHOD("_do_print", function(output, kind){ output.print(kind); output.space(); this.definitions.forEach(function(def, i){ if (i) output.comma(); def.print(output); }); var p = output.parent(); var in_for = p instanceof AST_For || p instanceof AST_ForIn; var avoid_semicolon = in_for && p.init === this; if (!avoid_semicolon) output.semicolon(); }); DEFPRINT(AST_Var, function(self, output){ self._do_print(output, "var"); }); DEFPRINT(AST_Const, function(self, output){ self._do_print(output, "const"); }); function parenthesize_for_noin(node, output, noin) { if (!noin) node.print(output); else try { // need to take some precautions here: // https://github.com/mishoo/UglifyJS2/issues/60 node.walk(new TreeWalker(function(node){ if (node instanceof AST_Binary && node.operator == "in") throw output; })); node.print(output); } catch(ex) { if (ex !== output) throw ex; node.print(output, true); } }; DEFPRINT(AST_VarDef, function(self, output){ self.name.print(output); if (self.value) { output.space(); output.print("="); output.space(); var p = output.parent(1); var noin = p instanceof AST_For || p instanceof AST_ForIn; parenthesize_for_noin(self.value, output, noin); } }); /* -----[ other expressions ]----- */ DEFPRINT(AST_Call, function(self, output){ self.expression.print(output); if (self instanceof AST_New && no_constructor_parens(self, output)) return; output.with_parens(function(){ self.args.forEach(function(expr, i){ if (i) output.comma(); expr.print(output); }); }); }); DEFPRINT(AST_New, function(self, output){ output.print("new"); output.space(); AST_Call.prototype._codegen(self, output); }); AST_Seq.DEFMETHOD("_do_print", function(output){ this.car.print(output); if (this.cdr) { output.comma(); if (output.should_break()) { output.newline(); output.indent(); } this.cdr.print(output); } }); DEFPRINT(AST_Seq, function(self, output){ self._do_print(output); // var p = output.parent(); // if (p instanceof AST_Statement) { // output.with_indent(output.next_indent(), function(){ // self._do_print(output); // }); // } else { // self._do_print(output); // } }); DEFPRINT(AST_Dot, function(self, output){ var expr = self.expression; expr.print(output); if (expr instanceof AST_Number && expr.getValue() >= 0) { if (!/[xa-f.]/i.test(output.last())) { output.print("."); } } output.print("."); // the name after dot would be mapped about here. output.add_mapping(self.end); output.print_name(self.property); }); DEFPRINT(AST_Sub, function(self, output){ self.expression.print(output); output.print("["); self.property.print(output); output.print("]"); }); DEFPRINT(AST_UnaryPrefix, function(self, output){ var op = self.operator; output.print(op); if (/^[a-z]/i.test(op) || (/[+-]$/.test(op) && self.expression instanceof AST_UnaryPrefix && /^[+-]/.test(self.expression.operator))) { output.space(); } self.expression.print(output); }); DEFPRINT(AST_UnaryPostfix, function(self, output){ self.expression.print(output); output.print(self.operator); }); DEFPRINT(AST_Binary, function(self, output){ self.left.print(output); output.space(); output.print(self.operator); if (self.operator == "<" && self.right instanceof AST_UnaryPrefix && self.right.operator == "!" && self.right.expression instanceof AST_UnaryPrefix && self.right.expression.operator == "--") { // space is mandatory to avoid outputting ") && S.newline_before) { forward(3); return skip_line_comment("comment4"); } } var ch = peek(); if (!ch) return token("eof"); var code = ch.charCodeAt(0); switch (code) { case 34: case 39: return read_string(); case 46: return handle_dot(); case 47: return handle_slash(); } if (is_digit(code)) return read_num(); if (PUNC_CHARS(ch)) return token("punc", next()); if (OPERATOR_CHARS(ch)) return read_operator(); if (code == 92 || is_identifier_start(code)) return read_word(); parse_error("Unexpected character '" + ch + "'"); }; next_token.context = function(nc) { if (nc) S = nc; return S; }; return next_token; }; /* -----[ Parser (constants) ]----- */ var UNARY_PREFIX = makePredicate([ "typeof", "void", "delete", "--", "++", "!", "~", "-", "+" ]); var UNARY_POSTFIX = makePredicate([ "--", "++" ]); var ASSIGNMENT = makePredicate([ "=", "+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=" ]); var PRECEDENCE = (function(a, ret){ for (var i = 0; i < a.length; ++i) { var b = a[i]; for (var j = 0; j < b.length; ++j) { ret[b[j]] = i + 1; } } return ret; })( [ ["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"] ], {} ); var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]); var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]); /* -----[ Parser ]----- */ function parse($TEXT, options) { options = defaults(options, { strict : false, filename : null, toplevel : null, expression : false, html5_comments : true, }); var S = { input : (typeof $TEXT == "string" ? tokenizer($TEXT, options.filename, options.html5_comments) : $TEXT), token : null, prev : null, peeked : null, in_function : 0, in_directives : true, in_loop : 0, labels : [] }; S.token = next(); function is(type, value) { return is_token(S.token, type, value); }; function peek() { return S.peeked || (S.peeked = S.input()); }; function next() { S.prev = S.token; if (S.peeked) { S.token = S.peeked; S.peeked = null; } else { S.token = S.input(); } S.in_directives = S.in_directives && ( S.token.type == "string" || is("punc", ";") ); return S.token; }; function prev() { return S.prev; }; function croak(msg, line, col, pos) { var ctx = S.input.context(); js_error(msg, ctx.filename, line != null ? line : ctx.tokline, col != null ? col : ctx.tokcol, pos != null ? pos : ctx.tokpos); }; function token_error(token, msg) { croak(msg, token.line, token.col); }; function unexpected(token) { if (token == null) token = S.token; token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")"); }; function expect_token(type, val) { if (is(type, val)) { return next(); } token_error(S.token, "Unexpected token " + S.token.type + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»"); }; function expect(punc) { return expect_token("punc", punc); }; function can_insert_semicolon() { return !options.strict && ( S.token.nlb || is("eof") || is("punc", "}") ); }; function semicolon() { if (is("punc", ";")) next(); else if (!can_insert_semicolon()) unexpected(); }; function parenthesised() { expect("("); var exp = expression(true); expect(")"); return exp; }; function embed_tokens(parser) { return function() { var start = S.token; var expr = parser(); var end = prev(); expr.start = start; expr.end = end; return expr; }; }; function handle_regexp() { if (is("operator", "/") || is("operator", "/=")) { S.peeked = null; S.token = S.input(S.token.value.substr(1)); // force regexp } }; var statement = embed_tokens(function() { var tmp; handle_regexp(); switch (S.token.type) { case "string": var dir = S.in_directives, stat = simple_statement(); // XXXv2: decide how to fix directives if (dir && stat.body instanceof AST_String && !is("punc", ",")) return new AST_Directive({ value: stat.body.value }); return stat; case "num": case "regexp": case "operator": case "atom": return simple_statement(); case "name": return is_token(peek(), "punc", ":") ? labeled_statement() : simple_statement(); case "punc": switch (S.token.value) { case "{": return new AST_BlockStatement({ start : S.token, body : block_(), end : prev() }); case "[": case "(": return simple_statement(); case ";": next(); return new AST_EmptyStatement(); default: unexpected(); } case "keyword": switch (tmp = S.token.value, next(), tmp) { case "break": return break_cont(AST_Break); case "continue": return break_cont(AST_Continue); case "debugger": semicolon(); return new AST_Debugger(); case "do": return new AST_Do({ body : in_loop(statement), condition : (expect_token("keyword", "while"), tmp = parenthesised(), semicolon(), tmp) }); case "while": return new AST_While({ condition : parenthesised(), body : in_loop(statement) }); case "for": return for_(); case "function": return function_(AST_Defun); case "if": return if_(); case "return": if (S.in_function == 0) croak("'return' outside of function"); return new AST_Return({ value: ( is("punc", ";") ? (next(), null) : can_insert_semicolon() ? null : (tmp = expression(true), semicolon(), tmp) ) }); case "switch": return new AST_Switch({ expression : parenthesised(), body : in_loop(switch_body_) }); case "throw": if (S.token.nlb) croak("Illegal newline after 'throw'"); return new AST_Throw({ value: (tmp = expression(true), semicolon(), tmp) }); case "try": return try_(); case "var": return tmp = var_(), semicolon(), tmp; case "const": return tmp = const_(), semicolon(), tmp; case "with": return new AST_With({ expression : parenthesised(), body : statement() }); default: unexpected(); } } }); function labeled_statement() { var label = as_symbol(AST_Label); if (find_if(function(l){ return l.name == label.name }, S.labels)) { // ECMA-262, 12.12: An ECMAScript program is considered // syntactically incorrect if it contains a // LabelledStatement that is enclosed by a // LabelledStatement with the same Identifier as label. croak("Label " + label.name + " defined twice"); } expect(":"); S.labels.push(label); var stat = statement(); S.labels.pop(); if (!(stat instanceof AST_IterationStatement)) { // check for `continue` that refers to this label. // those should be reported as syntax errors. // https://github.com/mishoo/UglifyJS2/issues/287 label.references.forEach(function(ref){ if (ref instanceof AST_Continue) { ref = ref.label.start; croak("Continue label `" + label.name + "` refers to non-IterationStatement.", ref.line, ref.col, ref.pos); } }); } return new AST_LabeledStatement({ body: stat, label: label }); }; function simple_statement(tmp) { return new AST_SimpleStatement({ body: (tmp = expression(true), semicolon(), tmp) }); }; function break_cont(type) { var label = null, ldef; if (!can_insert_semicolon()) { label = as_symbol(AST_LabelRef, true); } if (label != null) { ldef = find_if(function(l){ return l.name == label.name }, S.labels); if (!ldef) croak("Undefined label " + label.name); label.thedef = ldef; } else if (S.in_loop == 0) croak(type.TYPE + " not inside a loop or switch"); semicolon(); var stat = new type({ label: label }); if (ldef) ldef.references.push(stat); return stat; }; function for_() { expect("("); var init = null; if (!is("punc", ";")) { init = is("keyword", "var") ? (next(), var_(true)) : expression(true, true); if (is("operator", "in")) { if (init instanceof AST_Var && init.definitions.length > 1) croak("Only one variable declaration allowed in for..in loop"); next(); return for_in(init); } } return regular_for(init); }; function regular_for(init) { expect(";"); var test = is("punc", ";") ? null : expression(true); expect(";"); var step = is("punc", ")") ? null : expression(true); expect(")"); return new AST_For({ init : init, condition : test, step : step, body : in_loop(statement) }); }; function for_in(init) { var lhs = init instanceof AST_Var ? init.definitions[0].name : null; var obj = expression(true); expect(")"); return new AST_ForIn({ init : init, name : lhs, object : obj, body : in_loop(statement) }); }; var function_ = function(ctor) { var in_statement = ctor === AST_Defun; var name = is("name") ? as_symbol(in_statement ? AST_SymbolDefun : AST_SymbolLambda) : null; if (in_statement && !name) unexpected(); expect("("); return new ctor({ name: name, argnames: (function(first, a){ while (!is("punc", ")")) { if (first) first = false; else expect(","); a.push(as_symbol(AST_SymbolFunarg)); } next(); return a; })(true, []), body: (function(loop, labels){ ++S.in_function; S.in_directives = true; S.in_loop = 0; S.labels = []; var a = block_(); --S.in_function; S.in_loop = loop; S.labels = labels; return a; })(S.in_loop, S.labels) }); }; function if_() { var cond = parenthesised(), body = statement(), belse = null; if (is("keyword", "else")) { next(); belse = statement(); } return new AST_If({ condition : cond, body : body, alternative : belse }); }; function block_() { expect("{"); var a = []; while (!is("punc", "}")) { if (is("eof")) unexpected(); a.push(statement()); } next(); return a; }; function switch_body_() { expect("{"); var a = [], cur = null, branch = null, tmp; while (!is("punc", "}")) { if (is("eof")) unexpected(); if (is("keyword", "case")) { if (branch) branch.end = prev(); cur = []; branch = new AST_Case({ start : (tmp = S.token, next(), tmp), expression : expression(true), body : cur }); a.push(branch); expect(":"); } else if (is("keyword", "default")) { if (branch) branch.end = prev(); cur = []; branch = new AST_Default({ start : (tmp = S.token, next(), expect(":"), tmp), body : cur }); a.push(branch); } else { if (!cur) unexpected(); cur.push(statement()); } } if (branch) branch.end = prev(); next(); return a; }; function try_() { var body = block_(), bcatch = null, bfinally = null; if (is("keyword", "catch")) { var start = S.token; next(); expect("("); var name = as_symbol(AST_SymbolCatch); expect(")"); bcatch = new AST_Catch({ start : start, argname : name, body : block_(), end : prev() }); } if (is("keyword", "finally")) { var start = S.token; next(); bfinally = new AST_Finally({ start : start, body : block_(), end : prev() }); } if (!bcatch && !bfinally) croak("Missing catch/finally blocks"); return new AST_Try({ body : body, bcatch : bcatch, bfinally : bfinally }); }; function vardefs(no_in, in_const) { var a = []; for (;;) { a.push(new AST_VarDef({ start : S.token, name : as_symbol(in_const ? AST_SymbolConst : AST_SymbolVar), value : is("operator", "=") ? (next(), expression(false, no_in)) : null, end : prev() })); if (!is("punc", ",")) break; next(); } return a; }; var var_ = function(no_in) { return new AST_Var({ start : prev(), definitions : vardefs(no_in, false), end : prev() }); }; var const_ = function() { return new AST_Const({ start : prev(), definitions : vardefs(false, true), end : prev() }); }; var new_ = function() { var start = S.token; expect_token("operator", "new"); var newexp = expr_atom(false), args; if (is("punc", "(")) { next(); args = expr_list(")"); } else { args = []; } return subscripts(new AST_New({ start : start, expression : newexp, args : args, end : prev() }), true); }; function as_atom_node() { var tok = S.token, ret; switch (tok.type) { case "name": case "keyword": ret = _make_symbol(AST_SymbolRef); break; case "num": ret = new AST_Number({ start: tok, end: tok, value: tok.value }); break; case "string": ret = new AST_String({ start: tok, end: tok, value: tok.value }); break; case "regexp": ret = new AST_RegExp({ start: tok, end: tok, value: tok.value }); break; case "atom": switch (tok.value) { case "false": ret = new AST_False({ start: tok, end: tok }); break; case "true": ret = new AST_True({ start: tok, end: tok }); break; case "null": ret = new AST_Null({ start: tok, end: tok }); break; } break; } next(); return ret; }; var expr_atom = function(allow_calls) { if (is("operator", "new")) { return new_(); } var start = S.token; if (is("punc")) { switch (start.value) { case "(": next(); var ex = expression(true); ex.start = start; ex.end = S.token; expect(")"); return subscripts(ex, allow_calls); case "[": return subscripts(array_(), allow_calls); case "{": return subscripts(object_(), allow_calls); } unexpected(); } if (is("keyword", "function")) { next(); var func = function_(AST_Function); func.start = start; func.end = prev(); return subscripts(func, allow_calls); } if (ATOMIC_START_TOKEN[S.token.type]) { return subscripts(as_atom_node(), allow_calls); } unexpected(); }; function expr_list(closing, allow_trailing_comma, allow_empty) { var first = true, a = []; while (!is("punc", closing)) { if (first) first = false; else expect(","); if (allow_trailing_comma && is("punc", closing)) break; if (is("punc", ",") && allow_empty) { a.push(new AST_Hole({ start: S.token, end: S.token })); } else { a.push(expression(false)); } } next(); return a; }; var array_ = embed_tokens(function() { expect("["); return new AST_Array({ elements: expr_list("]", !options.strict, true) }); }); var object_ = embed_tokens(function() { expect("{"); var first = true, a = []; while (!is("punc", "}")) { if (first) first = false; else expect(","); if (!options.strict && is("punc", "}")) // allow trailing comma break; var start = S.token; var type = start.type; var name = as_property_name(); if (type == "name" && !is("punc", ":")) { if (name == "get") { a.push(new AST_ObjectGetter({ start : start, key : as_atom_node(), value : function_(AST_Accessor), end : prev() })); continue; } if (name == "set") { a.push(new AST_ObjectSetter({ start : start, key : as_atom_node(), value : function_(AST_Accessor), end : prev() })); continue; } } expect(":"); a.push(new AST_ObjectKeyVal({ start : start, key : name, value : expression(false), end : prev() })); } next(); return new AST_Object({ properties: a }); }); function as_property_name() { var tmp = S.token; next(); switch (tmp.type) { case "num": case "string": case "name": case "operator": case "keyword": case "atom": return tmp.value; default: unexpected(); } }; function as_name() { var tmp = S.token; next(); switch (tmp.type) { case "name": case "operator": case "keyword": case "atom": return tmp.value; default: unexpected(); } }; function _make_symbol(type) { var name = S.token.value; return new (name == "this" ? AST_This : type)({ name : String(name), start : S.token, end : S.token }); }; function as_symbol(type, noerror) { if (!is("name")) { if (!noerror) croak("Name expected"); return null; } var sym = _make_symbol(type); next(); return sym; }; var subscripts = function(expr, allow_calls) { var start = expr.start; if (is("punc", ".")) { next(); return subscripts(new AST_Dot({ start : start, expression : expr, property : as_name(), end : prev() }), allow_calls); } if (is("punc", "[")) { next(); var prop = expression(true); expect("]"); return subscripts(new AST_Sub({ start : start, expression : expr, property : prop, end : prev() }), allow_calls); } if (allow_calls && is("punc", "(")) { next(); return subscripts(new AST_Call({ start : start, expression : expr, args : expr_list(")"), end : prev() }), true); } return expr; }; var maybe_unary = function(allow_calls) { var start = S.token; if (is("operator") && UNARY_PREFIX(start.value)) { next(); handle_regexp(); var ex = make_unary(AST_UnaryPrefix, start.value, maybe_unary(allow_calls)); ex.start = start; ex.end = prev(); return ex; } var val = expr_atom(allow_calls); while (is("operator") && UNARY_POSTFIX(S.token.value) && !S.token.nlb) { val = make_unary(AST_UnaryPostfix, S.token.value, val); val.start = start; val.end = S.token; next(); } return val; }; function make_unary(ctor, op, expr) { if ((op == "++" || op == "--") && !is_assignable(expr)) croak("Invalid use of " + op + " operator"); return new ctor({ operator: op, expression: expr }); }; var expr_op = function(left, min_prec, no_in) { var op = is("operator") ? S.token.value : null; if (op == "in" && no_in) op = null; var prec = op != null ? PRECEDENCE[op] : null; if (prec != null && prec > min_prec) { next(); var right = expr_op(maybe_unary(true), prec, no_in); return expr_op(new AST_Binary({ start : left.start, left : left, operator : op, right : right, end : right.end }), min_prec, no_in); } return left; }; function expr_ops(no_in) { return expr_op(maybe_unary(true), 0, no_in); }; var maybe_conditional = function(no_in) { var start = S.token; var expr = expr_ops(no_in); if (is("operator", "?")) { next(); var yes = expression(false); expect(":"); return new AST_Conditional({ start : start, condition : expr, consequent : yes, alternative : expression(false, no_in), end : prev() }); } return expr; }; function is_assignable(expr) { if (!options.strict) return true; if (expr instanceof AST_This) return false; return (expr instanceof AST_PropAccess || expr instanceof AST_Symbol); }; var maybe_assign = function(no_in) { var start = S.token; var left = maybe_conditional(no_in), val = S.token.value; if (is("operator") && ASSIGNMENT(val)) { if (is_assignable(left)) { next(); return new AST_Assign({ start : start, left : left, operator : val, right : maybe_assign(no_in), end : prev() }); } croak("Invalid assignment"); } return left; }; var expression = function(commas, no_in) { var start = S.token; var expr = maybe_assign(no_in); if (commas && is("punc", ",")) { next(); return new AST_Seq({ start : start, car : expr, cdr : expression(true, no_in), end : peek() }); } return expr; }; function in_loop(cont) { ++S.in_loop; var ret = cont(); --S.in_loop; return ret; }; if (options.expression) { return expression(true); } return (function(){ var start = S.token; var body = []; while (!is("eof")) body.push(statement()); var end = prev(); var toplevel = options.toplevel; if (toplevel) { toplevel.body = toplevel.body.concat(body); toplevel.end = end; } else { toplevel = new AST_Toplevel({ start: start, body: body, end: end }); } return toplevel; })(); }; UglifyJS2-2.4.15/lib/scope.js000066400000000000000000000504741235725452400156210ustar00rootroot00000000000000/*********************************************************************** A JavaScript tokenizer / parser / beautifier / compressor. https://github.com/mishoo/UglifyJS2 -------------------------------- (C) --------------------------------- Author: Mihai Bazon http://mihai.bazon.net/blog Distributed under the BSD license: Copyright 2012 (c) Mihai Bazon Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ "use strict"; function SymbolDef(scope, index, orig) { this.name = orig.name; this.orig = [ orig ]; this.scope = scope; this.references = []; this.global = false; this.mangled_name = null; this.undeclared = false; this.constant = false; this.index = index; }; SymbolDef.prototype = { unmangleable: function(options) { return (this.global && !(options && options.toplevel)) || this.undeclared || (!(options && options.eval) && (this.scope.uses_eval || this.scope.uses_with)); }, mangle: function(options) { if (!this.mangled_name && !this.unmangleable(options)) { var s = this.scope; if (!options.screw_ie8 && this.orig[0] instanceof AST_SymbolLambda) s = s.parent_scope; this.mangled_name = s.next_mangled(options, this); } } }; AST_Toplevel.DEFMETHOD("figure_out_scope", function(options){ options = defaults(options, { screw_ie8: false }); // pass 1: setup scope chaining and handle definitions var self = this; var scope = self.parent_scope = null; var defun = null; var nesting = 0; var tw = new TreeWalker(function(node, descend){ if (options.screw_ie8 && node instanceof AST_Catch) { var save_scope = scope; scope = new AST_Scope(node); scope.init_scope_vars(nesting); scope.parent_scope = save_scope; descend(); scope = save_scope; return true; } if (node instanceof AST_Scope) { node.init_scope_vars(nesting); var save_scope = node.parent_scope = scope; var save_defun = defun; defun = scope = node; ++nesting; descend(); --nesting; scope = save_scope; defun = save_defun; return true; // don't descend again in TreeWalker } if (node instanceof AST_Directive) { node.scope = scope; push_uniq(scope.directives, node.value); return true; } if (node instanceof AST_With) { for (var s = scope; s; s = s.parent_scope) s.uses_with = true; return; } if (node instanceof AST_Symbol) { node.scope = scope; } if (node instanceof AST_SymbolLambda) { defun.def_function(node); } else if (node instanceof AST_SymbolDefun) { // Careful here, the scope where this should be defined is // the parent scope. The reason is that we enter a new // scope when we encounter the AST_Defun node (which is // instanceof AST_Scope) but we get to the symbol a bit // later. (node.scope = defun.parent_scope).def_function(node); } else if (node instanceof AST_SymbolVar || node instanceof AST_SymbolConst) { var def = defun.def_variable(node); def.constant = node instanceof AST_SymbolConst; def.init = tw.parent().value; } else if (node instanceof AST_SymbolCatch) { (options.screw_ie8 ? scope : defun) .def_variable(node); } }); self.walk(tw); // pass 2: find back references and eval var func = null; var globals = self.globals = new Dictionary(); var tw = new TreeWalker(function(node, descend){ if (node instanceof AST_Lambda) { var prev_func = func; func = node; descend(); func = prev_func; return true; } if (node instanceof AST_SymbolRef) { var name = node.name; var sym = node.scope.find_variable(name); if (!sym) { var g; if (globals.has(name)) { g = globals.get(name); } else { g = new SymbolDef(self, globals.size(), node); g.undeclared = true; g.global = true; globals.set(name, g); } node.thedef = g; if (name == "eval" && tw.parent() instanceof AST_Call) { for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope) s.uses_eval = true; } if (func && name == "arguments") { func.uses_arguments = true; } } else { node.thedef = sym; } node.reference(); return true; } }); self.walk(tw); }); AST_Scope.DEFMETHOD("init_scope_vars", function(nesting){ this.directives = []; // contains the directives defined in this scope, i.e. "use strict" this.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions) this.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope) this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval` this.parent_scope = null; // the parent scope this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes this.cname = -1; // the current index for mangling functions/variables this.nesting = nesting; // the nesting level of this scope (0 means toplevel) }); AST_Scope.DEFMETHOD("strict", function(){ return this.has_directive("use strict"); }); AST_Lambda.DEFMETHOD("init_scope_vars", function(){ AST_Scope.prototype.init_scope_vars.apply(this, arguments); this.uses_arguments = false; }); AST_SymbolRef.DEFMETHOD("reference", function() { var def = this.definition(); def.references.push(this); var s = this.scope; while (s) { push_uniq(s.enclosed, def); if (s === def.scope) break; s = s.parent_scope; } this.frame = this.scope.nesting - def.scope.nesting; }); AST_Scope.DEFMETHOD("find_variable", function(name){ if (name instanceof AST_Symbol) name = name.name; return this.variables.get(name) || (this.parent_scope && this.parent_scope.find_variable(name)); }); AST_Scope.DEFMETHOD("has_directive", function(value){ return this.parent_scope && this.parent_scope.has_directive(value) || (this.directives.indexOf(value) >= 0 ? this : null); }); AST_Scope.DEFMETHOD("def_function", function(symbol){ this.functions.set(symbol.name, this.def_variable(symbol)); }); AST_Scope.DEFMETHOD("def_variable", function(symbol){ var def; if (!this.variables.has(symbol.name)) { def = new SymbolDef(this, this.variables.size(), symbol); this.variables.set(symbol.name, def); def.global = !this.parent_scope; } else { def = this.variables.get(symbol.name); def.orig.push(symbol); } return symbol.thedef = def; }); AST_Scope.DEFMETHOD("next_mangled", function(options){ var ext = this.enclosed; out: while (true) { var m = base54(++this.cname); if (!is_identifier(m)) continue; // skip over "do" // https://github.com/mishoo/UglifyJS2/issues/242 -- do not // shadow a name excepted from mangling. if (options.except.indexOf(m) >= 0) continue; // we must ensure that the mangled name does not shadow a name // from some parent scope that is referenced in this or in // inner scopes. for (var i = ext.length; --i >= 0;) { var sym = ext[i]; var name = sym.mangled_name || (sym.unmangleable(options) && sym.name); if (m == name) continue out; } return m; } }); AST_Function.DEFMETHOD("next_mangled", function(options, def){ // #179, #326 // in Safari strict mode, something like (function x(x){...}) is a syntax error; // a function expression's argument cannot shadow the function expression's name var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition(); while (true) { var name = AST_Lambda.prototype.next_mangled.call(this, options, def); if (!(tricky_def && tricky_def.mangled_name == name)) return name; } }); AST_Scope.DEFMETHOD("references", function(sym){ if (sym instanceof AST_Symbol) sym = sym.definition(); return this.enclosed.indexOf(sym) < 0 ? null : sym; }); AST_Symbol.DEFMETHOD("unmangleable", function(options){ return this.definition().unmangleable(options); }); // property accessors are not mangleable AST_SymbolAccessor.DEFMETHOD("unmangleable", function(){ return true; }); // labels are always mangleable AST_Label.DEFMETHOD("unmangleable", function(){ return false; }); AST_Symbol.DEFMETHOD("unreferenced", function(){ return this.definition().references.length == 0 && !(this.scope.uses_eval || this.scope.uses_with); }); AST_Symbol.DEFMETHOD("undeclared", function(){ return this.definition().undeclared; }); AST_LabelRef.DEFMETHOD("undeclared", function(){ return false; }); AST_Label.DEFMETHOD("undeclared", function(){ return false; }); AST_Symbol.DEFMETHOD("definition", function(){ return this.thedef; }); AST_Symbol.DEFMETHOD("global", function(){ return this.definition().global; }); AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options){ return defaults(options, { except : [], eval : false, sort : false, toplevel : false, screw_ie8 : false }); }); AST_Toplevel.DEFMETHOD("mangle_names", function(options){ options = this._default_mangler_options(options); // We only need to mangle declaration nodes. Special logic wired // into the code generator will display the mangled name if it's // present (and for AST_SymbolRef-s it'll use the mangled name of // the AST_SymbolDeclaration that it points to). var lname = -1; var to_mangle = []; var tw = new TreeWalker(function(node, descend){ if (node instanceof AST_LabeledStatement) { // lname is incremented when we get to the AST_Label var save_nesting = lname; descend(); lname = save_nesting; return true; // don't descend again in TreeWalker } if (node instanceof AST_Scope) { var p = tw.parent(), a = []; node.variables.each(function(symbol){ if (options.except.indexOf(symbol.name) < 0) { a.push(symbol); } }); if (options.sort) a.sort(function(a, b){ return b.references.length - a.references.length; }); to_mangle.push.apply(to_mangle, a); return; } if (node instanceof AST_Label) { var name; do name = base54(++lname); while (!is_identifier(name)); node.mangled_name = name; return true; } if (options.screw_ie8 && node instanceof AST_SymbolCatch) { to_mangle.push(node.definition()); return; } }); this.walk(tw); to_mangle.forEach(function(def){ def.mangle(options) }); }); AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options){ options = this._default_mangler_options(options); var tw = new TreeWalker(function(node){ if (node instanceof AST_Constant) base54.consider(node.print_to_string()); else if (node instanceof AST_Return) base54.consider("return"); else if (node instanceof AST_Throw) base54.consider("throw"); else if (node instanceof AST_Continue) base54.consider("continue"); else if (node instanceof AST_Break) base54.consider("break"); else if (node instanceof AST_Debugger) base54.consider("debugger"); else if (node instanceof AST_Directive) base54.consider(node.value); else if (node instanceof AST_While) base54.consider("while"); else if (node instanceof AST_Do) base54.consider("do while"); else if (node instanceof AST_If) { base54.consider("if"); if (node.alternative) base54.consider("else"); } else if (node instanceof AST_Var) base54.consider("var"); else if (node instanceof AST_Const) base54.consider("const"); else if (node instanceof AST_Lambda) base54.consider("function"); else if (node instanceof AST_For) base54.consider("for"); else if (node instanceof AST_ForIn) base54.consider("for in"); else if (node instanceof AST_Switch) base54.consider("switch"); else if (node instanceof AST_Case) base54.consider("case"); else if (node instanceof AST_Default) base54.consider("default"); else if (node instanceof AST_With) base54.consider("with"); else if (node instanceof AST_ObjectSetter) base54.consider("set" + node.key); else if (node instanceof AST_ObjectGetter) base54.consider("get" + node.key); else if (node instanceof AST_ObjectKeyVal) base54.consider(node.key); else if (node instanceof AST_New) base54.consider("new"); else if (node instanceof AST_This) base54.consider("this"); else if (node instanceof AST_Try) base54.consider("try"); else if (node instanceof AST_Catch) base54.consider("catch"); else if (node instanceof AST_Finally) base54.consider("finally"); else if (node instanceof AST_Symbol && node.unmangleable(options)) base54.consider(node.name); else if (node instanceof AST_Unary || node instanceof AST_Binary) base54.consider(node.operator); else if (node instanceof AST_Dot) base54.consider(node.property); }); this.walk(tw); base54.sort(); }); var base54 = (function() { var string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789"; var chars, frequency; function reset() { frequency = Object.create(null); chars = string.split("").map(function(ch){ return ch.charCodeAt(0) }); chars.forEach(function(ch){ frequency[ch] = 0 }); } base54.consider = function(str){ for (var i = str.length; --i >= 0;) { var code = str.charCodeAt(i); if (code in frequency) ++frequency[code]; } }; base54.sort = function() { chars = mergeSort(chars, function(a, b){ if (is_digit(a) && !is_digit(b)) return 1; if (is_digit(b) && !is_digit(a)) return -1; return frequency[b] - frequency[a]; }); }; base54.reset = reset; reset(); base54.get = function(){ return chars }; base54.freq = function(){ return frequency }; function base54(num) { var ret = "", base = 54; do { ret += String.fromCharCode(chars[num % base]); num = Math.floor(num / base); base = 64; } while (num > 0); return ret; }; return base54; })(); AST_Toplevel.DEFMETHOD("scope_warnings", function(options){ options = defaults(options, { undeclared : false, // this makes a lot of noise unreferenced : true, assign_to_global : true, func_arguments : true, nested_defuns : true, eval : true }); var tw = new TreeWalker(function(node){ if (options.undeclared && node instanceof AST_SymbolRef && node.undeclared()) { // XXX: this also warns about JS standard names, // i.e. Object, Array, parseInt etc. Should add a list of // exceptions. AST_Node.warn("Undeclared symbol: {name} [{file}:{line},{col}]", { name: node.name, file: node.start.file, line: node.start.line, col: node.start.col }); } if (options.assign_to_global) { var sym = null; if (node instanceof AST_Assign && node.left instanceof AST_SymbolRef) sym = node.left; else if (node instanceof AST_ForIn && node.init instanceof AST_SymbolRef) sym = node.init; if (sym && (sym.undeclared() || (sym.global() && sym.scope !== sym.definition().scope))) { AST_Node.warn("{msg}: {name} [{file}:{line},{col}]", { msg: sym.undeclared() ? "Accidental global?" : "Assignment to global", name: sym.name, file: sym.start.file, line: sym.start.line, col: sym.start.col }); } } if (options.eval && node instanceof AST_SymbolRef && node.undeclared() && node.name == "eval") { AST_Node.warn("Eval is used [{file}:{line},{col}]", node.start); } if (options.unreferenced && (node instanceof AST_SymbolDeclaration || node instanceof AST_Label) && node.unreferenced()) { AST_Node.warn("{type} {name} is declared but not referenced [{file}:{line},{col}]", { type: node instanceof AST_Label ? "Label" : "Symbol", name: node.name, file: node.start.file, line: node.start.line, col: node.start.col }); } if (options.func_arguments && node instanceof AST_Lambda && node.uses_arguments) { AST_Node.warn("arguments used in function {name} [{file}:{line},{col}]", { name: node.name ? node.name.name : "anonymous", file: node.start.file, line: node.start.line, col: node.start.col }); } if (options.nested_defuns && node instanceof AST_Defun && !(tw.parent() instanceof AST_Scope)) { AST_Node.warn("Function {name} declared in nested statement \"{type}\" [{file}:{line},{col}]", { name: node.name.name, type: tw.parent().TYPE, file: node.start.file, line: node.start.line, col: node.start.col }); } }); this.walk(tw); }); UglifyJS2-2.4.15/lib/sourcemap.js000066400000000000000000000063341235725452400165020ustar00rootroot00000000000000/*********************************************************************** A JavaScript tokenizer / parser / beautifier / compressor. https://github.com/mishoo/UglifyJS2 -------------------------------- (C) --------------------------------- Author: Mihai Bazon http://mihai.bazon.net/blog Distributed under the BSD license: Copyright 2012 (c) Mihai Bazon Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ "use strict"; // a small wrapper around fitzgen's source-map library function SourceMap(options) { options = defaults(options, { file : null, root : null, orig : null, orig_line_diff : 0, dest_line_diff : 0, }); var generator = new MOZ_SourceMap.SourceMapGenerator({ file : options.file, sourceRoot : options.root }); var orig_map = options.orig && new MOZ_SourceMap.SourceMapConsumer(options.orig); function add(source, gen_line, gen_col, orig_line, orig_col, name) { if (orig_map) { var info = orig_map.originalPositionFor({ line: orig_line, column: orig_col }); if (info.source === null) { return; } source = info.source; orig_line = info.line; orig_col = info.column; name = info.name; } generator.addMapping({ generated : { line: gen_line + options.dest_line_diff, column: gen_col }, original : { line: orig_line + options.orig_line_diff, column: orig_col }, source : source, name : name }); }; return { add : add, get : function() { return generator }, toString : function() { return generator.toString() } }; }; UglifyJS2-2.4.15/lib/transform.js000066400000000000000000000154361235725452400165220ustar00rootroot00000000000000/*********************************************************************** A JavaScript tokenizer / parser / beautifier / compressor. https://github.com/mishoo/UglifyJS2 -------------------------------- (C) --------------------------------- Author: Mihai Bazon http://mihai.bazon.net/blog Distributed under the BSD license: Copyright 2012 (c) Mihai Bazon Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ "use strict"; // Tree transformer helpers. function TreeTransformer(before, after) { TreeWalker.call(this); this.before = before; this.after = after; } TreeTransformer.prototype = new TreeWalker; (function(undefined){ function _(node, descend) { node.DEFMETHOD("transform", function(tw, in_list){ var x, y; tw.push(this); if (tw.before) x = tw.before(this, descend, in_list); if (x === undefined) { if (!tw.after) { x = this; descend(x, tw); } else { tw.stack[tw.stack.length - 1] = x = this.clone(); descend(x, tw); y = tw.after(x, in_list); if (y !== undefined) x = y; } } tw.pop(); return x; }); }; function do_list(list, tw) { return MAP(list, function(node){ return node.transform(tw, true); }); }; _(AST_Node, noop); _(AST_LabeledStatement, function(self, tw){ self.label = self.label.transform(tw); self.body = self.body.transform(tw); }); _(AST_SimpleStatement, function(self, tw){ self.body = self.body.transform(tw); }); _(AST_Block, function(self, tw){ self.body = do_list(self.body, tw); }); _(AST_DWLoop, function(self, tw){ self.condition = self.condition.transform(tw); self.body = self.body.transform(tw); }); _(AST_For, function(self, tw){ if (self.init) self.init = self.init.transform(tw); if (self.condition) self.condition = self.condition.transform(tw); if (self.step) self.step = self.step.transform(tw); self.body = self.body.transform(tw); }); _(AST_ForIn, function(self, tw){ self.init = self.init.transform(tw); self.object = self.object.transform(tw); self.body = self.body.transform(tw); }); _(AST_With, function(self, tw){ self.expression = self.expression.transform(tw); self.body = self.body.transform(tw); }); _(AST_Exit, function(self, tw){ if (self.value) self.value = self.value.transform(tw); }); _(AST_LoopControl, function(self, tw){ if (self.label) self.label = self.label.transform(tw); }); _(AST_If, function(self, tw){ self.condition = self.condition.transform(tw); self.body = self.body.transform(tw); if (self.alternative) self.alternative = self.alternative.transform(tw); }); _(AST_Switch, function(self, tw){ self.expression = self.expression.transform(tw); self.body = do_list(self.body, tw); }); _(AST_Case, function(self, tw){ self.expression = self.expression.transform(tw); self.body = do_list(self.body, tw); }); _(AST_Try, function(self, tw){ self.body = do_list(self.body, tw); if (self.bcatch) self.bcatch = self.bcatch.transform(tw); if (self.bfinally) self.bfinally = self.bfinally.transform(tw); }); _(AST_Catch, function(self, tw){ self.argname = self.argname.transform(tw); self.body = do_list(self.body, tw); }); _(AST_Definitions, function(self, tw){ self.definitions = do_list(self.definitions, tw); }); _(AST_VarDef, function(self, tw){ self.name = self.name.transform(tw); if (self.value) self.value = self.value.transform(tw); }); _(AST_Lambda, function(self, tw){ if (self.name) self.name = self.name.transform(tw); self.argnames = do_list(self.argnames, tw); self.body = do_list(self.body, tw); }); _(AST_Call, function(self, tw){ self.expression = self.expression.transform(tw); self.args = do_list(self.args, tw); }); _(AST_Seq, function(self, tw){ self.car = self.car.transform(tw); self.cdr = self.cdr.transform(tw); }); _(AST_Dot, function(self, tw){ self.expression = self.expression.transform(tw); }); _(AST_Sub, function(self, tw){ self.expression = self.expression.transform(tw); self.property = self.property.transform(tw); }); _(AST_Unary, function(self, tw){ self.expression = self.expression.transform(tw); }); _(AST_Binary, function(self, tw){ self.left = self.left.transform(tw); self.right = self.right.transform(tw); }); _(AST_Conditional, function(self, tw){ self.condition = self.condition.transform(tw); self.consequent = self.consequent.transform(tw); self.alternative = self.alternative.transform(tw); }); _(AST_Array, function(self, tw){ self.elements = do_list(self.elements, tw); }); _(AST_Object, function(self, tw){ self.properties = do_list(self.properties, tw); }); _(AST_ObjectProperty, function(self, tw){ self.value = self.value.transform(tw); }); })(); UglifyJS2-2.4.15/lib/utils.js000066400000000000000000000216151235725452400156430ustar00rootroot00000000000000/*********************************************************************** A JavaScript tokenizer / parser / beautifier / compressor. https://github.com/mishoo/UglifyJS2 -------------------------------- (C) --------------------------------- Author: Mihai Bazon http://mihai.bazon.net/blog Distributed under the BSD license: Copyright 2012 (c) Mihai Bazon Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ "use strict"; function array_to_hash(a) { var ret = Object.create(null); for (var i = 0; i < a.length; ++i) ret[a[i]] = true; return ret; }; function slice(a, start) { return Array.prototype.slice.call(a, start || 0); }; function characters(str) { return str.split(""); }; function member(name, array) { for (var i = array.length; --i >= 0;) if (array[i] == name) return true; return false; }; function find_if(func, array) { for (var i = 0, n = array.length; i < n; ++i) { if (func(array[i])) return array[i]; } }; function repeat_string(str, i) { if (i <= 0) return ""; if (i == 1) return str; var d = repeat_string(str, i >> 1); d += d; if (i & 1) d += str; return d; }; function DefaultsError(msg, defs) { Error.call(this, msg); this.msg = msg; this.defs = defs; }; DefaultsError.prototype = Object.create(Error.prototype); DefaultsError.prototype.constructor = DefaultsError; DefaultsError.croak = function(msg, defs) { throw new DefaultsError(msg, defs); }; function defaults(args, defs, croak) { if (args === true) args = {}; var ret = args || {}; if (croak) for (var i in ret) if (ret.hasOwnProperty(i) && !defs.hasOwnProperty(i)) DefaultsError.croak("`" + i + "` is not a supported option", defs); for (var i in defs) if (defs.hasOwnProperty(i)) { ret[i] = (args && args.hasOwnProperty(i)) ? args[i] : defs[i]; } return ret; }; function merge(obj, ext) { for (var i in ext) if (ext.hasOwnProperty(i)) { obj[i] = ext[i]; } return obj; }; function noop() {}; var MAP = (function(){ function MAP(a, f, backwards) { var ret = [], top = [], i; function doit() { var val = f(a[i], i); var is_last = val instanceof Last; if (is_last) val = val.v; if (val instanceof AtTop) { val = val.v; if (val instanceof Splice) { top.push.apply(top, backwards ? val.v.slice().reverse() : val.v); } else { top.push(val); } } else if (val !== skip) { if (val instanceof Splice) { ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v); } else { ret.push(val); } } return is_last; }; if (a instanceof Array) { if (backwards) { for (i = a.length; --i >= 0;) if (doit()) break; ret.reverse(); top.reverse(); } else { for (i = 0; i < a.length; ++i) if (doit()) break; } } else { for (i in a) if (a.hasOwnProperty(i)) if (doit()) break; } return top.concat(ret); }; MAP.at_top = function(val) { return new AtTop(val) }; MAP.splice = function(val) { return new Splice(val) }; MAP.last = function(val) { return new Last(val) }; var skip = MAP.skip = {}; function AtTop(val) { this.v = val }; function Splice(val) { this.v = val }; function Last(val) { this.v = val }; return MAP; })(); function push_uniq(array, el) { if (array.indexOf(el) < 0) array.push(el); }; function string_template(text, props) { return text.replace(/\{(.+?)\}/g, function(str, p){ return props[p]; }); }; function remove(array, el) { for (var i = array.length; --i >= 0;) { if (array[i] === el) array.splice(i, 1); } }; function mergeSort(array, cmp) { if (array.length < 2) return array.slice(); function merge(a, b) { var r = [], ai = 0, bi = 0, i = 0; while (ai < a.length && bi < b.length) { cmp(a[ai], b[bi]) <= 0 ? r[i++] = a[ai++] : r[i++] = b[bi++]; } if (ai < a.length) r.push.apply(r, a.slice(ai)); if (bi < b.length) r.push.apply(r, b.slice(bi)); return r; }; function _ms(a) { if (a.length <= 1) return a; var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m); left = _ms(left); right = _ms(right); return merge(left, right); }; return _ms(array); }; function set_difference(a, b) { return a.filter(function(el){ return b.indexOf(el) < 0; }); }; function set_intersection(a, b) { return a.filter(function(el){ return b.indexOf(el) >= 0; }); }; // this function is taken from Acorn [1], written by Marijn Haverbeke // [1] https://github.com/marijnh/acorn function makePredicate(words) { if (!(words instanceof Array)) words = words.split(" "); var f = "", cats = []; out: for (var i = 0; i < words.length; ++i) { for (var j = 0; j < cats.length; ++j) if (cats[j][0].length == words[i].length) { cats[j].push(words[i]); continue out; } cats.push([words[i]]); } function compareTo(arr) { if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";"; f += "switch(str){"; for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":"; f += "return true}return false;"; } // When there are more than three length categories, an outer // switch first dispatches on the lengths, to save on comparisons. if (cats.length > 3) { cats.sort(function(a, b) {return b.length - a.length;}); f += "switch(str.length){"; for (var i = 0; i < cats.length; ++i) { var cat = cats[i]; f += "case " + cat[0].length + ":"; compareTo(cat); } f += "}"; // Otherwise, simply generate a flat `switch` statement. } else { compareTo(words); } return new Function("str", f); }; function all(array, predicate) { for (var i = array.length; --i >= 0;) if (!predicate(array[i])) return false; return true; }; function Dictionary() { this._values = Object.create(null); this._size = 0; }; Dictionary.prototype = { set: function(key, val) { if (!this.has(key)) ++this._size; this._values["$" + key] = val; return this; }, add: function(key, val) { if (this.has(key)) { this.get(key).push(val); } else { this.set(key, [ val ]); } return this; }, get: function(key) { return this._values["$" + key] }, del: function(key) { if (this.has(key)) { --this._size; delete this._values["$" + key]; } return this; }, has: function(key) { return ("$" + key) in this._values }, each: function(f) { for (var i in this._values) f(this._values[i], i.substr(1)); }, size: function() { return this._size; }, map: function(f) { var ret = []; for (var i in this._values) ret.push(f(this._values[i], i.substr(1))); return ret; } }; UglifyJS2-2.4.15/package.json000066400000000000000000000015271235725452400156650ustar00rootroot00000000000000{ "name": "uglify-js", "description": "JavaScript parser, mangler/compressor and beautifier toolkit", "homepage": "http://lisperator.net/uglifyjs", "main": "tools/node.js", "version": "2.4.15", "engines": { "node" : ">=0.4.0" }, "maintainers": [{ "name": "Mihai Bazon", "email": "mihai.bazon@gmail.com", "web": "http://lisperator.net/" }], "repository": { "type": "git", "url": "https://github.com/mishoo/UglifyJS2.git" }, "dependencies": { "async" : "~0.2.6", "source-map" : "0.1.34", "optimist" : "~0.3.5", "uglify-to-browserify": "~1.0.0" }, "browserify": { "transform": [ "uglify-to-browserify" ] }, "bin": { "uglifyjs" : "bin/uglifyjs" }, "scripts": {"test": "node test/run-tests.js"} } UglifyJS2-2.4.15/test/000077500000000000000000000000001235725452400143515ustar00rootroot00000000000000UglifyJS2-2.4.15/test/compress/000077500000000000000000000000001235725452400162045ustar00rootroot00000000000000UglifyJS2-2.4.15/test/compress/arrays.js000066400000000000000000000045731235725452400200540ustar00rootroot00000000000000holes_and_undefined: { input: { w = [1,,]; x = [1, 2, undefined]; y = [1, , 2, ]; z = [1, undefined, 3]; } expect: { w=[1,,]; x=[1,2,void 0]; y=[1,,2]; z=[1,void 0,3]; } } constant_join: { options = { unsafe : true, evaluate : true }; input: { var a = [ "foo", "bar", "baz" ].join(""); var a1 = [ "foo", "bar", "baz" ].join(); var b = [ "foo", 1, 2, 3, "bar" ].join(""); var c = [ boo(), "foo", 1, 2, 3, "bar", bar() ].join(""); var c1 = [ boo(), bar(), "foo", 1, 2, 3, "bar", bar() ].join(""); var c2 = [ 1, 2, "foo", "bar", baz() ].join(""); var d = [ "foo", 1 + 2 + "bar", "baz" ].join("-"); var e = [].join(foo + bar); var f = [].join(""); var g = [].join("foo"); } expect: { var a = "foobarbaz"; var a1 = "foo,bar,baz"; var b = "foo123bar"; var c = boo() + "foo123bar" + bar(); var c1 = "" + boo() + bar() + "foo123bar" + bar(); var c2 = "12foobar" + baz(); var d = "foo-3bar-baz"; var e = [].join(foo + bar); var f = ""; var g = ""; } } constant_join_2: { options = { unsafe : true, evaluate : true }; input: { var a = [ "foo", "bar", boo(), "baz", "x", "y" ].join(""); var b = [ "foo", "bar", boo(), "baz", "x", "y" ].join("-"); var c = [ "foo", "bar", boo(), "baz", "x", "y" ].join("really-long-separator"); var d = [ "foo", "bar", boo(), [ "foo", 1, 2, 3, "bar" ].join("+"), "baz", "x", "y" ].join("-"); var e = [ "foo", "bar", boo(), [ "foo", 1, 2, 3, "bar" ].join("+"), "baz", "x", "y" ].join("really-long-separator"); var f = [ "str", "str" + variable, "foo", "bar", "moo" + foo ].join(""); } expect: { var a = "foobar" + boo() + "bazxy"; var b = [ "foo-bar", boo(), "baz-x-y" ].join("-"); var c = [ "foo", "bar", boo(), "baz", "x", "y" ].join("really-long-separator"); var d = [ "foo-bar", boo(), "foo+1+2+3+bar-baz-x-y" ].join("-"); var e = [ "foo", "bar", boo(), "foo+1+2+3+bar", "baz", "x", "y" ].join("really-long-separator"); var f = "strstr" + variable + "foobarmoo" + foo; } } UglifyJS2-2.4.15/test/compress/blocks.js000066400000000000000000000014021235725452400200140ustar00rootroot00000000000000remove_blocks: { input: { {;} foo(); {}; { {}; }; bar(); {} } expect: { foo(); bar(); } } keep_some_blocks: { input: { // 1. if (foo) { {{{}}} if (bar) { baz(); } {{}} } else { stuff(); } // 2. if (foo) { for (var i = 0; i < 5; ++i) if (bar) baz(); } else { stuff(); } } expect: { // 1. if (foo) { if (bar) baz(); } else stuff(); // 2. if (foo) { for (var i = 0; i < 5; ++i) if (bar) baz(); } else stuff(); } } UglifyJS2-2.4.15/test/compress/concat-strings.js000066400000000000000000000011731235725452400215020ustar00rootroot00000000000000concat_1: { options = { evaluate: true }; input: { var a = "foo" + "bar" + x() + "moo" + "foo" + y() + "x" + "y" + "z" + q(); var b = "foo" + 1 + x() + 2 + "boo"; var c = 1 + x() + 2 + "boo"; // this CAN'T safely be shortened to 1 + x() + "5boo" var d = 1 + x() + 2 + 3 + "boo"; var e = 1 + x() + 2 + "X" + 3 + "boo"; } expect: { var a = "foobar" + x() + "moofoo" + y() + "xyz" + q(); var b = "foo1" + x() + "2boo"; var c = 1 + x() + 2 + "boo"; var d = 1 + x() + 2 + 3 + "boo"; var e = 1 + x() + 2 + "X3boo"; } } UglifyJS2-2.4.15/test/compress/conditionals.js000066400000000000000000000102541235725452400212320ustar00rootroot00000000000000ifs_1: { options = { conditionals: true }; input: { if (foo) bar(); if (!foo); else bar(); if (foo); else bar(); if (foo); else; } expect: { foo&&bar(); foo&&bar(); foo||bar(); foo; } } ifs_2: { options = { conditionals: true }; input: { if (foo) { x(); } else if (bar) { y(); } else if (baz) { z(); } if (foo) { x(); } else if (bar) { y(); } else if (baz) { z(); } else { t(); } } expect: { foo ? x() : bar ? y() : baz && z(); foo ? x() : bar ? y() : baz ? z() : t(); } } ifs_3_should_warn: { options = { conditionals : true, dead_code : true, evaluate : true, booleans : true }; input: { if (x && !(x + "1") && y) { // 1 var qq; foo(); } else { bar(); } if (x || !!(x + "1") || y) { // 2 foo(); } else { var jj; bar(); } } expect: { var qq; bar(); // 1 var jj; foo(); // 2 } } ifs_4: { options = { conditionals: true }; input: { if (foo && bar) { x(foo)[10].bar.baz = something(); } else x(foo)[10].bar.baz = something_else(); } expect: { x(foo)[10].bar.baz = (foo && bar) ? something() : something_else(); } } ifs_5: { options = { if_return: true, conditionals: true, comparisons: true, }; input: { function f() { if (foo) return; bar(); baz(); } function g() { if (foo) return; if (bar) return; if (baz) return; if (baa) return; a(); b(); } } expect: { function f() { if (!foo) { bar(); baz(); } } function g() { if (!(foo || bar || baz || baa)) { a(); b(); } } } } ifs_6: { options = { conditionals: true, comparisons: true }; input: { if (!foo && !bar && !baz && !boo) { x = 10; } else { x = 20; } } expect: { x = foo || bar || baz || boo ? 20 : 10; } } cond_1: { options = { conditionals: true }; input: { if (some_condition()) { do_something(x); } else { do_something(y); } } expect: { do_something(some_condition() ? x : y); } } cond_2: { options = { conditionals: true }; input: { if (some_condition()) { x = new FooBar(1); } else { x = new FooBar(2); } } expect: { x = new FooBar(some_condition() ? 1 : 2); } } cond_3: { options = { conditionals: true }; input: { if (some_condition()) { new FooBar(1); } else { FooBar(2); } } expect: { some_condition() ? new FooBar(1) : FooBar(2); } } cond_4: { options = { conditionals: true }; input: { if (some_condition()) { do_something(); } else { do_something(); } } expect: { some_condition(), do_something(); } } cond_5: { options = { conditionals: true }; input: { if (some_condition()) { if (some_other_condition()) { do_something(); } else { alternate(); } } else { alternate(); } if (some_condition()) { if (some_other_condition()) { do_something(); } } } expect: { some_condition() && some_other_condition() ? do_something() : alternate(); some_condition() && some_other_condition() && do_something(); } } UglifyJS2-2.4.15/test/compress/dead-code.js000066400000000000000000000035571235725452400203610ustar00rootroot00000000000000dead_code_1: { options = { dead_code: true }; input: { function f() { a(); b(); x = 10; return; if (x) { y(); } } } expect: { function f() { a(); b(); x = 10; return; } } } dead_code_2_should_warn: { options = { dead_code: true }; input: { function f() { g(); x = 10; throw "foo"; // completely discarding the `if` would introduce some // bugs. UglifyJS v1 doesn't deal with this issue; in v2 // we copy any declarations to the upper scope. if (x) { y(); var x; function g(){}; // but nested declarations should not be kept. (function(){ var q; function y(){}; })(); } } } expect: { function f() { g(); x = 10; throw "foo"; var x; function g(){}; } } } dead_code_constant_boolean_should_warn_more: { options = { dead_code : true, loops : true, booleans : true, conditionals : true, evaluate : true }; input: { while (!((foo && bar) || (x + "0"))) { console.log("unreachable"); var foo; function bar() {} } for (var x = 10; x && (y || x) && (!typeof x); ++x) { asdf(); foo(); var moo; } } expect: { var foo; function bar() {} // nothing for the while // as for the for, it should keep: var x = 10; var moo; } } UglifyJS2-2.4.15/test/compress/debugger.js000066400000000000000000000004771235725452400203360ustar00rootroot00000000000000keep_debugger: { options = { drop_debugger: false }; input: { debugger; } expect: { debugger; } } drop_debugger: { options = { drop_debugger: true }; input: { debugger; if (foo) debugger; } expect: { if (foo); } } UglifyJS2-2.4.15/test/compress/drop-unused.js000066400000000000000000000057421235725452400210170ustar00rootroot00000000000000unused_funarg_1: { options = { unused: true }; input: { function f(a, b, c, d, e) { return a + b; } } expect: { function f(a, b) { return a + b; } } } unused_funarg_2: { options = { unused: true }; input: { function f(a, b, c, d, e) { return a + c; } } expect: { function f(a, b, c) { return a + c; } } } unused_nested_function: { options = { unused: true }; input: { function f(x, y) { function g() { something(); } return x + y; } }; expect: { function f(x, y) { return x + y; } } } unused_circular_references_1: { options = { unused: true }; input: { function f(x, y) { // circular reference function g() { return h(); } function h() { return g(); } return x + y; } }; expect: { function f(x, y) { return x + y; } } } unused_circular_references_2: { options = { unused: true }; input: { function f(x, y) { var foo = 1, bar = baz, baz = foo + bar, qwe = moo(); return x + y; } }; expect: { function f(x, y) { moo(); // keeps side effect return x + y; } } } unused_circular_references_3: { options = { unused: true }; input: { function f(x, y) { var g = function() { return h() }; var h = function() { return g() }; return x + y; } }; expect: { function f(x, y) { return x + y; } } } unused_keep_setter_arg: { options = { unused: true }; input: { var x = { _foo: null, set foo(val) { }, get foo() { return this._foo; } } } expect: { var x = { _foo: null, set foo(val) { }, get foo() { return this._foo; } } } } unused_var_in_catch: { options = { unused: true }; input: { function foo() { try { foo(); } catch(ex) { var x = 10; } } } expect: { function foo() { try { foo(); } catch(ex) {} } } } used_var_in_catch: { options = { unused: true }; input: { function foo() { try { foo(); } catch(ex) { var x = 10; } return x; } } expect: { function foo() { try { foo(); } catch(ex) { var x = 10; } return x; } } } UglifyJS2-2.4.15/test/compress/issue-105.js000066400000000000000000000010261235725452400201740ustar00rootroot00000000000000typeof_eq_undefined: { options = { comparisons: true }; input: { a = typeof b.c != "undefined" } expect: { a = "undefined" != typeof b.c } } typeof_eq_undefined_unsafe: { options = { comparisons: true, unsafe: true }; input: { a = typeof b.c != "undefined" } expect: { a = void 0 !== b.c } } typeof_eq_undefined_unsafe2: { options = { comparisons: true, unsafe: true }; input: { a = "undefined" != typeof b.c } expect: { a = void 0 !== b.c } } UglifyJS2-2.4.15/test/compress/issue-12.js000066400000000000000000000004111235725452400201060ustar00rootroot00000000000000keep_name_of_getter: { options = { unused: true }; input: { a = { get foo () {} } } expect: { a = { get foo () {} } } } keep_name_of_setter: { options = { unused: true }; input: { a = { set foo () {} } } expect: { a = { set foo () {} } } } UglifyJS2-2.4.15/test/compress/issue-126.js000066400000000000000000000015071235725452400202030ustar00rootroot00000000000000concatenate_rhs_strings: { options = { evaluate: true, unsafe: true, } input: { foo(bar() + 123 + "Hello" + "World"); foo(bar() + (123 + "Hello") + "World"); foo((bar() + 123) + "Hello" + "World"); foo(bar() + 123 + "Hello" + "World" + ("Foo" + "Bar")); foo("Foo" + "Bar" + bar() + 123 + "Hello" + "World" + ("Foo" + "Bar")); foo("Hello" + bar() + 123 + "World"); foo(bar() + 'Foo' + (10 + parseInt('10'))); } expect: { foo(bar() + 123 + "HelloWorld"); foo(bar() + "123HelloWorld"); foo((bar() + 123) + "HelloWorld"); foo(bar() + 123 + "HelloWorldFooBar"); foo("FooBar" + bar() + "123HelloWorldFooBar"); foo("Hello" + bar() + "123World"); foo(bar() + 'Foo' + (10 + parseInt('10'))); } } UglifyJS2-2.4.15/test/compress/issue-143.js000066400000000000000000000021101235725452400201710ustar00rootroot00000000000000/** * There was an incorrect sort behaviour documented in issue #143: * (x = f(…)) <= x → x >= (x = f(…)) * * For example, let the equation be: * (a = parseInt('100')) <= a * * If a was an integer and has the value of 99, * (a = parseInt('100')) <= a → 100 <= 100 → true * * When transformed incorrectly: * a >= (a = parseInt('100')) → 99 >= 100 → false */ tranformation_sort_order_equal: { options = { comparisons: true, }; input: { (a = parseInt('100')) == a } expect: { (a = parseInt('100')) == a } } tranformation_sort_order_unequal: { options = { comparisons: true, }; input: { (a = parseInt('100')) != a } expect: { (a = parseInt('100')) != a } } tranformation_sort_order_lesser_or_equal: { options = { comparisons: true, }; input: { (a = parseInt('100')) <= a } expect: { (a = parseInt('100')) <= a } } tranformation_sort_order_greater_or_equal: { options = { comparisons: true, }; input: { (a = parseInt('100')) >= a } expect: { (a = parseInt('100')) >= a } }UglifyJS2-2.4.15/test/compress/issue-22.js000066400000000000000000000005201235725452400201100ustar00rootroot00000000000000return_with_no_value_in_if_body: { options = { conditionals: true }; input: { function foo(bar) { if (bar) { return; } else { return 1; } } } expect: { function foo (bar) { return bar ? void 0 : 1; } } } UglifyJS2-2.4.15/test/compress/issue-267.js000066400000000000000000000003061235725452400202050ustar00rootroot00000000000000issue_267: { options = { comparisons: true }; input: { x = a % b / b * c * 2; x = a % b * 2 } expect: { x = a % b / b * c * 2; x = a % b * 2; } } UglifyJS2-2.4.15/test/compress/issue-269.js000066400000000000000000000014401235725452400202070ustar00rootroot00000000000000issue_269_1: { options = {unsafe: true}; input: { f( String(x), Number(x), Boolean(x), String(), Number(), Boolean() ); } expect: { f( x + '', +x, !!x, '', 0, false ); } } issue_269_dangers: { options = {unsafe: true}; input: { f( String(x, x), Number(x, x), Boolean(x, x) ); } expect: { f(String(x, x), Number(x, x), Boolean(x, x)); } } issue_269_in_scope: { options = {unsafe: true}; input: { var String, Number, Boolean; f( String(x), Number(x, x), Boolean(x) ); } expect: { var String, Number, Boolean; f(String(x), Number(x, x), Boolean(x)); } } strings_concat: { options = {unsafe: true}; input: { f( String(x + 'str'), String('str' + x) ); } expect: { f( x + 'str', 'str' + x ); } } UglifyJS2-2.4.15/test/compress/issue-44.js000066400000000000000000000011311235725452400201130ustar00rootroot00000000000000issue_44_valid_ast_1: { options = { unused: true }; input: { function a(b) { for (var i = 0, e = b.qoo(); ; i++) {} } } expect: { function a(b) { var i = 0; for (b.qoo(); ; i++); } } } issue_44_valid_ast_2: { options = { unused: true }; input: { function a(b) { if (foo) for (var i = 0, e = b.qoo(); ; i++) {} } } expect: { function a(b) { if (foo) { var i = 0; for (b.qoo(); ; i++); } } } } UglifyJS2-2.4.15/test/compress/issue-59.js000066400000000000000000000010471235725452400201270ustar00rootroot00000000000000keep_continue: { options = { dead_code: true, evaluate: true }; input: { while (a) { if (b) { switch (true) { case c(): d(); } continue; } f(); } } expect: { while (a) { if (b) { switch (true) { case c(): d(); } continue; } f(); } } } UglifyJS2-2.4.15/test/compress/labels.js000066400000000000000000000060401235725452400200040ustar00rootroot00000000000000labels_1: { options = { if_return: true, conditionals: true, dead_code: true }; input: { out: { if (foo) break out; console.log("bar"); } }; expect: { foo || console.log("bar"); } } labels_2: { options = { if_return: true, conditionals: true, dead_code: true }; input: { out: { if (foo) print("stuff"); else break out; console.log("here"); } }; expect: { if (foo) { print("stuff"); console.log("here"); } } } labels_3: { options = { if_return: true, conditionals: true, dead_code: true }; input: { for (var i = 0; i < 5; ++i) { if (i < 3) continue; console.log(i); } }; expect: { for (var i = 0; i < 5; ++i) i < 3 || console.log(i); } } labels_4: { options = { if_return: true, conditionals: true, dead_code: true }; input: { out: for (var i = 0; i < 5; ++i) { if (i < 3) continue out; console.log(i); } }; expect: { for (var i = 0; i < 5; ++i) i < 3 || console.log(i); } } labels_5: { options = { if_return: true, conditionals: true, dead_code: true }; // should keep the break-s in the following input: { while (foo) { if (bar) break; console.log("foo"); } out: while (foo) { if (bar) break out; console.log("foo"); } }; expect: { while (foo) { if (bar) break; console.log("foo"); } out: while (foo) { if (bar) break out; console.log("foo"); } } } labels_6: { input: { out: break out; }; expect: {} } labels_7: { options = { if_return: true, conditionals: true, dead_code: true }; input: { while (foo) { x(); y(); continue; } }; expect: { while (foo) { x(); y(); } } } labels_8: { options = { if_return: true, conditionals: true, dead_code: true }; input: { while (foo) { x(); y(); break; } }; expect: { while (foo) { x(); y(); break; } } } labels_9: { options = { if_return: true, conditionals: true, dead_code: true }; input: { out: while (foo) { x(); y(); continue out; z(); k(); } }; expect: { while (foo) { x(); y(); } } } labels_10: { options = { if_return: true, conditionals: true, dead_code: true }; input: { out: while (foo) { x(); y(); break out; z(); k(); } }; expect: { out: while (foo) { x(); y(); break out; } } } UglifyJS2-2.4.15/test/compress/loops.js000066400000000000000000000041421235725452400176770ustar00rootroot00000000000000while_becomes_for: { options = { loops: true }; input: { while (foo()) bar(); } expect: { for (; foo(); ) bar(); } } drop_if_break_1: { options = { loops: true }; input: { for (;;) if (foo()) break; } expect: { for (; !foo();); } } drop_if_break_2: { options = { loops: true }; input: { for (;bar();) if (foo()) break; } expect: { for (; bar() && !foo();); } } drop_if_break_3: { options = { loops: true }; input: { for (;bar();) { if (foo()) break; stuff1(); stuff2(); } } expect: { for (; bar() && !foo();) { stuff1(); stuff2(); } } } drop_if_break_4: { options = { loops: true, sequences: true }; input: { for (;bar();) { x(); y(); if (foo()) break; z(); k(); } } expect: { for (; bar() && (x(), y(), !foo());) z(), k(); } } drop_if_else_break_1: { options = { loops: true }; input: { for (;;) if (foo()) bar(); else break; } expect: { for (; foo(); ) bar(); } } drop_if_else_break_2: { options = { loops: true }; input: { for (;bar();) { if (foo()) baz(); else break; } } expect: { for (; bar() && foo();) baz(); } } drop_if_else_break_3: { options = { loops: true }; input: { for (;bar();) { if (foo()) baz(); else break; stuff1(); stuff2(); } } expect: { for (; bar() && foo();) { baz(); stuff1(); stuff2(); } } } drop_if_else_break_4: { options = { loops: true, sequences: true }; input: { for (;bar();) { x(); y(); if (foo()) baz(); else break; z(); k(); } } expect: { for (; bar() && (x(), y(), foo());) baz(), z(), k(); } } UglifyJS2-2.4.15/test/compress/negate-iife.js000066400000000000000000000030551235725452400207220ustar00rootroot00000000000000negate_iife_1: { options = { negate_iife: true }; input: { (function(){ stuff() })(); } expect: { !function(){ stuff() }(); } } negate_iife_2: { options = { negate_iife: true }; input: { (function(){ return {} })().x = 10; // should not transform this one } expect: { (function(){ return {} })().x = 10; } } negate_iife_3: { options = { negate_iife: true, }; input: { (function(){ return true })() ? console.log(true) : console.log(false); } expect: { !function(){ return true }() ? console.log(false) : console.log(true); } } negate_iife_3: { options = { negate_iife: true, sequences: true }; input: { (function(){ return true })() ? console.log(true) : console.log(false); (function(){ console.log("something"); })(); } expect: { !function(){ return true }() ? console.log(false) : console.log(true), function(){ console.log("something"); }(); } } negate_iife_4: { options = { negate_iife: true, sequences: true, conditionals: true, }; input: { if ((function(){ return true })()) { foo(true); } else { bar(false); } (function(){ console.log("something"); })(); } expect: { !function(){ return true }() ? bar(false) : foo(true), function(){ console.log("something"); }(); } } UglifyJS2-2.4.15/test/compress/properties.js000066400000000000000000000025441235725452400207430ustar00rootroot00000000000000keep_properties: { options = { properties: false }; input: { a["foo"] = "bar"; } expect: { a["foo"] = "bar"; } } dot_properties: { options = { properties: true }; input: { a["foo"] = "bar"; a["if"] = "if"; a["*"] = "asterisk"; a["\u0EB3"] = "unicode"; a[""] = "whitespace"; a["1_1"] = "foo"; } expect: { a.foo = "bar"; a["if"] = "if"; a["*"] = "asterisk"; a["\u0EB3"] = "unicode"; a[""] = "whitespace"; a["1_1"] = "foo"; } } dot_properties_es5: { options = { properties: true, screw_ie8: true }; input: { a["foo"] = "bar"; a["if"] = "if"; a["*"] = "asterisk"; a["\u0EB3"] = "unicode"; a[""] = "whitespace"; } expect: { a.foo = "bar"; a.if = "if"; a["*"] = "asterisk"; a["\u0EB3"] = "unicode"; a[""] = "whitespace"; } } evaluate_length: { options = { properties: true, unsafe: true, evaluate: true }; input: { a = "foo".length; a = ("foo" + "bar")["len" + "gth"]; a = b.length; a = ("foo" + b).length; } expect: { a = 3; a = 6; a = b.length; a = ("foo" + b).length; } } UglifyJS2-2.4.15/test/compress/sequences.js000066400000000000000000000054321235725452400205410ustar00rootroot00000000000000make_sequences_1: { options = { sequences: true }; input: { foo(); bar(); baz(); } expect: { foo(),bar(),baz(); } } make_sequences_2: { options = { sequences: true }; input: { if (boo) { foo(); bar(); baz(); } else { x(); y(); z(); } } expect: { if (boo) foo(),bar(),baz(); else x(),y(),z(); } } make_sequences_3: { options = { sequences: true }; input: { function f() { foo(); bar(); return baz(); } function g() { foo(); bar(); throw new Error(); } } expect: { function f() { return foo(), bar(), baz(); } function g() { throw foo(), bar(), new Error(); } } } make_sequences_4: { options = { sequences: true }; input: { x = 5; if (y) z(); x = 5; for (i = 0; i < 5; i++) console.log(i); x = 5; for (; i < 5; i++) console.log(i); x = 5; switch (y) {} x = 5; with (obj) {} } expect: { if (x = 5, y) z(); for (x = 5, i = 0; i < 5; i++) console.log(i); for (x = 5; i < 5; i++) console.log(i); switch (x = 5, y) {} with (x = 5, obj); } } lift_sequences_1: { options = { sequences: true }; input: { foo = !(x(), y(), bar()); } expect: { x(), y(), foo = !bar(); } } lift_sequences_2: { options = { sequences: true, evaluate: true }; input: { foo.x = (foo = {}, 10); bar = (bar = {}, 10); } expect: { foo.x = (foo = {}, 10), bar = {}, bar = 10; } } lift_sequences_3: { options = { sequences: true, conditionals: true }; input: { x = (foo(), bar(), baz()) ? 10 : 20; } expect: { foo(), bar(), x = baz() ? 10 : 20; } } lift_sequences_4: { options = { side_effects: true }; input: { x = (foo, bar, baz); } expect: { x = baz; } } for_sequences: { options = { sequences: true }; input: { // 1 foo(); bar(); for (; false;); // 2 foo(); bar(); for (x = 5; false;); // 3 x = (foo in bar); for (; false;); // 4 x = (foo in bar); for (y = 5; false;); } expect: { // 1 for (foo(), bar(); false;); // 2 for (foo(), bar(), x = 5; false;); // 3 x = (foo in bar); for (; false;); // 4 x = (foo in bar); for (y = 5; false;); } } UglifyJS2-2.4.15/test/compress/switch.js000066400000000000000000000116111235725452400200430ustar00rootroot00000000000000constant_switch_1: { options = { dead_code: true, evaluate: true }; input: { switch (1+1) { case 1: foo(); break; case 1+1: bar(); break; case 1+1+1: baz(); break; } } expect: { bar(); } } constant_switch_2: { options = { dead_code: true, evaluate: true }; input: { switch (1) { case 1: foo(); case 1+1: bar(); break; case 1+1+1: baz(); } } expect: { foo(); bar(); } } constant_switch_3: { options = { dead_code: true, evaluate: true }; input: { switch (10) { case 1: foo(); case 1+1: bar(); break; case 1+1+1: baz(); default: def(); } } expect: { def(); } } constant_switch_4: { options = { dead_code: true, evaluate: true }; input: { switch (2) { case 1: x(); if (foo) break; y(); break; case 1+1: bar(); default: def(); } } expect: { bar(); def(); } } constant_switch_5: { options = { dead_code: true, evaluate: true }; input: { switch (1) { case 1: x(); if (foo) break; y(); break; case 1+1: bar(); default: def(); } } expect: { // the break inside the if ruins our job // we can still get rid of irrelevant cases. switch (1) { case 1: x(); if (foo) break; y(); } // XXX: we could optimize this better by inventing an outer // labeled block, but that's kinda tricky. } } constant_switch_6: { options = { dead_code: true, evaluate: true }; input: { OUT: { foo(); switch (1) { case 1: x(); if (foo) break OUT; y(); case 1+1: bar(); break; default: def(); } } } expect: { OUT: { foo(); x(); if (foo) break OUT; y(); bar(); } } } constant_switch_7: { options = { dead_code: true, evaluate: true }; input: { OUT: { foo(); switch (1) { case 1: x(); if (foo) break OUT; for (var x = 0; x < 10; x++) { if (x > 5) break; // this break refers to the for, not to the switch; thus it // shouldn't ruin our optimization console.log(x); } y(); case 1+1: bar(); break; default: def(); } } } expect: { OUT: { foo(); x(); if (foo) break OUT; for (var x = 0; x < 10; x++) { if (x > 5) break; console.log(x); } y(); bar(); } } } constant_switch_8: { options = { dead_code: true, evaluate: true }; input: { OUT: switch (1) { case 1: x(); for (;;) break OUT; y(); break; case 1+1: bar(); default: def(); } } expect: { OUT: { x(); for (;;) break OUT; y(); } } } constant_switch_9: { options = { dead_code: true, evaluate: true }; input: { OUT: switch (1) { case 1: x(); for (;;) if (foo) break OUT; y(); case 1+1: bar(); default: def(); } } expect: { OUT: { x(); for (;;) if (foo) break OUT; y(); bar(); def(); } } } drop_default_1: { options = { dead_code: true }; input: { switch (foo) { case 'bar': baz(); default: } } expect: { switch (foo) { case 'bar': baz(); } } } drop_default_2: { options = { dead_code: true }; input: { switch (foo) { case 'bar': baz(); break; default: break; } } expect: { switch (foo) { case 'bar': baz(); } } } keep_default: { options = { dead_code: true }; input: { switch (foo) { case 'bar': baz(); default: something(); break; } } expect: { switch (foo) { case 'bar': baz(); default: something(); } } } UglifyJS2-2.4.15/test/compress/typeof.js000066400000000000000000000007431235725452400200540ustar00rootroot00000000000000typeof_evaluation: { options = { evaluate: true }; input: { a = typeof 1; b = typeof 'test'; c = typeof []; d = typeof {}; e = typeof /./; f = typeof false; g = typeof function(){}; h = typeof undefined; } expect: { a='number'; b='string'; c=typeof[]; d=typeof{}; e=typeof/./; f='boolean'; g='function'; h='undefined'; } } UglifyJS2-2.4.15/test/run-tests.js000077500000000000000000000124331235725452400166610ustar00rootroot00000000000000#! /usr/bin/env node var U = require("../tools/node"); var path = require("path"); var fs = require("fs"); var assert = require("assert"); var sys = require("util"); var tests_dir = path.dirname(module.filename); var failures = 0; var failed_files = {}; run_compress_tests(); if (failures) { sys.error("\n!!! Failed " + failures + " test cases."); sys.error("!!! " + Object.keys(failed_files).join(", ")); process.exit(1); } /* -----[ utils ]----- */ function tmpl() { return U.string_template.apply(this, arguments); } function log() { var txt = tmpl.apply(this, arguments); sys.puts(txt); } function log_directory(dir) { log("*** Entering [{dir}]", { dir: dir }); } function log_start_file(file) { log("--- {file}", { file: file }); } function log_test(name) { log(" Running test [{name}]", { name: name }); } function find_test_files(dir) { var files = fs.readdirSync(dir).filter(function(name){ return /\.js$/i.test(name); }); if (process.argv.length > 2) { var x = process.argv.slice(2); files = files.filter(function(f){ return x.indexOf(f) >= 0; }); } return files; } function test_directory(dir) { return path.resolve(tests_dir, dir); } function as_toplevel(input) { if (input instanceof U.AST_BlockStatement) input = input.body; else if (input instanceof U.AST_Statement) input = [ input ]; else throw new Error("Unsupported input syntax"); var toplevel = new U.AST_Toplevel({ body: input }); toplevel.figure_out_scope(); return toplevel; } function run_compress_tests() { var dir = test_directory("compress"); log_directory("compress"); var files = find_test_files(dir); function test_file(file) { log_start_file(file); function test_case(test) { log_test(test.name); var options = U.defaults(test.options, { warnings: false }); var cmp = new U.Compressor(options, true); var expect = make_code(as_toplevel(test.expect), false); var input = as_toplevel(test.input); var input_code = make_code(test.input); var output = input.transform(cmp); output.figure_out_scope(); output = make_code(output, false); if (expect != output) { log("!!! failed\n---INPUT---\n{input}\n---OUTPUT---\n{output}\n---EXPECTED---\n{expected}\n\n", { input: input_code, output: output, expected: expect }); failures++; failed_files[file] = 1; } } var tests = parse_test(path.resolve(dir, file)); for (var i in tests) if (tests.hasOwnProperty(i)) { test_case(tests[i]); } } files.forEach(function(file){ test_file(file); }); } function parse_test(file) { var script = fs.readFileSync(file, "utf8"); var ast = U.parse(script, { filename: file }); var tests = {}; var tw = new U.TreeWalker(function(node, descend){ if (node instanceof U.AST_LabeledStatement && tw.parent() instanceof U.AST_Toplevel) { var name = node.label.name; tests[name] = get_one_test(name, node.body); return true; } if (!(node instanceof U.AST_Toplevel)) croak(node); }); ast.walk(tw); return tests; function croak(node) { throw new Error(tmpl("Can't understand test file {file} [{line},{col}]\n{code}", { file: file, line: node.start.line, col: node.start.col, code: make_code(node, false) })); } function get_one_test(name, block) { var test = { name: name, options: {} }; var tw = new U.TreeWalker(function(node, descend){ if (node instanceof U.AST_Assign) { if (!(node.left instanceof U.AST_SymbolRef)) { croak(node); } var name = node.left.name; test[name] = evaluate(node.right); return true; } if (node instanceof U.AST_LabeledStatement) { assert.ok( node.label.name == "input" || node.label.name == "expect", tmpl("Unsupported label {name} [{line},{col}]", { name: node.label.name, line: node.label.start.line, col: node.label.start.col }) ); var stat = node.body; if (stat instanceof U.AST_BlockStatement) { if (stat.body.length == 1) stat = stat.body[0]; else if (stat.body.length == 0) stat = new U.AST_EmptyStatement(); } test[node.label.name] = stat; return true; } }); block.walk(tw); return test; }; } function make_code(ast, beautify) { if (arguments.length == 1) beautify = true; var stream = U.OutputStream({ beautify: beautify }); ast.print(stream); return stream.get(); } function evaluate(code) { if (code instanceof U.AST_Node) code = make_code(code); return new Function("return(" + code + ")")(); } UglifyJS2-2.4.15/tools/000077500000000000000000000000001235725452400145325ustar00rootroot00000000000000UglifyJS2-2.4.15/tools/node.js000066400000000000000000000122371235725452400160220ustar00rootroot00000000000000var path = require("path"); var fs = require("fs"); var vm = require("vm"); var sys = require("util"); var UglifyJS = vm.createContext({ sys : sys, console : console, MOZ_SourceMap : require("source-map") }); function load_global(file) { file = path.resolve(path.dirname(module.filename), file); try { var code = fs.readFileSync(file, "utf8"); return vm.runInContext(code, UglifyJS, file); } catch(ex) { // XXX: in case of a syntax error, the message is kinda // useless. (no location information). sys.debug("ERROR in file: " + file + " / " + ex); process.exit(1); } }; var FILES = exports.FILES = [ "../lib/utils.js", "../lib/ast.js", "../lib/parse.js", "../lib/transform.js", "../lib/scope.js", "../lib/output.js", "../lib/compress.js", "../lib/sourcemap.js", "../lib/mozilla-ast.js" ].map(function(file){ return path.join(path.dirname(fs.realpathSync(__filename)), file); }); FILES.forEach(load_global); UglifyJS.AST_Node.warn_function = function(txt) { sys.error("WARN: " + txt); }; // XXX: perhaps we shouldn't export everything but heck, I'm lazy. for (var i in UglifyJS) { if (UglifyJS.hasOwnProperty(i)) { exports[i] = UglifyJS[i]; } } exports.minify = function(files, options) { options = UglifyJS.defaults(options, { spidermonkey : false, outSourceMap : null, sourceRoot : null, inSourceMap : null, fromString : false, warnings : false, mangle : {}, output : null, compress : {} }); UglifyJS.base54.reset(); // 1. parse var toplevel = null, sourcesContent = {}; if (options.spidermonkey) { toplevel = UglifyJS.AST_Node.from_mozilla_ast(files); } else { if (typeof files == "string") files = [ files ]; files.forEach(function(file){ var code = options.fromString ? file : fs.readFileSync(file, "utf8"); sourcesContent[file] = code; toplevel = UglifyJS.parse(code, { filename: options.fromString ? "?" : file, toplevel: toplevel }); }); } // 2. compress if (options.compress) { var compress = { warnings: options.warnings }; UglifyJS.merge(compress, options.compress); toplevel.figure_out_scope(); var sq = UglifyJS.Compressor(compress); toplevel = toplevel.transform(sq); } // 3. mangle if (options.mangle) { toplevel.figure_out_scope(); toplevel.compute_char_frequency(); toplevel.mangle_names(options.mangle); } // 4. output var inMap = options.inSourceMap; var output = {}; if (typeof options.inSourceMap == "string") { inMap = fs.readFileSync(options.inSourceMap, "utf8"); } if (options.outSourceMap) { output.source_map = UglifyJS.SourceMap({ file: options.outSourceMap, orig: inMap, root: options.sourceRoot }); if (options.sourceMapIncludeSources) { for (var file in sourcesContent) { if (sourcesContent.hasOwnProperty(file)) { output.source_map.get().setSourceContent(file, sourcesContent[file]); } } } } if (options.output) { UglifyJS.merge(output, options.output); } var stream = UglifyJS.OutputStream(output); toplevel.print(stream); if(options.outSourceMap){ stream += "\n//# sourceMappingURL=" + options.outSourceMap; } return { code : stream + "", map : output.source_map + "" }; }; // exports.describe_ast = function() { // function doitem(ctor) { // var sub = {}; // ctor.SUBCLASSES.forEach(function(ctor){ // sub[ctor.TYPE] = doitem(ctor); // }); // var ret = {}; // if (ctor.SELF_PROPS.length > 0) ret.props = ctor.SELF_PROPS; // if (ctor.SUBCLASSES.length > 0) ret.sub = sub; // return ret; // } // return doitem(UglifyJS.AST_Node).sub; // } exports.describe_ast = function() { var out = UglifyJS.OutputStream({ beautify: true }); function doitem(ctor) { out.print("AST_" + ctor.TYPE); var props = ctor.SELF_PROPS.filter(function(prop){ return !/^\$/.test(prop); }); if (props.length > 0) { out.space(); out.with_parens(function(){ props.forEach(function(prop, i){ if (i) out.space(); out.print(prop); }); }); } if (ctor.documentation) { out.space(); out.print_string(ctor.documentation); } if (ctor.SUBCLASSES.length > 0) { out.space(); out.with_block(function(){ ctor.SUBCLASSES.forEach(function(ctor, i){ out.indent(); doitem(ctor); out.newline(); }); }); } }; doitem(UglifyJS.AST_Node); return out + ""; };