Showing preview only (354K chars total). Download the full file or copy to clipboard to get everything.
Repository: mishoo/UglifyJS-old
Branch: master
Commit: 2bc1d02363db
Files: 118
Total size: 325.8 KB
Directory structure:
gitextract_mr1693vq/
├── .gitignore
├── README.html
├── README.org
├── bin/
│ └── uglifyjs
├── docstyle.css
├── lib/
│ ├── consolidator.js
│ ├── parse-js.js
│ ├── process.js
│ └── squeeze-more.js
├── package.json
├── test/
│ ├── beautify.js
│ ├── testconsolidator.js
│ ├── testparser.js
│ └── unit/
│ ├── compress/
│ │ ├── expected/
│ │ │ ├── 1e21.js
│ │ │ ├── array1.js
│ │ │ ├── array2.js
│ │ │ ├── array3.js
│ │ │ ├── array4.js
│ │ │ ├── assignment.js
│ │ │ ├── concatstring.js
│ │ │ ├── const.js
│ │ │ ├── div-with-regexp.js
│ │ │ ├── empty-blocks.js
│ │ │ ├── forstatement.js
│ │ │ ├── if-not.js
│ │ │ ├── if.js
│ │ │ ├── ifreturn.js
│ │ │ ├── ifreturn2.js
│ │ │ ├── infinite.js
│ │ │ ├── issue10.js
│ │ │ ├── issue11.js
│ │ │ ├── issue13.js
│ │ │ ├── issue14.js
│ │ │ ├── issue16.js
│ │ │ ├── issue17.js
│ │ │ ├── issue20.js
│ │ │ ├── issue21.js
│ │ │ ├── issue25.js
│ │ │ ├── issue27.js
│ │ │ ├── issue278.js
│ │ │ ├── issue28.js
│ │ │ ├── issue29.js
│ │ │ ├── issue30.js
│ │ │ ├── issue34.js
│ │ │ ├── issue349.js
│ │ │ ├── issue353.js
│ │ │ ├── issue372.js
│ │ │ ├── issue4.js
│ │ │ ├── issue471.js
│ │ │ ├── issue48.js
│ │ │ ├── issue50.js
│ │ │ ├── issue53.js
│ │ │ ├── issue54.1.js
│ │ │ ├── issue68.js
│ │ │ ├── issue69.js
│ │ │ ├── issue9.js
│ │ │ ├── issues222_324.js
│ │ │ ├── mangle.js
│ │ │ ├── null_string.js
│ │ │ ├── strict-equals.js
│ │ │ ├── var.js
│ │ │ ├── whitespace.js
│ │ │ └── with.js
│ │ └── test/
│ │ ├── 1e21.js
│ │ ├── array1.js
│ │ ├── array2.js
│ │ ├── array3.js
│ │ ├── array4.js
│ │ ├── assignment.js
│ │ ├── concatstring.js
│ │ ├── const.js
│ │ ├── div-with-regexp.js
│ │ ├── empty-blocks.js
│ │ ├── forstatement.js
│ │ ├── if-not.js
│ │ ├── if.js
│ │ ├── ifreturn.js
│ │ ├── ifreturn2.js
│ │ ├── infinite.js
│ │ ├── issue10.js
│ │ ├── issue11.js
│ │ ├── issue13.js
│ │ ├── issue14.js
│ │ ├── issue16.js
│ │ ├── issue17.js
│ │ ├── issue20.js
│ │ ├── issue21.js
│ │ ├── issue25.js
│ │ ├── issue27.js
│ │ ├── issue278.js
│ │ ├── issue28.js
│ │ ├── issue29.js
│ │ ├── issue30.js
│ │ ├── issue34.js
│ │ ├── issue349.js
│ │ ├── issue353.js
│ │ ├── issue372.js
│ │ ├── issue4.js
│ │ ├── issue471.js
│ │ ├── issue48.js
│ │ ├── issue50.js
│ │ ├── issue53.js
│ │ ├── issue54.1.js
│ │ ├── issue68.js
│ │ ├── issue69.js
│ │ ├── issue9.js
│ │ ├── issues222_324.js
│ │ ├── mangle.js
│ │ ├── null_string.js
│ │ ├── strict-equals.js
│ │ ├── var.js
│ │ ├── whitespace.js
│ │ └── with.js
│ └── scripts.js
├── tmp/
│ ├── hoist.js
│ ├── instrument.js
│ └── test.js
└── uglify-js.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
.DS_Store
.tmp*~
*.local.*
.pinf-*
node_modules/
npm-debug.log
================================================
FILE: README.html
================================================
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
lang="en" xml:lang="en">
<head>
<title>UglifyJS – a JavaScript parser/compressor/beautifier</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<meta name="generator" content="Org-mode"/>
<meta name="generated" content="2012-11-22 10:46:14 EET"/>
<meta name="author" content="Mihai Bazon"/>
<meta name="description" content="a JavaScript parser/compressor/beautifier in JavaScript"/>
<meta name="keywords" content="javascript, js, parser, compiler, compressor, mangle, minify, minifier"/>
<style type="text/css">
<!--/*--><![CDATA[/*><!--*/
html { font-family: Times, serif; font-size: 12pt; }
.title { text-align: center; }
.todo { color: red; }
.done { color: green; }
.tag { background-color: #add8e6; font-weight:normal }
.target { }
.timestamp { color: #bebebe; }
.timestamp-kwd { color: #5f9ea0; }
.right {margin-left:auto; margin-right:0px; text-align:right;}
.left {margin-left:0px; margin-right:auto; text-align:left;}
.center {margin-left:auto; margin-right:auto; text-align:center;}
p.verse { margin-left: 3% }
pre {
border: 1pt solid #AEBDCC;
background-color: #F3F5F7;
padding: 5pt;
font-family: courier, monospace;
font-size: 90%;
overflow:auto;
}
table { border-collapse: collapse; }
td, th { vertical-align: top; }
th.right { text-align:center; }
th.left { text-align:center; }
th.center { text-align:center; }
td.right { text-align:right; }
td.left { text-align:left; }
td.center { text-align:center; }
dt { font-weight: bold; }
div.figure { padding: 0.5em; }
div.figure p { text-align: center; }
div.inlinetask {
padding:10px;
border:2px solid gray;
margin:10px;
background: #ffffcc;
}
textarea { overflow-x: auto; }
.linenr { font-size:smaller }
.code-highlighted {background-color:#ffff00;}
.org-info-js_info-navigation { border-style:none; }
#org-info-js_console-label { font-size:10px; font-weight:bold;
white-space:nowrap; }
.org-info-js_search-highlight {background-color:#ffff00; color:#000000;
font-weight:bold; }
/*]]>*/-->
</style>
<link rel="stylesheet" type="text/css" href="docstyle.css" />
<script type="text/javascript">
<!--/*--><![CDATA[/*><!--*/
function CodeHighlightOn(elem, id)
{
var target = document.getElementById(id);
if(null != target) {
elem.cacheClassElem = elem.className;
elem.cacheClassTarget = target.className;
target.className = "code-highlighted";
elem.className = "code-highlighted";
}
}
function CodeHighlightOff(elem, id)
{
var target = document.getElementById(id);
if(elem.cacheClassElem)
elem.className = elem.cacheClassElem;
if(elem.cacheClassTarget)
target.className = elem.cacheClassTarget;
}
/*]]>*///-->
</script>
</head>
<body>
<div id="preamble">
</div>
<div id="content">
<h1 class="title">UglifyJS – a JavaScript parser/compressor/beautifier</h1>
<div id="table-of-contents">
<h2>Table of Contents</h2>
<div id="text-table-of-contents">
<ul>
<li><a href="#sec-1">1 NEW: UglifyJS2 </a></li>
<li><a href="#sec-2">2 UglifyJS — a JavaScript parser/compressor/beautifier </a>
<ul>
<li><a href="#sec-2-1">2.1 Unsafe transformations </a>
<ul>
<li><a href="#sec-2-1-1">2.1.1 Calls involving the global Array constructor </a></li>
<li><a href="#sec-2-1-2">2.1.2 <code>obj.toString()</code> ==> <code>obj+“”</code> </a></li>
</ul>
</li>
<li><a href="#sec-2-2">2.2 Install (NPM) </a></li>
<li><a href="#sec-2-3">2.3 Install latest code from GitHub </a></li>
<li><a href="#sec-2-4">2.4 Usage </a>
<ul>
<li><a href="#sec-2-4-1">2.4.1 API </a></li>
<li><a href="#sec-2-4-2">2.4.2 Beautifier shortcoming – no more comments </a></li>
<li><a href="#sec-2-4-3">2.4.3 Use as a code pre-processor </a></li>
</ul>
</li>
<li><a href="#sec-2-5">2.5 Compression – how good is it? </a></li>
<li><a href="#sec-2-6">2.6 Bugs? </a></li>
<li><a href="#sec-2-7">2.7 Links </a></li>
<li><a href="#sec-2-8">2.8 License </a></li>
</ul>
</li>
</ul>
</div>
</div>
<div id="outline-container-1" class="outline-2">
<h2 id="sec-1"><span class="section-number-2">1</span> NEW: UglifyJS2 </h2>
<div class="outline-text-2" id="text-1">
<p>
I started working on UglifyJS's successor, version 2. It's almost a full
rewrite (except for the parser which is heavily modified, everything else
starts from scratch). I've detailed my reasons in the README, see the
project page.
</p>
<p>
<a href="https://github.com/mishoo/UglifyJS2">https://github.com/mishoo/UglifyJS2</a>
</p>
<p>
Version 1 will continue to be maintained for fixing show-stopper bugs, but
no new features should be expected.
</p>
</div>
</div>
<div id="outline-container-2" class="outline-2">
<h2 id="sec-2"><span class="section-number-2">2</span> UglifyJS — a JavaScript parser/compressor/beautifier </h2>
<div class="outline-text-2" id="text-2">
<p>
This package implements a general-purpose JavaScript
parser/compressor/beautifier toolkit. It is developed on <a href="http://nodejs.org/">NodeJS</a>, but it
should work on any JavaScript platform supporting the CommonJS module system
(and if your platform of choice doesn't support CommonJS, you can easily
implement it, or discard the <code>exports.*</code> lines from UglifyJS sources).
</p>
<p>
The tokenizer/parser generates an abstract syntax tree from JS code. You
can then traverse the AST to learn more about the code, or do various
manipulations on it. This part is implemented in <a href="../lib/parse-js.js">parse-js.js</a> and it's a
port to JavaScript of the excellent <a href="http://marijn.haverbeke.nl/parse-js/">parse-js</a> Common Lisp library from <a href="http://marijn.haverbeke.nl/">Marijn Haverbeke</a>.
</p>
<p>
( See <a href="http://github.com/mishoo/cl-uglify-js">cl-uglify-js</a> if you're looking for the Common Lisp version of
UglifyJS. )
</p>
<p>
The second part of this package, implemented in <a href="../lib/process.js">process.js</a>, inspects and
manipulates the AST generated by the parser to provide the following:
</p>
<ul>
<li>ability to re-generate JavaScript code from the AST. Optionally
indented—you can use this if you want to “beautify” a program that has
been compressed, so that you can inspect the source. But you can also run
our code generator to print out an AST without any whitespace, so you
achieve compression as well.
</li>
<li>shorten variable names (usually to single characters). Our mangler will
analyze the code and generate proper variable names, depending on scope
and usage, and is smart enough to deal with globals defined elsewhere, or
with <code>eval()</code> calls or <code>with{}</code> statements. In short, if <code>eval()</code> or
<code>with{}</code> are used in some scope, then all variables in that scope and any
variables in the parent scopes will remain unmangled, and any references
to such variables remain unmangled as well.
</li>
<li>various small optimizations that may lead to faster code but certainly
lead to smaller code. Where possible, we do the following:
<ul>
<li>foo["bar"] ==> foo.bar
</li>
<li>remove block brackets <code>{}</code>
</li>
<li>join consecutive var declarations:
var a = 10; var b = 20; ==> var a=10,b=20;
</li>
<li>resolve simple constant expressions: 1 +2 * 3 ==> 7. We only do the
replacement if the result occupies less bytes; for example 1/3 would
translate to 0.333333333333, so in this case we don't replace it.
</li>
<li>consecutive statements in blocks are merged into a sequence; in many
cases, this leaves blocks with a single statement, so then we can remove
the block brackets.
</li>
<li>various optimizations for IF statements:
<ul>
<li>if (foo) bar(); else baz(); ==> foo?bar():baz();
</li>
<li>if (!foo) bar(); else baz(); ==> foo?baz():bar();
</li>
<li>if (foo) bar(); ==> foo&&bar();
</li>
<li>if (!foo) bar(); ==> foo||bar();
</li>
<li>if (foo) return bar(); else return baz(); ==> return foo?bar():baz();
</li>
<li>if (foo) return bar(); else something(); ==> {if(foo)return bar();something()}
</li>
</ul>
</li>
<li>remove some unreachable code and warn about it (code that follows a
<code>return</code>, <code>throw</code>, <code>break</code> or <code>continue</code> statement, except
function/variable declarations).
</li>
<li>act a limited version of a pre-processor (c.f. the pre-processor of
C/C++) to allow you to safely replace selected global symbols with
specified values. When combined with the optimisations above this can
make UglifyJS operate slightly more like a compilation process, in
that when certain symbols are replaced by constant values, entire code
blocks may be optimised away as unreachable.
</li>
</ul>
</li>
</ul>
</div>
<div id="outline-container-2-1" class="outline-3">
<h3 id="sec-2-1"><span class="section-number-3">2.1</span> <span class="target">Unsafe transformations</span> </h3>
<div class="outline-text-3" id="text-2-1">
<p>
The following transformations can in theory break code, although they're
probably safe in most practical cases. To enable them you need to pass the
<code>--unsafe</code> flag.
</p>
</div>
<div id="outline-container-2-1-1" class="outline-4">
<h4 id="sec-2-1-1"><span class="section-number-4">2.1.1</span> Calls involving the global Array constructor </h4>
<div class="outline-text-4" id="text-2-1-1">
<p>
The following transformations occur:
</p>
<pre class="src src-js"><span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3, 4) => [1,2,3,4]
Array(a, b, c) => [a,b,c]
<span class="org-keyword">new</span> <span class="org-type">Array</span>(5) => Array(5)
<span class="org-keyword">new</span> <span class="org-type">Array</span>(a) => Array(a)
</pre>
<p>
These are all safe if the Array name isn't redefined. JavaScript does allow
one to globally redefine Array (and pretty much everything, in fact) but I
personally don't see why would anyone do that.
</p>
<p>
UglifyJS does handle the case where Array is redefined locally, or even
globally but with a <code>function</code> or <code>var</code> declaration. Therefore, in the
following cases UglifyJS <b>doesn't touch</b> calls or instantiations of Array:
</p>
<pre class="src src-js"><span class="org-comment-delimiter">// </span><span class="org-comment">case 1. globally declared variable</span>
<span class="org-keyword">var</span> <span class="org-variable-name">Array</span>;
<span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3);
Array(a, b);
<span class="org-comment-delimiter">// </span><span class="org-comment">or (can be declared later)</span>
<span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3);
<span class="org-keyword">var</span> <span class="org-variable-name">Array</span>;
<span class="org-comment-delimiter">// </span><span class="org-comment">or (can be a function)</span>
<span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3);
<span class="org-keyword">function</span> <span class="org-function-name">Array</span>() { ... }
<span class="org-comment-delimiter">// </span><span class="org-comment">case 2. declared in a function</span>
(<span class="org-keyword">function</span>(){
a = <span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3);
b = Array(5, 6);
<span class="org-keyword">var</span> <span class="org-variable-name">Array</span>;
})();
<span class="org-comment-delimiter">// </span><span class="org-comment">or</span>
(<span class="org-keyword">function</span>(<span class="org-variable-name">Array</span>){
<span class="org-keyword">return</span> Array(5, 6, 7);
})();
<span class="org-comment-delimiter">// </span><span class="org-comment">or</span>
(<span class="org-keyword">function</span>(){
<span class="org-keyword">return</span> <span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3, 4);
<span class="org-keyword">function</span> <span class="org-function-name">Array</span>() { ... }
})();
<span class="org-comment-delimiter">// </span><span class="org-comment">etc.</span>
</pre>
</div>
</div>
<div id="outline-container-2-1-2" class="outline-4">
<h4 id="sec-2-1-2"><span class="section-number-4">2.1.2</span> <code>obj.toString()</code> ==> <code>obj+“”</code> </h4>
<div class="outline-text-4" id="text-2-1-2">
</div>
</div>
</div>
<div id="outline-container-2-2" class="outline-3">
<h3 id="sec-2-2"><span class="section-number-3">2.2</span> Install (NPM) </h3>
<div class="outline-text-3" id="text-2-2">
<p>
UglifyJS is now available through NPM — <code>npm install uglify-js@1</code> should
do the job.
</p>
<p>
<b>NOTE:</b> The NPM package has been upgraded to UglifyJS2. If you need to
install version 1.x you need to add `@1` to the command, as I did above. I
strongly suggest you to try to upgrade, though this might not be simple (v2
has a completely different AST structure and API).
</p>
</div>
</div>
<div id="outline-container-2-3" class="outline-3">
<h3 id="sec-2-3"><span class="section-number-3">2.3</span> Install latest code from GitHub </h3>
<div class="outline-text-3" id="text-2-3">
<pre class="src src-sh"><span class="org-comment-delimiter">## </span><span class="org-comment">clone the repository</span>
mkdir -p /where/you/wanna/put/it
<span class="org-builtin">cd</span> /where/you/wanna/put/it
git clone git://github.com/mishoo/UglifyJS.git
<span class="org-comment-delimiter">## </span><span class="org-comment">make the module available to Node</span>
mkdir -p ~/.node_libraries/
<span class="org-builtin">cd</span> ~/.node_libraries/
ln -s /where/you/wanna/put/it/UglifyJS/uglify-js.js
<span class="org-comment-delimiter">## </span><span class="org-comment">and if you want the CLI script too:</span>
mkdir -p ~/bin
<span class="org-builtin">cd</span> ~/bin
ln -s /where/you/wanna/put/it/UglifyJS/bin/uglifyjs
<span class="org-comment-delimiter"># </span><span class="org-comment">(then add ~/bin to your $PATH if it's not there already)</span>
</pre>
</div>
</div>
<div id="outline-container-2-4" class="outline-3">
<h3 id="sec-2-4"><span class="section-number-3">2.4</span> Usage </h3>
<div class="outline-text-3" id="text-2-4">
<p>
There is a command-line tool that exposes the functionality of this library
for your shell-scripting needs:
</p>
<pre class="src src-sh">uglifyjs [ options... ] [ filename ]
</pre>
<p>
<code>filename</code> should be the last argument and should name the file from which
to read the JavaScript code. If you don't specify it, it will read code
from STDIN.
</p>
<p>
Supported options:
</p>
<ul>
<li><code>-b</code> or <code>--beautify</code> — output indented code; when passed, additional
options control the beautifier:
<ul>
<li><code>-i N</code> or <code>--indent N</code> — indentation level (number of spaces)
</li>
<li><code>-q</code> or <code>--quote-keys</code> — quote keys in literal objects (by default,
only keys that cannot be identifier names will be quotes).
</li>
</ul>
</li>
<li><code>-c</code> or <code>----consolidate-primitive-values</code> — consolidates null, Boolean,
and String values. Known as aliasing in the Closure Compiler. Worsens the
data compression ratio of gzip.
</li>
<li><code>--ascii</code> — pass this argument to encode non-ASCII characters as
<code>\uXXXX</code> sequences. By default UglifyJS won't bother to do it and will
output Unicode characters instead. (the output is always encoded in UTF8,
but if you pass this option you'll only get ASCII).
</li>
<li><code>-nm</code> or <code>--no-mangle</code> — don't mangle names.
</li>
<li><code>-nmf</code> or <code>--no-mangle-functions</code> – in case you want to mangle variable
names, but not touch function names.
</li>
<li><code>-ns</code> or <code>--no-squeeze</code> — don't call <code>ast_squeeze()</code> (which does various
optimizations that result in smaller, less readable code).
</li>
<li><code>-mt</code> or <code>--mangle-toplevel</code> — mangle names in the toplevel scope too
(by default we don't do this).
</li>
<li><code>--no-seqs</code> — when <code>ast_squeeze()</code> is called (thus, unless you pass
<code>--no-squeeze</code>) it will reduce consecutive statements in blocks into a
sequence. For example, "a = 10; b = 20; foo();" will be written as
"a=10,b=20,foo();". In various occasions, this allows us to discard the
block brackets (since the block becomes a single statement). This is ON
by default because it seems safe and saves a few hundred bytes on some
libs that I tested it on, but pass <code>--no-seqs</code> to disable it.
</li>
<li><code>--no-dead-code</code> — by default, UglifyJS will remove code that is
obviously unreachable (code that follows a <code>return</code>, <code>throw</code>, <code>break</code> or
<code>continue</code> statement and is not a function/variable declaration). Pass
this option to disable this optimization.
</li>
<li><code>-nc</code> or <code>--no-copyright</code> — by default, <code>uglifyjs</code> will keep the initial
comment tokens in the generated code (assumed to be copyright information
etc.). If you pass this it will discard it.
</li>
<li><code>-o filename</code> or <code>--output filename</code> — put the result in <code>filename</code>. If
this isn't given, the result goes to standard output (or see next one).
</li>
<li><code>--overwrite</code> — if the code is read from a file (not from STDIN) and you
pass <code>--overwrite</code> then the output will be written in the same file.
</li>
<li><code>--ast</code> — pass this if you want to get the Abstract Syntax Tree instead
of JavaScript as output. Useful for debugging or learning more about the
internals.
</li>
<li><code>-v</code> or <code>--verbose</code> — output some notes on STDERR (for now just how long
each operation takes).
</li>
<li><code>-d SYMBOL[=VALUE]</code> or <code>--define SYMBOL[=VALUE]</code> — will replace
all instances of the specified symbol where used as an identifier
(except where symbol has properly declared by a var declaration or
use as function parameter or similar) with the specified value. This
argument may be specified multiple times to define multiple
symbols - if no value is specified the symbol will be replaced with
the value <code>true</code>, or you can specify a numeric value (such as
<code>1024</code>), a quoted string value (such as ="object"= or
='https://github.com'<code>), or the name of another symbol or keyword (such as =null</code> or <code>document</code>).
This allows you, for example, to assign meaningful names to key
constant values but discard the symbolic names in the uglified
version for brevity/efficiency, or when used wth care, allows
UglifyJS to operate as a form of <b>conditional compilation</b>
whereby defining appropriate values may, by dint of the constant
folding and dead code removal features above, remove entire
superfluous code blocks (e.g. completely remove instrumentation or
trace code for production use).
Where string values are being defined, the handling of quotes are
likely to be subject to the specifics of your command shell
environment, so you may need to experiment with quoting styles
depending on your platform, or you may find the option
<code>--define-from-module</code> more suitable for use.
</li>
<li><code>-define-from-module SOMEMODULE</code> — will load the named module (as
per the NodeJS <code>require()</code> function) and iterate all the exported
properties of the module defining them as symbol names to be defined
(as if by the <code>--define</code> option) per the name of each property
(i.e. without the module name prefix) and given the value of the
property. This is a much easier way to handle and document groups of
symbols to be defined rather than a large number of <code>--define</code>
options.
</li>
<li><code>--unsafe</code> — enable other additional optimizations that are known to be
unsafe in some contrived situations, but could still be generally useful.
For now only these:
<ul>
<li>foo.toString() ==> foo+""
</li>
<li>new Array(x,…) ==> [x,…]
</li>
<li>new Array(x) ==> Array(x)
</li>
</ul>
</li>
<li><code>--max-line-len</code> (default 32K characters) — add a newline after around
32K characters. I've seen both FF and Chrome croak when all the code was
on a single line of around 670K. Pass –max-line-len 0 to disable this
safety feature.
</li>
<li><code>--reserved-names</code> — some libraries rely on certain names to be used, as
pointed out in issue #92 and #81, so this option allow you to exclude such
names from the mangler. For example, to keep names <code>require</code> and <code>$super</code>
intact you'd specify –reserved-names "require,$super".
</li>
<li><code>--inline-script</code> – when you want to include the output literally in an
HTML <code><script></code> tag you can use this option to prevent <code></script</code> from
showing up in the output.
</li>
<li><code>--lift-vars</code> – when you pass this, UglifyJS will apply the following
transformations (see the notes in API, <code>ast_lift_variables</code>):
<ul>
<li>put all <code>var</code> declarations at the start of the scope
</li>
<li>make sure a variable is declared only once
</li>
<li>discard unused function arguments
</li>
<li>discard unused inner (named) functions
</li>
<li>finally, try to merge assignments into that one <code>var</code> declaration, if
possible.
</li>
</ul>
</li>
</ul>
</div>
<div id="outline-container-2-4-1" class="outline-4">
<h4 id="sec-2-4-1"><span class="section-number-4">2.4.1</span> API </h4>
<div class="outline-text-4" id="text-2-4-1">
<p>
To use the library from JavaScript, you'd do the following (example for
NodeJS):
</p>
<pre class="src src-js"><span class="org-keyword">var</span> <span class="org-variable-name">jsp</span> = require(<span class="org-string">"uglify-js"</span>).parser;
<span class="org-keyword">var</span> <span class="org-variable-name">pro</span> = require(<span class="org-string">"uglify-js"</span>).uglify;
<span class="org-keyword">var</span> <span class="org-variable-name">orig_code</span> = <span class="org-string">"... JS code here"</span>;
<span class="org-keyword">var</span> <span class="org-variable-name">ast</span> = jsp.parse(orig_code); <span class="org-comment-delimiter">// </span><span class="org-comment">parse code and get the initial AST</span>
ast = pro.ast_mangle(ast); <span class="org-comment-delimiter">// </span><span class="org-comment">get a new AST with mangled names</span>
ast = pro.ast_squeeze(ast); <span class="org-comment-delimiter">// </span><span class="org-comment">get an AST with compression optimizations</span>
<span class="org-keyword">var</span> <span class="org-variable-name">final_code</span> = pro.gen_code(ast); <span class="org-comment-delimiter">// </span><span class="org-comment">compressed code here</span>
</pre>
<p>
The above performs the full compression that is possible right now. As you
can see, there are a sequence of steps which you can apply. For example if
you want compressed output but for some reason you don't want to mangle
variable names, you would simply skip the line that calls
<code>pro.ast_mangle(ast)</code>.
</p>
<p>
Some of these functions take optional arguments. Here's a description:
</p>
<ul>
<li><code>jsp.parse(code, strict_semicolons)</code> – parses JS code and returns an AST.
<code>strict_semicolons</code> is optional and defaults to <code>false</code>. If you pass
<code>true</code> then the parser will throw an error when it expects a semicolon and
it doesn't find it. For most JS code you don't want that, but it's useful
if you want to strictly sanitize your code.
</li>
<li><code>pro.ast_lift_variables(ast)</code> – merge and move <code>var</code> declarations to the
scop of the scope; discard unused function arguments or variables; discard
unused (named) inner functions. It also tries to merge assignments
following the <code>var</code> declaration into it.
<p>
If your code is very hand-optimized concerning <code>var</code> declarations, this
lifting variable declarations might actually increase size. For me it
helps out. On jQuery it adds 865 bytes (243 after gzip). YMMV. Also
note that (since it's not enabled by default) this operation isn't yet
heavily tested (please report if you find issues!).
</p>
<p>
Note that although it might increase the image size (on jQuery it gains
865 bytes, 243 after gzip) it's technically more correct: in certain
situations, dead code removal might drop variable declarations, which
would not happen if the variables are lifted in advance.
</p>
<p>
Here's an example of what it does:
</p></li>
</ul>
<pre class="src src-js"><span class="org-keyword">function</span> <span class="org-function-name">f</span>(<span class="org-variable-name">a</span>, <span class="org-variable-name">b</span>, <span class="org-variable-name">c</span>, <span class="org-variable-name">d</span>, <span class="org-variable-name">e</span>) {
<span class="org-keyword">var</span> <span class="org-variable-name">q</span>;
<span class="org-keyword">var</span> <span class="org-variable-name">w</span>;
w = 10;
q = 20;
<span class="org-keyword">for</span> (<span class="org-keyword">var</span> <span class="org-variable-name">i</span> = 1; i < 10; ++i) {
<span class="org-keyword">var</span> <span class="org-variable-name">boo</span> = foo(a);
}
<span class="org-keyword">for</span> (<span class="org-keyword">var</span> <span class="org-variable-name">i</span> = 0; i < 1; ++i) {
<span class="org-keyword">var</span> <span class="org-variable-name">boo</span> = bar(c);
}
<span class="org-keyword">function</span> <span class="org-function-name">foo</span>(){ ... }
<span class="org-keyword">function</span> <span class="org-function-name">bar</span>(){ ... }
<span class="org-keyword">function</span> <span class="org-function-name">baz</span>(){ ... }
}
<span class="org-comment-delimiter">// </span><span class="org-comment">transforms into ==></span>
<span class="org-keyword">function</span> <span class="org-function-name">f</span>(<span class="org-variable-name">a</span>, <span class="org-variable-name">b</span>, <span class="org-variable-name">c</span>) {
<span class="org-keyword">var</span> <span class="org-variable-name">i</span>, <span class="org-variable-name">boo</span>, <span class="org-variable-name">w</span> = 10, <span class="org-variable-name">q</span> = 20;
<span class="org-keyword">for</span> (i = 1; i < 10; ++i) {
boo = foo(a);
}
<span class="org-keyword">for</span> (i = 0; i < 1; ++i) {
boo = bar(c);
}
<span class="org-keyword">function</span> <span class="org-function-name">foo</span>() { ... }
<span class="org-keyword">function</span> <span class="org-function-name">bar</span>() { ... }
}
</pre>
<ul>
<li><code>pro.ast_mangle(ast, options)</code> – generates a new AST containing mangled
(compressed) variable and function names. It supports the following
options:
<ul>
<li><code>toplevel</code> – mangle toplevel names (by default we don't touch them).
</li>
<li><code>except</code> – an array of names to exclude from compression.
</li>
<li><code>defines</code> – an object with properties named after symbols to
replace (see the <code>--define</code> option for the script) and the values
representing the AST replacement value. For example,
<code>{ defines: { DEBUG: ['name', 'false'], VERSION: ['string', '1.0'] } }</code>
</li>
</ul>
</li>
<li><code>pro.ast_squeeze(ast, options)</code> – employs further optimizations designed
to reduce the size of the code that <code>gen_code</code> would generate from the
AST. Returns a new AST. <code>options</code> can be a hash; the supported options
are:
<ul>
<li><code>make_seqs</code> (default true) which will cause consecutive statements in a
block to be merged using the "sequence" (comma) operator
</li>
<li><code>dead_code</code> (default true) which will remove unreachable code.
</li>
</ul>
</li>
<li><code>pro.gen_code(ast, options)</code> – generates JS code from the AST. By
default it's minified, but using the <code>options</code> argument you can get nicely
formatted output. <code>options</code> is, well, optional :-) and if you pass it it
must be an object and supports the following properties (below you can see
the default values):
<ul>
<li><code>beautify: false</code> – pass <code>true</code> if you want indented output
</li>
<li><code>indent_start: 0</code> (only applies when <code>beautify</code> is <code>true</code>) – initial
indentation in spaces
</li>
<li><code>indent_level: 4</code> (only applies when <code>beautify</code> is <code>true</code>) --
indentation level, in spaces (pass an even number)
</li>
<li><code>quote_keys: false</code> – if you pass <code>true</code> it will quote all keys in
literal objects
</li>
<li><code>space_colon: false</code> (only applies when <code>beautify</code> is <code>true</code>) – wether
to put a space before the colon in object literals
</li>
<li><code>ascii_only: false</code> – pass <code>true</code> if you want to encode non-ASCII
characters as <code>\uXXXX</code>.
</li>
<li><code>inline_script: false</code> – pass <code>true</code> to escape occurrences of
<code></script</code> in strings
</li>
</ul>
</li>
</ul>
</div>
</div>
<div id="outline-container-2-4-2" class="outline-4">
<h4 id="sec-2-4-2"><span class="section-number-4">2.4.2</span> Beautifier shortcoming – no more comments </h4>
<div class="outline-text-4" id="text-2-4-2">
<p>
The beautifier can be used as a general purpose indentation tool. It's
useful when you want to make a minified file readable. One limitation,
though, is that it discards all comments, so you don't really want to use it
to reformat your code, unless you don't have, or don't care about, comments.
</p>
<p>
In fact it's not the beautifier who discards comments — they are dumped at
the parsing stage, when we build the initial AST. Comments don't really
make sense in the AST, and while we could add nodes for them, it would be
inconvenient because we'd have to add special rules to ignore them at all
the processing stages.
</p>
</div>
</div>
<div id="outline-container-2-4-3" class="outline-4">
<h4 id="sec-2-4-3"><span class="section-number-4">2.4.3</span> Use as a code pre-processor </h4>
<div class="outline-text-4" id="text-2-4-3">
<p>
The <code>--define</code> option can be used, particularly when combined with the
constant folding logic, as a form of pre-processor to enable or remove
particular constructions, such as might be used for instrumenting
development code, or to produce variations aimed at a specific
platform.
</p>
<p>
The code below illustrates the way this can be done, and how the
symbol replacement is performed.
</p>
<pre class="src src-js">CLAUSE1: <span class="org-keyword">if</span> (<span class="org-keyword">typeof</span> DEVMODE === <span class="org-string">'undefined'</span>) {
DEVMODE = <span class="org-constant">true</span>;
}
<span class="org-function-name">CLAUSE2</span>: <span class="org-keyword">function</span> init() {
<span class="org-keyword">if</span> (DEVMODE) {
console.log(<span class="org-string">"init() called"</span>);
}
....
DEVMODE &amp;&amp; console.log(<span class="org-string">"init() complete"</span>);
}
<span class="org-function-name">CLAUSE3</span>: <span class="org-keyword">function</span> reportDeviceStatus(<span class="org-variable-name">device</span>) {
<span class="org-keyword">var</span> <span class="org-variable-name">DEVMODE</span> = device.mode, <span class="org-variable-name">DEVNAME</span> = device.name;
<span class="org-keyword">if</span> (DEVMODE === <span class="org-string">'open'</span>) {
....
}
}
</pre>
<p>
When the above code is normally executed, the undeclared global
variable <code>DEVMODE</code> will be assigned the value <b>true</b> (see <code>CLAUSE1</code>)
and so the <code>init()</code> function (<code>CLAUSE2</code>) will write messages to the
console log when executed, but in <code>CLAUSE3</code> a locally declared
variable will mask access to the <code>DEVMODE</code> global symbol.
</p>
<p>
If the above code is processed by UglifyJS with an argument of
<code>--define DEVMODE=false</code> then UglifyJS will replace <code>DEVMODE</code> with the
boolean constant value <b>false</b> within <code>CLAUSE1</code> and <code>CLAUSE2</code>, but it
will leave <code>CLAUSE3</code> as it stands because there <code>DEVMODE</code> resolves to
a validly declared variable.
</p>
<p>
And more so, the constant-folding features of UglifyJS will recognise
that the <code>if</code> condition of <code>CLAUSE1</code> is thus always false, and so will
remove the test and body of <code>CLAUSE1</code> altogether (including the
otherwise slightly problematical statement <code>false = true;</code> which it
will have formed by replacing <code>DEVMODE</code> in the body). Similarly,
within <code>CLAUSE2</code> both calls to <code>console.log()</code> will be removed
altogether.
</p>
<p>
In this way you can mimic, to a limited degree, the functionality of
the C/C++ pre-processor to enable or completely remove blocks
depending on how certain symbols are defined - perhaps using UglifyJS
to generate different versions of source aimed at different
environments
</p>
<p>
It is recommmended (but not made mandatory) that symbols designed for
this purpose are given names consisting of <code>UPPER_CASE_LETTERS</code> to
distinguish them from other (normal) symbols and avoid the sort of
clash that <code>CLAUSE3</code> above illustrates.
</p>
</div>
</div>
</div>
<div id="outline-container-2-5" class="outline-3">
<h3 id="sec-2-5"><span class="section-number-3">2.5</span> Compression – how good is it? </h3>
<div class="outline-text-3" id="text-2-5">
<p>
Here are updated statistics. (I also updated my Google Closure and YUI
installations).
</p>
<p>
We're still a lot better than YUI in terms of compression, though slightly
slower. We're still a lot faster than Closure, and compression after gzip
is comparable.
</p>
<table border="2" cellspacing="0" cellpadding="6" rules="groups" frame="hsides">
<caption></caption>
<colgroup><col class="left" /><col class="left" /><col class="right" /><col class="left" /><col class="right" /><col class="left" /><col class="right" />
</colgroup>
<thead>
<tr><th scope="col" class="left">File</th><th scope="col" class="left">UglifyJS</th><th scope="col" class="right">UglifyJS+gzip</th><th scope="col" class="left">Closure</th><th scope="col" class="right">Closure+gzip</th><th scope="col" class="left">YUI</th><th scope="col" class="right">YUI+gzip</th></tr>
</thead>
<tbody>
<tr><td class="left">jquery-1.6.2.js</td><td class="left">91001 (0:01.59)</td><td class="right">31896</td><td class="left">90678 (0:07.40)</td><td class="right">31979</td><td class="left">101527 (0:01.82)</td><td class="right">34646</td></tr>
<tr><td class="left">paper.js</td><td class="left">142023 (0:01.65)</td><td class="right">43334</td><td class="left">134301 (0:07.42)</td><td class="right">42495</td><td class="left">173383 (0:01.58)</td><td class="right">48785</td></tr>
<tr><td class="left">prototype.js</td><td class="left">88544 (0:01.09)</td><td class="right">26680</td><td class="left">86955 (0:06.97)</td><td class="right">26326</td><td class="left">92130 (0:00.79)</td><td class="right">28624</td></tr>
<tr><td class="left">thelib-full.js (DynarchLIB)</td><td class="left">251939 (0:02.55)</td><td class="right">72535</td><td class="left">249911 (0:09.05)</td><td class="right">72696</td><td class="left">258869 (0:01.94)</td><td class="right">76584</td></tr>
</tbody>
</table>
</div>
</div>
<div id="outline-container-2-6" class="outline-3">
<h3 id="sec-2-6"><span class="section-number-3">2.6</span> Bugs? </h3>
<div class="outline-text-3" id="text-2-6">
<p>
Unfortunately, for the time being there is no automated test suite. But I
ran the compressor manually on non-trivial code, and then I tested that the
generated code works as expected. A few hundred times.
</p>
<p>
DynarchLIB was started in times when there was no good JS minifier.
Therefore I was quite religious about trying to write short code manually,
and as such DL contains a lot of syntactic hacks<sup><a class="footref" name="fnr.1" href="#fn.1">1</a></sup> such as “foo == bar ? a
= 10 : b = 20”, though the more readable version would clearly be to use
“if/else”.
</p>
<p>
Since the parser/compressor runs fine on DL and jQuery, I'm quite confident
that it's solid enough for production use. If you can identify any bugs,
I'd love to hear about them (<a href="http://groups.google.com/group/uglifyjs">use the Google Group</a> or email me directly).
</p>
</div>
</div>
<div id="outline-container-2-7" class="outline-3">
<h3 id="sec-2-7"><span class="section-number-3">2.7</span> Links </h3>
<div class="outline-text-3" id="text-2-7">
<ul>
<li>Twitter: <a href="http://twitter.com/UglifyJS">@UglifyJS</a>
</li>
<li>Project at GitHub: <a href="http://github.com/mishoo/UglifyJS">http://github.com/mishoo/UglifyJS</a>
</li>
<li>Google Group: <a href="http://groups.google.com/group/uglifyjs">http://groups.google.com/group/uglifyjs</a>
</li>
<li>Common Lisp JS parser: <a href="http://marijn.haverbeke.nl/parse-js/">http://marijn.haverbeke.nl/parse-js/</a>
</li>
<li>JS-to-Lisp compiler: <a href="http://github.com/marijnh/js">http://github.com/marijnh/js</a>
</li>
<li>Common Lisp JS uglifier: <a href="http://github.com/mishoo/cl-uglify-js">http://github.com/mishoo/cl-uglify-js</a>
</li>
</ul>
</div>
</div>
<div id="outline-container-2-8" class="outline-3">
<h3 id="sec-2-8"><span class="section-number-3">2.8</span> License </h3>
<div class="outline-text-3" id="text-2-8">
<p>
UglifyJS is released under the BSD license:
</p>
<pre class="example">Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
Based on parse-js (http://marijn.haverbeke.nl/parse-js/).
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.
</pre>
<div id="footnotes">
<h2 class="footnotes">Footnotes: </h2>
<div id="text-footnotes">
<p class="footnote"><sup><a class="footnum" name="fn.1" href="#fnr.1">1</a></sup> I even reported a few bugs and suggested some fixes in the original
<a href="http://marijn.haverbeke.nl/parse-js/">parse-js</a> library, and Marijn pushed fixes literally in minutes.
</p></div>
</div>
</div>
</div>
</div>
</div>
<div id="postamble">
<p class="date">Date: 2012-11-22 10:46:14 EET</p>
<p class="author">Author: Mihai Bazon</p>
<p class="creator">Org version 7.7 with Emacs version 24</p>
<a href="http://validator.w3.org/check?uri=referer">Validate XHTML 1.0</a>
</div>
</body>
</html>
================================================
FILE: README.org
================================================
#+TITLE: UglifyJS -- a JavaScript parser/compressor/beautifier
#+KEYWORDS: javascript, js, parser, compiler, compressor, mangle, minify, minifier
#+DESCRIPTION: a JavaScript parser/compressor/beautifier in JavaScript
#+STYLE: <link rel="stylesheet" type="text/css" href="docstyle.css" />
#+AUTHOR: Mihai Bazon
#+EMAIL: mihai.bazon@gmail.com
* NEW: UglifyJS2
I started working on UglifyJS's successor, version 2. It's almost a full
rewrite (except for the parser which is heavily modified, everything else
starts from scratch). I've detailed my reasons in the README, see the
project page.
[[https://github.com/mishoo/UglifyJS2][https://github.com/mishoo/UglifyJS2]]
Version 1 will continue to be maintained for fixing show-stopper bugs, but
no new features should be expected.
* UglifyJS --- a JavaScript parser/compressor/beautifier
This package implements a general-purpose JavaScript
parser/compressor/beautifier toolkit. It is developed on [[http://nodejs.org/][NodeJS]], but it
should work on any JavaScript platform supporting the CommonJS module system
(and if your platform of choice doesn't support CommonJS, you can easily
implement it, or discard the =exports.*= lines from UglifyJS sources).
The tokenizer/parser generates an abstract syntax tree from JS code. You
can then traverse the AST to learn more about the code, or do various
manipulations on it. This part is implemented in [[../lib/parse-js.js][parse-js.js]] and it's a
port to JavaScript of the excellent [[http://marijn.haverbeke.nl/parse-js/][parse-js]] Common Lisp library from [[http://marijn.haverbeke.nl/][Marijn
Haverbeke]].
( See [[http://github.com/mishoo/cl-uglify-js][cl-uglify-js]] if you're looking for the Common Lisp version of
UglifyJS. )
The second part of this package, implemented in [[../lib/process.js][process.js]], inspects and
manipulates the AST generated by the parser to provide the following:
- ability to re-generate JavaScript code from the AST. Optionally
indented---you can use this if you want to “beautify” a program that has
been compressed, so that you can inspect the source. But you can also run
our code generator to print out an AST without any whitespace, so you
achieve compression as well.
- shorten variable names (usually to single characters). Our mangler will
analyze the code and generate proper variable names, depending on scope
and usage, and is smart enough to deal with globals defined elsewhere, or
with =eval()= calls or =with{}= statements. In short, if =eval()= or
=with{}= are used in some scope, then all variables in that scope and any
variables in the parent scopes will remain unmangled, and any references
to such variables remain unmangled as well.
- various small optimizations that may lead to faster code but certainly
lead to smaller code. Where possible, we do the following:
- foo["bar"] ==> foo.bar
- remove block brackets ={}=
- join consecutive var declarations:
var a = 10; var b = 20; ==> var a=10,b=20;
- resolve simple constant expressions: 1 +2 * 3 ==> 7. We only do the
replacement if the result occupies less bytes; for example 1/3 would
translate to 0.333333333333, so in this case we don't replace it.
- consecutive statements in blocks are merged into a sequence; in many
cases, this leaves blocks with a single statement, so then we can remove
the block brackets.
- various optimizations for IF statements:
- if (foo) bar(); else baz(); ==> foo?bar():baz();
- if (!foo) bar(); else baz(); ==> foo?baz():bar();
- if (foo) bar(); ==> foo&&bar();
- if (!foo) bar(); ==> foo||bar();
- if (foo) return bar(); else return baz(); ==> return foo?bar():baz();
- if (foo) return bar(); else something(); ==> {if(foo)return bar();something()}
- remove some unreachable code and warn about it (code that follows a
=return=, =throw=, =break= or =continue= statement, except
function/variable declarations).
- act a limited version of a pre-processor (c.f. the pre-processor of
C/C++) to allow you to safely replace selected global symbols with
specified values. When combined with the optimisations above this can
make UglifyJS operate slightly more like a compilation process, in
that when certain symbols are replaced by constant values, entire code
blocks may be optimised away as unreachable.
** <<Unsafe transformations>>
The following transformations can in theory break code, although they're
probably safe in most practical cases. To enable them you need to pass the
=--unsafe= flag.
*** Calls involving the global Array constructor
The following transformations occur:
#+BEGIN_SRC js
new Array(1, 2, 3, 4) => [1,2,3,4]
Array(a, b, c) => [a,b,c]
new Array(5) => Array(5)
new Array(a) => Array(a)
#+END_SRC
These are all safe if the Array name isn't redefined. JavaScript does allow
one to globally redefine Array (and pretty much everything, in fact) but I
personally don't see why would anyone do that.
UglifyJS does handle the case where Array is redefined locally, or even
globally but with a =function= or =var= declaration. Therefore, in the
following cases UglifyJS *doesn't touch* calls or instantiations of Array:
#+BEGIN_SRC js
// case 1. globally declared variable
var Array;
new Array(1, 2, 3);
Array(a, b);
// or (can be declared later)
new Array(1, 2, 3);
var Array;
// or (can be a function)
new Array(1, 2, 3);
function Array() { ... }
// case 2. declared in a function
(function(){
a = new Array(1, 2, 3);
b = Array(5, 6);
var Array;
})();
// or
(function(Array){
return Array(5, 6, 7);
})();
// or
(function(){
return new Array(1, 2, 3, 4);
function Array() { ... }
})();
// etc.
#+END_SRC
*** =obj.toString()= ==> =obj+“”=
** Install (NPM)
UglifyJS is now available through NPM --- =npm install uglify-js@1= should
do the job.
*NOTE:* The NPM package has been upgraded to UglifyJS2. If you need to
install version 1.x you need to add `@1` to the command, as I did above. I
strongly suggest you to try to upgrade, though this might not be simple (v2
has a completely different AST structure and API).
** Install latest code from GitHub
#+BEGIN_SRC sh
## clone the repository
mkdir -p /where/you/wanna/put/it
cd /where/you/wanna/put/it
git clone git://github.com/mishoo/UglifyJS.git
## make the module available to Node
mkdir -p ~/.node_libraries/
cd ~/.node_libraries/
ln -s /where/you/wanna/put/it/UglifyJS/uglify-js.js
## and if you want the CLI script too:
mkdir -p ~/bin
cd ~/bin
ln -s /where/you/wanna/put/it/UglifyJS/bin/uglifyjs
# (then add ~/bin to your $PATH if it's not there already)
#+END_SRC
** Usage
There is a command-line tool that exposes the functionality of this library
for your shell-scripting needs:
#+BEGIN_SRC sh
uglifyjs [ options... ] [ filename ]
#+END_SRC
=filename= should be the last argument and should name the file from which
to read the JavaScript code. If you don't specify it, it will read code
from STDIN.
Supported options:
- =-b= or =--beautify= --- output indented code; when passed, additional
options control the beautifier:
- =-i N= or =--indent N= --- indentation level (number of spaces)
- =-q= or =--quote-keys= --- quote keys in literal objects (by default,
only keys that cannot be identifier names will be quotes).
- =-c= or =----consolidate-primitive-values= --- consolidates null, Boolean,
and String values. Known as aliasing in the Closure Compiler. Worsens the
data compression ratio of gzip.
- =--ascii= --- pass this argument to encode non-ASCII characters as
=\uXXXX= sequences. By default UglifyJS won't bother to do it and will
output Unicode characters instead. (the output is always encoded in UTF8,
but if you pass this option you'll only get ASCII).
- =-nm= or =--no-mangle= --- don't mangle names.
- =-nmf= or =--no-mangle-functions= -- in case you want to mangle variable
names, but not touch function names.
- =-ns= or =--no-squeeze= --- don't call =ast_squeeze()= (which does various
optimizations that result in smaller, less readable code).
- =-mt= or =--mangle-toplevel= --- mangle names in the toplevel scope too
(by default we don't do this).
- =--no-seqs= --- when =ast_squeeze()= is called (thus, unless you pass
=--no-squeeze=) it will reduce consecutive statements in blocks into a
sequence. For example, "a = 10; b = 20; foo();" will be written as
"a=10,b=20,foo();". In various occasions, this allows us to discard the
block brackets (since the block becomes a single statement). This is ON
by default because it seems safe and saves a few hundred bytes on some
libs that I tested it on, but pass =--no-seqs= to disable it.
- =--no-dead-code= --- by default, UglifyJS will remove code that is
obviously unreachable (code that follows a =return=, =throw=, =break= or
=continue= statement and is not a function/variable declaration). Pass
this option to disable this optimization.
- =-nc= or =--no-copyright= --- by default, =uglifyjs= will keep the initial
comment tokens in the generated code (assumed to be copyright information
etc.). If you pass this it will discard it.
- =-o filename= or =--output filename= --- put the result in =filename=. If
this isn't given, the result goes to standard output (or see next one).
- =--overwrite= --- if the code is read from a file (not from STDIN) and you
pass =--overwrite= then the output will be written in the same file.
- =--ast= --- pass this if you want to get the Abstract Syntax Tree instead
of JavaScript as output. Useful for debugging or learning more about the
internals.
- =-v= or =--verbose= --- output some notes on STDERR (for now just how long
each operation takes).
- =-d SYMBOL[=VALUE]= or =--define SYMBOL[=VALUE]= --- will replace
all instances of the specified symbol where used as an identifier
(except where symbol has properly declared by a var declaration or
use as function parameter or similar) with the specified value. This
argument may be specified multiple times to define multiple
symbols - if no value is specified the symbol will be replaced with
the value =true=, or you can specify a numeric value (such as
=1024=), a quoted string value (such as ="object"= or
='https://github.com'=), or the name of another symbol or keyword
(such as =null= or =document=).
This allows you, for example, to assign meaningful names to key
constant values but discard the symbolic names in the uglified
version for brevity/efficiency, or when used wth care, allows
UglifyJS to operate as a form of *conditional compilation*
whereby defining appropriate values may, by dint of the constant
folding and dead code removal features above, remove entire
superfluous code blocks (e.g. completely remove instrumentation or
trace code for production use).
Where string values are being defined, the handling of quotes are
likely to be subject to the specifics of your command shell
environment, so you may need to experiment with quoting styles
depending on your platform, or you may find the option
=--define-from-module= more suitable for use.
- =-define-from-module SOMEMODULE= --- will load the named module (as
per the NodeJS =require()= function) and iterate all the exported
properties of the module defining them as symbol names to be defined
(as if by the =--define= option) per the name of each property
(i.e. without the module name prefix) and given the value of the
property. This is a much easier way to handle and document groups of
symbols to be defined rather than a large number of =--define=
options.
- =--unsafe= --- enable other additional optimizations that are known to be
unsafe in some contrived situations, but could still be generally useful.
For now only these:
- foo.toString() ==> foo+""
- new Array(x,...) ==> [x,...]
- new Array(x) ==> Array(x)
- =--max-line-len= (default 32K characters) --- add a newline after around
32K characters. I've seen both FF and Chrome croak when all the code was
on a single line of around 670K. Pass --max-line-len 0 to disable this
safety feature.
- =--reserved-names= --- some libraries rely on certain names to be used, as
pointed out in issue #92 and #81, so this option allow you to exclude such
names from the mangler. For example, to keep names =require= and =$super=
intact you'd specify --reserved-names "require,$super".
- =--inline-script= -- when you want to include the output literally in an
HTML =<script>= tag you can use this option to prevent =</script= from
showing up in the output.
- =--lift-vars= -- when you pass this, UglifyJS will apply the following
transformations (see the notes in API, =ast_lift_variables=):
- put all =var= declarations at the start of the scope
- make sure a variable is declared only once
- discard unused function arguments
- discard unused inner (named) functions
- finally, try to merge assignments into that one =var= declaration, if
possible.
*** API
To use the library from JavaScript, you'd do the following (example for
NodeJS):
#+BEGIN_SRC js
var jsp = require("uglify-js").parser;
var pro = require("uglify-js").uglify;
var orig_code = "... JS code here";
var ast = jsp.parse(orig_code); // parse code and get the initial AST
ast = pro.ast_mangle(ast); // get a new AST with mangled names
ast = pro.ast_squeeze(ast); // get an AST with compression optimizations
var final_code = pro.gen_code(ast); // compressed code here
#+END_SRC
The above performs the full compression that is possible right now. As you
can see, there are a sequence of steps which you can apply. For example if
you want compressed output but for some reason you don't want to mangle
variable names, you would simply skip the line that calls
=pro.ast_mangle(ast)=.
Some of these functions take optional arguments. Here's a description:
- =jsp.parse(code, strict_semicolons)= -- parses JS code and returns an AST.
=strict_semicolons= is optional and defaults to =false=. If you pass
=true= then the parser will throw an error when it expects a semicolon and
it doesn't find it. For most JS code you don't want that, but it's useful
if you want to strictly sanitize your code.
- =pro.ast_lift_variables(ast)= -- merge and move =var= declarations to the
scop of the scope; discard unused function arguments or variables; discard
unused (named) inner functions. It also tries to merge assignments
following the =var= declaration into it.
If your code is very hand-optimized concerning =var= declarations, this
lifting variable declarations might actually increase size. For me it
helps out. On jQuery it adds 865 bytes (243 after gzip). YMMV. Also
note that (since it's not enabled by default) this operation isn't yet
heavily tested (please report if you find issues!).
Note that although it might increase the image size (on jQuery it gains
865 bytes, 243 after gzip) it's technically more correct: in certain
situations, dead code removal might drop variable declarations, which
would not happen if the variables are lifted in advance.
Here's an example of what it does:
#+BEGIN_SRC js
function f(a, b, c, d, e) {
var q;
var w;
w = 10;
q = 20;
for (var i = 1; i < 10; ++i) {
var boo = foo(a);
}
for (var i = 0; i < 1; ++i) {
var boo = bar(c);
}
function foo(){ ... }
function bar(){ ... }
function baz(){ ... }
}
// transforms into ==>
function f(a, b, c) {
var i, boo, w = 10, q = 20;
for (i = 1; i < 10; ++i) {
boo = foo(a);
}
for (i = 0; i < 1; ++i) {
boo = bar(c);
}
function foo() { ... }
function bar() { ... }
}
#+END_SRC
- =pro.ast_mangle(ast, options)= -- generates a new AST containing mangled
(compressed) variable and function names. It supports the following
options:
- =toplevel= -- mangle toplevel names (by default we don't touch them).
- =except= -- an array of names to exclude from compression.
- =defines= -- an object with properties named after symbols to
replace (see the =--define= option for the script) and the values
representing the AST replacement value. For example,
={ defines: { DEBUG: ['name', 'false'], VERSION: ['string', '1.0'] } }=
- =pro.ast_squeeze(ast, options)= -- employs further optimizations designed
to reduce the size of the code that =gen_code= would generate from the
AST. Returns a new AST. =options= can be a hash; the supported options
are:
- =make_seqs= (default true) which will cause consecutive statements in a
block to be merged using the "sequence" (comma) operator
- =dead_code= (default true) which will remove unreachable code.
- =pro.gen_code(ast, options)= -- generates JS code from the AST. By
default it's minified, but using the =options= argument you can get nicely
formatted output. =options= is, well, optional :-) and if you pass it it
must be an object and supports the following properties (below you can see
the default values):
- =beautify: false= -- pass =true= if you want indented output
- =indent_start: 0= (only applies when =beautify= is =true=) -- initial
indentation in spaces
- =indent_level: 4= (only applies when =beautify= is =true=) --
indentation level, in spaces (pass an even number)
- =quote_keys: false= -- if you pass =true= it will quote all keys in
literal objects
- =space_colon: false= (only applies when =beautify= is =true=) -- wether
to put a space before the colon in object literals
- =ascii_only: false= -- pass =true= if you want to encode non-ASCII
characters as =\uXXXX=.
- =inline_script: false= -- pass =true= to escape occurrences of
=</script= in strings
*** Beautifier shortcoming -- no more comments
The beautifier can be used as a general purpose indentation tool. It's
useful when you want to make a minified file readable. One limitation,
though, is that it discards all comments, so you don't really want to use it
to reformat your code, unless you don't have, or don't care about, comments.
In fact it's not the beautifier who discards comments --- they are dumped at
the parsing stage, when we build the initial AST. Comments don't really
make sense in the AST, and while we could add nodes for them, it would be
inconvenient because we'd have to add special rules to ignore them at all
the processing stages.
*** Use as a code pre-processor
The =--define= option can be used, particularly when combined with the
constant folding logic, as a form of pre-processor to enable or remove
particular constructions, such as might be used for instrumenting
development code, or to produce variations aimed at a specific
platform.
The code below illustrates the way this can be done, and how the
symbol replacement is performed.
#+BEGIN_SRC js
CLAUSE1: if (typeof DEVMODE === 'undefined') {
DEVMODE = true;
}
CLAUSE2: function init() {
if (DEVMODE) {
console.log("init() called");
}
....
DEVMODE && console.log("init() complete");
}
CLAUSE3: function reportDeviceStatus(device) {
var DEVMODE = device.mode, DEVNAME = device.name;
if (DEVMODE === 'open') {
....
}
}
#+END_SRC
When the above code is normally executed, the undeclared global
variable =DEVMODE= will be assigned the value *true* (see =CLAUSE1=)
and so the =init()= function (=CLAUSE2=) will write messages to the
console log when executed, but in =CLAUSE3= a locally declared
variable will mask access to the =DEVMODE= global symbol.
If the above code is processed by UglifyJS with an argument of
=--define DEVMODE=false= then UglifyJS will replace =DEVMODE= with the
boolean constant value *false* within =CLAUSE1= and =CLAUSE2=, but it
will leave =CLAUSE3= as it stands because there =DEVMODE= resolves to
a validly declared variable.
And more so, the constant-folding features of UglifyJS will recognise
that the =if= condition of =CLAUSE1= is thus always false, and so will
remove the test and body of =CLAUSE1= altogether (including the
otherwise slightly problematical statement =false = true;= which it
will have formed by replacing =DEVMODE= in the body). Similarly,
within =CLAUSE2= both calls to =console.log()= will be removed
altogether.
In this way you can mimic, to a limited degree, the functionality of
the C/C++ pre-processor to enable or completely remove blocks
depending on how certain symbols are defined - perhaps using UglifyJS
to generate different versions of source aimed at different
environments
It is recommmended (but not made mandatory) that symbols designed for
this purpose are given names consisting of =UPPER_CASE_LETTERS= to
distinguish them from other (normal) symbols and avoid the sort of
clash that =CLAUSE3= above illustrates.
** Compression -- how good is it?
Here are updated statistics. (I also updated my Google Closure and YUI
installations).
We're still a lot better than YUI in terms of compression, though slightly
slower. We're still a lot faster than Closure, and compression after gzip
is comparable.
| File | UglifyJS | UglifyJS+gzip | Closure | Closure+gzip | YUI | YUI+gzip |
|-----------------------------+------------------+---------------+------------------+--------------+------------------+----------|
| jquery-1.6.2.js | 91001 (0:01.59) | 31896 | 90678 (0:07.40) | 31979 | 101527 (0:01.82) | 34646 |
| paper.js | 142023 (0:01.65) | 43334 | 134301 (0:07.42) | 42495 | 173383 (0:01.58) | 48785 |
| prototype.js | 88544 (0:01.09) | 26680 | 86955 (0:06.97) | 26326 | 92130 (0:00.79) | 28624 |
| thelib-full.js (DynarchLIB) | 251939 (0:02.55) | 72535 | 249911 (0:09.05) | 72696 | 258869 (0:01.94) | 76584 |
** Bugs?
Unfortunately, for the time being there is no automated test suite. But I
ran the compressor manually on non-trivial code, and then I tested that the
generated code works as expected. A few hundred times.
DynarchLIB was started in times when there was no good JS minifier.
Therefore I was quite religious about trying to write short code manually,
and as such DL contains a lot of syntactic hacks[1] such as “foo == bar ? a
= 10 : b = 20”, though the more readable version would clearly be to use
“if/else”.
Since the parser/compressor runs fine on DL and jQuery, I'm quite confident
that it's solid enough for production use. If you can identify any bugs,
I'd love to hear about them ([[http://groups.google.com/group/uglifyjs][use the Google Group]] or email me directly).
[1] I even reported a few bugs and suggested some fixes in the original
[[http://marijn.haverbeke.nl/parse-js/][parse-js]] library, and Marijn pushed fixes literally in minutes.
** Links
- Twitter: [[http://twitter.com/UglifyJS][@UglifyJS]]
- Project at GitHub: [[http://github.com/mishoo/UglifyJS][http://github.com/mishoo/UglifyJS]]
- Google Group: [[http://groups.google.com/group/uglifyjs][http://groups.google.com/group/uglifyjs]]
- Common Lisp JS parser: [[http://marijn.haverbeke.nl/parse-js/][http://marijn.haverbeke.nl/parse-js/]]
- JS-to-Lisp compiler: [[http://github.com/marijnh/js][http://github.com/marijnh/js]]
- Common Lisp JS uglifier: [[http://github.com/mishoo/cl-uglify-js][http://github.com/mishoo/cl-uglify-js]]
** License
UglifyJS is released under the BSD license:
#+BEGIN_EXAMPLE
Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
Based on parse-js (http://marijn.haverbeke.nl/parse-js/).
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.
#+END_EXAMPLE
================================================
FILE: bin/uglifyjs
================================================
#!/usr/bin/env node
// -*- js -*-
global.sys = require(/^v0\.[012]/.test(process.version) ? "sys" : "util");
var fs = require("fs"), path = require("path");
var uglify = require("../uglify-js"), // symlink ~/.node_libraries/uglify-js.js to ../uglify-js.js
consolidator = uglify.consolidator,
jsp = uglify.parser,
pro = uglify.uglify;
var options = {
ast: false,
consolidate: false,
mangle: true,
mangle_toplevel: false,
no_mangle_functions: false,
squeeze: true,
make_seqs: true,
dead_code: true,
verbose: false,
show_copyright: true,
out_same_file: false,
max_line_length: 32 * 1024,
unsafe: false,
reserved_names: null,
defines: { },
lift_vars: false,
codegen_options: {
ascii_only: false,
beautify: false,
indent_level: 4,
indent_start: 0,
quote_keys: false,
space_colon: false,
inline_script: false
},
make: false,
output: true // stdout
};
var args = jsp.slice(process.argv, 2);
var filename;
out: while (args.length > 0) {
var v = args.shift();
switch (v) {
case "-b":
case "--beautify":
options.codegen_options.beautify = true;
break;
case "-c":
case "--consolidate-primitive-values":
options.consolidate = true;
break;
case "-i":
case "--indent":
options.codegen_options.indent_level = args.shift();
break;
case "-q":
case "--quote-keys":
options.codegen_options.quote_keys = true;
break;
case "-mt":
case "--mangle-toplevel":
options.mangle_toplevel = true;
break;
case "-nmf":
case "--no-mangle-functions":
options.no_mangle_functions = true;
break;
case "--no-mangle":
case "-nm":
options.mangle = false;
break;
case "--no-squeeze":
case "-ns":
options.squeeze = false;
break;
case "--no-seqs":
options.make_seqs = false;
break;
case "--no-dead-code":
options.dead_code = false;
break;
case "--no-copyright":
case "-nc":
options.show_copyright = false;
break;
case "-o":
case "--output":
options.output = args.shift();
break;
case "--overwrite":
options.out_same_file = true;
break;
case "-v":
case "--verbose":
options.verbose = true;
break;
case "--ast":
options.ast = true;
break;
case "--unsafe":
options.unsafe = true;
break;
case "--max-line-len":
options.max_line_length = parseInt(args.shift(), 10);
break;
case "--reserved-names":
options.reserved_names = args.shift().split(",");
break;
case "--lift-vars":
options.lift_vars = true;
break;
case "-d":
case "--define":
var defarg = args.shift();
try {
var defsym = function(sym) {
// KEYWORDS_ATOM doesn't include NaN or Infinity - should we check
// for them too ?? We don't check reserved words and the like as the
// define values are only substituted AFTER parsing
if (jsp.KEYWORDS_ATOM.hasOwnProperty(sym)) {
throw "Don't define values for inbuilt constant '"+sym+"'";
}
return sym;
},
defval = function(v) {
if (v.match(/^"(.*)"$/) || v.match(/^'(.*)'$/)) {
return [ "string", RegExp.$1 ];
}
else if (!isNaN(parseFloat(v))) {
return [ "num", parseFloat(v) ];
}
else if (v.match(/^[a-z\$_][a-z\$_0-9]*$/i)) {
return [ "name", v ];
}
else if (!v.match(/"/)) {
return [ "string", v ];
}
else if (!v.match(/'/)) {
return [ "string", v ];
}
throw "Can't understand the specified value: "+v;
};
if (defarg.match(/^([a-z_\$][a-z_\$0-9]*)(=(.*))?$/i)) {
var sym = defsym(RegExp.$1),
val = RegExp.$2 ? defval(RegExp.$2.substr(1)) : [ 'name', 'true' ];
options.defines[sym] = val;
}
else {
throw "The --define option expects SYMBOL[=value]";
}
} catch(ex) {
sys.print("ERROR: In option --define "+defarg+"\n"+ex+"\n");
process.exit(1);
}
break;
case "--define-from-module":
var defmodarg = args.shift();
var defmodule = require(defmodarg);
var sym, val;
for (sym in defmodule) {
if (defmodule.hasOwnProperty(sym)) {
options.defines[sym] = function(val) {
if (typeof val == "string")
return [ "string", val ];
if (typeof val == "number")
return [ "num", val ];
if (val === true)
return [ 'name', 'true' ];
if (val === false)
return [ 'name', 'false' ];
if (val === null)
return [ 'name', 'null' ];
if (val === undefined)
return [ 'name', 'undefined' ];
sys.print("ERROR: In option --define-from-module "+defmodarg+"\n");
sys.print("ERROR: Unknown object type for: "+sym+"="+val+"\n");
process.exit(1);
return null;
}(defmodule[sym]);
}
}
break;
case "--ascii":
options.codegen_options.ascii_only = true;
break;
case "--make":
options.make = true;
break;
case "--inline-script":
options.codegen_options.inline_script = true;
break;
default:
filename = v;
break out;
}
}
if (options.verbose) {
pro.set_logger(function(msg){
sys.debug(msg);
});
}
jsp.set_logger(function(msg){
sys.debug(msg);
});
if (options.make) {
options.out_same_file = false; // doesn't make sense in this case
var makefile = global.eval("(" + fs.readFileSync(filename || "Makefile.uglify.js").toString() + ")");
var dir = path.dirname(filename);
output(makefile.files.map(function(file){
var code = fs.readFileSync(path.join(dir, file.name)).toString();
if (file.module) {
code = "!function(exports, global){global = this;\n" + code + "\n;this." + file.module + " = exports;}({})";
}
else if (file.hide) {
code = "(function(){" + code + "}());";
}
return squeeze_it(code);
}).join("\n"));
}
else if (filename) {
fs.readFile(filename, "utf8", function(err, text){
if (err) throw err;
output(squeeze_it(text));
});
}
else {
var stdin = process.openStdin();
stdin.setEncoding("utf8");
var text = "";
stdin.on("data", function(chunk){
text += chunk;
});
stdin.on("end", function() {
output(squeeze_it(text));
});
}
function output(text) {
var out;
if (options.out_same_file && filename)
options.output = filename;
if (options.output === true) {
out = process.stdout;
} else {
out = fs.createWriteStream(options.output, {
flags: "w",
encoding: "utf8",
mode: 0644
});
}
out.write(text.replace(/;*$/, ";"));
if (options.output !== true) {
out.end();
}
};
// --------- main ends here.
function show_copyright(comments) {
var ret = "";
for (var i = 0; i < comments.length; ++i) {
var c = comments[i];
if (c.type == "comment1") {
ret += "//" + c.value + "\n";
} else {
ret += "/*" + c.value + "*/";
}
}
return ret;
};
function squeeze_it(code) {
var result = "";
if (options.show_copyright) {
var tok = jsp.tokenizer(code), c;
c = tok();
result += show_copyright(c.comments_before);
}
try {
var ast = time_it("parse", function(){ return jsp.parse(code); });
if (options.consolidate) ast = time_it("consolidate", function(){
return consolidator.ast_consolidate(ast);
});
if (options.lift_vars) {
ast = time_it("lift", function(){ return pro.ast_lift_variables(ast); });
}
ast = time_it("mangle", function(){
return pro.ast_mangle(ast, {
mangle : options.mangle,
toplevel : options.mangle_toplevel,
defines : options.defines,
except : options.reserved_names,
no_functions : options.no_mangle_functions
});
});
if (options.squeeze) ast = time_it("squeeze", function(){
ast = pro.ast_squeeze(ast, {
make_seqs : options.make_seqs,
dead_code : options.dead_code,
keep_comps : !options.unsafe,
unsafe : options.unsafe
});
if (options.unsafe)
ast = pro.ast_squeeze_more(ast);
return ast;
});
if (options.ast)
return sys.inspect(ast, null, null);
result += time_it("generate", function(){ return pro.gen_code(ast, options.codegen_options) });
if (!options.codegen_options.beautify && options.max_line_length) {
result = time_it("split", function(){ return pro.split_lines(result, options.max_line_length) });
}
return result;
} catch(ex) {
sys.debug(ex.stack);
sys.debug(sys.inspect(ex));
sys.debug(JSON.stringify(ex));
process.exit(1);
}
};
function time_it(name, cont) {
if (!options.verbose)
return cont();
var t1 = new Date().getTime();
try { return cont(); }
finally { sys.debug("// " + name + ": " + ((new Date().getTime() - t1) / 1000).toFixed(3) + " sec."); }
};
================================================
FILE: docstyle.css
================================================
html { font-family: "Lucida Grande","Trebuchet MS",sans-serif; font-size: 12pt; }
body { max-width: 60em; }
.title { text-align: center; }
.todo { color: red; }
.done { color: green; }
.tag { background-color:lightblue; font-weight:normal }
.target { }
.timestamp { color: grey }
.timestamp-kwd { color: CadetBlue }
p.verse { margin-left: 3% }
pre {
border: 1pt solid #AEBDCC;
background-color: #F3F5F7;
padding: 5pt;
font-family: monospace;
font-size: 90%;
overflow:auto;
}
pre.src {
background-color: #eee; color: #112; border: 1px solid #000;
}
table { border-collapse: collapse; }
td, th { vertical-align: top; }
dt { font-weight: bold; }
div.figure { padding: 0.5em; }
div.figure p { text-align: center; }
.linenr { font-size:smaller }
.code-highlighted {background-color:#ffff00;}
.org-info-js_info-navigation { border-style:none; }
#org-info-js_console-label { font-size:10px; font-weight:bold;
white-space:nowrap; }
.org-info-js_search-highlight {background-color:#ffff00; color:#000000;
font-weight:bold; }
sup {
vertical-align: baseline;
position: relative;
top: -0.5em;
font-size: 80%;
}
sup a:link, sup a:visited {
text-decoration: none;
color: #c00;
}
sup a:before { content: "["; color: #999; }
sup a:after { content: "]"; color: #999; }
h1.title { border-bottom: 4px solid #000; padding-bottom: 5px; margin-bottom: 2em; }
#postamble {
color: #777;
font-size: 90%;
padding-top: 1em; padding-bottom: 1em; border-top: 1px solid #999;
margin-top: 2em;
padding-left: 2em;
padding-right: 2em;
text-align: right;
}
#postamble p { margin: 0; }
#footnotes { border-top: 1px solid #000; }
h1 { font-size: 200% }
h2 { font-size: 175% }
h3 { font-size: 150% }
h4 { font-size: 125% }
h1, h2, h3, h4 { font-family: "Bookman",Georgia,"Times New Roman",serif; font-weight: normal; }
@media print {
html { font-size: 11pt; }
}
================================================
FILE: lib/consolidator.js
================================================
/**
* @preserve Copyright 2012 Robert Gust-Bardon <http://robert.gust-bardon.org/>.
* All rights reserved.
*
* 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.
*/
/**
* @fileoverview Enhances <a href="https://github.com/mishoo/UglifyJS/"
* >UglifyJS</a> with consolidation of null, Boolean, and String values.
* <p>Also known as aliasing, this feature has been deprecated in <a href=
* "http://closure-compiler.googlecode.com/">the Closure Compiler</a> since its
* initial release, where it is unavailable from the <abbr title=
* "command line interface">CLI</a>. The Closure Compiler allows one to log and
* influence this process. In contrast, this implementation does not introduce
* any variable declarations in global code and derives String values from
* identifier names used as property accessors.</p>
* <p>Consolidating literals may worsen the data compression ratio when an <a
* href="http://tools.ietf.org/html/rfc2616#section-3.5">encoding
* transformation</a> is applied. For instance, <a href=
* "http://code.jquery.com/jquery-1.7.1.js">jQuery 1.7.1</a> takes 248235 bytes.
* Building it with <a href="https://github.com/mishoo/UglifyJS/tarball/v1.2.5">
* UglifyJS v1.2.5</a> results in 93647 bytes (37.73% of the original) which are
* then compressed to 33154 bytes (13.36% of the original) using <a href=
* "http://linux.die.net/man/1/gzip">gzip(1)</a>. Building it with the same
* version of UglifyJS 1.2.5 patched with the implementation of consolidation
* results in 80784 bytes (a decrease of 12863 bytes, i.e. 13.74%, in comparison
* to the aforementioned 93647 bytes) which are then compressed to 34013 bytes
* (an increase of 859 bytes, i.e. 2.59%, in comparison to the aforementioned
* 33154 bytes).</p>
* <p>Written in <a href="http://es5.github.com/#x4.2.2">the strict variant</a>
* of <a href="http://es5.github.com/">ECMA-262 5.1 Edition</a>. Encoded in <a
* href="http://tools.ietf.org/html/rfc3629">UTF-8</a>. Follows <a href=
* "http://google-styleguide.googlecode.com/svn-history/r76/trunk/javascriptguide.xml"
* >Revision 2.28 of the Google JavaScript Style Guide</a> (except for the
* discouraged use of the {@code function} tag and the {@code namespace} tag).
* 100% typed for the <a href=
* "http://closure-compiler.googlecode.com/files/compiler-20120123.tar.gz"
* >Closure Compiler Version 1741</a>.</p>
* <p>Should you find this software useful, please consider <a href=
* "https://paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=JZLW72X8FD4WG"
* >a donation</a>.</p>
* @author follow.me@RGustBardon (Robert Gust-Bardon)
* @supported Tested with:
* <ul>
* <li><a href="http://nodejs.org/dist/v0.6.10/">Node v0.6.10</a>,</li>
* <li><a href="https://github.com/mishoo/UglifyJS/tarball/v1.2.5">UglifyJS
* v1.2.5</a>.</li>
* </ul>
*/
/*global console:false, exports:true, module:false, require:false */
/*jshint sub:true */
/**
* Consolidates null, Boolean, and String values found inside an <abbr title=
* "abstract syntax tree">AST</abbr>.
* @param {!TSyntacticCodeUnit} oAbstractSyntaxTree An array-like object
* representing an <abbr title="abstract syntax tree">AST</abbr>.
* @return {!TSyntacticCodeUnit} An array-like object representing an <abbr
* title="abstract syntax tree">AST</abbr> with its null, Boolean, and
* String values consolidated.
*/
// TODO(user) Consolidation of mathematical values found in numeric literals.
// TODO(user) Unconsolidation.
// TODO(user) Consolidation of ECMA-262 6th Edition programs.
// TODO(user) Rewrite in ECMA-262 6th Edition.
exports['ast_consolidate'] = function(oAbstractSyntaxTree) {
'use strict';
/*jshint bitwise:true, curly:true, eqeqeq:true, forin:true, immed:true,
latedef:true, newcap:true, noarge:true, noempty:true, nonew:true,
onevar:true, plusplus:true, regexp:true, undef:true, strict:true,
sub:false, trailing:true */
var _,
/**
* A record consisting of data about one or more source elements.
* @constructor
* @nosideeffects
*/
TSourceElementsData = function() {
/**
* The category of the elements.
* @type {number}
* @see ESourceElementCategories
*/
this.nCategory = ESourceElementCategories.N_OTHER;
/**
* The number of occurrences (within the elements) of each primitive
* value that could be consolidated.
* @type {!Array.<!Object.<string, number>>}
*/
this.aCount = [];
this.aCount[EPrimaryExpressionCategories.N_IDENTIFIER_NAMES] = {};
this.aCount[EPrimaryExpressionCategories.N_STRING_LITERALS] = {};
this.aCount[EPrimaryExpressionCategories.N_NULL_AND_BOOLEAN_LITERALS] =
{};
/**
* Identifier names found within the elements.
* @type {!Array.<string>}
*/
this.aIdentifiers = [];
/**
* Prefixed representation Strings of each primitive value that could be
* consolidated within the elements.
* @type {!Array.<string>}
*/
this.aPrimitiveValues = [];
},
/**
* A record consisting of data about a primitive value that could be
* consolidated.
* @constructor
* @nosideeffects
*/
TPrimitiveValue = function() {
/**
* The difference in the number of terminal symbols between the original
* source text and the one with the primitive value consolidated. If the
* difference is positive, the primitive value is considered worthwhile.
* @type {number}
*/
this.nSaving = 0;
/**
* An identifier name of the variable that will be declared and assigned
* the primitive value if the primitive value is consolidated.
* @type {string}
*/
this.sName = '';
},
/**
* A record consisting of data on what to consolidate within the range of
* source elements that is currently being considered.
* @constructor
* @nosideeffects
*/
TSolution = function() {
/**
* An object whose keys are prefixed representation Strings of each
* primitive value that could be consolidated within the elements and
* whose values are corresponding data about those primitive values.
* @type {!Object.<string, {nSaving: number, sName: string}>}
* @see TPrimitiveValue
*/
this.oPrimitiveValues = {};
/**
* The difference in the number of terminal symbols between the original
* source text and the one with all the worthwhile primitive values
* consolidated.
* @type {number}
* @see TPrimitiveValue#nSaving
*/
this.nSavings = 0;
},
/**
* The processor of <abbr title="abstract syntax tree">AST</abbr>s found
* in UglifyJS.
* @namespace
* @type {!TProcessor}
*/
oProcessor = (/** @type {!TProcessor} */ require('./process')),
/**
* A record consisting of a number of constants that represent the
* difference in the number of terminal symbols between a source text with
* a modified syntactic code unit and the original one.
* @namespace
* @type {!Object.<string, number>}
*/
oWeights = {
/**
* The difference in the number of punctuators required by the bracket
* notation and the dot notation.
* <p><code>'[]'.length - '.'.length</code></p>
* @const
* @type {number}
*/
N_PROPERTY_ACCESSOR: 1,
/**
* The number of punctuators required by a variable declaration with an
* initialiser.
* <p><code>':'.length + ';'.length</code></p>
* @const
* @type {number}
*/
N_VARIABLE_DECLARATION: 2,
/**
* The number of terminal symbols required to introduce a variable
* statement (excluding its variable declaration list).
* <p><code>'var '.length</code></p>
* @const
* @type {number}
*/
N_VARIABLE_STATEMENT_AFFIXATION: 4,
/**
* The number of terminal symbols needed to enclose source elements
* within a function call with no argument values to a function with an
* empty parameter list.
* <p><code>'(function(){}());'.length</code></p>
* @const
* @type {number}
*/
N_CLOSURE: 17
},
/**
* Categories of primary expressions from which primitive values that
* could be consolidated are derivable.
* @namespace
* @enum {number}
*/
EPrimaryExpressionCategories = {
/**
* Identifier names used as property accessors.
* @type {number}
*/
N_IDENTIFIER_NAMES: 0,
/**
* String literals.
* @type {number}
*/
N_STRING_LITERALS: 1,
/**
* Null and Boolean literals.
* @type {number}
*/
N_NULL_AND_BOOLEAN_LITERALS: 2
},
/**
* Prefixes of primitive values that could be consolidated.
* The String values of the prefixes must have same number of characters.
* The prefixes must not be used in any properties defined in any version
* of <a href=
* "http://www.ecma-international.org/publications/standards/Ecma-262.htm"
* >ECMA-262</a>.
* @namespace
* @enum {string}
*/
EValuePrefixes = {
/**
* Identifies String values.
* @type {string}
*/
S_STRING: '#S',
/**
* Identifies null and Boolean values.
* @type {string}
*/
S_SYMBOLIC: '#O'
},
/**
* Categories of source elements in terms of their appropriateness of
* having their primitive values consolidated.
* @namespace
* @enum {number}
*/
ESourceElementCategories = {
/**
* Identifies a source element that includes the <a href=
* "http://es5.github.com/#x12.10">{@code with}</a> statement.
* @type {number}
*/
N_WITH: 0,
/**
* Identifies a source element that includes the <a href=
* "http://es5.github.com/#x15.1.2.1">{@code eval}</a> identifier name.
* @type {number}
*/
N_EVAL: 1,
/**
* Identifies a source element that must be excluded from the process
* unless its whole scope is examined.
* @type {number}
*/
N_EXCLUDABLE: 2,
/**
* Identifies source elements not posing any problems.
* @type {number}
*/
N_OTHER: 3
},
/**
* The list of literals (other than the String ones) whose primitive
* values can be consolidated.
* @const
* @type {!Array.<string>}
*/
A_OTHER_SUBSTITUTABLE_LITERALS = [
'null', // The null literal.
'false', // The Boolean literal {@code false}.
'true' // The Boolean literal {@code true}.
];
(/**
* Consolidates all worthwhile primitive values in a syntactic code unit.
* @param {!TSyntacticCodeUnit} oSyntacticCodeUnit An array-like object
* representing the branch of the abstract syntax tree representing the
* syntactic code unit along with its scope.
* @see TPrimitiveValue#nSaving
*/
function fExamineSyntacticCodeUnit(oSyntacticCodeUnit) {
var _,
/**
* Indicates whether the syntactic code unit represents global code.
* @type {boolean}
*/
bIsGlobal = 'toplevel' === oSyntacticCodeUnit[0],
/**
* Indicates whether the whole scope is being examined.
* @type {boolean}
*/
bIsWhollyExaminable = !bIsGlobal,
/**
* An array-like object representing source elements that constitute a
* syntactic code unit.
* @type {!TSyntacticCodeUnit}
*/
oSourceElements,
/**
* A record consisting of data about the source element that is
* currently being examined.
* @type {!TSourceElementsData}
*/
oSourceElementData,
/**
* The scope of the syntactic code unit.
* @type {!TScope}
*/
oScope,
/**
* An instance of an object that allows the traversal of an <abbr
* title="abstract syntax tree">AST</abbr>.
* @type {!TWalker}
*/
oWalker,
/**
* An object encompassing collections of functions used during the
* traversal of an <abbr title="abstract syntax tree">AST</abbr>.
* @namespace
* @type {!Object.<string, !Object.<string, function(...[*])>>}
*/
oWalkers = {
/**
* A collection of functions used during the surveyance of source
* elements.
* @namespace
* @type {!Object.<string, function(...[*])>}
*/
oSurveySourceElement: {
/**#nocode+*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
/**
* Classifies the source element as excludable if it does not
* contain a {@code with} statement or the {@code eval} identifier
* name. Adds the identifier of the function and its formal
* parameters to the list of identifier names found.
* @param {string} sIdentifier The identifier of the function.
* @param {!Array.<string>} aFormalParameterList Formal parameters.
* @param {!TSyntacticCodeUnit} oFunctionBody Function code.
*/
'defun': function(
sIdentifier,
aFormalParameterList,
oFunctionBody) {
fClassifyAsExcludable();
fAddIdentifier(sIdentifier);
aFormalParameterList.forEach(fAddIdentifier);
},
/**
* Increments the count of the number of occurrences of the String
* value that is equivalent to the sequence of terminal symbols
* that constitute the encountered identifier name.
* @param {!TSyntacticCodeUnit} oExpression The nonterminal
* MemberExpression.
* @param {string} sIdentifierName The identifier name used as the
* property accessor.
* @return {!Array} The encountered branch of an <abbr title=
* "abstract syntax tree">AST</abbr> with its nonterminal
* MemberExpression traversed.
*/
'dot': function(oExpression, sIdentifierName) {
fCountPrimaryExpression(
EPrimaryExpressionCategories.N_IDENTIFIER_NAMES,
EValuePrefixes.S_STRING + sIdentifierName);
return ['dot', oWalker.walk(oExpression), sIdentifierName];
},
/**
* Adds the optional identifier of the function and its formal
* parameters to the list of identifier names found.
* @param {?string} sIdentifier The optional identifier of the
* function.
* @param {!Array.<string>} aFormalParameterList Formal parameters.
* @param {!TSyntacticCodeUnit} oFunctionBody Function code.
*/
'function': function(
sIdentifier,
aFormalParameterList,
oFunctionBody) {
if ('string' === typeof sIdentifier) {
fAddIdentifier(sIdentifier);
}
aFormalParameterList.forEach(fAddIdentifier);
},
/**
* Either increments the count of the number of occurrences of the
* encountered null or Boolean value or classifies a source element
* as containing the {@code eval} identifier name.
* @param {string} sIdentifier The identifier encountered.
*/
'name': function(sIdentifier) {
if (-1 !== A_OTHER_SUBSTITUTABLE_LITERALS.indexOf(sIdentifier)) {
fCountPrimaryExpression(
EPrimaryExpressionCategories.N_NULL_AND_BOOLEAN_LITERALS,
EValuePrefixes.S_SYMBOLIC + sIdentifier);
} else {
if ('eval' === sIdentifier) {
oSourceElementData.nCategory =
ESourceElementCategories.N_EVAL;
}
fAddIdentifier(sIdentifier);
}
},
/**
* Classifies the source element as excludable if it does not
* contain a {@code with} statement or the {@code eval} identifier
* name.
* @param {TSyntacticCodeUnit} oExpression The expression whose
* value is to be returned.
*/
'return': function(oExpression) {
fClassifyAsExcludable();
},
/**
* Increments the count of the number of occurrences of the
* encountered String value.
* @param {string} sStringValue The String value of the string
* literal encountered.
*/
'string': function(sStringValue) {
if (sStringValue.length > 0) {
fCountPrimaryExpression(
EPrimaryExpressionCategories.N_STRING_LITERALS,
EValuePrefixes.S_STRING + sStringValue);
}
},
/**
* Adds the identifier reserved for an exception to the list of
* identifier names found.
* @param {!TSyntacticCodeUnit} oTry A block of code in which an
* exception can occur.
* @param {Array} aCatch The identifier reserved for an exception
* and a block of code to handle the exception.
* @param {TSyntacticCodeUnit} oFinally An optional block of code
* to be evaluated regardless of whether an exception occurs.
*/
'try': function(oTry, aCatch, oFinally) {
if (Array.isArray(aCatch)) {
fAddIdentifier(aCatch[0]);
}
},
/**
* Classifies the source element as excludable if it does not
* contain a {@code with} statement or the {@code eval} identifier
* name. Adds the identifier of each declared variable to the list
* of identifier names found.
* @param {!Array.<!Array>} aVariableDeclarationList Variable
* declarations.
*/
'var': function(aVariableDeclarationList) {
fClassifyAsExcludable();
aVariableDeclarationList.forEach(fAddVariable);
},
/**
* Classifies a source element as containing the {@code with}
* statement.
* @param {!TSyntacticCodeUnit} oExpression An expression whose
* value is to be converted to a value of type Object and
* become the binding object of a new object environment
* record of a new lexical environment in which the statement
* is to be executed.
* @param {!TSyntacticCodeUnit} oStatement The statement to be
* executed in the augmented lexical environment.
* @return {!Array} An empty array to stop the traversal.
*/
'with': function(oExpression, oStatement) {
oSourceElementData.nCategory = ESourceElementCategories.N_WITH;
return [];
}
/**#nocode-*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
},
/**
* A collection of functions used while looking for nested functions.
* @namespace
* @type {!Object.<string, function(...[*])>}
*/
oExamineFunctions: {
/**#nocode+*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
/**
* Orders an examination of a nested function declaration.
* @this {!TSyntacticCodeUnit} An array-like object representing
* the branch of an <abbr title="abstract syntax tree"
* >AST</abbr> representing the syntactic code unit along with
* its scope.
* @return {!Array} An empty array to stop the traversal.
*/
'defun': function() {
fExamineSyntacticCodeUnit(this);
return [];
},
/**
* Orders an examination of a nested function expression.
* @this {!TSyntacticCodeUnit} An array-like object representing
* the branch of an <abbr title="abstract syntax tree"
* >AST</abbr> representing the syntactic code unit along with
* its scope.
* @return {!Array} An empty array to stop the traversal.
*/
'function': function() {
fExamineSyntacticCodeUnit(this);
return [];
}
/**#nocode-*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
}
},
/**
* Records containing data about source elements.
* @type {Array.<TSourceElementsData>}
*/
aSourceElementsData = [],
/**
* The index (in the source text order) of the source element
* immediately following a <a href="http://es5.github.com/#x14.1"
* >Directive Prologue</a>.
* @type {number}
*/
nAfterDirectivePrologue = 0,
/**
* The index (in the source text order) of the source element that is
* currently being considered.
* @type {number}
*/
nPosition,
/**
* The index (in the source text order) of the source element that is
* the last element of the range of source elements that is currently
* being considered.
* @type {(undefined|number)}
*/
nTo,
/**
* Initiates the traversal of a source element.
* @param {!TWalker} oWalker An instance of an object that allows the
* traversal of an abstract syntax tree.
* @param {!TSyntacticCodeUnit} oSourceElement A source element from
* which the traversal should commence.
* @return {function(): !TSyntacticCodeUnit} A function that is able to
* initiate the traversal from a given source element.
*/
cContext = function(oWalker, oSourceElement) {
/**
* @return {!TSyntacticCodeUnit} A function that is able to
* initiate the traversal from a given source element.
*/
var fLambda = function() {
return oWalker.walk(oSourceElement);
};
return fLambda;
},
/**
* Classifies the source element as excludable if it does not
* contain a {@code with} statement or the {@code eval} identifier
* name.
*/
fClassifyAsExcludable = function() {
if (oSourceElementData.nCategory ===
ESourceElementCategories.N_OTHER) {
oSourceElementData.nCategory =
ESourceElementCategories.N_EXCLUDABLE;
}
},
/**
* Adds an identifier to the list of identifier names found.
* @param {string} sIdentifier The identifier to be added.
*/
fAddIdentifier = function(sIdentifier) {
if (-1 === oSourceElementData.aIdentifiers.indexOf(sIdentifier)) {
oSourceElementData.aIdentifiers.push(sIdentifier);
}
},
/**
* Adds the identifier of a variable to the list of identifier names
* found.
* @param {!Array} aVariableDeclaration A variable declaration.
*/
fAddVariable = function(aVariableDeclaration) {
fAddIdentifier(/** @type {string} */ aVariableDeclaration[0]);
},
/**
* Increments the count of the number of occurrences of the prefixed
* String representation attributed to the primary expression.
* @param {number} nCategory The category of the primary expression.
* @param {string} sName The prefixed String representation attributed
* to the primary expression.
*/
fCountPrimaryExpression = function(nCategory, sName) {
if (!oSourceElementData.aCount[nCategory].hasOwnProperty(sName)) {
oSourceElementData.aCount[nCategory][sName] = 0;
if (-1 === oSourceElementData.aPrimitiveValues.indexOf(sName)) {
oSourceElementData.aPrimitiveValues.push(sName);
}
}
oSourceElementData.aCount[nCategory][sName] += 1;
},
/**
* Consolidates all worthwhile primitive values in a range of source
* elements.
* @param {number} nFrom The index (in the source text order) of the
* source element that is the first element of the range.
* @param {number} nTo The index (in the source text order) of the
* source element that is the last element of the range.
* @param {boolean} bEnclose Indicates whether the range should be
* enclosed within a function call with no argument values to a
* function with an empty parameter list if any primitive values
* are consolidated.
* @see TPrimitiveValue#nSaving
*/
fExamineSourceElements = function(nFrom, nTo, bEnclose) {
var _,
/**
* The index of the last mangled name.
* @type {number}
*/
nIndex = oScope.cname,
/**
* The index of the source element that is currently being
* considered.
* @type {number}
*/
nPosition,
/**
* A collection of functions used during the consolidation of
* primitive values and identifier names used as property
* accessors.
* @namespace
* @type {!Object.<string, function(...[*])>}
*/
oWalkersTransformers = {
/**
* If the String value that is equivalent to the sequence of
* terminal symbols that constitute the encountered identifier
* name is worthwhile, a syntactic conversion from the dot
* notation to the bracket notation ensues with that sequence
* being substituted by an identifier name to which the value
* is assigned.
* Applies to property accessors that use the dot notation.
* @param {!TSyntacticCodeUnit} oExpression The nonterminal
* MemberExpression.
* @param {string} sIdentifierName The identifier name used as
* the property accessor.
* @return {!Array} A syntactic code unit that is equivalent to
* the one encountered.
* @see TPrimitiveValue#nSaving
*/
'dot': function(oExpression, sIdentifierName) {
/**
* The prefixed String value that is equivalent to the
* sequence of terminal symbols that constitute the
* encountered identifier name.
* @type {string}
*/
var sPrefixed = EValuePrefixes.S_STRING + sIdentifierName;
return oSolutionBest.oPrimitiveValues.hasOwnProperty(
sPrefixed) &&
oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
['sub',
oWalker.walk(oExpression),
['name',
oSolutionBest.oPrimitiveValues[sPrefixed].sName]] :
['dot', oWalker.walk(oExpression), sIdentifierName];
},
/**
* If the encountered identifier is a null or Boolean literal
* and its value is worthwhile, the identifier is substituted
* by an identifier name to which that value is assigned.
* Applies to identifier names.
* @param {string} sIdentifier The identifier encountered.
* @return {!Array} A syntactic code unit that is equivalent to
* the one encountered.
* @see TPrimitiveValue#nSaving
*/
'name': function(sIdentifier) {
/**
* The prefixed representation String of the identifier.
* @type {string}
*/
var sPrefixed = EValuePrefixes.S_SYMBOLIC + sIdentifier;
return [
'name',
oSolutionBest.oPrimitiveValues.hasOwnProperty(sPrefixed) &&
oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
oSolutionBest.oPrimitiveValues[sPrefixed].sName :
sIdentifier
];
},
/**
* If the encountered String value is worthwhile, it is
* substituted by an identifier name to which that value is
* assigned.
* Applies to String values.
* @param {string} sStringValue The String value of the string
* literal encountered.
* @return {!Array} A syntactic code unit that is equivalent to
* the one encountered.
* @see TPrimitiveValue#nSaving
*/
'string': function(sStringValue) {
/**
* The prefixed representation String of the primitive value
* of the literal.
* @type {string}
*/
var sPrefixed =
EValuePrefixes.S_STRING + sStringValue;
return oSolutionBest.oPrimitiveValues.hasOwnProperty(
sPrefixed) &&
oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
['name',
oSolutionBest.oPrimitiveValues[sPrefixed].sName] :
['string', sStringValue];
}
},
/**
* Such data on what to consolidate within the range of source
* elements that is currently being considered that lead to the
* greatest known reduction of the number of the terminal symbols
* in comparison to the original source text.
* @type {!TSolution}
*/
oSolutionBest = new TSolution(),
/**
* Data representing an ongoing attempt to find a better
* reduction of the number of the terminal symbols in comparison
* to the original source text than the best one that is
* currently known.
* @type {!TSolution}
* @see oSolutionBest
*/
oSolutionCandidate = new TSolution(),
/**
* A record consisting of data about the range of source elements
* that is currently being examined.
* @type {!TSourceElementsData}
*/
oSourceElementsData = new TSourceElementsData(),
/**
* Variable declarations for each primitive value that is to be
* consolidated within the elements.
* @type {!Array.<!Array>}
*/
aVariableDeclarations = [],
/**
* Augments a list with a prefixed representation String.
* @param {!Array.<string>} aList A list that is to be augmented.
* @return {function(string)} A function that augments a list
* with a prefixed representation String.
*/
cAugmentList = function(aList) {
/**
* @param {string} sPrefixed Prefixed representation String of
* a primitive value that could be consolidated within the
* elements.
*/
var fLambda = function(sPrefixed) {
if (-1 === aList.indexOf(sPrefixed)) {
aList.push(sPrefixed);
}
};
return fLambda;
},
/**
* Adds the number of occurrences of a primitive value of a given
* category that could be consolidated in the source element with
* a given index to the count of occurrences of that primitive
* value within the range of source elements that is currently
* being considered.
* @param {number} nPosition The index (in the source text order)
* of a source element.
* @param {number} nCategory The category of the primary
* expression from which the primitive value is derived.
* @return {function(string)} A function that performs the
* addition.
* @see cAddOccurrencesInCategory
*/
cAddOccurrences = function(nPosition, nCategory) {
/**
* @param {string} sPrefixed The prefixed representation String
* of a primitive value.
*/
var fLambda = function(sPrefixed) {
if (!oSourceElementsData.aCount[nCategory].hasOwnProperty(
sPrefixed)) {
oSourceElementsData.aCount[nCategory][sPrefixed] = 0;
}
oSourceElementsData.aCount[nCategory][sPrefixed] +=
aSourceElementsData[nPosition].aCount[nCategory][
sPrefixed];
};
return fLambda;
},
/**
* Adds the number of occurrences of each primitive value of a
* given category that could be consolidated in the source
* element with a given index to the count of occurrences of that
* primitive values within the range of source elements that is
* currently being considered.
* @param {number} nPosition The index (in the source text order)
* of a source element.
* @return {function(number)} A function that performs the
* addition.
* @see fAddOccurrences
*/
cAddOccurrencesInCategory = function(nPosition) {
/**
* @param {number} nCategory The category of the primary
* expression from which the primitive value is derived.
*/
var fLambda = function(nCategory) {
Object.keys(
aSourceElementsData[nPosition].aCount[nCategory]
).forEach(cAddOccurrences(nPosition, nCategory));
};
return fLambda;
},
/**
* Adds the number of occurrences of each primitive value that
* could be consolidated in the source element with a given index
* to the count of occurrences of that primitive values within
* the range of source elements that is currently being
* considered.
* @param {number} nPosition The index (in the source text order)
* of a source element.
*/
fAddOccurrences = function(nPosition) {
Object.keys(aSourceElementsData[nPosition].aCount).forEach(
cAddOccurrencesInCategory(nPosition));
},
/**
* Creates a variable declaration for a primitive value if that
* primitive value is to be consolidated within the elements.
* @param {string} sPrefixed Prefixed representation String of a
* primitive value that could be consolidated within the
* elements.
* @see aVariableDeclarations
*/
cAugmentVariableDeclarations = function(sPrefixed) {
if (oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0) {
aVariableDeclarations.push([
oSolutionBest.oPrimitiveValues[sPrefixed].sName,
[0 === sPrefixed.indexOf(EValuePrefixes.S_SYMBOLIC) ?
'name' : 'string',
sPrefixed.substring(EValuePrefixes.S_SYMBOLIC.length)]
]);
}
},
/**
* Sorts primitive values with regard to the difference in the
* number of terminal symbols between the original source text
* and the one with those primitive values consolidated.
* @param {string} sPrefixed0 The prefixed representation String
* of the first of the two primitive values that are being
* compared.
* @param {string} sPrefixed1 The prefixed representation String
* of the second of the two primitive values that are being
* compared.
* @return {number}
* <dl>
* <dt>-1</dt>
* <dd>if the first primitive value must be placed before
* the other one,</dd>
* <dt>0</dt>
* <dd>if the first primitive value may be placed before
* the other one,</dd>
* <dt>1</dt>
* <dd>if the first primitive value must not be placed
* before the other one.</dd>
* </dl>
* @see TSolution.oPrimitiveValues
*/
cSortPrimitiveValues = function(sPrefixed0, sPrefixed1) {
/**
* The difference between:
* <ol>
* <li>the difference in the number of terminal symbols
* between the original source text and the one with the
* first primitive value consolidated, and</li>
* <li>the difference in the number of terminal symbols
* between the original source text and the one with the
* second primitive value consolidated.</li>
* </ol>
* @type {number}
*/
var nDifference =
oSolutionCandidate.oPrimitiveValues[sPrefixed0].nSaving -
oSolutionCandidate.oPrimitiveValues[sPrefixed1].nSaving;
return nDifference > 0 ? -1 : nDifference < 0 ? 1 : 0;
},
/**
* Assigns an identifier name to a primitive value and calculates
* whether instances of that primitive value are worth
* consolidating.
* @param {string} sPrefixed The prefixed representation String
* of a primitive value that is being evaluated.
*/
fEvaluatePrimitiveValue = function(sPrefixed) {
var _,
/**
* The index of the last mangled name.
* @type {number}
*/
nIndex,
/**
* The representation String of the primitive value that is
* being evaluated.
* @type {string}
*/
sName =
sPrefixed.substring(EValuePrefixes.S_SYMBOLIC.length),
/**
* The number of source characters taken up by the
* representation String of the primitive value that is
* being evaluated.
* @type {number}
*/
nLengthOriginal = sName.length,
/**
* The number of source characters taken up by the
* identifier name that could substitute the primitive
* value that is being evaluated.
* substituted.
* @type {number}
*/
nLengthSubstitution,
/**
* The number of source characters taken up by by the
* representation String of the primitive value that is
* being evaluated when it is represented by a string
* literal.
* @type {number}
*/
nLengthString = oProcessor.make_string(sName).length;
oSolutionCandidate.oPrimitiveValues[sPrefixed] =
new TPrimitiveValue();
do { // Find an identifier unused in this or any nested scope.
nIndex = oScope.cname;
oSolutionCandidate.oPrimitiveValues[sPrefixed].sName =
oScope.next_mangled();
} while (-1 !== oSourceElementsData.aIdentifiers.indexOf(
oSolutionCandidate.oPrimitiveValues[sPrefixed].sName));
nLengthSubstitution = oSolutionCandidate.oPrimitiveValues[
sPrefixed].sName.length;
if (0 === sPrefixed.indexOf(EValuePrefixes.S_SYMBOLIC)) {
// foo:null, or foo:null;
oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving -=
nLengthSubstitution + nLengthOriginal +
oWeights.N_VARIABLE_DECLARATION;
// null vs foo
oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
oSourceElementsData.aCount[
EPrimaryExpressionCategories.
N_NULL_AND_BOOLEAN_LITERALS][sPrefixed] *
(nLengthOriginal - nLengthSubstitution);
} else {
// foo:'fromCharCode';
oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving -=
nLengthSubstitution + nLengthString +
oWeights.N_VARIABLE_DECLARATION;
// .fromCharCode vs [foo]
if (oSourceElementsData.aCount[
EPrimaryExpressionCategories.N_IDENTIFIER_NAMES
].hasOwnProperty(sPrefixed)) {
oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
oSourceElementsData.aCount[
EPrimaryExpressionCategories.N_IDENTIFIER_NAMES
][sPrefixed] *
(nLengthOriginal - nLengthSubstitution -
oWeights.N_PROPERTY_ACCESSOR);
}
// 'fromCharCode' vs foo
if (oSourceElementsData.aCount[
EPrimaryExpressionCategories.N_STRING_LITERALS
].hasOwnProperty(sPrefixed)) {
oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
oSourceElementsData.aCount[
EPrimaryExpressionCategories.N_STRING_LITERALS
][sPrefixed] *
(nLengthString - nLengthSubstitution);
}
}
if (oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving >
0) {
oSolutionCandidate.nSavings +=
oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving;
} else {
oScope.cname = nIndex; // Free the identifier name.
}
},
/**
* Adds a variable declaration to an existing variable statement.
* @param {!Array} aVariableDeclaration A variable declaration
* with an initialiser.
*/
cAddVariableDeclaration = function(aVariableDeclaration) {
(/** @type {!Array} */ oSourceElements[nFrom][1]).unshift(
aVariableDeclaration);
};
if (nFrom > nTo) {
return;
}
// If the range is a closure, reuse the closure.
if (nFrom === nTo &&
'stat' === oSourceElements[nFrom][0] &&
'call' === oSourceElements[nFrom][1][0] &&
'function' === oSourceElements[nFrom][1][1][0]) {
fExamineSyntacticCodeUnit(oSourceElements[nFrom][1][1]);
return;
}
// Create a list of all derived primitive values within the range.
for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
aSourceElementsData[nPosition].aPrimitiveValues.forEach(
cAugmentList(oSourceElementsData.aPrimitiveValues));
}
if (0 === oSourceElementsData.aPrimitiveValues.length) {
return;
}
for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
// Add the number of occurrences to the total count.
fAddOccurrences(nPosition);
// Add identifiers of this or any nested scope to the list.
aSourceElementsData[nPosition].aIdentifiers.forEach(
cAugmentList(oSourceElementsData.aIdentifiers));
}
// Distribute identifier names among derived primitive values.
do { // If there was any progress, find a better distribution.
oSolutionBest = oSolutionCandidate;
if (Object.keys(oSolutionCandidate.oPrimitiveValues).length > 0) {
// Sort primitive values descending by their worthwhileness.
oSourceElementsData.aPrimitiveValues.sort(cSortPrimitiveValues);
}
oSolutionCandidate = new TSolution();
oSourceElementsData.aPrimitiveValues.forEach(
fEvaluatePrimitiveValue);
oScope.cname = nIndex;
} while (oSolutionCandidate.nSavings > oSolutionBest.nSavings);
// Take the necessity of adding a variable statement into account.
if ('var' !== oSourceElements[nFrom][0]) {
oSolutionBest.nSavings -= oWeights.N_VARIABLE_STATEMENT_AFFIXATION;
}
if (bEnclose) {
// Take the necessity of forming a closure into account.
oSolutionBest.nSavings -= oWeights.N_CLOSURE;
}
if (oSolutionBest.nSavings > 0) {
// Create variable declarations suitable for UglifyJS.
Object.keys(oSolutionBest.oPrimitiveValues).forEach(
cAugmentVariableDeclarations);
// Rewrite expressions that contain worthwhile primitive values.
for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
oWalker = oProcessor.ast_walker();
oSourceElements[nPosition] =
oWalker.with_walkers(
oWalkersTransformers,
cContext(oWalker, oSourceElements[nPosition]));
}
if ('var' === oSourceElements[nFrom][0]) { // Reuse the statement.
(/** @type {!Array.<!Array>} */ aVariableDeclarations.reverse(
)).forEach(cAddVariableDeclaration);
} else { // Add a variable statement.
Array.prototype.splice.call(
oSourceElements,
nFrom,
0,
['var', aVariableDeclarations]);
nTo += 1;
}
if (bEnclose) {
// Add a closure.
Array.prototype.splice.call(
oSourceElements,
nFrom,
0,
['stat', ['call', ['function', null, [], []], []]]);
// Copy source elements into the closure.
for (nPosition = nTo + 1; nPosition > nFrom; nPosition -= 1) {
Array.prototype.unshift.call(
oSourceElements[nFrom][1][1][3],
oSourceElements[nPosition]);
}
// Remove source elements outside the closure.
Array.prototype.splice.call(
oSourceElements,
nFrom + 1,
nTo - nFrom + 1);
}
}
if (bEnclose) {
// Restore the availability of identifier names.
oScope.cname = nIndex;
}
};
oSourceElements = (/** @type {!TSyntacticCodeUnit} */
oSyntacticCodeUnit[bIsGlobal ? 1 : 3]);
if (0 === oSourceElements.length) {
return;
}
oScope = bIsGlobal ? oSyntacticCodeUnit.scope : oSourceElements.scope;
// Skip a Directive Prologue.
while (nAfterDirectivePrologue < oSourceElements.length &&
'directive' === oSourceElements[nAfterDirectivePrologue][0]) {
nAfterDirectivePrologue += 1;
aSourceElementsData.push(null);
}
if (oSourceElements.length === nAfterDirectivePrologue) {
return;
}
for (nPosition = nAfterDirectivePrologue;
nPosition < oSourceElements.length;
nPosition += 1) {
oSourceElementData = new TSourceElementsData();
oWalker = oProcessor.ast_walker();
// Classify a source element.
// Find its derived primitive values and count their occurrences.
// Find all identifiers used (including nested scopes).
oWalker.with_walkers(
oWalkers.oSurveySourceElement,
cContext(oWalker, oSourceElements[nPosition]));
// Establish whether the scope is still wholly examinable.
bIsWhollyExaminable = bIsWhollyExaminable &&
ESourceElementCategories.N_WITH !== oSourceElementData.nCategory &&
ESourceElementCategories.N_EVAL !== oSourceElementData.nCategory;
aSourceElementsData.push(oSourceElementData);
}
if (bIsWhollyExaminable) { // Examine the whole scope.
fExamineSourceElements(
nAfterDirectivePrologue,
oSourceElements.length - 1,
false);
} else { // Examine unexcluded ranges of source elements.
for (nPosition = oSourceElements.length - 1;
nPosition >= nAfterDirectivePrologue;
nPosition -= 1) {
oSourceElementData = (/** @type {!TSourceElementsData} */
aSourceElementsData[nPosition]);
if (ESourceElementCategories.N_OTHER ===
oSourceElementData.nCategory) {
if ('undefined' === typeof nTo) {
nTo = nPosition; // Indicate the end of a range.
}
// Examine the range if it immediately follows a Directive Prologue.
if (nPosition === nAfterDirectivePrologue) {
fExamineSourceElements(nPosition, nTo, true);
}
} else {
if ('undefined' !== typeof nTo) {
// Examine the range that immediately follows this source element.
fExamineSourceElements(nPosition + 1, nTo, true);
nTo = void 0; // Obliterate the range.
}
// Examine nested functions.
oWalker = oProcessor.ast_walker();
oWalker.with_walkers(
oWalkers.oExamineFunctions,
cContext(oWalker, oSourceElements[nPosition]));
}
}
}
}(oAbstractSyntaxTree = oProcessor.ast_add_scope(oAbstractSyntaxTree)));
return oAbstractSyntaxTree;
};
/*jshint sub:false */
/* Local Variables: */
/* mode: js */
/* coding: utf-8 */
/* indent-tabs-mode: nil */
/* tab-width: 2 */
/* End: */
/* vim: set ft=javascript fenc=utf-8 et ts=2 sts=2 sw=2: */
/* :mode=javascript:noTabs=true:tabSize=2:indentSize=2:deepIndent=true: */
================================================
FILE: lib/parse-js.js
================================================
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
This version is suitable for Node.js. With minimal changes (the
exports stuff) it should work on any JS platform.
This file contains the tokenizer/parser. It is a port to JavaScript
of parse-js [1], a JavaScript parser library written in Common Lisp
by Marijn Haverbeke. Thank you Marijn!
[1] http://marijn.haverbeke.nl/parse-js/
Exported functions:
- tokenizer(code) -- returns a function. Call the returned
function to fetch the next token.
- parse(code) -- returns an AST of the given JavaScript code.
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
Based on parse-js (http://marijn.haverbeke.nl/parse-js/).
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.
***********************************************************************/
/* -----[ Tokenizer (constants) ]----- */
var KEYWORDS = array_to_hash([
"break",
"case",
"catch",
"const",
"continue",
"debugger",
"default",
"delete",
"do",
"else",
"finally",
"for",
"function",
"if",
"in",
"instanceof",
"new",
"return",
"switch",
"throw",
"try",
"typeof",
"var",
"void",
"while",
"with"
]);
var RESERVED_WORDS = array_to_hash([
"abstract",
"boolean",
"byte",
"char",
"class",
"double",
"enum",
"export",
"extends",
"final",
"float",
"goto",
"implements",
"import",
"int",
"interface",
"long",
"native",
"package",
"private",
"protected",
"public",
"short",
"static",
"super",
"synchronized",
"throws",
"transient",
"volatile"
]);
var KEYWORDS_BEFORE_EXPRESSION = array_to_hash([
"return",
"new",
"delete",
"throw",
"else",
"case"
]);
var KEYWORDS_ATOM = array_to_hash([
"false",
"null",
"true",
"undefined"
]);
var OPERATOR_CHARS = array_to_hash(characters("+-*&%=<>!?|~^"));
var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i;
var RE_OCT_NUMBER = /^0[0-7]+$/;
var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;
var OPERATORS = array_to_hash([
"in",
"instanceof",
"typeof",
"new",
"void",
"delete",
"++",
"--",
"+",
"-",
"!",
"~",
"&",
"|",
"^",
"*",
"/",
"%",
">>",
"<<",
">>>",
"<",
">",
"<=",
">=",
"==",
"===",
"!=",
"!==",
"?",
"=",
"+=",
"-=",
"/=",
"*=",
"%=",
">>=",
"<<=",
">>>=",
"|=",
"^=",
"&=",
"&&",
"||"
]);
var WHITESPACE_CHARS = array_to_hash(characters(" \u00a0\n\r\t\f\u000b\u200b\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\uFEFF"));
var PUNC_BEFORE_EXPRESSION = array_to_hash(characters("[{(,.;:"));
var PUNC_CHARS = array_to_hash(characters("[]{}(),;:"));
var REGEXP_MODIFIERS = array_to_hash(characters("gmsiy"));
/* -----[ Tokenizer ]----- */
var UNICODE = { // Unicode 6.1
letter: new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0527\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0\\u08A2-\\u08AC\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0977\\u0979-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F0\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA697\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA793\\uA7A0-\\uA7AA\\uA7F8-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA80-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]"),
combining_mark: new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065F\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0859-\\u085B\\u08E4-\\u08FE\\u0900-\\u0903\\u093A-\\u093C\\u093E-\\u094F\\u0951-\\u0957\\u0962\\u0963\\u0981-\\u0983\\u09BC\\u09BE-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CD\\u09D7\\u09E2\\u09E3\\u0A01-\\u0A03\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81-\\u0A83\\u0ABC\\u0ABE-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AE2\\u0AE3\\u0B01-\\u0B03\\u0B3C\\u0B3E-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B62\\u0B63\\u0B82\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD7\\u0C01-\\u0C03\\u0C3E-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0C82\\u0C83\\u0CBC\\u0CBE-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CE2\\u0CE3\\u0D02\\u0D03\\u0D3E-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4D\\u0D57\\u0D62\\u0D63\\u0D82\\u0D83\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F3E\\u0F3F\\u0F71-\\u0F84\\u0F86\\u0F87\\u0F8D-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102B-\\u103E\\u1056-\\u1059\\u105E-\\u1060\\u1062-\\u1064\\u1067-\\u106D\\u1071-\\u1074\\u1082-\\u108D\\u108F\\u109A-\\u109D\\u135D-\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B4-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u192B\\u1930-\\u193B\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A17-\\u1A1B\\u1A55-\\u1A5E\\u1A60-\\u1A7C\\u1A7F\\u1B00-\\u1B04\\u1B34-\\u1B44\\u1B6B-\\u1B73\\u1B80-\\u1B82\\u1BA1-\\u1BAD\\u1BE6-\\u1BF3\\u1C24-\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE8\\u1CED\\u1CF2-\\u1CF4\\u1DC0-\\u1DE6\\u1DFC-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2D7F\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA674-\\uA67D\\uA69F\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA823-\\uA827\\uA880\\uA881\\uA8B4-\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA953\\uA980-\\uA983\\uA9B3-\\uA9C0\\uAA29-\\uAA36\\uAA43\\uAA4C\\uAA4D\\uAA7B\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uAAEB-\\uAAEF\\uAAF5\\uAAF6\\uABE3-\\uABEA\\uABEC\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"),
connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]"),
digit: new RegExp("[\\u0030-\\u0039\\u0660-\\u0669\\u06F0-\\u06F9\\u07C0-\\u07C9\\u0966-\\u096F\\u09E6-\\u09EF\\u0A66-\\u0A6F\\u0AE6-\\u0AEF\\u0B66-\\u0B6F\\u0BE6-\\u0BEF\\u0C66-\\u0C6F\\u0CE6-\\u0CEF\\u0D66-\\u0D6F\\u0E50-\\u0E59\\u0ED0-\\u0ED9\\u0F20-\\u0F29\\u1040-\\u1049\\u1090-\\u1099\\u17E0-\\u17E9\\u1810-\\u1819\\u1946-\\u194F\\u19D0-\\u19D9\\u1A80-\\u1A89\\u1A90-\\u1A99\\u1B50-\\u1B59\\u1BB0-\\u1BB9\\u1C40-\\u1C49\\u1C50-\\u1C59\\uA620-\\uA629\\uA8D0-\\uA8D9\\uA900-\\uA909\\uA9D0-\\uA9D9\\uAA50-\\uAA59\\uABF0-\\uABF9\\uFF10-\\uFF19]")
};
function is_letter(ch) {
return UNICODE.letter.test(ch);
};
function is_digit(ch) {
ch = ch.charCodeAt(0);
return ch >= 48 && ch <= 57;
};
function is_unicode_digit(ch) {
return UNICODE.digit.test(ch);
}
function is_alphanumeric_char(ch) {
return is_digit(ch) || is_letter(ch);
};
function is_unicode_combining_mark(ch) {
return UNICODE.combining_mark.test(ch);
};
function is_unicode_connector_punctuation(ch) {
return UNICODE.connector_punctuation.test(ch);
};
function is_identifier_start(ch) {
return ch == "$" || ch == "_" || is_letter(ch);
};
function is_identifier_char(ch) {
return is_identifier_start(ch)
|| is_unicode_combining_mark(ch)
|| is_unicode_digit(ch)
|| is_unicode_connector_punctuation(ch)
|| ch == "\u200c" // zero-width non-joiner <ZWNJ>
|| ch == "\u200d" // zero-width joiner <ZWJ> (in my ECMA-262 PDF, this is also 200c)
;
};
function parse_js_number(num) {
if (RE_HEX_NUMBER.test(num)) {
return parseInt(num.substr(2), 16);
} else if (RE_OCT_NUMBER.test(num)) {
return parseInt(num.substr(1), 8);
} else if (RE_DEC_NUMBER.test(num)) {
return parseFloat(num);
}
};
function JS_Parse_Error(message, line, col, pos) {
this.message = message;
this.line = line + 1;
this.col = col + 1;
this.pos = pos + 1;
this.stack = new Error().stack;
};
JS_Parse_Error.prototype.toString = function() {
return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack;
};
function js_error(message, line, col, pos) {
throw new JS_Parse_Error(message, line, col, pos);
};
function is_token(token, type, val) {
return token.type == type && (val == null || token.value == val);
};
var EX_EOF = {};
function tokenizer($TEXT) {
var S = {
text : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, ''),
pos : 0,
tokpos : 0,
line : 0,
tokline : 0,
col : 0,
tokcol : 0,
newline_before : false,
regex_allowed : false,
comments_before : []
};
function peek() { return S.text.charAt(S.pos); };
function next(signal_eof, in_string) {
var ch = S.text.charAt(S.pos++);
if (signal_eof && !ch)
throw EX_EOF;
if (ch == "\n") {
S.newline_before = S.newline_before || !in_string;
++S.line;
S.col = 0;
} else {
++S.col;
}
return ch;
};
function eof() {
return !S.peek();
};
function find(what, signal_eof) {
var pos = S.text.indexOf(what, S.pos);
if (signal_eof && pos == -1) throw EX_EOF;
return pos;
};
function start_token() {
S.tokline = S.line;
S.tokcol = S.col;
S.tokpos = S.pos;
};
function token(type, value, is_comment) {
S.regex_allowed = ((type == "operator" && !HOP(UNARY_POSTFIX, value)) ||
(type == "keyword" && HOP(KEYWORDS_BEFORE_EXPRESSION, value)) ||
(type == "punc" && HOP(PUNC_BEFORE_EXPRESSION, value)));
var ret = {
type : type,
value : value,
line : S.tokline,
col : S.tokcol,
pos : S.tokpos,
endpos : S.pos,
nlb : S.newline_before
};
if (!is_comment) {
ret.comments_before = S.comments_before;
S.comments_before = [];
// make note of any newlines in the comments that came before
for (var i = 0, len = ret.comments_before.length; i < len; i++) {
ret.nlb = ret.nlb || ret.comments_before[i].nlb;
}
}
S.newline_before = false;
return ret;
};
function skip_whitespace() {
while (HOP(WHITESPACE_CHARS, peek()))
next();
};
function read_while(pred) {
var ret = "", ch = peek(), i = 0;
while (ch && pred(ch, i++)) {
ret += next();
ch = peek();
}
return ret;
};
function parse_error(err) {
js_error(err, S.tokline, S.tokcol, S.tokpos);
};
function read_num(prefix) {
var has_e = false, after_e = false, has_x = false, has_dot = prefix == ".";
var num = read_while(function(ch, i){
if (ch == "x" || ch == "X") {
if (has_x) return false;
return has_x = true;
}
if (!has_x && (ch == "E" || ch == "e")) {
if (has_e) return false;
return has_e = after_e = true;
}
if (ch == "-") {
if (after_e || (i == 0 && !prefix)) return true;
return false;
}
if (ch == "+") return after_e;
after_e = false;
if (ch == ".") {
if (!has_dot && !has_x && !has_e)
return has_dot = true;
return false;
}
return is_alphanumeric_char(ch);
});
if (prefix)
num = prefix + num;
var valid = parse_js_number(num);
if (!isNaN(valid)) {
return token("num", valid);
} else {
parse_error("Invalid syntax: " + num);
}
};
function read_escaped_char(in_string) {
var ch = next(true, in_string);
switch (ch) {
case "n" : return "\n";
case "r" : return "\r";
case "t" : return "\t";
case "b" : return "\b";
case "v" : return "\u000b";
case "f" : return "\f";
case "0" : return "\0";
case "x" : return String.fromCharCode(hex_bytes(2));
case "u" : return String.fromCharCode(hex_bytes(4));
case "\n": return "";
default : return ch;
}
};
function hex_bytes(n) {
var num = 0;
for (; n > 0; --n) {
var digit = parseInt(next(true), 16);
if (isNaN(digit))
parse_error("Invalid hex-character pattern in string");
num = (num << 4) | digit;
}
return num;
};
function read_string() {
return with_eof_error("Unterminated string constant", function(){
var quote = next(), ret = "";
for (;;) {
var ch = next(true);
if (ch == "\\") {
// read OctalEscapeSequence (XXX: deprecated if "strict mode")
// https://github.com/mishoo/UglifyJS/issues/178
var octal_len = 0, first = null;
ch = read_while(function(ch){
if (ch >= "0" && ch <= "7") {
if (!first) {
first = ch;
return ++octal_len;
}
else if (first <= "3" && octal_len <= 2) return ++octal_len;
else if (first >= "4" && octal_len <= 1) return ++octal_len;
}
return false;
});
if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8));
else ch = read_escaped_char(true);
}
else if (ch == quote) break;
else if (ch == "\n") throw EX_EOF;
ret += ch;
}
return token("string", ret);
});
};
function read_line_comment() {
next();
var i = find("\n"), ret;
if (i == -1) {
ret = S.text.substr(S.pos);
S.pos = S.text.length;
} else {
ret = S.text.substring(S.pos, i);
S.pos = i;
}
return token("comment1", ret, true);
};
function read_multiline_comment() {
next();
return with_eof_error("Unterminated multiline comment", function(){
var i = find("*/", true),
text = S.text.substring(S.pos, i);
S.pos = i + 2;
S.line += text.split("\n").length - 1;
S.newline_before = S.newline_before || text.indexOf("\n") >= 0;
// https://github.com/mishoo/UglifyJS/issues/#issue/100
if (/^@cc_on/i.test(text)) {
warn("WARNING: at line " + S.line);
warn("*** Found \"conditional comment\": " + text);
warn("*** UglifyJS DISCARDS ALL COMMENTS. This means your code might no longer work properly in Internet Explorer.");
}
return token("comment2", text, true);
});
};
function read_name() {
var backslash = false, name = "", ch, escaped = false, hex;
while ((ch = peek()) != null) {
if (!backslash) {
if (ch == "\\") escaped = backslash = true, next();
else if (is_identifier_char(ch)) name += next();
else break;
}
else {
if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX");
ch = read_escaped_char();
if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier");
name += ch;
backslash = false;
}
}
if (HOP(KEYWORDS, name) && escaped) {
hex = name.charCodeAt(0).toString(16).toUpperCase();
name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1);
}
return name;
};
function read_regexp(regexp) {
return with_eof_error("Unterminated regular expression", function(){
var prev_backslash = false, ch, in_class = false;
while ((ch = next(true))) if (prev_backslash) {
regexp += "\\" + ch;
prev_backslash = false;
} else if (ch == "[") {
in_class = true;
regexp += ch;
} else if (ch == "]" && in_class) {
in_class = false;
regexp += ch;
} else if (ch == "/" && !in_class) {
break;
} else if (ch == "\\") {
prev_backslash = true;
} else {
regexp += ch;
}
var mods = read_name();
return token("regexp", [ regexp, mods ]);
});
};
function read_operator(prefix) {
function grow(op) {
if (!peek()) return op;
var bigger = op + peek();
if (HOP(OPERATORS, bigger)) {
next();
return grow(bigger);
} else {
return op;
}
};
return token("operator", grow(prefix || next()));
};
function handle_slash() {
next();
var regex_allowed = S.regex_allowed;
switch (peek()) {
case "/":
S.comments_before.push(read_line_comment());
S.regex_allowed = regex_allowed;
return next_token();
case "*":
S.comments_before.push(read_multiline_comment());
S.regex_allowed = regex_allowed;
return next_token();
}
return S.regex_allowed ? read_regexp("") : read_operator("/");
};
function handle_dot() {
next();
return is_digit(peek())
? read_num(".")
: token("punc", ".");
};
function read_word() {
var word = read_name();
return !HOP(KEYWORDS, word)
? token("name", word)
: HOP(OPERATORS, word)
? token("operator", word)
: HOP(KEYWORDS_ATOM, word)
? token("atom", word)
: token("keyword", word);
};
function with_eof_error(eof_error, cont) {
try {
return cont();
} catch(ex) {
if (ex === EX_EOF) parse_error(eof_error);
else throw ex;
}
};
function next_token(force_regexp) {
if (force_regexp != null)
return read_regexp(force_regexp);
skip_whitespace();
start_token();
var ch = peek();
if (!ch) return token("eof");
if (is_digit(ch)) return read_num();
if (ch == '"' || ch == "'") return read_string();
if (HOP(PUNC_CHARS, ch)) return token("punc", next());
if (ch == ".") return handle_dot();
if (ch == "/") return handle_slash();
if (HOP(OPERATOR_CHARS, ch)) return read_operator();
if (ch == "\\" || is_identifier_start(ch)) 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 = array_to_hash([
"typeof",
"void",
"delete",
"--",
"++",
"!",
"~",
"-",
"+"
]);
var UNARY_POSTFIX = array_to_hash([ "--", "++" ]);
var ASSIGNMENT = (function(a, ret, i){
while (i < a.length) {
ret[a[i]] = a[i].substr(0, a[i].length - 1);
i++;
}
return ret;
})(
["+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&="],
{ "=": true },
0
);
var PRECEDENCE = (function(a, ret){
for (var i = 0, n = 1; i < a.length; ++i, ++n) {
var b = a[i];
for (var j = 0; j < b.length; ++j) {
ret[b[j]] = n;
}
}
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 NodeWithToken(str, start, end) {
this.name = str;
this.start = start;
this.end = end;
};
NodeWithToken.prototype.toString = function() { return this.name; };
function parse($TEXT, exigent_mode, embed_tokens) {
var S = {
input : typeof $TEXT == "string" ? tokenizer($TEXT, true) : $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,
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 + ", expected " + type);
};
function expect(punc) { return expect_token("punc", punc); };
function can_insert_semicolon() {
return !exigent_mode && (
S.token.nlb || is("eof") || is("punc", "}")
);
};
function semicolon() {
if (is("punc", ";")) next();
else if (!can_insert_semicolon()) unexpected();
};
function as() {
return slice(arguments);
};
function parenthesised() {
expect("(");
var ex = expression();
expect(")");
return ex;
};
function add_tokens(str, start, end) {
return str instanceof NodeWithToken ? str : new NodeWithToken(str, start, end);
};
function maybe_embed_tokens(parser) {
if (embed_tokens) return function() {
var start = S.token;
var ast = parser.apply(this, arguments);
ast[0] = add_tokens(ast[0], start, prev());
return ast;
};
else return parser;
};
var statement = maybe_embed_tokens(function() {
if (is("operator", "/") || is("operator", "/=")) {
S.peeked = null;
S.token = S.input(S.token.value.substr(1)); // force regexp
}
switch (S.token.type) {
case "string":
var dir = S.in_directives, stat = simple_statement();
if (dir && stat[1][0] == "string" && !is("punc", ","))
return as("directive", stat[1][1]);
return stat;
case "num":
case "regexp":
case "operator":
case "atom":
return simple_statement();
case "name":
return is_token(peek(), "punc", ":")
? labeled_statement(prog1(S.token.value, next, next))
: simple_statement();
case "punc":
switch (S.token.value) {
case "{":
return as("block", block_());
case "[":
case "(":
return simple_statement();
case ";":
next();
return as("block");
default:
unexpected();
}
case "keyword":
switch (prog1(S.token.value, next)) {
case "break":
return break_cont("break");
case "continue":
return break_cont("continue");
case "debugger":
semicolon();
return as("debugger");
case "do":
return (function(body){
expect_token("keyword", "while");
return as("do", prog1(parenthesised, semicolon), body);
})(in_loop(statement));
case "for":
return for_();
case "function":
return function_(true);
case "if":
return if_();
case "return":
if (S.in_function == 0)
croak("'return' outside of function");
return as("return",
is("punc", ";")
? (next(), null)
: can_insert_semicolon()
? null
: prog1(expression, semicolon));
case "switch":
return as("switch", parenthesised(), switch_block_());
case "throw":
if (S.token.nlb)
croak("Illegal newline after 'throw'");
return as("throw", prog1(expression, semicolon));
case "try":
return try_();
case "var":
return prog1(var_, semicolon);
case "const":
return prog1(const_, semicolon);
case "while":
return as("while", parenthesised(), in_loop(statement));
case "with":
return as("with", parenthesised(), statement());
default:
unexpected();
}
}
});
function labeled_statement(label) {
S.labels.push(label);
var start = S.token, stat = statement();
if (exigent_mode && !HOP(STATEMENTS_WITH_LABELS, stat[0]))
unexpected(start);
S.labels.pop();
return as("label", label, stat);
};
function simple_statement() {
return as("stat", prog1(expression, semicolon));
};
function break_cont(type) {
var name;
if (!can_insert_semicolon()) {
name = is("name") ? S.token.value : null;
}
if (name != null) {
next();
if (!member(name, S.labels))
croak("Label " + name + " without matching loop or statement");
}
else if (S.in_loop == 0)
croak(type + " not inside a loop or switch");
semicolon();
return as(type, name);
};
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[0] == "var" && init[1].length > 1)
croak("Only one variable declaration allowed in for..in loop");
return for_in(init);
}
}
return regular_for(init);
};
function regular_for(init) {
expect(";");
var test = is("punc", ";") ? null : expression();
expect(";");
var step = is("punc", ")") ? null : expression();
expect(")");
return as("for", init, test, step, in_loop(statement));
};
function for_in(init) {
var lhs = init[0] == "var" ? as("name", init[1][0]) : init;
next();
var obj = expression();
expect(")");
return as("for-in", init, lhs, obj, in_loop(statement));
};
var function_ = function(in_statement) {
var name = is("name") ? prog1(S.token.value, next) : null;
if (in_statement && !name)
unexpected();
expect("(");
return as(in_statement ? "defun" : "function",
name,
// arguments
(function(first, a){
while (!is("punc", ")")) {
if (first) first = false; else expect(",");
if (!is("name")) unexpected();
a.push(S.token.value);
next();
}
next();
return a;
})(true, []),
// body
(function(){
++S.in_function;
var loop = S.in_loop;
S.in_directives = true;
S.in_loop = 0;
var a = block_();
--S.in_function;
S.in_loop = loop;
return a;
})());
};
function if_() {
var cond = parenthesised(), body = statement(), belse;
if (is("keyword", "else")) {
next();
belse = statement();
}
return as("if", cond, body, belse);
};
function block_() {
expect("{");
var a = [];
while (!is("punc", "}")) {
if (is("eof")) unexpected();
a.push(statement());
}
next();
return a;
};
var switch_block_ = curry(in_loop, function(){
expect("{");
var a = [], cur = null;
while (!is("punc", "}")) {
if (is("eof")) unexpected();
if (is("keyword", "case")) {
next();
cur = [];
a.push([ expression(), cur ]);
expect(":");
}
else if (is("keyword", "default")) {
next();
expect(":");
cur = [];
a.push([ null, cur ]);
}
else {
if (!cur) unexpected();
cur.push(statement());
}
}
next();
return a;
});
function try_() {
var body = block_(), bcatch, bfinally;
if (is("keyword", "catch")) {
next();
expect("(");
if (!is("name"))
croak("Name expected");
var name = S.token.value;
next();
expect(")");
bcatch = [ name, block_() ];
}
if (is("keyword", "finally")) {
next();
bfinally = block_();
}
if (!bcatch && !bfinally)
croak("Missing catch/finally blocks");
return as("try", body, bcatch, bfinally);
};
function vardefs(no_in) {
var a = [];
for (;;) {
if (!is("name"))
unexpected();
var name = S.token.value;
next();
if (is("operator", "=")) {
next();
a.push([ name, expression(false, no_in) ]);
} else {
a.push([ name ]);
}
if (!is("punc", ","))
break;
next();
}
return a;
};
function var_(no_in) {
return as("var", vardefs(no_in));
};
function const_() {
return as("const", vardefs());
};
function new_() {
var newexp = expr_atom(false), args;
if (is("punc", "(")) {
next();
args = expr_list(")");
} else {
args = [];
}
return subscripts(as("new", newexp, args), true);
};
var expr_atom = maybe_embed_tokens(function(allow_calls) {
if (is("operator", "new")) {
next();
return new_();
}
if (is("punc")) {
switch (S.token.value) {
case "(":
next();
return subscripts(prog1(expression, curry(expect, ")")), allow_calls);
case "[":
next();
return subscripts(array_(), allow_calls);
case "{":
next();
return subscripts(object_(), allow_calls);
}
unexpected();
}
if (is("keyword", "function")) {
next();
return subscripts(function_(false), allow_calls);
}
if (HOP(ATOMIC_START_TOKEN, S.token.type)) {
var atom = S.token.type == "regexp"
? as("regexp", S.token.value[0], S.token.value[1])
: as(S.token.type, S.token.value);
return subscripts(prog1(atom, next), 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([ "atom", "undefined" ]);
} else {
a.push(expression(false));
}
}
next();
return a;
};
function array_() {
return as("array", expr_list("]", !exigent_mode, true));
};
function object_() {
var first = true, a = [];
while (!is("punc", "}")) {
if (first) first = false; else expect(",");
if (!exigent_mode && is("punc", "}"))
// allow trailing comma
break;
var type = S.token.type;
var name = as_property_name();
if (type == "name" && (name == "get" || name == "set") && !is("punc", ":")) {
a.push([ as_name(), function_(false), name ]);
} else {
expect(":");
a.push([ name, expression(false) ]);
}
}
next();
return as("object", a);
};
function as_property_name() {
switch (S.token.type) {
case "num":
case "string":
return prog1(S.token.value, next);
}
return as_name();
};
function as_name() {
switch (S.token.type) {
case "name":
case "operator":
case "keyword":
case "atom":
return prog1(S.token.value, next);
default:
unexpected();
}
};
function subscripts(expr, allow_calls) {
if (is("punc", ".")) {
next();
return subscripts(as("dot", expr, as_name()), allow_calls);
}
if (is("punc", "[")) {
next();
return subscripts(as("sub", expr, prog1(expression, curry(expect, "]"))), allow_calls);
}
if (allow_calls && is("punc", "(")) {
next();
return subscripts(as("call", expr, expr_list(")")), true);
}
return expr;
};
function maybe_unary(allow_calls) {
if (is("operator") && HOP(UNARY_PREFIX, S.token.value)) {
return make_unary("unary-prefix",
prog1(S.token.value, next),
maybe_unary(allow_calls));
}
var val = expr_atom(allow_calls);
while (is("operator") && HOP(UNARY_POSTFIX, S.token.value) && !S.token.nlb) {
val = make_unary("unary-postfix", S.token.value, val);
next();
}
return val;
};
function make_unary(tag, op, expr) {
if ((op == "++" || op == "--") && !is_assignable(expr))
croak("Invalid use of " + op + " operator");
return as(tag, op, expr);
};
function expr_op(left, min_prec, no_in) {
var op = is("operator") ? S.token.value : null;
if (op && 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(as("binary", op, left, right), min_prec, no_in);
}
return left;
};
function expr_ops(no_in) {
return expr_op(maybe_unary(true), 0, no_in);
};
function maybe_conditional(no_in) {
var expr = expr_ops(no_in);
if (is("operator", "?")) {
next();
var yes = expression(false);
expect(":");
return as("conditional", expr, yes, expression(false, no_in));
}
return expr;
};
function is_assignable(expr) {
if (!exigent_mode) return true;
switch (expr[0]+"") {
case "dot":
case "sub":
case "new":
case "call":
return true;
case "name":
return expr[1] != "this";
}
};
function maybe_assign(no_in) {
var left = maybe_conditional(no_in), val = S.token.value;
if (is("operator") && HOP(ASSIGNMENT, val)) {
if (is_assignable(left)) {
next();
return as("assign", ASSIGNMENT[val], left, maybe_assign(no_in));
}
croak("Invalid assignment");
}
return left;
};
var expression = maybe_embed_tokens(function(commas, no_in) {
if (arguments.length == 0)
commas = true;
var expr = maybe_assign(no_in);
if (commas && is("punc", ",")) {
next();
return as("seq", expr, expression(true, no_in));
}
return expr;
});
function in_loop(cont) {
try {
++S.in_loop;
return cont();
} finally {
--S.in_loop;
}
};
return as("toplevel", (function(a){
while (!is("eof"))
a.push(statement());
return a;
})([]));
};
/* -----[ Utilities ]----- */
function curry(f) {
var args = slice(arguments, 1);
return function() { return f.apply(this, args.concat(slice(arguments))); };
};
function prog1(ret) {
if (ret instanceof Function)
ret = ret();
for (var i = 1, n = arguments.length; --n > 0; ++i)
arguments[i]();
return ret;
};
function array_to_hash(a) {
var ret = {};
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 HOP(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
};
var warn = function() {};
/* -----[ Exports ]----- */
exports.tokenizer = tokenizer;
exports.parse = parse;
exports.slice = slice;
exports.curry = curry;
exports.member = member;
exports.array_to_hash = array_to_hash;
exports.PRECEDENCE = PRECEDENCE;
exports.KEYWORDS_ATOM = KEYWORDS_ATOM;
exports.RESERVED_WORDS = RESERVED_WORDS;
exports.KEYWORDS = KEYWORDS;
exports.ATOMIC_START_TOKEN = ATOMIC_START_TOKEN;
exports.OPERATORS = OPERATORS;
exports.is_alphanumeric_char = is_alphanumeric_char;
exports.is_identifier_start = is_identifier_start;
exports.is_identifier_char = is_identifier_char;
exports.set_logger = function(logger) {
warn = logger;
};
// Local variables:
// js-indent-level: 4
// End:
================================================
FILE: lib/process.js
================================================
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
This version is suitable for Node.js. With minimal changes (the
exports stuff) it should work on any JS platform.
This file implements some AST processors. They work on data built
by parse-js.
Exported functions:
- ast_mangle(ast, options) -- mangles the variable/function names
in the AST. Returns an AST.
- ast_squeeze(ast) -- employs various optimizations to make the
final generated code even smaller. Returns an AST.
- gen_code(ast, options) -- generates JS code from the AST. Pass
true (or an object, see the code for some options) as second
argument to get "pretty" (indented) code.
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
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.
***********************************************************************/
var jsp = require("./parse-js"),
curry = jsp.curry,
slice = jsp.slice,
member = jsp.member,
is_identifier_char = jsp.is_identifier_char,
PRECEDENCE = jsp.PRECEDENCE,
OPERATORS = jsp.OPERATORS;
/* -----[ helper for AST traversal ]----- */
function ast_walker() {
function _vardefs(defs) {
return [ this[0], MAP(defs, function(def){
var a = [ def[0] ];
if (def.length > 1)
a[1] = walk(def[1]);
return a;
}) ];
};
function _block(statements) {
var out = [ this[0] ];
if (statements != null)
out.push(MAP(statements, walk));
return out;
};
var walkers = {
"string": function(str) {
return [ this[0], str ];
},
"num": function(num) {
return [ this[0], num ];
},
"name": function(name) {
return [ this[0], name ];
},
"toplevel": function(statements) {
return [ this[0], MAP(statements, walk) ];
},
"block": _block,
"splice": _block,
"var": _vardefs,
"const": _vardefs,
"try": function(t, c, f) {
return [
this[0],
MAP(t, walk),
c != null ? [ c[0], MAP(c[1], walk) ] : null,
f != null ? MAP(f, walk) : null
];
},
"throw": function(expr) {
return [ this[0], walk(expr) ];
},
"new": function(ctor, args) {
return [ this[0], walk(ctor), MAP(args, walk) ];
},
"switch": function(expr, body) {
return [ this[0], walk(expr), MAP(body, function(branch){
return [ branch[0] ? walk(branch[0]) : null,
MAP(branch[1], walk) ];
}) ];
},
"break": function(label) {
return [ this[0], label ];
},
"continue": function(label) {
return [ this[0], label ];
},
"conditional": function(cond, t, e) {
return [ this[0], walk(cond), walk(t), walk(e) ];
},
"assign": function(op, lvalue, rvalue) {
return [ this[0], op, walk(lvalue), walk(rvalue) ];
},
"dot": function(expr) {
return [ this[0], walk(expr) ].concat(slice(arguments, 1));
},
"call": function(expr, args) {
return [ this[0], walk(expr), MAP(args, walk) ];
},
"function": function(name, args, body) {
return [ this[0], name, args.slice(), MAP(body, walk) ];
},
"debugger": function() {
return [ this[0] ];
},
"defun": function(name, args, body) {
return [ this[0], name, args.slice(), MAP(body, walk) ];
},
"if": function(conditional, t, e) {
return [ this[0], walk(conditional), walk(t), walk(e) ];
},
"for": function(init, cond, step, block) {
return [ this[0], walk(init), walk(cond), walk(step), walk(block) ];
},
"for-in": function(vvar, key, hash, block) {
return [ this[0], walk(vvar), walk(key), walk(hash), walk(block) ];
},
"while": function(cond, block) {
return [ this[0], walk(cond), walk(block) ];
},
"do": function(cond, block) {
return [ this[0], walk(cond), walk(block) ];
},
"return": function(expr) {
return [ this[0], walk(expr) ];
},
"binary": function(op, left, right) {
return [ this[0], op, walk(left), walk(right) ];
},
"unary-prefix": function(op, expr) {
return [ this[0], op, walk(expr) ];
},
"unary-postfix": function(op, expr) {
return [ this[0], op, walk(expr) ];
},
"sub": function(expr, subscript) {
return [ this[0], walk(expr), walk(subscript) ];
},
"object": function(props) {
return [ this[0], MAP(props, function(p){
return p.length == 2
? [ p[0], walk(p[1]) ]
: [ p[0], walk(p[1]), p[2] ]; // get/set-ter
}) ];
},
"regexp": function(rx, mods) {
return [ this[0], rx, mods ];
},
"array": function(elements) {
return [ this[0], MAP(elements, walk) ];
},
"stat": function(stat) {
return [ this[0], walk(stat) ];
},
"seq": function() {
return [ this[0] ].concat(MAP(slice(arguments), walk));
},
"label": function(name, block) {
return [ this[0], name, walk(block) ];
},
"with": function(expr, block) {
return [ this[0], walk(expr), walk(block) ];
},
"atom": function(name) {
return [ this[0], name ];
},
"directive": function(dir) {
return [ this[0], dir ];
}
};
var user = {};
var stack = [];
function walk(ast) {
if (ast == null)
return null;
try {
stack.push(ast);
var type = ast[0];
var gen = user[type];
if (gen) {
var ret = gen.apply(ast, ast.slice(1));
if (ret != null)
return ret;
}
gen = walkers[type];
return gen.apply(ast, ast.slice(1));
} finally {
stack.pop();
}
};
function dive(ast) {
if (ast == null)
return null;
try {
stack.push(ast);
return walkers[ast[0]].apply(ast, ast.slice(1));
} finally {
stack.pop();
}
};
function with_walkers(walkers, cont){
var save = {}, i;
for (i in walkers) if (HOP(walkers, i)) {
save[i] = user[i];
user[i] = walkers[i];
}
var ret = cont();
for (i in save) if (HOP(save, i)) {
if (!save[i]) delete user[i];
else user[i] = save[i];
}
return ret;
};
return {
walk: walk,
dive: dive,
with_walkers: with_walkers,
parent: function() {
return stack[stack.length - 2]; // last one is current node
},
stack: function() {
return stack;
}
};
};
/* -----[ Scope and mangling ]----- */
function Scope(parent) {
this.names = {}; // names defined in this scope
this.mangled = {}; // mangled names (orig.name => mangled)
this.rev_mangled = {}; // reverse lookup (mangled => orig.name)
this.cname = -1; // current mangled name
this.refs = {}; // names referenced from this scope
this.uses_with = false; // will become TRUE if with() is detected in this or any subscopes
this.uses_eval = false; // will become TRUE if eval() is detected in this or any subscopes
this.directives = []; // directives activated from this scope
this.parent = parent; // parent scope
this.children = []; // sub-scopes
if (parent) {
this.level = parent.level + 1;
parent.children.push(this);
} else {
this.level = 0;
}
};
function base54_digits() {
if (typeof DIGITS_OVERRIDE_FOR_TESTING != "undefined")
return DIGITS_OVERRIDE_FOR_TESTING;
else
return "etnrisouaflchpdvmgybwESxTNCkLAOM_DPHBjFIqRUzWXV$JKQGYZ0516372984";
}
var base54 = (function(){
var DIGITS = base54_digits();
return function(num) {
var ret = "", base = 54;
do {
ret += DIGITS.charAt(num % base);
num = Math.floor(num / base);
base = 64;
} while (num > 0);
return ret;
};
})();
Scope.prototype = {
has: function(name) {
for (var s = this; s; s = s.parent)
if (HOP(s.names, name))
return s;
},
has_mangled: function(mname) {
for (var s = this; s; s = s.parent)
if (HOP(s.rev_mangled, mname))
return s;
},
toJSON: function() {
return {
names: this.names,
uses_eval: this.uses_eval,
uses_with: this.uses_with
};
},
next_mangled: function() {
// we must be careful that the new mangled name:
//
// 1. doesn't shadow a mangled name from a parent
// scope, unless we don't reference the original
// name from this scope OR from any sub-scopes!
// This will get slow.
//
// 2. doesn't shadow an original name from a parent
// scope, in the event that the name is not mangled
// in the parent scope and we reference that name
// here OR IN ANY SUBSCOPES!
//
// 3. doesn't shadow a name that is referenced but not
// defined (possibly global defined elsewhere).
for (;;) {
var m = base54(++this.cname), prior;
// case 1.
prior = this.has_mangled(m);
if (prior && this.refs[prior.rev_mangled[m]] === prior)
continue;
// case 2.
prior = this.has(m);
if (prior && prior !== this && this.refs[m] === prior && !prior.has_mangled(m))
continue;
// case 3.
if (HOP(this.refs, m) && this.refs[m] == null)
continue;
// I got "do" once. :-/
if (!is_identifier(m))
continue;
return m;
}
},
set_mangle: function(name, m) {
this.rev_mangled[m] = name;
return this.mangled[name] = m;
},
get_mangled: function(name, newMangle) {
if (this.uses_eval || this.uses_with) return name; // no mangle if eval or with is in use
var s = this.has(name);
if (!s) return name; // not in visible scope, no mangle
if (HOP(s.mangled, name)) return s.mangled[name]; // already mangled in this scope
if (!newMangle) return name; // not found and no mangling requested
return s.set_mangle(name, s.next_mangled());
},
references: function(name) {
return name && !this.parent || this.uses_with || this.uses_eval || this.refs[name];
},
define: function(name, type) {
if (name != null) {
if (type == "var" || !HOP(this.names, name))
this.names[name] = type || "var";
return name;
}
},
active_directive: function(dir) {
return member(dir, this.directives) || this.parent && this.parent.active_directive(dir);
}
};
function ast_add_scope(ast) {
var current_scope = null;
var w = ast_walker(), walk = w.walk;
var having_eval = [];
function with_new_scope(cont) {
current_scope = new Scope(current_scope);
current_scope.labels = new Scope();
var ret = current_scope.body = cont();
ret.scope = current_scope;
current_scope = current_scope.parent;
return ret;
};
function define(name, type) {
return current_scope.define(name, type);
};
function reference(name) {
current_scope.refs[name] = true;
};
function _lambda(name, args, body) {
var is_defun = this[0] == "defun";
return [ this[0], is_defun ? define(name, "defun") : name, args, with_new_scope(function(){
if (!is_defun) define(name, "lambda");
MAP(args, function(name){ define(name, "arg") });
return MAP(body, walk);
})];
};
function _vardefs(type) {
return function(defs) {
MAP(defs, function(d){
define(d[0], type);
if (d[1]) reference(d[0]);
});
};
};
function _breacont(label) {
if (label)
current_scope.labels.refs[label] = true;
};
return with_new_scope(function(){
// process AST
var ret = w.with_walkers({
"function": _lambda,
"defun": _lambda,
"label": function(name, stat) { current_scope.labels.define(name) },
"break": _breacont,
"continue": _breacont,
"with": function(expr, block) {
for (var s = current_scope; s; s = s.parent)
s.uses_with = true;
},
"var": _vardefs("var"),
"const": _vardefs("const"),
"try": function(t, c, f) {
if (c != null) return [
this[0],
MAP(t, walk),
[ define(c[0], "catch"), MAP(c[1], walk) ],
f != null ? MAP(f, walk) : null
];
},
"name": function(name) {
if (name == "eval")
having_eval.push(current_scope);
reference(name);
}
}, function(){
return walk(ast);
});
// the reason why we need an additional pass here is
// that names can be used prior to their definition.
// scopes where eval was detected and their parents
// are marked with uses_eval, unless they define the
// "eval" name.
MAP(having_eval, function(scope){
if (!scope.has("eval")) while (scope) {
scope.uses_eval = true;
scope = scope.parent;
}
});
// for referenced names it might be useful to know
// their origin scope. current_scope here is the
// toplevel one.
function fixrefs(scope, i) {
// do children first; order shouldn't matter
for (i = scope.children.length; --i >= 0;)
fixrefs(scope.children[i]);
for (i in scope.refs) if (HOP(scope.refs, i)) {
// find origin scope and propagate the reference to origin
for (var origin = scope.has(i), s = scope; s; s = s.parent) {
s.refs[i] = origin;
if (s === origin) break;
}
}
};
fixrefs(current_scope);
return ret;
});
};
/* -----[ mangle names ]----- */
function ast_mangle(ast, options) {
var w = ast_walker(), walk = w.walk, scope;
options = defaults(options, {
mangle : true,
toplevel : false,
defines : null,
except : null,
no_functions : false
});
function get_mangled(name, newMangle) {
if (!options.mangle) return name;
if (!options.toplevel && !scope.parent) return name; // don't mangle toplevel
if (options.except && member(name, options.except))
return name;
if (options.no_functions && HOP(scope.names, name) &&
(scope.names[name] == 'defun' || scope.names[name] == 'lambda'))
return name;
return scope.get_mangled(name, newMangle);
};
function get_define(name) {
if (options.defines) {
// we always lookup a defined symbol for the current scope FIRST, so declared
// vars trump a DEFINE symbol, but if no such var is found, then match a DEFINE value
if (!scope.has(name)) {
if (HOP(options.defines, name)) {
return options.defines[name];
}
}
return null;
}
};
function _lambda(name, args, body) {
if (!options.no_functions && options.mangle) {
var is_defun = this[0] == "defun", extra;
if (name) {
if (is_defun) name = get_mangled(name);
else if (body.scope.references(name)) {
extra = {};
if (!(scope.uses_eval || scope.uses_with))
name = extra[name] = scope.next_mangled();
else
extra[name] = name;
}
else name = null;
}
}
body = with_scope(body.scope, function(){
args = MAP(args, function(name){ return get_mangled(name) });
return MAP(body, walk);
}, extra);
return [ this[0], name, args, body ];
};
function with_scope(s, cont, extra) {
var _scope = scope;
scope = s;
if (extra) for (var i in extra) if (HOP(extra, i)) {
s.set_mangle(i, extra[i]);
}
for (var i in s.names) if (HOP(s.names, i)) {
get_mangled(i, true);
}
var ret = cont();
ret.scope = s;
scope = _scope;
return ret;
};
function _vardefs(defs) {
return [ this[0], MAP(defs, function(d){
return [ get_mangled(d[0]), walk(d[1]) ];
}) ];
};
function _breacont(label) {
if (label)
gitextract_mr1693vq/ ├── .gitignore ├── README.html ├── README.org ├── bin/ │ └── uglifyjs ├── docstyle.css ├── lib/ │ ├── consolidator.js │ ├── parse-js.js │ ├── process.js │ └── squeeze-more.js ├── package.json ├── test/ │ ├── beautify.js │ ├── testconsolidator.js │ ├── testparser.js │ └── unit/ │ ├── compress/ │ │ ├── expected/ │ │ │ ├── 1e21.js │ │ │ ├── array1.js │ │ │ ├── array2.js │ │ │ ├── array3.js │ │ │ ├── array4.js │ │ │ ├── assignment.js │ │ │ ├── concatstring.js │ │ │ ├── const.js │ │ │ ├── div-with-regexp.js │ │ │ ├── empty-blocks.js │ │ │ ├── forstatement.js │ │ │ ├── if-not.js │ │ │ ├── if.js │ │ │ ├── ifreturn.js │ │ │ ├── ifreturn2.js │ │ │ ├── infinite.js │ │ │ ├── issue10.js │ │ │ ├── issue11.js │ │ │ ├── issue13.js │ │ │ ├── issue14.js │ │ │ ├── issue16.js │ │ │ ├── issue17.js │ │ │ ├── issue20.js │ │ │ ├── issue21.js │ │ │ ├── issue25.js │ │ │ ├── issue27.js │ │ │ ├── issue278.js │ │ │ ├── issue28.js │ │ │ ├── issue29.js │ │ │ ├── issue30.js │ │ │ ├── issue34.js │ │ │ ├── issue349.js │ │ │ ├── issue353.js │ │ │ ├── issue372.js │ │ │ ├── issue4.js │ │ │ ├── issue471.js │ │ │ ├── issue48.js │ │ │ ├── issue50.js │ │ │ ├── issue53.js │ │ │ ├── issue54.1.js │ │ │ ├── issue68.js │ │ │ ├── issue69.js │ │ │ ├── issue9.js │ │ │ ├── issues222_324.js │ │ │ ├── mangle.js │ │ │ ├── null_string.js │ │ │ ├── strict-equals.js │ │ │ ├── var.js │ │ │ ├── whitespace.js │ │ │ └── with.js │ │ └── test/ │ │ ├── 1e21.js │ │ ├── array1.js │ │ ├── array2.js │ │ ├── array3.js │ │ ├── array4.js │ │ ├── assignment.js │ │ ├── concatstring.js │ │ ├── const.js │ │ ├── div-with-regexp.js │ │ ├── empty-blocks.js │ │ ├── forstatement.js │ │ ├── if-not.js │ │ ├── if.js │ │ ├── ifreturn.js │ │ ├── ifreturn2.js │ │ ├── infinite.js │ │ ├── issue10.js │ │ ├── issue11.js │ │ ├── issue13.js │ │ ├── issue14.js │ │ ├── issue16.js │ │ ├── issue17.js │ │ ├── issue20.js │ │ ├── issue21.js │ │ ├── issue25.js │ │ ├── issue27.js │ │ ├── issue278.js │ │ ├── issue28.js │ │ ├── issue29.js │ │ ├── issue30.js │ │ ├── issue34.js │ │ ├── issue349.js │ │ ├── issue353.js │ │ ├── issue372.js │ │ ├── issue4.js │ │ ├── issue471.js │ │ ├── issue48.js │ │ ├── issue50.js │ │ ├── issue53.js │ │ ├── issue54.1.js │ │ ├── issue68.js │ │ ├── issue69.js │ │ ├── issue9.js │ │ ├── issues222_324.js │ │ ├── mangle.js │ │ ├── null_string.js │ │ ├── strict-equals.js │ │ ├── var.js │ │ ├── whitespace.js │ │ └── with.js │ └── scripts.js ├── tmp/ │ ├── hoist.js │ ├── instrument.js │ └── test.js └── uglify-js.js
SYMBOL INDEX (93 symbols across 33 files)
FILE: lib/parse-js.js
function is_letter (line 209) | function is_letter(ch) {
function is_digit (line 213) | function is_digit(ch) {
function is_unicode_digit (line 218) | function is_unicode_digit(ch) {
function is_alphanumeric_char (line 222) | function is_alphanumeric_char(ch) {
function is_unicode_combining_mark (line 226) | function is_unicode_combining_mark(ch) {
function is_unicode_connector_punctuation (line 230) | function is_unicode_connector_punctuation(ch) {
function is_identifier_start (line 234) | function is_identifier_start(ch) {
function is_identifier_char (line 238) | function is_identifier_char(ch) {
function parse_js_number (line 248) | function parse_js_number(num) {
function JS_Parse_Error (line 258) | function JS_Parse_Error(message, line, col, pos) {
function js_error (line 270) | function js_error(message, line, col, pos) {
function is_token (line 274) | function is_token(token, type, val) {
function tokenizer (line 280) | function tokenizer($TEXT) {
function NodeWithToken (line 684) | function NodeWithToken(str, start, end) {
function parse (line 692) | function parse($TEXT, exigent_mode, embed_tokens) {
function curry (line 1305) | function curry(f) {
function prog1 (line 1310) | function prog1(ret) {
function array_to_hash (line 1318) | function array_to_hash(a) {
function slice (line 1325) | function slice(a, start) {
function characters (line 1329) | function characters(str) {
function member (line 1333) | function member(name, array) {
function HOP (line 1340) | function HOP(obj, prop) {
FILE: lib/process.js
function ast_walker (line 71) | function ast_walker() {
function Scope (line 274) | function Scope(parent) {
function base54_digits (line 293) | function base54_digits() {
function ast_add_scope (line 398) | function ast_add_scope(ast) {
function ast_mangle (line 512) | function ast_mangle(ast, options) {
function best_of (line 655) | function best_of(ast1, ast2) {
function last_stat (line 659) | function last_stat(b) {
function aborts (line 665) | function aborts(t) {
function boolean_expr (line 675) | function boolean_expr(expr) {
function empty (line 700) | function empty(b) {
function is_string (line 704) | function is_string(node) {
function evaluate (line 717) | function evaluate(expr) {
function warn_unreachable (line 810) | function warn_unreachable(ast) {
function prepare_ifs (line 815) | function prepare_ifs(ast) {
function for_side_effects (line 892) | function for_side_effects(ast, handler) {
function ast_lift_variables (line 938) | function ast_lift_variables(ast) {
function ast_squeeze (line 1030) | function ast_squeeze(ast, options) {
function squeeze_1 (line 1036) | function squeeze_1(ast, options) {
function squeeze_2 (line 1421) | function squeeze_2(ast, options) {
function make_string (line 1463) | function make_string(str, ascii_only) {
function to_ascii (line 1485) | function to_ascii(str) {
function gen_code (line 1495) | function gen_code(ast, options) {
function split_lines (line 1989) | function split_lines(code, max_line_length) {
function repeat_string (line 2034) | function repeat_string(str, i) {
function defaults (line 2043) | function defaults(args, defs) {
function is_identifier (line 2053) | function is_identifier(name) {
function HOP (line 2061) | function HOP(obj, prop) {
function doit (line 2072) | function doit() {
function AtTop (line 2097) | function AtTop(val) { this.v = val }
function Splice (line 2098) | function Splice(val) { this.v = val }
FILE: lib/squeeze-more.js
function ast_squeeze_more (line 10) | function ast_squeeze_more(ast) {
FILE: test/beautify.js
function time_it (line 24) | function time_it(name, cont) {
FILE: test/testparser.js
function ParserTestSuite (line 26) | function ParserTestSuite(callback){
FILE: test/unit/compress/expected/array3.js
function a (line 1) | function a(){}
FILE: test/unit/compress/expected/array4.js
function a (line 1) | function a(){}
FILE: test/unit/compress/expected/empty-blocks.js
function bar (line 1) | function bar(){return--x}
function foo (line 1) | function foo(){while(bar());}
function mak (line 1) | function mak(){for(;;);}
FILE: test/unit/compress/expected/ifreturn.js
function a (line 1) | function a(a){return a==1?2:17}
FILE: test/unit/compress/expected/ifreturn2.js
function x (line 1) | function x(a){return typeof a=="object"?a:a===42?0:a*2}
function y (line 1) | function y(a){return typeof a=="object"?a:null}
FILE: test/unit/compress/expected/infinite.js
method NaN (line 1) | get NaN(){throw 0}
method Infinity (line 1) | get Infinity(){throw 0}
FILE: test/unit/compress/expected/issue10.js
function f (line 1) | function f(){var a;return(a="a")?a:a}
FILE: test/unit/compress/expected/issue353.js
function test (line 1) | function test(){debugger;return}
FILE: test/unit/compress/expected/issue372.js
function a (line 1) | function a(){function a(){function a(){void "c"}function b(){"salmon";vo...
FILE: test/unit/compress/expected/issue50.js
function bar (line 1) | function bar(a){try{foo()}catch(b){alert("Exception caught (foo not defi...
FILE: test/unit/compress/expected/issue68.js
function f (line 1) | function f(){function b(){}if(a)return;b()}
FILE: test/unit/compress/expected/whitespace.js
function id (line 1) | function id(a){return a}
FILE: test/unit/compress/test/array3.js
function Array (line 3) | function Array() {}
FILE: test/unit/compress/test/array4.js
function Array (line 5) | function Array(){}
FILE: test/unit/compress/test/empty-blocks.js
function bar (line 2) | function bar() { return --x; }
function foo (line 3) | function foo() { while (bar()); }
function mak (line 4) | function mak() { for(;;); }
FILE: test/unit/compress/test/ifreturn.js
function a (line 1) | function a(b) {
FILE: test/unit/compress/test/ifreturn2.js
function x (line 1) | function x(a) {
function y (line 11) | function y(a) {
FILE: test/unit/compress/test/infinite.js
method NaN (line 1) | get NaN(){throw 0}
method Infinity (line 1) | get Infinity(){throw 0}
FILE: test/unit/compress/test/issue10.js
function f (line 1) | function f() { var a; if (a = 'a') { return a; } else { return a; } }
FILE: test/unit/compress/test/issue353.js
function test (line 1) | function test() {
FILE: test/unit/compress/test/issue372.js
function a (line 4) | function a() {
FILE: test/unit/compress/test/issue50.js
function bar (line 1) | function bar(a) {
FILE: test/unit/compress/test/issue68.js
function f (line 1) | function f() {
FILE: test/unit/compress/test/whitespace.js
function id (line 1) | function id(a) {
FILE: test/unit/scripts.js
function compress (line 14) | function compress(code) {
function getTester (line 25) | function getTester(script) {
FILE: tmp/hoist.js
function foo (line 1) | function foo(arg1, arg2, arg3, arg4, arg5, arg6) {
FILE: tmp/instrument.js
function instrument (line 6) | function instrument(code) {
function test (line 67) | function test() {
FILE: uglify-js.js
function uglify (line 2) | function uglify(orig_code, options){
Condensed preview — 118 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (359K chars).
[
{
"path": ".gitignore",
"chars": 63,
"preview": ".DS_Store\n.tmp*~\n*.local.*\n.pinf-*\nnode_modules/\nnpm-debug.log\n"
},
{
"path": "README.html",
"chars": 40977,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n \"http://w"
},
{
"path": "README.org",
"chars": 24984,
"preview": "#+TITLE: UglifyJS -- a JavaScript parser/compressor/beautifier\n#+KEYWORDS: javascript, js, parser, compiler, compressor,"
},
{
"path": "bin/uglifyjs",
"chars": 10307,
"preview": "#!/usr/bin/env node\n// -*- js -*-\n\nglobal.sys = require(/^v0\\.[012]/.test(process.version) ? \"sys\" : \"util\");\nvar fs = r"
},
{
"path": "docstyle.css",
"chars": 1889,
"preview": "html { font-family: \"Lucida Grande\",\"Trebuchet MS\",sans-serif; font-size: 12pt; }\nbody { max-width: 60em; }\n.title { te"
},
{
"path": "lib/consolidator.js",
"chars": 55067,
"preview": "/**\n * @preserve Copyright 2012 Robert Gust-Bardon <http://robert.gust-bardon.org/>.\n * All rights reserved.\n *\n * Redis"
},
{
"path": "lib/parse-js.js",
"chars": 46288,
"preview": "/***********************************************************************\n\n A JavaScript tokenizer / parser / beautifier"
},
{
"path": "lib/process.js",
"chars": 74665,
"preview": "/***********************************************************************\n\n A JavaScript tokenizer / parser / beautifier"
},
{
"path": "lib/squeeze-more.js",
"chars": 2940,
"preview": "var jsp = require(\"./parse-js\"),\n pro = require(\"./process\"),\n slice = jsp.slice,\n member = jsp.member,\n cur"
},
{
"path": "package.json",
"chars": 836,
"preview": "{\n \"name\" : \"uglify-js\",\n\n \"description\" : \"JavaScript parser and compressor/beautifier toolkit\",\n\n "
},
{
"path": "test/beautify.js",
"chars": 1009,
"preview": "#! /usr/bin/env node\n\nglobal.sys = require(\"sys\");\nvar fs = require(\"fs\");\n\nvar jsp = require(\"../lib/parse-js\");\nvar pr"
},
{
"path": "test/testconsolidator.js",
"chars": 42576,
"preview": "#! /usr/bin/env node\nglobal.DIGITS_OVERRIDE_FOR_TESTING = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456"
},
{
"path": "test/testparser.js",
"chars": 15920,
"preview": "#! /usr/bin/env node\nglobal.DIGITS_OVERRIDE_FOR_TESTING = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456"
},
{
"path": "test/unit/compress/expected/1e21.js",
"chars": 9,
"preview": "1e20,1e21"
},
{
"path": "test/unit/compress/expected/array1.js",
"chars": 20,
"preview": "[],Array(1),[1,2,3]\n"
},
{
"path": "test/unit/compress/expected/array2.js",
"chars": 57,
"preview": "(function(){var a=function(){};return new a(1,2,3,4)})()\n"
},
{
"path": "test/unit/compress/expected/array3.js",
"chars": 52,
"preview": "(function(){function a(){}return new a(1,2,3,4)})()\n"
},
{
"path": "test/unit/compress/expected/array4.js",
"chars": 66,
"preview": "(function(){function a(){}(function(){return new a(1,2,3)})()})()\n"
},
{
"path": "test/unit/compress/expected/assignment.js",
"chars": 102,
"preview": "a=1,b=a,c=1,d=b,e=d,longname=2;if(longname+1){x=3;if(x)var z=7}z=1,y=1,x=1,g+=1,h=g,++i,j=i,i++,j=i+17"
},
{
"path": "test/unit/compress/expected/concatstring.js",
"chars": 59,
"preview": "var a=a+\"a\"+\"b\"+1+c,b=a+\"c\"+\"ds\"+123+c,c=a+\"c\"+123+d+\"ds\"+c"
},
{
"path": "test/unit/compress/expected/const.js",
"chars": 14,
"preview": "var a=13,b=1/3"
},
{
"path": "test/unit/compress/expected/div-with-regexp.js",
"chars": 18,
"preview": "print(a/ /[a-z]/)\n"
},
{
"path": "test/unit/compress/expected/empty-blocks.js",
"chars": 86,
"preview": "function bar(){return--x}function foo(){while(bar());}function mak(){for(;;);}var x=5\n"
},
{
"path": "test/unit/compress/expected/forstatement.js",
"chars": 111,
"preview": "a=func(),b=z;for(a++;i<10;i++)alert(i);var z=1;g=2;for(;i<10;i++)alert(i);var a=2;for(var i=1;i<10;i++)alert(i)"
},
{
"path": "test/unit/compress/expected/if-not.js",
"chars": 3,
"preview": "_,_"
},
{
"path": "test/unit/compress/expected/if.js",
"chars": 21,
"preview": "var a=1;a==1?a=2:a=17"
},
{
"path": "test/unit/compress/expected/ifreturn.js",
"chars": 31,
"preview": "function a(a){return a==1?2:17}"
},
{
"path": "test/unit/compress/expected/ifreturn2.js",
"chars": 103,
"preview": "function x(a){return typeof a==\"object\"?a:a===42?0:a*2}function y(a){return typeof a==\"object\"?a:null}\n"
},
{
"path": "test/unit/compress/expected/infinite.js",
"chars": 66,
"preview": "with({get NaN(){throw 0},get Infinity(){throw 0}})0/0,0/0,1/0,-1/0"
},
{
"path": "test/unit/compress/expected/issue10.js",
"chars": 40,
"preview": "function f(){var a;return(a=\"a\")?a:a}f()"
},
{
"path": "test/unit/compress/expected/issue11.js",
"chars": 29,
"preview": "new(A,B),new(A||B),new(X?A:B)"
},
{
"path": "test/unit/compress/expected/issue13.js",
"chars": 132,
"preview": "var a=/^(?:(\\w+):)?(?:\\/\\/(?:(?:([^:@\\/]*):?([^:@\\/]*))?@)?([^:\\/?#])(?::(\\d))?)?(..?$|(?:[^?#\\/]\\/))([^?#]*)(?:\\?([^#])"
},
{
"path": "test/unit/compress/expected/issue14.js",
"chars": 84,
"preview": "var a={\"\\b\":\"\\\\b\",\"\t\":\"\\\\t\",\"\\n\":\"\\\\n\",\"\\f\":\"\\\\f\",\"\\r\":\"\\\\r\",'\"':'\\\\\"',\"\\\\\":\"\\\\\\\\\"}\n"
},
{
"path": "test/unit/compress/expected/issue16.js",
"chars": 16,
"preview": "var a=3250441966"
},
{
"path": "test/unit/compress/expected/issue17.js",
"chars": 26,
"preview": "var a=function(b){b(),a()}"
},
{
"path": "test/unit/compress/expected/issue20.js",
"chars": 2,
"preview": "1\n"
},
{
"path": "test/unit/compress/expected/issue21.js",
"chars": 29,
"preview": "var a=0;switch(a){case 0:a++}"
},
{
"path": "test/unit/compress/expected/issue25.js",
"chars": 25,
"preview": "a:break a;console.log(1)\n"
},
{
"path": "test/unit/compress/expected/issue27.js",
"chars": 11,
"preview": "(a?b:c)?d:e"
},
{
"path": "test/unit/compress/expected/issue278.js",
"chars": 15,
"preview": "if(!x)debugger\n"
},
{
"path": "test/unit/compress/expected/issue28.js",
"chars": 31,
"preview": "o={\".5\":.5},o={.5:.5},o={.5:.5}"
},
{
"path": "test/unit/compress/expected/issue29.js",
"chars": 29,
"preview": "result=function(){return 1}()"
},
{
"path": "test/unit/compress/expected/issue30.js",
"chars": 15,
"preview": "var a=8,b=4,c=4"
},
{
"path": "test/unit/compress/expected/issue34.js",
"chars": 29,
"preview": "var a={};a[\"this\"]=1,a.that=2"
},
{
"path": "test/unit/compress/expected/issue349.js",
"chars": 202,
"preview": "(function(){var a;if(noFreeCakes)return;return a=new FreeCake,a})()(function(){var a;if(noFreeCakes)return;return a=new "
},
{
"path": "test/unit/compress/expected/issue353.js",
"chars": 33,
"preview": "function test(){debugger;return}\n"
},
{
"path": "test/unit/compress/expected/issue372.js",
"chars": 214,
"preview": "\"use strict\";function a(){function a(){function a(){void \"c\"}function b(){\"salmon\";void \"d\"}void \"b\"}function b(){\"salmo"
},
{
"path": "test/unit/compress/expected/issue4.js",
"chars": 23,
"preview": "var a=2e3,b=.002,c=2e-5"
},
{
"path": "test/unit/compress/expected/issue471.js",
"chars": 14,
"preview": "((a||b)&&c)()\n"
},
{
"path": "test/unit/compress/expected/issue48.js",
"chars": 16,
"preview": "var s,i;s=\"\",i=0"
},
{
"path": "test/unit/compress/expected/issue50.js",
"chars": 96,
"preview": "function bar(a){try{foo()}catch(b){alert(\"Exception caught (foo not defined)\")}alert(a)}bar(10)\n"
},
{
"path": "test/unit/compress/expected/issue53.js",
"chars": 8,
"preview": "x=(y,z)\n"
},
{
"path": "test/unit/compress/expected/issue54.1.js",
"chars": 41,
"preview": "foo+\"\",a.toString(16),b.toString.call(c)\n"
},
{
"path": "test/unit/compress/expected/issue68.js",
"chars": 44,
"preview": "function f(){function b(){}if(a)return;b()}\n"
},
{
"path": "test/unit/compress/expected/issue69.js",
"chars": 8,
"preview": "[(a,b)]\n"
},
{
"path": "test/unit/compress/expected/issue9.js",
"chars": 15,
"preview": "var a={a:1,b:2}"
},
{
"path": "test/unit/compress/expected/issues222_324.js",
"chars": 244,
"preview": "!(function(){\"use strict\";var a,b,c}),!function(){\"use strict\";var a,b},!function(){\"use strict\";var a,b,c,d,e,f,g,h,i,j"
},
{
"path": "test/unit/compress/expected/mangle.js",
"chars": 50,
"preview": "(function(){var a=function b(a,b,c){return b}})()\n"
},
{
"path": "test/unit/compress/expected/null_string.js",
"chars": 19,
"preview": "var nullString=\"\\0\""
},
{
"path": "test/unit/compress/expected/strict-equals.js",
"chars": 38,
"preview": "typeof a==\"string\",b+\"\"!=c+\"\",d<e==f<g"
},
{
"path": "test/unit/compress/expected/var.js",
"chars": 11,
"preview": "var a=1,b=2"
},
{
"path": "test/unit/compress/expected/whitespace.js",
"chars": 25,
"preview": "function id(a){return a}\n"
},
{
"path": "test/unit/compress/expected/with.js",
"chars": 10,
"preview": "with({});\n"
},
{
"path": "test/unit/compress/test/1e21.js",
"chars": 9,
"preview": "1e20,1e21"
},
{
"path": "test/unit/compress/test/array1.js",
"chars": 47,
"preview": "new Array();\nnew Array(1);\nnew Array(1, 2, 3);\n"
},
{
"path": "test/unit/compress/test/array2.js",
"chars": 91,
"preview": "(function(){\n var Array = function(){};\n return new Array(1, 2, 3, 4);\n})();\n"
},
{
"path": "test/unit/compress/test/array3.js",
"chars": 86,
"preview": "(function(){\n return new Array(1, 2, 3, 4);\n function Array() {};\n})();\n"
},
{
"path": "test/unit/compress/test/array4.js",
"chars": 125,
"preview": "(function(){\n (function(){\n return new Array(1, 2, 3);\n })();\n function Array(){};\n}"
},
{
"path": "test/unit/compress/test/assignment.js",
"chars": 136,
"preview": "a=1;\nb=a;\nc=1;\nd=b;\ne=d;\nlongname=2;\nif (longname+1) {\n x=3;\n if (x) var z = 7;\n}\nz=1,y=1,x=1\n\ng+=1;\nh=g;\n\n++i;\nj="
},
{
"path": "test/unit/compress/test/concatstring.js",
"chars": 102,
"preview": "var a = a + \"a\" + \"b\" + 1 + c;\nvar b = a + \"c\" + \"ds\" + 123 + c;\nvar c = a + \"c\" + 123 + d + \"ds\" + c;"
},
{
"path": "test/unit/compress/test/const.js",
"chars": 154,
"preview": "// test that the calculation is fold to 13\r\nvar a = 1 + 2 * 6;\r\n\r\n// test that it isn't replaced with 0.3333 because tha"
},
{
"path": "test/unit/compress/test/div-with-regexp.js",
"chars": 20,
"preview": "print(a / /[a-z]/);\n"
},
{
"path": "test/unit/compress/test/empty-blocks.js",
"chars": 104,
"preview": "var x = 5;\nfunction bar() { return --x; }\nfunction foo() { while (bar()); }\nfunction mak() { for(;;); }\n"
},
{
"path": "test/unit/compress/test/forstatement.js",
"chars": 156,
"preview": "a=func();\nb=z;\nfor (a++; i < 10; i++) { alert(i); }\n\nvar z=1;\ng=2;\nfor (; i < 10; i++) { alert(i); }\n\nvar a = 2;\nfor (va"
},
{
"path": "test/unit/compress/test/if-not.js",
"chars": 17,
"preview": "if(_);if(_);else;"
},
{
"path": "test/unit/compress/test/if.js",
"chars": 59,
"preview": "var a = 1;\r\nif (a == 1) {\r\n\ta = 2;\r\n} else {\r\n\ta = 17;\r\n}\r\n"
},
{
"path": "test/unit/compress/test/ifreturn.js",
"chars": 90,
"preview": "function a(b) {\r\n\tif (b == 1) {\r\n\t\treturn 2;\r\n\t} else {\r\n\t\treturn 17;\r\n\t}\r\n\r\n\treturn 3;\r\n}"
},
{
"path": "test/unit/compress/test/ifreturn2.js",
"chars": 210,
"preview": "function x(a) {\n if (typeof a === 'object')\n return a;\n\n if (a === 42)\n return 0;\n\n return a * 2;"
},
{
"path": "test/unit/compress/test/infinite.js",
"chars": 84,
"preview": "with({get NaN(){throw 0},get Infinity(){throw 0}})(1/0)/(1/0),0/0,123456/0,-123456/0"
},
{
"path": "test/unit/compress/test/issue10.js",
"chars": 75,
"preview": "function f() { var a; if (a = 'a') { return a; } else { return a; } }; f();"
},
{
"path": "test/unit/compress/test/issue11.js",
"chars": 39,
"preview": "new (A, B)\nnew (A || B)\nnew (X ? A : B)"
},
{
"path": "test/unit/compress/test/issue13.js",
"chars": 135,
"preview": "var a = /^(?:(\\w+):)?(?:\\/\\/(?:(?:([^:@\\/]*):?([^:@\\/]*))?@)?([^:\\/?#])(?::(\\d))?)?(..?$|(?:[^?#\\/]\\/))([^?#]*)(?:\\?([^#"
},
{
"path": "test/unit/compress/test/issue14.js",
"chars": 101,
"preview": "var a = {'\\b': '\\\\b', '\\t': '\\\\t', '\\n': '\\\\n', '\\f': '\\\\f', '\\r': '\\\\r', '\"' : '\\\\\"', '\\\\': '\\\\\\\\'};"
},
{
"path": "test/unit/compress/test/issue16.js",
"chars": 19,
"preview": "var a = 0xC1BDCEEE;"
},
{
"path": "test/unit/compress/test/issue17.js",
"chars": 41,
"preview": "var a = function(b) {\n b();\n a()\n}\n"
},
{
"path": "test/unit/compress/test/issue20.js",
"chars": 6,
"preview": "{a: 1}"
},
{
"path": "test/unit/compress/test/issue21.js",
"chars": 64,
"preview": "var a = 0;\nswitch(a) {\n case 0:\n a++;\n break;\n}"
},
{
"path": "test/unit/compress/test/issue25.js",
"chars": 99,
"preview": "label1 : {\n label2 : {\n break label2;\n console.log(2);\n }\n console.log(1);\n}"
},
{
"path": "test/unit/compress/test/issue27.js",
"chars": 19,
"preview": "(a ? b : c) ? d : e"
},
{
"path": "test/unit/compress/test/issue278.js",
"chars": 18,
"preview": "if (!x) debugger;\n"
},
{
"path": "test/unit/compress/test/issue28.js",
"chars": 41,
"preview": "o = {'.5':.5}\no = {'0.5':.5}\no = {0.5:.5}"
},
{
"path": "test/unit/compress/test/issue29.js",
"chars": 33,
"preview": "result=(function(){ return 1;})()"
},
{
"path": "test/unit/compress/test/issue30.js",
"chars": 48,
"preview": "var a = 1 << 3;\nvar b = 8 >> 1;\nvar c = 8 >>> 1;"
},
{
"path": "test/unit/compress/test/issue34.js",
"chars": 41,
"preview": "var a = {};\na[\"this\"] = 1;\na[\"that\"] = 2;"
},
{
"path": "test/unit/compress/test/issue349.js",
"chars": 653,
"preview": "(function () {\n var cake\n if (noFreeCakes) return /* I would\n insert something\n "
},
{
"path": "test/unit/compress/test/issue353.js",
"chars": 42,
"preview": "function test() {\n debugger;\n return;\n}\n"
},
{
"path": "test/unit/compress/test/issue372.js",
"chars": 609,
"preview": "\"use strict\";\n\"use strict\";\n\nfunction a() {\n void \"a\";\n function b() {\n \"use strict\";\n void \"b\";\n "
},
{
"path": "test/unit/compress/test/issue4.js",
"chars": 40,
"preview": "var a = 2e3;\nvar b = 2e-3;\nvar c = 2e-5;"
},
{
"path": "test/unit/compress/test/issue471.js",
"chars": 19,
"preview": "((a || b) && c)();\n"
},
{
"path": "test/unit/compress/test/issue48.js",
"chars": 24,
"preview": "var s, i; s = ''; i = 0;"
},
{
"path": "test/unit/compress/test/issue50.js",
"chars": 226,
"preview": "function bar(a) {\n try {\n foo();\n } catch(e) {\n alert(\"Exception caught (foo"
},
{
"path": "test/unit/compress/test/issue53.js",
"chars": 11,
"preview": "x = (y, z)\n"
},
{
"path": "test/unit/compress/test/issue54.1.js",
"chars": 52,
"preview": "foo.toString();\na.toString(16);\nb.toString.call(c);\n"
},
{
"path": "test/unit/compress/test/issue68.js",
"chars": 77,
"preview": "function f() {\n if (a) return;\n g();\n function g(){}\n};\n"
},
{
"path": "test/unit/compress/test/issue69.js",
"chars": 8,
"preview": "[(a,b)]\n"
},
{
"path": "test/unit/compress/test/issue9.js",
"chars": 55,
"preview": "var a = {\n a: 1,\n b: 2, // <-- trailing comma\n};\n"
},
{
"path": "test/unit/compress/test/issues222_324.js",
"chars": 1783,
"preview": "!function() {\n 'use strict';\n\n var 七, // issue #222\n $1, // issue #222\n ლ_ಠ益ಠ_ლ; // issue #324\n};\n\n!funct"
},
{
"path": "test/unit/compress/test/mangle.js",
"chars": 85,
"preview": "(function() {\n var x = function fun(a, fun, b) {\n return fun;\n };\n}());\n"
},
{
"path": "test/unit/compress/test/null_string.js",
"chars": 21,
"preview": "var nullString = \"\\0\""
},
{
"path": "test/unit/compress/test/strict-equals.js",
"chars": 56,
"preview": "typeof a === 'string'\nb + \"\" !== c + \"\"\nd < e === f < g\n"
},
{
"path": "test/unit/compress/test/var.js",
"chars": 79,
"preview": "// var declarations after each other should be combined\r\nvar a = 1;\r\nvar b = 2;"
},
{
"path": "test/unit/compress/test/whitespace.js",
"chars": 410,
"preview": "function id(a) {\n \f// Form-Feed\n \u000b// Vertical Tab\n // No-Break Space\n // Mongolian Vowel Separator\n // En quad\n "
},
{
"path": "test/unit/compress/test/with.js",
"chars": 14,
"preview": "with({}) {\n};\n"
},
{
"path": "test/unit/scripts.js",
"chars": 1645,
"preview": "global.DIGITS_OVERRIDE_FOR_TESTING = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789\";\n\nvar fs = requi"
},
{
"path": "tmp/hoist.js",
"chars": 663,
"preview": "function foo(arg1, arg2, arg3, arg4, arg5, arg6) {\n var a = 5;\n {\n var d = 10, mak = 20, bu"
},
{
"path": "tmp/instrument.js",
"chars": 3321,
"preview": "// sample on how to use the parser and walker API to instrument some code\n\nvar jsp = require(\"uglify-js\").parser;\nvar pr"
},
{
"path": "tmp/test.js",
"chars": 824,
"preview": "#! /usr/bin/env node\n\nglobal.sys = require(/^v0\\.[012]/.test(process.version) ? \"sys\" : \"util\");\nvar fs = require(\"fs\");"
},
{
"path": "uglify-js.js",
"chars": 720,
"preview": "//convienence function(src, [options]);\nfunction uglify(orig_code, options){\n options || (options = {});\n var jsp = ug"
}
]
About this extraction
This page contains the full source code of the mishoo/UglifyJS-old GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 118 files (325.8 KB), approximately 91.6k tokens, and a symbol index with 93 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.