[Pkg-javascript-commits] [node-acorn-jsx] 244/484: Replaced UglifyJS2 with Traceur for fair comparison of ES6-enabled parsers.
Bastien Roucariès
rouca at moszumanska.debian.org
Sat Aug 19 14:20:38 UTC 2017
This is an automated email from the git hooks/post-receive script.
rouca pushed a commit to branch master
in repository node-acorn-jsx.
commit 8b1924661590e9e8528369fcb5f345a20980acb7
Author: Ingvar Stepanyan <me at rreverser.com>
Date: Sat Jul 26 20:49:29 2014 +0300
Replaced UglifyJS2 with Traceur for fair comparison of ES6-enabled parsers.
---
test/bench.html | 28 +-
test/compare/uglifyjs.js | 1372 -------------------------
test/compare/uglifyjs2.js | 2494 ---------------------------------------------
3 files changed, 17 insertions(+), 3877 deletions(-)
diff --git a/test/bench.html b/test/bench.html
index 31494f6..9b07d3b 100644
--- a/test/bench.html
+++ b/test/bench.html
@@ -4,7 +4,7 @@
<title>Acorn benchmark</title>
<script src="../acorn.js"></script>
<script src="compare/esprima.js"></script>
- <script src="compare/uglifyjs2.js"></script>
+ <script src="compare/traceur.js"></script>
<script src="jquery-string.js"></script>
<script src="codemirror-string.js"></script>
<style>
@@ -15,11 +15,11 @@
</style>
</head>
-<h1>Acorn/Esprima/UglifyJS2 speed comparison</h1>
+<h1>Acorn/Esprima/Traceur speed comparison</h1>
-<p>This will run each of the three parsers on the source code of
+<p>This will run each of the three ES6 parsers on the source code of
jQuery 1.6.4 and CodeMirror 3.0b1 for two seconds, and show a table
-indicating the number of lines parsed per second. Note that UglifyJS
+indicating the number of lines parsed per second. Note that Traceur
always stores location data, and is thus not fairly compared by the
benchmark <em>without</em> location data.<p>
@@ -35,28 +35,34 @@ numbers.</p>
<span id="running"></span>
<script>
+ var sourceFileName = 'source.js';
+
function runAcorn(code, locations) {
- acorn.parse(code, {ecmaVersion: 6, locations: locations});
+ acorn.parse(code, {ecmaVersion: 6, locations: locations, sourceFile: sourceFileName});
}
function runEsprima(code, locations) {
- esprima.parse(code, {loc: locations});
+ esprima.parse(code, {loc: locations, source: sourceFileName});
}
- function runUglifyJS(code) {
- uglifyjs.parse(code);
+ function runTraceur(code) {
+ var file = new traceur.syntax.SourceFile(sourceFileName, code);
+ var parser = new traceur.syntax.Parser(file);
+ parser.parseScript();
}
var totalLines = codemirror30.split("\n").length + jquery164.split("\n").length;
+ var nowHost = (typeof performance === 'object' && 'now' in performance) ? performance : Date;
+
function benchmark(runner, locations) {
// Give it a chance to warm up (first runs are usually outliers)
runner(jquery164, locations);
runner(codemirror30, locations);
- var t0 = +new Date, t1, lines = 0;
+ var t0 = nowHost.now(), t1, lines = 0;
for (;;) {
runner(jquery164, locations);
runner(codemirror30, locations);
lines += totalLines;
- t1 = +new Date;
+ t1 = nowHost.now();
if (t1 - t0 > 2000) break;
}
return lines / ((t1 - t0) / 1000);
@@ -75,7 +81,7 @@ numbers.</p>
running.innerHTML = "Running benchmark...";
var data = [{name: "Acorn", runner: runAcorn},
{name: "Esprima", runner: runEsprima},
- {name: "UglifyJS2", runner: runUglifyJS}];
+ {name: "Traceur", runner: runTraceur}];
if (acornOnly) data.length = 1;
var pos = 0;
function next() {
diff --git a/test/compare/uglifyjs.js b/test/compare/uglifyjs.js
deleted file mode 100644
index b22fdeb..0000000
--- a/test/compare/uglifyjs.js
+++ /dev/null
@@ -1,1372 +0,0 @@
-/***********************************************************************
-
- 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 at gmail.com>
- http://mihai.bazon.net/blog
-
- Distributed under the BSD license:
-
- Copyright 2010 (c) Mihai Bazon <mihai.bazon at 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) ]----- */
-(function(exports) {
-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"));
-
-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 [...]
- 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\\u09 [...]
- 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-\\uA90 [...]
-};
-
-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;
- 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) ]);
- }
- // FIXME [!!] Line not in original parse-js,
- // added to be able to warn about unquoted
- // keyword properties
- a[a.length - 1].type = type;
- }
- 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;
-};
-})(typeof exports == "undefined" ? window.uglifyjs = {} : exports);
-// Local variables:
-// js-indent-level: 8
-// End:
diff --git a/test/compare/uglifyjs2.js b/test/compare/uglifyjs2.js
deleted file mode 100644
index f02305e..0000000
--- a/test/compare/uglifyjs2.js
+++ /dev/null
@@ -1,2494 +0,0 @@
-/***********************************************************************
-
- A JavaScript tokenizer / parser / beautifier / compressor.
- https://github.com/mishoo/UglifyJS2
-
- -------------------------------- (C) ---------------------------------
-
- Author: Mihai Bazon
- <mihai.bazon at gmail.com>
- http://mihai.bazon.net/blog
-
- Distributed under the BSD license:
-
- Copyright 2012 (c) Mihai Bazon <mihai.bazon at gmail.com>
- Parser 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.
-
- ***********************************************************************/
-(function(exports){
-"use strict";
-
-function array_to_hash(a) {
- var ret = Object.create(null);
- for (var i = 0; i < a.length; ++i)
- ret[a[i]] = true;
- return ret;
-};
-
-function slice(a, start) {
- return Array.prototype.slice.call(a, start || 0);
-};
-
-function characters(str) {
- return str.split("");
-};
-
-function member(name, array) {
- for (var i = array.length; --i >= 0;)
- if (array[i] == name)
- return true;
- return false;
-};
-
-function find_if(func, array) {
- for (var i = 0, n = array.length; i < n; ++i) {
- if (func(array[i]))
- return array[i];
- }
-};
-
-function repeat_string(str, i) {
- if (i <= 0) return "";
- if (i == 1) return str;
- var d = repeat_string(str, i >> 1);
- d += d;
- if (i & 1) d += str;
- return d;
-};
-
-function DefaultsError(msg, defs) {
- this.msg = msg;
- this.defs = defs;
-};
-
-function defaults(args, defs, croak) {
- if (args === true)
- args = {};
- var ret = args || {};
- if (croak) for (var i in ret) if (ret.hasOwnProperty(i) && !defs.hasOwnProperty(i))
- throw new DefaultsError("`" + i + "` is not a supported option", defs);
- for (var i in defs) if (defs.hasOwnProperty(i)) {
- ret[i] = (args && args.hasOwnProperty(i)) ? args[i] : defs[i];
- }
- return ret;
-};
-
-function merge(obj, ext) {
- for (var i in ext) if (ext.hasOwnProperty(i)) {
- obj[i] = ext[i];
- }
- return obj;
-};
-
-function noop() {};
-
-var MAP = (function(){
- function MAP(a, f, backwards) {
- var ret = [], top = [], i;
- function doit() {
- var val = f(a[i], i);
- var is_last = val instanceof Last;
- if (is_last) val = val.v;
- if (val instanceof AtTop) {
- val = val.v;
- if (val instanceof Splice) {
- top.push.apply(top, backwards ? val.v.slice().reverse() : val.v);
- } else {
- top.push(val);
- }
- }
- else if (val !== skip) {
- if (val instanceof Splice) {
- ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v);
- } else {
- ret.push(val);
- }
- }
- return is_last;
- };
- if (a instanceof Array) {
- if (backwards) {
- for (i = a.length; --i >= 0;) if (doit()) break;
- ret.reverse();
- top.reverse();
- } else {
- for (i = 0; i < a.length; ++i) if (doit()) break;
- }
- }
- else {
- for (i in a) if (a.hasOwnProperty(i)) if (doit()) break;
- }
- return top.concat(ret);
- };
- MAP.at_top = function(val) { return new AtTop(val) };
- MAP.splice = function(val) { return new Splice(val) };
- MAP.last = function(val) { return new Last(val) };
- var skip = MAP.skip = {};
- function AtTop(val) { this.v = val };
- function Splice(val) { this.v = val };
- function Last(val) { this.v = val };
- return MAP;
-})();
-
-function push_uniq(array, el) {
- if (array.indexOf(el) < 0)
- array.push(el);
-};
-
-function string_template(text, props) {
- return text.replace(/\{(.+?)\}/g, function(str, p){
- return props[p];
- });
-};
-
-function mergeSort(array, cmp) {
- if (array.length < 2) return array.slice();
- function merge(a, b) {
- var r = [], ai = 0, bi = 0, i = 0;
- while (ai < a.length && bi < b.length) {
- cmp(a[ai], b[bi]) <= 0
- ? r[i++] = a[ai++]
- : r[i++] = b[bi++];
- }
- if (ai < a.length) r.push.apply(r, a.slice(ai));
- if (bi < b.length) r.push.apply(r, b.slice(bi));
- return r;
- };
- function _ms(a) {
- if (a.length <= 1)
- return a;
- var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m);
- left = _ms(left);
- right = _ms(right);
- return merge(left, right);
- };
- return _ms(array);
-};
-
-function set_difference(a, b) {
- return a.filter(function(el){
- return b.indexOf(el) < 0;
- });
-};
-
-function set_intersection(a, b) {
- return a.filter(function(el){
- return b.indexOf(el) >= 0;
- });
-};
-
-// this function is taken from Acorn [1], written by Marijn Haverbeke
-// [1] https://github.com/marijnh/acorn
-function makePredicate(words) {
- if (!(words instanceof Array)) words = words.split(" ");
- var f = "", cats = [];
- out: for (var i = 0; i < words.length; ++i) {
- for (var j = 0; j < cats.length; ++j)
- if (cats[j][0].length == words[i].length) {
- cats[j].push(words[i]);
- continue out;
- }
- cats.push([words[i]]);
- }
- function compareTo(arr) {
- if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";";
- f += "switch(str){";
- for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":";
- f += "return true}return false;";
- }
- // When there are more than three length categories, an outer
- // switch first dispatches on the lengths, to save on comparisons.
- if (cats.length > 3) {
- cats.sort(function(a, b) {return b.length - a.length;});
- f += "switch(str.length){";
- for (var i = 0; i < cats.length; ++i) {
- var cat = cats[i];
- f += "case " + cat[0].length + ":";
- compareTo(cat);
- }
- f += "}";
- // Otherwise, simply generate a flat `switch` statement.
- } else {
- compareTo(words);
- }
- return new Function("str", f);
-};
-
-function DEFNODE(type, props, methods, base) {
- if (arguments.length < 4) base = AST_Node;
- if (!props) props = [];
- else props = props.split(/\s+/);
- var self_props = props;
- if (base && base.PROPS)
- props = props.concat(base.PROPS);
- var code = "return function AST_" + type + "(props){ if (props) { ";
- for (var i = props.length; --i >= 0;) {
- code += "this." + props[i] + " = props." + props[i] + ";";
- }
- var proto = base && new base;
- if (proto && proto.initialize || (methods && methods.initialize))
- code += "this.initialize();";
- code += "}}";
- var ctor = new Function(code)();
- if (proto) {
- ctor.prototype = proto;
- ctor.BASE = base;
- }
- if (base) base.SUBCLASSES.push(ctor);
- ctor.prototype.CTOR = ctor;
- ctor.PROPS = props || null;
- ctor.SELF_PROPS = self_props;
- ctor.SUBCLASSES = [];
- if (type) {
- ctor.prototype.TYPE = ctor.TYPE = type;
- }
- if (methods) for (i in methods) if (methods.hasOwnProperty(i)) {
- if (/^\$/.test(i)) {
- ctor[i.substr(1)] = methods[i];
- } else {
- ctor.prototype[i] = methods[i];
- }
- }
- ctor.DEFMETHOD = function(name, method) {
- this.prototype[name] = method;
- };
- return ctor;
-};
-
-var AST_Token = DEFNODE("Token", "type value line col pos endpos nlb comments_before file", {
-}, null);
-
-var AST_Node = DEFNODE("Node", "start end", {
- clone: function() {
- return new this.CTOR(this);
- },
- $documentation: "Base class of all AST nodes",
- $propdoc: {
- start: "[AST_Token] The first token of this node",
- end: "[AST_Token] The last token of this node"
- },
- _walk: function(visitor) {
- return visitor._visit(this);
- },
- walk: function(visitor) {
- return this._walk(visitor); // not sure the indirection will be any help
- }
-}, null);
-
-AST_Node.warn_function = null;
-AST_Node.warn = function(txt, props) {
- if (AST_Node.warn_function)
- AST_Node.warn_function(string_template(txt, props));
-};
-
-/* -----[ statements ]----- */
-
-var AST_Statement = DEFNODE("Statement", null, {
- $documentation: "Base class of all statements",
-});
-
-var AST_Debugger = DEFNODE("Debugger", null, {
- $documentation: "Represents a debugger statement",
-}, AST_Statement);
-
-var AST_Directive = DEFNODE("Directive", "value scope", {
- $documentation: "Represents a directive, like \"use strict\";",
- $propdoc: {
- value: "[string] The value of this directive as a plain string (it's not an AST_String!)",
- scope: "[AST_Scope/S] The scope that this directive affects"
- },
-}, AST_Statement);
-
-var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", {
- $documentation: "A statement consisting of an expression, i.e. a = 1 + 2",
- $propdoc: {
- body: "[AST_Node] an expression node (should not be instanceof AST_Statement)"
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- this.body._walk(visitor);
- });
- }
-}, AST_Statement);
-
-function walk_body(node, visitor) {
- if (node.body instanceof AST_Statement) {
- node.body._walk(visitor);
- }
- else node.body.forEach(function(stat){
- stat._walk(visitor);
- });
-};
-
-var AST_Block = DEFNODE("Block", "body", {
- $documentation: "A body of statements (usually bracketed)",
- $propdoc: {
- body: "[AST_Statement*] an array of statements"
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- walk_body(this, visitor);
- });
- }
-}, AST_Statement);
-
-var AST_BlockStatement = DEFNODE("BlockStatement", null, {
- $documentation: "A block statement",
-}, AST_Block);
-
-var AST_EmptyStatement = DEFNODE("EmptyStatement", null, {
- $documentation: "The empty statement (empty block or simply a semicolon)",
- _walk: function(visitor) {
- return visitor._visit(this);
- }
-}, AST_Statement);
-
-var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", {
- $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`",
- $propdoc: {
- body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement"
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- this.body._walk(visitor);
- });
- }
-}, AST_Statement);
-
-var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", {
- $documentation: "Statement with a label",
- $propdoc: {
- label: "[AST_Label] a label definition"
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- this.label._walk(visitor);
- this.body._walk(visitor);
- });
- }
-}, AST_StatementWithBody);
-
-var AST_DWLoop = DEFNODE("DWLoop", "condition", {
- $documentation: "Base class for do/while statements",
- $propdoc: {
- condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement"
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- this.condition._walk(visitor);
- this.body._walk(visitor);
- });
- }
-}, AST_StatementWithBody);
-
-var AST_Do = DEFNODE("Do", null, {
- $documentation: "A `do` statement",
-}, AST_DWLoop);
-
-var AST_While = DEFNODE("While", null, {
- $documentation: "A `while` statement",
-}, AST_DWLoop);
-
-var AST_For = DEFNODE("For", "init condition step", {
- $documentation: "A `for` statement",
- $propdoc: {
- init: "[AST_Node?] the `for` initialization code, or null if empty",
- condition: "[AST_Node?] the `for` termination clause, or null if empty",
- step: "[AST_Node?] the `for` update clause, or null if empty"
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- if (this.init) this.init._walk(visitor);
- if (this.condition) this.condition._walk(visitor);
- if (this.step) this.step._walk(visitor);
- this.body._walk(visitor);
- });
- }
-}, AST_StatementWithBody);
-
-var AST_ForIn = DEFNODE("ForIn", "init name object", {
- $documentation: "A `for ... in` statement",
- $propdoc: {
- init: "[AST_Node] the `for/in` initialization code",
- name: "[AST_SymbolRef?] the loop variable, only if `init` is AST_Var",
- object: "[AST_Node] the object that we're looping through"
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- this.init._walk(visitor);
- this.object._walk(visitor);
- this.body._walk(visitor);
- });
- }
-}, AST_StatementWithBody);
-
-var AST_With = DEFNODE("With", "expression", {
- $documentation: "A `with` statement",
- $propdoc: {
- expression: "[AST_Node] the `with` expression"
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- this.expression._walk(visitor);
- this.body._walk(visitor);
- });
- }
-}, AST_StatementWithBody);
-
-/* -----[ scope and functions ]----- */
-
-var AST_Scope = DEFNODE("Scope", "directives variables functions uses_with uses_eval parent_scope enclosed cname", {
- $documentation: "Base class for all statements introducing a lexical scope",
- $propdoc: {
- directives: "[string*/S] an array of directives declared in this scope",
- variables: "[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope",
- functions: "[Object/S] like `variables`, but only lists function declarations",
- uses_with: "[boolean/S] tells whether this scope uses the `with` statement",
- uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`",
- parent_scope: "[AST_Scope?/S] link to the parent scope",
- enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",
- cname: "[integer/S] current index for mangling variables (used internally by the mangler)",
- },
-}, AST_Block);
-
-var AST_Toplevel = DEFNODE("Toplevel", "globals", {
- $documentation: "The toplevel scope",
- $propdoc: {
- globals: "[Object/S] a map of name -> SymbolDef for all undeclared names",
- },
- wrap_commonjs: function(name, export_all) {
- var self = this;
- if (export_all) {
- self.figure_out_scope();
- var to_export = [];
- self.walk(new TreeWalker(function(node){
- if (node instanceof AST_SymbolDeclaration && node.definition().global) {
- if (!find_if(function(n){ return n.name == node.name }, to_export))
- to_export.push(node);
- }
- }));
- }
- var wrapped_tl = "(function(exports, global){ global['" + name + "'] = exports; '$ORIG'; '$EXPORTS'; }({}, (function(){return this}())))";
- wrapped_tl = parse(wrapped_tl);
- wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){
- if (node instanceof AST_SimpleStatement) {
- node = node.body;
- if (node instanceof AST_String) switch (node.getValue()) {
- case "$ORIG":
- return MAP.splice(self.body);
- case "$EXPORTS":
- var body = [];
- to_export.forEach(function(sym){
- body.push(new AST_SimpleStatement({
- body: new AST_Assign({
- left: new AST_Sub({
- expression: new AST_SymbolRef({ name: "exports" }),
- property: new AST_String({ value: sym.name }),
- }),
- operator: "=",
- right: new AST_SymbolRef(sym),
- }),
- }));
- });
- return MAP.splice(body);
- }
- }
- }));
- return wrapped_tl;
- }
-}, AST_Scope);
-
-var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments", {
- $documentation: "Base class for functions",
- $propdoc: {
- name: "[AST_SymbolDeclaration?] the name of this function",
- argnames: "[AST_SymbolFunarg*] array of function arguments",
- uses_arguments: "[boolean/S] tells whether this function accesses the arguments array"
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- if (this.name) this.name._walk(visitor);
- this.argnames.forEach(function(arg){
- arg._walk(visitor);
- });
- walk_body(this, visitor);
- });
- }
-}, AST_Scope);
-
-var AST_Function = DEFNODE("Function", null, {
- $documentation: "A function expression"
-}, AST_Lambda);
-
-var AST_Defun = DEFNODE("Defun", null, {
- $documentation: "A function definition"
-}, AST_Lambda);
-
-/* -----[ JUMPS ]----- */
-
-var AST_Jump = DEFNODE("Jump", null, {
- $documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"
-}, AST_Statement);
-
-var AST_Exit = DEFNODE("Exit", "value", {
- $documentation: "Base class for “exits” (`return` and `throw`)",
- $propdoc: {
- value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return"
- },
- _walk: function(visitor) {
- return visitor._visit(this, this.value && function(){
- this.value._walk(visitor);
- });
- }
-}, AST_Jump);
-
-var AST_Return = DEFNODE("Return", null, {
- $documentation: "A `return` statement"
-}, AST_Exit);
-
-var AST_Throw = DEFNODE("Throw", null, {
- $documentation: "A `throw` statement"
-}, AST_Exit);
-
-var AST_LoopControl = DEFNODE("LoopControl", "label", {
- $documentation: "Base class for loop control statements (`break` and `continue`)",
- $propdoc: {
- label: "[AST_LabelRef?] the label, or null if none",
- },
- _walk: function(visitor) {
- return visitor._visit(this, this.label && function(){
- this.label._walk(visitor);
- });
- }
-}, AST_Jump);
-
-var AST_Break = DEFNODE("Break", null, {
- $documentation: "A `break` statement"
-}, AST_LoopControl);
-
-var AST_Continue = DEFNODE("Continue", null, {
- $documentation: "A `continue` statement"
-}, AST_LoopControl);
-
-/* -----[ IF ]----- */
-
-var AST_If = DEFNODE("If", "condition alternative", {
- $documentation: "A `if` statement",
- $propdoc: {
- condition: "[AST_Node] the `if` condition",
- alternative: "[AST_Statement?] the `else` part, or null if not present"
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- this.condition._walk(visitor);
- this.body._walk(visitor);
- if (this.alternative) this.alternative._walk(visitor);
- });
- }
-}, AST_StatementWithBody);
-
-/* -----[ SWITCH ]----- */
-
-var AST_Switch = DEFNODE("Switch", "expression", {
- $documentation: "A `switch` statement",
- $propdoc: {
- expression: "[AST_Node] the `switch` “discriminant”"
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- this.expression._walk(visitor);
- walk_body(this, visitor);
- });
- }
-}, AST_Block);
-
-var AST_SwitchBranch = DEFNODE("SwitchBranch", null, {
- $documentation: "Base class for `switch` branches",
-}, AST_Block);
-
-var AST_Default = DEFNODE("Default", null, {
- $documentation: "A `default` switch branch",
-}, AST_SwitchBranch);
-
-var AST_Case = DEFNODE("Case", "expression", {
- $documentation: "A `case` switch branch",
- $propdoc: {
- expression: "[AST_Node] the `case` expression"
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- this.expression._walk(visitor);
- walk_body(this, visitor);
- });
- }
-}, AST_SwitchBranch);
-
-/* -----[ EXCEPTIONS ]----- */
-
-var AST_Try = DEFNODE("Try", "bcatch bfinally", {
- $documentation: "A `try` statement",
- $propdoc: {
- bcatch: "[AST_Catch?] the catch block, or null if not present",
- bfinally: "[AST_Finally?] the finally block, or null if not present"
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- walk_body(this, visitor);
- if (this.bcatch) this.bcatch._walk(visitor);
- if (this.bfinally) this.bfinally._walk(visitor);
- });
- }
-}, AST_Block);
-
-// XXX: this is wrong according to ECMA-262 (12.4). the catch block
-// should introduce another scope, as the argname should be visible
-// only inside the catch block. However, doing it this way because of
-// IE which simply introduces the name in the surrounding scope. If
-// we ever want to fix this then AST_Catch should inherit from
-// AST_Scope.
-var AST_Catch = DEFNODE("Catch", "argname", {
- $documentation: "A `catch` node; only makes sense as part of a `try` statement",
- $propdoc: {
- argname: "[AST_SymbolCatch] symbol for the exception"
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- this.argname._walk(visitor);
- walk_body(this, visitor);
- });
- }
-}, AST_Block);
-
-var AST_Finally = DEFNODE("Finally", null, {
- $documentation: "A `finally` node; only makes sense as part of a `try` statement"
-}, AST_Block);
-
-/* -----[ VAR/CONST ]----- */
-
-var AST_Definitions = DEFNODE("Definitions", "definitions", {
- $documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)",
- $propdoc: {
- definitions: "[AST_VarDef*] array of variable definitions"
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- this.definitions.forEach(function(def){
- def._walk(visitor);
- });
- });
- }
-}, AST_Statement);
-
-var AST_Var = DEFNODE("Var", null, {
- $documentation: "A `var` statement"
-}, AST_Definitions);
-
-var AST_Const = DEFNODE("Const", null, {
- $documentation: "A `const` statement"
-}, AST_Definitions);
-
-var AST_VarDef = DEFNODE("VarDef", "name value", {
- $documentation: "A variable declaration; only appears in a AST_Definitions node",
- $propdoc: {
- name: "[AST_SymbolVar|AST_SymbolConst] name of the variable",
- value: "[AST_Node?] initializer, or null of there's no initializer"
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- this.name._walk(visitor);
- if (this.value) this.value._walk(visitor);
- });
- }
-});
-
-/* -----[ OTHER ]----- */
-
-var AST_Call = DEFNODE("Call", "expression args", {
- $documentation: "A function call expression",
- $propdoc: {
- expression: "[AST_Node] expression to invoke as function",
- args: "[AST_Node*] array of arguments"
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- this.expression._walk(visitor);
- this.args.forEach(function(arg){
- arg._walk(visitor);
- });
- });
- }
-});
-
-var AST_New = DEFNODE("New", null, {
- $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties"
-}, AST_Call);
-
-var AST_Seq = DEFNODE("Seq", "car cdr", {
- $documentation: "A sequence expression (two comma-separated expressions)",
- $propdoc: {
- car: "[AST_Node] first element in sequence",
- cdr: "[AST_Node] second element in sequence"
- },
- $cons: function(x, y) {
- var seq = new AST_Seq(x);
- seq.car = x;
- seq.cdr = y;
- return seq;
- },
- $from_array: function(array) {
- if (array.length == 0) return null;
- if (array.length == 1) return array[0].clone();
- var list = null;
- for (var i = array.length; --i >= 0;) {
- list = AST_Seq.cons(array[i], list);
- }
- var p = list;
- while (p) {
- if (p.cdr && !p.cdr.cdr) {
- p.cdr = p.cdr.car;
- break;
- }
- p = p.cdr;
- }
- return list;
- },
- add: function(node) {
- var p = this;
- while (p) {
- if (!(p.cdr instanceof AST_Seq)) {
- var cell = AST_Seq.cons(p.cdr, node);
- return p.cdr = cell;
- }
- p = p.cdr;
- }
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- this.car._walk(visitor);
- if (this.cdr) this.cdr._walk(visitor);
- });
- }
-});
-
-var AST_PropAccess = DEFNODE("PropAccess", "expression property", {
- $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`",
- $propdoc: {
- expression: "[AST_Node] the “container” expression",
- property: "[AST_Node|string] the property to access. For AST_Dot this is always a plain string, while for AST_Sub it's an arbitrary AST_Node"
- }
-});
-
-var AST_Dot = DEFNODE("Dot", null, {
- $documentation: "A dotted property access expression",
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- this.expression._walk(visitor);
- });
- }
-}, AST_PropAccess);
-
-var AST_Sub = DEFNODE("Sub", null, {
- $documentation: "Index-style property access, i.e. `a[\"foo\"]`",
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- this.expression._walk(visitor);
- this.property._walk(visitor);
- });
- }
-}, AST_PropAccess);
-
-var AST_Unary = DEFNODE("Unary", "operator expression", {
- $documentation: "Base class for unary expressions",
- $propdoc: {
- operator: "[string] the operator",
- expression: "[AST_Node] expression that this unary operator applies to"
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- this.expression._walk(visitor);
- });
- }
-});
-
-var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, {
- $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`"
-}, AST_Unary);
-
-var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, {
- $documentation: "Unary postfix expression, i.e. `i++`"
-}, AST_Unary);
-
-var AST_Binary = DEFNODE("Binary", "left operator right", {
- $documentation: "Binary expression, i.e. `a + b`",
- $propdoc: {
- left: "[AST_Node] left-hand side expression",
- operator: "[string] the operator",
- right: "[AST_Node] right-hand side expression"
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- this.left._walk(visitor);
- this.right._walk(visitor);
- });
- }
-});
-
-var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", {
- $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`",
- $propdoc: {
- condition: "[AST_Node]",
- consequent: "[AST_Node]",
- alternative: "[AST_Node]"
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- this.condition._walk(visitor);
- this.consequent._walk(visitor);
- this.alternative._walk(visitor);
- });
- }
-});
-
-var AST_Assign = DEFNODE("Assign", null, {
- $documentation: "An assignment expression — `a = b + 5`",
-}, AST_Binary);
-
-/* -----[ LITERALS ]----- */
-
-var AST_Array = DEFNODE("Array", "elements", {
- $documentation: "An array literal",
- $propdoc: {
- elements: "[AST_Node*] array of elements"
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- this.elements.forEach(function(el){
- el._walk(visitor);
- });
- });
- }
-});
-
-var AST_Object = DEFNODE("Object", "properties", {
- $documentation: "An object literal",
- $propdoc: {
- properties: "[AST_ObjectProperty*] array of properties"
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- this.properties.forEach(function(prop){
- prop._walk(visitor);
- });
- });
- }
-});
-
-var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", {
- $documentation: "Base class for literal object properties",
- $propdoc: {
- key: "[string] the property name; it's always a plain string in our AST, no matter if it was a string, number or identifier in original code",
- value: "[AST_Node] property value. For setters and getters this is an AST_Function."
- },
- _walk: function(visitor) {
- return visitor._visit(this, function(){
- this.value._walk(visitor);
- });
- }
-});
-
-var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", null, {
- $documentation: "A key: value object property",
-}, AST_ObjectProperty);
-
-var AST_ObjectSetter = DEFNODE("ObjectSetter", null, {
- $documentation: "An object setter property",
-}, AST_ObjectProperty);
-
-var AST_ObjectGetter = DEFNODE("ObjectGetter", null, {
- $documentation: "An object getter property",
-}, AST_ObjectProperty);
-
-var AST_Symbol = DEFNODE("Symbol", "scope name thedef", {
- $propdoc: {
- name: "[string] name of this symbol",
- scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)",
- thedef: "[SymbolDef/S] the definition of this symbol"
- },
- $documentation: "Base class for all symbols",
-});
-
-var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", {
- $documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)",
- $propdoc: {
- init: "[AST_Node*/S] array of initializers for this declaration."
- }
-}, AST_Symbol);
-
-var AST_SymbolVar = DEFNODE("SymbolVar", null, {
- $documentation: "Symbol defining a variable",
-}, AST_SymbolDeclaration);
-
-var AST_SymbolConst = DEFNODE("SymbolConst", null, {
- $documentation: "A constant declaration"
-}, AST_SymbolDeclaration);
-
-var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, {
- $documentation: "Symbol naming a function argument",
-}, AST_SymbolVar);
-
-var AST_SymbolDefun = DEFNODE("SymbolDefun", null, {
- $documentation: "Symbol defining a function",
-}, AST_SymbolDeclaration);
-
-var AST_SymbolLambda = DEFNODE("SymbolLambda", null, {
- $documentation: "Symbol naming a function expression",
-}, AST_SymbolDeclaration);
-
-var AST_SymbolCatch = DEFNODE("SymbolCatch", null, {
- $documentation: "Symbol naming the exception in catch",
-}, AST_SymbolDeclaration);
-
-var AST_Label = DEFNODE("Label", "references", {
- $documentation: "Symbol naming a label (declaration)",
- $propdoc: {
- references: "[AST_LabelRef*] a list of nodes referring to this label"
- }
-}, AST_Symbol);
-
-var AST_SymbolRef = DEFNODE("SymbolRef", null, {
- $documentation: "Reference to some symbol (not definition/declaration)",
-}, AST_Symbol);
-
-var AST_LabelRef = DEFNODE("LabelRef", null, {
- $documentation: "Reference to a label symbol",
-}, AST_SymbolRef);
-
-var AST_This = DEFNODE("This", null, {
- $documentation: "The `this` symbol",
-}, AST_Symbol);
-
-var AST_Constant = DEFNODE("Constant", null, {
- $documentation: "Base class for all constants",
- getValue: function() {
- return this.value;
- }
-});
-
-var AST_String = DEFNODE("String", "value", {
- $documentation: "A string literal",
- $propdoc: {
- value: "[string] the contents of this string"
- }
-}, AST_Constant);
-
-var AST_Number = DEFNODE("Number", "value", {
- $documentation: "A number literal",
- $propdoc: {
- value: "[number] the numeric value"
- }
-}, AST_Constant);
-
-var AST_RegExp = DEFNODE("RegExp", "value", {
- $documentation: "A regexp literal",
- $propdoc: {
- value: "[RegExp] the actual regexp"
- }
-}, AST_Constant);
-
-var AST_Atom = DEFNODE("Atom", null, {
- $documentation: "Base class for atoms",
-}, AST_Constant);
-
-var AST_Null = DEFNODE("Null", null, {
- $documentation: "The `null` atom",
- value: null
-}, AST_Atom);
-
-var AST_NaN = DEFNODE("NaN", null, {
- $documentation: "The impossible value",
- value: 0/0
-}, AST_Atom);
-
-var AST_Undefined = DEFNODE("Undefined", null, {
- $documentation: "The `undefined` value",
- value: (function(){}())
-}, AST_Atom);
-
-var AST_Infinity = DEFNODE("Infinity", null, {
- $documentation: "The `Infinity` value",
- value: 1/0
-}, AST_Atom);
-
-var AST_Boolean = DEFNODE("Boolean", null, {
- $documentation: "Base class for booleans",
-}, AST_Atom);
-
-var AST_False = DEFNODE("False", null, {
- $documentation: "The `false` atom",
- value: false
-}, AST_Boolean);
-
-var AST_True = DEFNODE("True", null, {
- $documentation: "The `true` atom",
- value: true
-}, AST_Boolean);
-
-/* -----[ TreeWalker ]----- */
-
-function TreeWalker(callback) {
- this.visit = callback;
- this.stack = [];
-};
-TreeWalker.prototype = {
- _visit: function(node, descend) {
- this.stack.push(node);
- var ret = this.visit(node, descend ? function(){
- descend.call(node);
- } : noop);
- if (!ret && descend) {
- descend.call(node);
- }
- this.stack.pop();
- return ret;
- },
- parent: function(n) {
- return this.stack[this.stack.length - 2 - (n || 0)];
- },
- push: function (node) {
- this.stack.push(node);
- },
- pop: function() {
- return this.stack.pop();
- },
- self: function() {
- return this.stack[this.stack.length - 1];
- },
- find_parent: function(type) {
- var stack = this.stack;
- for (var i = stack.length; --i >= 0;) {
- var x = stack[i];
- if (x instanceof type) return x;
- }
- },
- in_boolean_context: function() {
- var stack = this.stack;
- var i = stack.length, self = stack[--i];
- while (i > 0) {
- var p = stack[--i];
- if ((p instanceof AST_If && p.condition === self) ||
- (p instanceof AST_Conditional && p.condition === self) ||
- (p instanceof AST_DWLoop && p.condition === self) ||
- (p instanceof AST_For && p.condition === self) ||
- (p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self))
- {
- return true;
- }
- if (!(p instanceof AST_Binary && (p.operator == "&&" || p.operator == "||")))
- return false;
- self = p;
- }
- },
- loopcontrol_target: function(label) {
- var stack = this.stack;
- if (label) {
- for (var i = stack.length; --i >= 0;) {
- var x = stack[i];
- if (x instanceof AST_LabeledStatement && x.label.name == label.name) {
- return x.body;
- }
- }
- } else {
- for (var i = stack.length; --i >= 0;) {
- var x = stack[i];
- if (x instanceof AST_Switch) return x;
- if (x instanceof AST_For || x instanceof AST_ForIn || x instanceof AST_DWLoop) {
- return (x.body instanceof AST_BlockStatement ? x.body : x);
- }
- }
- }
- }
-};
-
-var KEYWORDS = '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 KEYWORDS_ATOM = 'false null true';
-var RESERVED_WORDS = '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 this throws transient volatile'
- + " " + KEYWORDS_ATOM + " " + KEYWORDS;
-var KEYWORDS_BEFORE_EXPRESSION = 'return new delete throw else case';
-
-KEYWORDS = makePredicate(KEYWORDS);
-RESERVED_WORDS = makePredicate(RESERVED_WORDS);
-KEYWORDS_BEFORE_EXPRESSION = makePredicate(KEYWORDS_BEFORE_EXPRESSION);
-KEYWORDS_ATOM = makePredicate(KEYWORDS_ATOM);
-
-var OPERATOR_CHARS = makePredicate(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 = makePredicate([
- "in",
- "instanceof",
- "typeof",
- "new",
- "void",
- "delete",
- "++",
- "--",
- "+",
- "-",
- "!",
- "~",
- "&",
- "|",
- "^",
- "*",
- "/",
- "%",
- ">>",
- "<<",
- ">>>",
- "<",
- ">",
- "<=",
- ">=",
- "==",
- "===",
- "!=",
- "!==",
- "?",
- "=",
- "+=",
- "-=",
- "/=",
- "*=",
- "%=",
- ">>=",
- "<<=",
- ">>>=",
- "|=",
- "^=",
- "&=",
- "&&",
- "||"
-]);
-
-var WHITESPACE_CHARS = makePredicate(characters(" \u00a0\n\r\t\f\u000b\u200b\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000"));
-
-var PUNC_BEFORE_EXPRESSION = makePredicate(characters("[{(,.;:"));
-
-var PUNC_CHARS = makePredicate(characters("[]{}(),;:"));
-
-var REGEXP_MODIFIERS = makePredicate(characters("gmsiy"));
-
-/* -----[ Tokenizer ]----- */
-
-// regexps adapted from http://xregexp.com/plugins/#unicode
-var UNICODE = {
- 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-\\u0523\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0621-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u0 [...]
- non_spacing_mark: new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065E\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0900-\\u0902\\u093C\\u0941-\\u0948\\u094D\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09BC\\u09C1-\\u09C4\\u09CD\\u09E2\\u09E3\\u0A01\\u0A02\\u0A3C\\u0A41\\u0A42\\u0 [...]
- space_combining_mark: new RegExp("[\\u0903\\u093E-\\u0940\\u0949-\\u094C\\u094E\\u0982\\u0983\\u09BE-\\u09C0\\u09C7\\u09C8\\u09CB\\u09CC\\u09D7\\u0A03\\u0A3E-\\u0A40\\u0A83\\u0ABE-\\u0AC0\\u0AC9\\u0ACB\\u0ACC\\u0B02\\u0B03\\u0B3E\\u0B40\\u0B47\\u0B48\\u0B4B\\u0B4C\\u0B57\\u0BBE\\u0BBF\\u0BC1\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCC\\u0BD7\\u0C01-\\u0C03\\u0C41-\\u0C44\\u0C82\\u0C83\\u0CBE\\u0CC0-\\u0CC4\\u0CC7\\u0CC8\\u0CCA\\u0CCB\\u0CD5\\u0CD6\\u0D02\\u0D03\\u0D3E-\\u0D40\\u0D46-\\u0D48 [...]
- connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]")
-};
-
-function is_letter(code) {
- return (code >= 97 && code <= 122)
- || (code >= 65 && code <= 90)
- || (code >= 0xaa && UNICODE.letter.test(String.fromCharCode(code)));
-};
-
-function is_digit(code) {
- return code >= 48 && code <= 57; //XXX: find out if "UnicodeDigit" means something else than 0..9
-};
-
-function is_alphanumeric_char(code) {
- return is_digit(code) || is_letter(code);
-};
-
-function is_unicode_combining_mark(ch) {
- return UNICODE.non_spacing_mark.test(ch) || UNICODE.space_combining_mark.test(ch);
-};
-
-function is_unicode_connector_punctuation(ch) {
- return UNICODE.connector_punctuation.test(ch);
-};
-
-function is_identifier(name) {
- return /^[a-z_$][a-z0-9_$]*$/i.test(name) && !RESERVED_WORDS(name);
-};
-
-function is_identifier_start(code) {
- return code == 36 || code == 95 || is_letter(code);
-};
-
-function is_identifier_char(ch) {
- var code = ch.charCodeAt(0);
- return is_identifier_start(code)
- || is_digit(code)
- || code == 8204 // \u200c: zero-width non-joiner <ZWNJ>
- || code == 8205 // \u200d: zero-width joiner <ZWJ> (in my ECMA-262 PDF, this is also 200c)
- || is_unicode_combining_mark(ch)
- || is_unicode_connector_punctuation(ch)
- ;
-};
-
-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;
- this.col = col;
- this.pos = pos;
- 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, filename, line, col, pos) {
- AST_Node.warn("ERROR: {message} [{file}:{line},{col}]", {
- message: message,
- file: filename,
- line: line,
- col: col
- });
- 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, filename) {
-
- var S = {
- text : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/\uFEFF/g, ''),
- filename : filename,
- pos : 0,
- tokpos : 0,
- line : 1,
- 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 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" && !UNARY_POSTFIX[value]) ||
- (type == "keyword" && KEYWORDS_BEFORE_EXPRESSION(value)) ||
- (type == "punc" && 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,
- file : filename
- };
- 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 new AST_Token(ret);
- };
-
- function skip_whitespace() {
- while (WHITESPACE_CHARS(peek()))
- next();
- };
-
- function read_while(pred) {
- var ret = "", ch, i = 0;
- while ((ch = peek()) && pred(ch, i++))
- ret += next();
- return ret;
- };
-
- function parse_error(err) {
- js_error(err, filename, 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){
- var code = ch.charCodeAt(0);
- switch (code) {
- case 120: case 88: // xX
- return has_x ? false : (has_x = true);
- case 101: case 69: // eE
- return has_x ? true : has_e ? false : (has_e = after_e = true);
- case 45: // -
- return after_e || (i == 0 && !prefix);
- case 43: // +
- return after_e;
- case (after_e = false, 46): // .
- return (!has_dot && !has_x && !has_e) ? (has_dot = true) : false;
- }
- return is_alphanumeric_char(code);
- });
- 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.charCodeAt(0)) {
- case 110 : return "\n";
- case 114 : return "\r";
- case 116 : return "\t";
- case 98 : return "\b";
- case 118 : return "\u000b"; // \v
- case 102 : return "\f";
- case 48 : return "\0";
- case 120 : return String.fromCharCode(hex_bytes(2)); // \x
- case 117 : return String.fromCharCode(hex_bytes(4)); // \u
- case 10 : return ""; // newline
- 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;
- };
-
- var read_string = 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;
- 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);
- };
-
- var read_multiline_comment = with_eof_error("Unterminated multiline comment", function(){
- next();
- var i = find("*/", true);
- var text = S.text.substring(S.pos, i);
- var a = text.split("\n"), n = a.length;
- // update stream position
- S.pos = i + 2;
- S.line += n - 1;
- if (n > 1) S.col = a[n - 1].length;
- else S.col += a[n - 1].length;
- S.col += 2;
- S.newline_before = S.newline_before || text.indexOf("\n") >= 0;
- 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 (KEYWORDS(name) && escaped) {
- hex = name.charCodeAt(0).toString(16).toUpperCase();
- name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1);
- }
- return name;
- };
-
- var read_regexp = with_eof_error("Unterminated regular expression", function(regexp){
- 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", new RegExp(regexp, mods));
- });
-
- function read_operator(prefix) {
- function grow(op) {
- if (!peek()) return op;
- var bigger = op + peek();
- if (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().charCodeAt(0))
- ? read_num(".")
- : token("punc", ".");
- };
-
- function read_word() {
- var word = read_name();
- return KEYWORDS_ATOM(word) ? token("atom", word)
- : !KEYWORDS(word) ? token("name", word)
- : OPERATORS(word) ? token("operator", word)
- : token("keyword", word);
- };
-
- function with_eof_error(eof_error, cont) {
- return function(x) {
- try {
- return cont(x);
- } 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");
- var code = ch.charCodeAt(0);
- switch (code) {
- case 34: case 39: return read_string();
- case 46: return handle_dot();
- case 47: return handle_slash();
- }
- if (is_digit(code)) return read_num();
- if (PUNC_CHARS(ch)) return token("punc", next());
- if (OPERATOR_CHARS(ch)) return read_operator();
- if (code == 92 || is_identifier_start(code)) return read_word();
- parse_error("Unexpected character '" + ch + "'");
- };
-
- next_token.context = function(nc) {
- if (nc) S = nc;
- return S;
- };
-
- return next_token;
-
-};
-
-/* -----[ Parser (constants) ]----- */
-
-var UNARY_PREFIX = makePredicate([
- "typeof",
- "void",
- "delete",
- "--",
- "++",
- "!",
- "~",
- "-",
- "+"
-]);
-
-var UNARY_POSTFIX = makePredicate([ "--", "++" ]);
-
-var ASSIGNMENT = makePredicate([ "=", "+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=" ]);
-
-var PRECEDENCE = (function(a, ret){
- for (var i = 0, 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 parse($TEXT, options) {
-
- options = defaults(options, {
- strict : false,
- filename : null,
- toplevel : null
- });
-
- var S = {
- input : typeof $TEXT == "string" ? tokenizer($TEXT, options.filename) : $TEXT,
- token : null,
- prev : null,
- peeked : null,
- in_function : 0,
- in_directives : true,
- in_loop : 0,
- labels : []
- };
-
- S.token = next();
-
- function is(type, value) {
- return is_token(S.token, type, value);
- };
-
- function peek() { return S.peeked || (S.peeked = S.input()); };
-
- function next() {
- S.prev = S.token;
- if (S.peeked) {
- S.token = S.peeked;
- S.peeked = null;
- } else {
- S.token = S.input();
- }
- S.in_directives = S.in_directives && (
- S.token.type == "string" || is("punc", ";")
- );
- return S.token;
- };
-
- function prev() {
- return S.prev;
- };
-
- function croak(msg, line, col, pos) {
- var ctx = S.input.context();
- js_error(msg,
- ctx.filename,
- line != null ? line : ctx.tokline,
- col != null ? col : ctx.tokcol,
- pos != null ? pos : ctx.tokpos);
- };
-
- function token_error(token, msg) {
- croak(msg, token.line, token.col);
- };
-
- function unexpected(token) {
- if (token == null)
- token = S.token;
- token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")");
- };
-
- function expect_token(type, val) {
- if (is(type, val)) {
- return next();
- }
- token_error(S.token, "Unexpected token " + S.token.type + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»");
- };
-
- function expect(punc) { return expect_token("punc", punc); };
-
- function can_insert_semicolon() {
- return !options.strict && (
- S.token.nlb || is("eof") || is("punc", "}")
- );
- };
-
- function semicolon() {
- if (is("punc", ";")) next();
- else if (!can_insert_semicolon()) unexpected();
- };
-
- function parenthesised() {
- expect("(");
- var exp = expression(true);
- expect(")");
- return exp;
- };
-
- function embed_tokens(parser) {
- return function() {
- var start = S.token;
- var expr = parser();
- var end = prev();
- expr.start = start;
- expr.end = end;
- return expr;
- };
- };
-
- var statement = embed_tokens(function() {
- var tmp;
- 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();
- // XXXv2: decide how to fix directives
- if (dir && stat.body instanceof AST_String && !is("punc", ","))
- return new AST_Directive({ value: stat.body.value });
- return stat;
- case "num":
- case "regexp":
- case "operator":
- case "atom":
- return simple_statement();
-
- case "name":
- return is_token(peek(), "punc", ":")
- ? labeled_statement()
- : simple_statement();
-
- case "punc":
- switch (S.token.value) {
- case "{":
- return new AST_BlockStatement({
- start : S.token,
- body : block_(),
- end : prev()
- });
- case "[":
- case "(":
- return simple_statement();
- case ";":
- next();
- return new AST_EmptyStatement();
- default:
- unexpected();
- }
-
- case "keyword":
- switch (tmp = S.token.value, next(), tmp) {
- case "break":
- return break_cont(AST_Break);
-
- case "continue":
- return break_cont(AST_Continue);
-
- case "debugger":
- semicolon();
- return new AST_Debugger();
-
- case "do":
- return new AST_Do({
- body : in_loop(statement),
- condition : (expect_token("keyword", "while"), tmp = parenthesised(), semicolon(), tmp)
- });
-
- case "while":
- return new AST_While({
- condition : parenthesised(),
- body : in_loop(statement)
- });
-
- case "for":
- return for_();
-
- case "function":
- return function_(true);
-
- case "if":
- return if_();
-
- case "return":
- if (S.in_function == 0)
- croak("'return' outside of function");
- return new AST_Return({
- value: ( is("punc", ";")
- ? (next(), null)
- : can_insert_semicolon()
- ? null
- : (tmp = expression(true), semicolon(), tmp) )
- });
-
- case "switch":
- return new AST_Switch({
- expression : parenthesised(),
- body : in_loop(switch_body_)
- });
-
- case "throw":
- if (S.token.nlb)
- croak("Illegal newline after 'throw'");
- return new AST_Throw({
- value: (tmp = expression(true), semicolon(), tmp)
- });
-
- case "try":
- return try_();
-
- case "var":
- return tmp = var_(), semicolon(), tmp;
-
- case "const":
- return tmp = const_(), semicolon(), tmp;
-
- case "with":
- return new AST_With({
- expression : parenthesised(),
- body : statement()
- });
-
- default:
- unexpected();
- }
- }
- });
-
- function labeled_statement() {
- var label = as_symbol(AST_Label);
- if (find_if(function(l){ return l.name == label.name }, S.labels)) {
- // ECMA-262, 12.12: An ECMAScript program is considered
- // syntactically incorrect if it contains a
- // LabelledStatement that is enclosed by a
- // LabelledStatement with the same Identifier as label.
- croak("Label " + label.name + " defined twice");
- }
- expect(":");
- S.labels.push(label);
- var stat = statement();
- S.labels.pop();
- return new AST_LabeledStatement({ body: stat, label: label });
- };
-
- function simple_statement(tmp) {
- return new AST_SimpleStatement({ body: (tmp = expression(true), semicolon(), tmp) });
- };
-
- function break_cont(type) {
- var label = null;
- if (!can_insert_semicolon()) {
- label = as_symbol(AST_LabelRef, true);
- }
- if (label != null) {
- if (!find_if(function(l){ return l.name == label.name }, S.labels))
- croak("Undefined label " + label.name);
- }
- else if (S.in_loop == 0)
- croak(type.TYPE + " not inside a loop or switch");
- semicolon();
- return new type({ label: label });
- };
-
- function for_() {
- expect("(");
- var init = null;
- if (!is("punc", ";")) {
- init = is("keyword", "var")
- ? (next(), var_(true))
- : expression(true, true);
- if (is("operator", "in")) {
- if (init instanceof AST_Var && init.definitions.length > 1)
- croak("Only one variable declaration allowed in for..in loop");
- next();
- return for_in(init);
- }
- }
- return regular_for(init);
- };
-
- function regular_for(init) {
- expect(";");
- var test = is("punc", ";") ? null : expression(true);
- expect(";");
- var step = is("punc", ")") ? null : expression(true);
- expect(")");
- return new AST_For({
- init : init,
- condition : test,
- step : step,
- body : in_loop(statement)
- });
- };
-
- function for_in(init) {
- var lhs = init instanceof AST_Var ? init.definitions[0].name : null;
- var obj = expression(true);
- expect(")");
- return new AST_ForIn({
- init : init,
- name : lhs,
- object : obj,
- body : in_loop(statement)
- });
- };
-
- var function_ = function(in_statement, ctor) {
- var name = is("name") ? as_symbol(in_statement
- ? AST_SymbolDefun
- : AST_SymbolLambda) : null;
- if (in_statement && !name)
- unexpected();
- expect("(");
- if (!ctor) ctor = in_statement ? AST_Defun : AST_Function;
- return new ctor({
- name: name,
- argnames: (function(first, a){
- while (!is("punc", ")")) {
- if (first) first = false; else expect(",");
- a.push(as_symbol(AST_SymbolFunarg));
- }
- next();
- return a;
- })(true, []),
- body: (function(loop, labels){
- ++S.in_function;
- S.in_directives = true;
- S.in_loop = 0;
- S.labels = [];
- var a = block_();
- --S.in_function;
- S.in_loop = loop;
- S.labels = labels;
- return a;
- })(S.in_loop, S.labels)
- });
- };
-
- function if_() {
- var cond = parenthesised(), body = statement(), belse = null;
- if (is("keyword", "else")) {
- next();
- belse = statement();
- }
- return new AST_If({
- condition : cond,
- body : body,
- alternative : belse
- });
- };
-
- function block_() {
- expect("{");
- var a = [];
- while (!is("punc", "}")) {
- if (is("eof")) unexpected();
- a.push(statement());
- }
- next();
- return a;
- };
-
- function switch_body_() {
- expect("{");
- var a = [], cur = null, branch = null, tmp;
- while (!is("punc", "}")) {
- if (is("eof")) unexpected();
- if (is("keyword", "case")) {
- if (branch) branch.end = prev();
- cur = [];
- branch = new AST_Case({
- start : (tmp = S.token, next(), tmp),
- expression : expression(true),
- body : cur
- });
- a.push(branch);
- expect(":");
- }
- else if (is("keyword", "default")) {
- if (branch) branch.end = prev();
- cur = [];
- branch = new AST_Default({
- start : (tmp = S.token, next(), expect(":"), tmp),
- body : cur
- });
- a.push(branch);
- }
- else {
- if (!cur) unexpected();
- cur.push(statement());
- }
- }
- if (branch) branch.end = prev();
- next();
- return a;
- };
-
- function try_() {
- var body = block_(), bcatch = null, bfinally = null;
- if (is("keyword", "catch")) {
- var start = S.token;
- next();
- expect("(");
- var name = as_symbol(AST_SymbolCatch);
- expect(")");
- bcatch = new AST_Catch({
- start : start,
- argname : name,
- body : block_(),
- end : prev()
- });
- }
- if (is("keyword", "finally")) {
- var start = S.token;
- next();
- bfinally = new AST_Finally({
- start : start,
- body : block_(),
- end : prev()
- });
- }
- if (!bcatch && !bfinally)
- croak("Missing catch/finally blocks");
- return new AST_Try({
- body : body,
- bcatch : bcatch,
- bfinally : bfinally
- });
- };
-
- function vardefs(no_in, in_const) {
- var a = [];
- for (;;) {
- a.push(new AST_VarDef({
- start : S.token,
- name : as_symbol(in_const ? AST_SymbolConst : AST_SymbolVar),
- value : is("operator", "=") ? (next(), expression(false, no_in)) : null,
- end : prev()
- }));
- if (!is("punc", ","))
- break;
- next();
- }
- return a;
- };
-
- var var_ = function(no_in) {
- return new AST_Var({
- start : prev(),
- definitions : vardefs(no_in, false),
- end : prev()
- });
- };
-
- var const_ = function() {
- return new AST_Const({
- start : prev(),
- definitions : vardefs(false, true),
- end : prev()
- });
- };
-
- var new_ = function() {
- var start = S.token;
- expect_token("operator", "new");
- var newexp = expr_atom(false), args;
- if (is("punc", "(")) {
- next();
- args = expr_list(")");
- } else {
- args = [];
- }
- return subscripts(new AST_New({
- start : start,
- expression : newexp,
- args : args,
- end : prev()
- }), true);
- };
-
- function as_atom_node() {
- var tok = S.token, ret;
- switch (tok.type) {
- case "name":
- return as_symbol(AST_SymbolRef);
- case "num":
- ret = new AST_Number({ start: tok, end: tok, value: tok.value });
- break;
- case "string":
- ret = new AST_String({ start: tok, end: tok, value: tok.value });
- break;
- case "regexp":
- ret = new AST_RegExp({ start: tok, end: tok, value: tok.value });
- break;
- case "atom":
- switch (tok.value) {
- case "false":
- ret = new AST_False({ start: tok, end: tok });
- break;
- case "true":
- ret = new AST_True({ start: tok, end: tok });
- break;
- case "null":
- ret = new AST_Null({ start: tok, end: tok });
- break;
- }
- break;
- }
- next();
- return ret;
- };
-
- var expr_atom = function(allow_calls) {
- if (is("operator", "new")) {
- return new_();
- }
- var start = S.token;
- if (is("punc")) {
- switch (start.value) {
- case "(":
- next();
- var ex = expression(true);
- ex.start = start;
- ex.end = S.token;
- expect(")");
- return subscripts(ex, allow_calls);
- case "[":
- return subscripts(array_(), allow_calls);
- case "{":
- return subscripts(object_(), allow_calls);
- }
- unexpected();
- }
- if (is("keyword", "function")) {
- next();
- var func = function_(false);
- func.start = start;
- func.end = prev();
- return subscripts(func, allow_calls);
- }
- if (ATOMIC_START_TOKEN[S.token.type]) {
- return subscripts(as_atom_node(), allow_calls);
- }
- unexpected();
- };
-
- function expr_list(closing, allow_trailing_comma, allow_empty) {
- var first = true, a = [];
- while (!is("punc", closing)) {
- if (first) first = false; else expect(",");
- if (allow_trailing_comma && is("punc", closing)) break;
- if (is("punc", ",") && allow_empty) {
- a.push(new AST_Undefined({ start: S.token, end: S.token }));
- } else {
- a.push(expression(false));
- }
- }
- next();
- return a;
- };
-
- var array_ = embed_tokens(function() {
- expect("[");
- return new AST_Array({
- elements: expr_list("]", !options.strict, true)
- });
- });
-
- var object_ = embed_tokens(function() {
- expect("{");
- var first = true, a = [];
- while (!is("punc", "}")) {
- if (first) first = false; else expect(",");
- if (!options.strict && is("punc", "}"))
- // allow trailing comma
- break;
- var start = S.token;
- var type = start.type;
- var name = as_property_name();
- if (type == "name" && !is("punc", ":")) {
- if (name == "get") {
- a.push(new AST_ObjectGetter({
- start : start,
- key : name,
- value : function_(false, AST_Lambda),
- end : prev()
- }));
- continue;
- }
- if (name == "set") {
- a.push(new AST_ObjectSetter({
- start : start,
- key : name,
- value : function_(false, AST_Lambda),
- end : prev()
- }));
- continue;
- }
- }
- expect(":");
- a.push(new AST_ObjectKeyVal({
- start : start,
- key : name,
- value : expression(false),
- end : prev()
- }));
- }
- next();
- return new AST_Object({ properties: a });
- });
-
- function as_property_name() {
- var tmp;
- switch (S.token.type) {
- case "num":
- case "string":
- case "name":
- case "operator":
- case "keyword":
- case "atom":
- return (tmp = S.token.value, next(), tmp);
- default:
- unexpected();
- }
- };
-
- function as_name() {
- var tmp;
- switch (S.token.type) {
- case "name":
- case "operator":
- case "keyword":
- case "atom":
- return (tmp = S.token.value, next(), tmp);
- default:
- unexpected();
- }
- };
-
- function as_symbol(type, noerror) {
- if (!is("name")) {
- if (!noerror) croak("Name expected");
- return null;
- }
- var name = S.token.value;
- var sym = new (name == "this" ? AST_This : type)({
- name : String(S.token.value),
- start : S.token,
- end : S.token
- });
- next();
- return sym;
- };
-
- var subscripts = function(expr, allow_calls) {
- var start = expr.start;
- if (is("punc", ".")) {
- next();
- return subscripts(new AST_Dot({
- start : start,
- expression : expr,
- property : as_name(),
- end : prev()
- }), allow_calls);
- }
- if (is("punc", "[")) {
- next();
- var prop = expression(true);
- expect("]");
- return subscripts(new AST_Sub({
- start : start,
- expression : expr,
- property : prop,
- end : prev()
- }), allow_calls);
- }
- if (allow_calls && is("punc", "(")) {
- next();
- return subscripts(new AST_Call({
- start : start,
- expression : expr,
- args : expr_list(")"),
- end : prev()
- }), true);
- }
- return expr;
- };
-
- var maybe_unary = function(allow_calls) {
- var start = S.token, tmp;
- if (is("operator") && UNARY_PREFIX(S.token.value)) {
- var ex = make_unary(AST_UnaryPrefix,
- (tmp = S.token.value, next(), tmp),
- maybe_unary(allow_calls));
- ex.start = start;
- ex.end = prev();
- return ex;
- }
- var val = expr_atom(allow_calls);
- while (is("operator") && UNARY_POSTFIX(S.token.value) && !S.token.nlb) {
- val = make_unary(AST_UnaryPostfix, S.token.value, val);
- val.start = start;
- val.end = S.token;
- next();
- }
- return val;
- };
-
- function make_unary(ctor, op, expr) {
- if ((op == "++" || op == "--") && !is_assignable(expr))
- croak("Invalid use of " + op + " operator");
- return new ctor({ operator: op, expression: expr });
- };
-
- var expr_op = function(left, min_prec, no_in) {
- var op = is("operator") ? S.token.value : null;
- if (op == "in" && no_in) op = null;
- var prec = op != null ? PRECEDENCE[op] : null;
- if (prec != null && prec > min_prec) {
- next();
- var right = expr_op(maybe_unary(true), prec, no_in);
- return expr_op(new AST_Binary({
- start : left.start,
- left : left,
- operator : op,
- right : right,
- end : right.end
- }), min_prec, no_in);
- }
- return left;
- };
-
- function expr_ops(no_in) {
- return expr_op(maybe_unary(true), 0, no_in);
- };
-
- var maybe_conditional = function(no_in) {
- var start = S.token;
- var expr = expr_ops(no_in);
- if (is("operator", "?")) {
- next();
- var yes = expression(false);
- expect(":");
- return new AST_Conditional({
- start : start,
- condition : expr,
- consequent : yes,
- alternative : expression(false, no_in),
- end : peek()
- });
- }
- return expr;
- };
-
- function is_assignable(expr) {
- if (!options.strict) return true;
- switch (expr[0]+"") {
- case "dot":
- case "sub":
- case "new":
- case "call":
- return true;
- case "name":
- return expr[1] != "this";
- }
- };
-
- var maybe_assign = function(no_in) {
- var start = S.token;
- var left = maybe_conditional(no_in), val = S.token.value;
- if (is("operator") && ASSIGNMENT(val)) {
- if (is_assignable(left)) {
- next();
- return new AST_Assign({
- start : start,
- left : left,
- operator : val,
- right : maybe_assign(no_in),
- end : peek()
- });
- }
- croak("Invalid assignment");
- }
- return left;
- };
-
- var expression = function(commas, no_in) {
- var start = S.token;
- var expr = maybe_assign(no_in);
- if (commas && is("punc", ",")) {
- next();
- return new AST_Seq({
- start : start,
- car : expr,
- cdr : expression(true, no_in),
- end : peek()
- });
- }
- return expr;
- };
-
- function in_loop(cont) {
- ++S.in_loop;
- var ret = cont();
- --S.in_loop;
- return ret;
- };
-
- return (function(){
- var start = S.token;
- var body = [];
- while (!is("eof"))
- body.push(statement());
- var end = prev();
- var toplevel = options.toplevel;
- if (toplevel) {
- toplevel.body = toplevel.body.concat(body);
- toplevel.end = end;
- } else {
- toplevel = new AST_Toplevel({ start: start, body: body, end: end });
- }
- return toplevel;
- })();
-
-};
-exports.parse = parse;
-})(typeof exports === "undefined" ? (window.uglifyjs = {}) : exports);
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/node-acorn-jsx.git
More information about the Pkg-javascript-commits
mailing list