diff --git a/deps/narcissus/LICENSE b/deps/narcissus/LICENSE deleted file mode 100644 index 173bdc47..00000000 --- a/deps/narcissus/LICENSE +++ /dev/null @@ -1,5 +0,0 @@ -This software is available under your choice of the following licenses: - - * MPL 1.1 or later: http://www.mozilla.org/MPL/ - * GPL 2.0 or later: http://www.gnu.org/licenses/gpl.html - * LGPL 2.1 or later: http://www.gnu.org/licenses/lgpl.html diff --git a/deps/narcissus/README.md b/deps/narcissus/README.md deleted file mode 100644 index 02e7daa1..00000000 --- a/deps/narcissus/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# Narcissus - -Narcissus is a JavaScript interpreter written in pure JavaScript (i.e., a [meta-circular evaluator](http://en.wikipedia.org/wiki/Meta-circular_evaluator)), using the [SpiderMonkey](http://www.mozilla.org/js/spidermonkey/) engine. - -Originally a proof-of-concept by [Brendan Eich](http://brendaneich.com/), Narcissus is being revived as a test-bed for rapidly prototyping new language features for the JavaScript language (as well as the ECMAScript standard). - -# Documentation - -Documentation can be found on the [Narcissus wiki](https://github.com/mozilla/narcissus/wiki). - -# Contributors - -* Tom Austin -* Brendan Eich -* Andreas Gal -* Shu-yu Guo -* Dave Herman -* Bruno Jouhier -* Gregor Richards -* Dimitris Vardoulakis -* Patrick Walton diff --git a/deps/narcissus/jstests b/deps/narcissus/jstests deleted file mode 100755 index c62465bf..00000000 --- a/deps/narcissus/jstests +++ /dev/null @@ -1,44 +0,0 @@ -#!/bin/sh - -# Root of the narcissus tree -NJS_HOME=`dirname $0` -NJS_HOME=`(cd $NJS_HOME; pwd)` - -# Fake information for the test harness's |xulRuntime| configuration object. -XUL_INFO=none:none:true - -if [ $# -eq 1 -a "$1" = "-h" ]; then - echo "usage: jstests [-h | -a | ...]" 1>&2 - echo " -h display this usage information and quit" 1>&2 - echo " -a run all but the slowest tests (those in xfail/narcissus-slow.txt)" 1>&2 - echo " path to individual test (relative to test directory)" 1>&2 - echo "" 1>&2 - echo "With no arguments, jstests runs all tests except those listed in" 1>&2 - echo "xfail/narcissus-failures.txt, which includes all the tests listed in" 1>&2 - echo "xfail/narcissus-slow.txt." 1>&2 - echo "" 1>&2 - echo "The test directory is searched for either in NJS_TESTS or in" 1>&2 - echo "a tests/ subdirectory of the Narcissus home directory." - exit -elif [ $# -gt 0 -a "$1" = "-a" ]; then - shift - XFAIL=narcissus-slow.txt -else - XFAIL=narcissus-failures.txt -fi - -if [ ! -z $NJS_TESTS -a -d $NJS_TESTS ]; then - cd $NJS_TESTS -elif [ -d $NJS_HOME/tests ]; then - cd $NJS_HOME/tests -else - echo 'Expected a test directory in $NJS_TESTS or '"$NJS_HOME/tests." 1>&2 - echo "Run jstests -h for more information." 1>&2 - exit 1 -fi - -if [ $# -gt 0 ]; then - exec python jstests.py --xul-info=$XUL_INFO -s -o -d -j 4 $NJS_HOME/njs $* -else - exec python jstests.py --xul-info=$XUL_INFO -d -j 4 $NJS_HOME/njs -x $NJS_HOME/xfail/$XFAIL -fi diff --git a/deps/narcissus/lib/decompiler.js b/deps/narcissus/lib/decompiler.js deleted file mode 100644 index 92946458..00000000 --- a/deps/narcissus/lib/decompiler.js +++ /dev/null @@ -1,50 +0,0 @@ -/* vim: set sw=4 ts=4 et tw=78: */ -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is the Narcissus JavaScript engine. - * - * The Initial Developer of the Original Code is - * Brendan Eich . - * Portions created by the Initial Developer are Copyright (C) 2004 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * Tom Austin - * Brendan Eich - * Shu-Yu Guo - * Dave Herman - * Dimitris Vardoulakis - * Patrick Walton - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -require("./jsdefs"); -require("./jslex"); -require("./jsparse"); -require("./jsdecomp"); - -for (var exp in Narcissus.decompiler) - exports[exp] = Narcissus.decompiler[exp]; diff --git a/deps/narcissus/lib/definitions.js b/deps/narcissus/lib/definitions.js deleted file mode 100644 index 4412b4a1..00000000 --- a/deps/narcissus/lib/definitions.js +++ /dev/null @@ -1,47 +0,0 @@ -/* vim: set sw=4 ts=4 et tw=78: */ -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is the Narcissus JavaScript engine. - * - * The Initial Developer of the Original Code is - * Brendan Eich . - * Portions created by the Initial Developer are Copyright (C) 2004 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * Tom Austin - * Brendan Eich - * Shu-Yu Guo - * Dave Herman - * Dimitris Vardoulakis - * Patrick Walton - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -require("./jsdefs"); - -for (var exp in Narcissus.definitions) - exports[exp] = Narcissus.definitions[exp]; diff --git a/deps/narcissus/lib/jsbrowser.js b/deps/narcissus/lib/jsbrowser.js deleted file mode 100644 index eb03e05a..00000000 --- a/deps/narcissus/lib/jsbrowser.js +++ /dev/null @@ -1,65 +0,0 @@ -/* -*- Mode: JS; tab-width: 4; indent-tabs-mode: nil; -*- - * vim: set sw=4 ts=8 et tw=78: -/* ***** BEGIN LICENSE BLOCK ***** - * - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is the Narcissus JavaScript engine. - * - * The Initial Developer of the Original Code is - * Brendan Eich . - * Portions created by the Initial Developer are Copyright (C) 2004 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -/* - * Narcissus - JS implemented in JS. - * - * Browser-specific tweaks needed for Narcissus to execute properly - */ - -// Prevent setTimeout from breaking out to SpiderMonkey -Narcissus.interpreter.globalBase.setTimeout = function(code, delay) { - var timeoutCode = (typeof code === "string") ? - function() { Narcissus.interpreter.evaluate(code); } : - code; - return setTimeout(timeoutCode, delay); -}; - -// Prevent setInterval from breaking out to SpiderMonkey -Narcissus.interpreter.globalBase.setInterval = function(code, delay) { - var timeoutCode = (typeof code === "string") ? - function() { Narcissus.interpreter.evaluate(code); } : - code; - return setInterval(timeoutCode, delay); -}; - -// Hack to avoid problems with the Image constructor in Narcissus. -Narcissus.interpreter.globalBase.Image = function() {}; - - diff --git a/deps/narcissus/lib/jsdecomp.js b/deps/narcissus/lib/jsdecomp.js deleted file mode 100644 index 3121198e..00000000 --- a/deps/narcissus/lib/jsdecomp.js +++ /dev/null @@ -1,529 +0,0 @@ -/* vim: set sw=4 ts=4 et tw=78: */ -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is the Narcissus JavaScript engine. - * - * The Initial Developer of the Original Code is - * Brendan Eich . - * Portions created by the Initial Developer are Copyright (C) 2010 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * Shu-Yu Guo - * Bruno Jouhier - * Gregor Richards - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -/* - * Narcissus - JS implemented in JS. - * - * Decompiler and pretty-printer. - */ - -Narcissus.decompiler = (function() { - - const parser = Narcissus.parser; - const definitions = Narcissus.definitions; - const tokens = definitions.tokens; - - // Set constants in the local scope. - eval(definitions.consts); - - function indent(n, s) { - var ss = "", d = true; - - for (var i = 0, j = s.length; i < j; i++) { - if (d) - for (var k = 0; k < n; k++) - ss += " "; - ss += s[i]; - d = s[i] === '\n'; - } - - return ss; - } - - function isBlock(n) { - return n && (n.type === BLOCK); - } - - function isNonEmptyBlock(n) { - return isBlock(n) && n.children.length > 0; - } - - function nodeStr(n) { - return '"' + - n.value.replace(/\\/g, "\\\\") - .replace(/"/g, "\\\"") - .replace(/\n/g, "\\n") - .replace(/\r/g, "\\r") + - '"'; - } - - function pp(n, d, inLetHead) { - var topScript = false; - - if (!n) - return ""; - if (!(n instanceof Object)) - return n; - if (!d) { - topScript = true; - d = 1; - } - - var p = ""; - - if (n.parenthesized) - p += "("; - - switch (n.type) { - case FUNCTION: - case GETTER: - case SETTER: - if (n.type === FUNCTION) - p += "function"; - else if (n.type === GETTER) - p += "get"; - else - p += "set"; - - p += (n.name ? " " + n.name : "") + "("; - for (var i = 0, j = n.params.length; i < j; i++) - p += (i > 0 ? ", " : "") + pp(n.params[i], d); - p += ") " + pp(n.body, d); - break; - - case SCRIPT: - case BLOCK: - var nc = n.children; - if (topScript) { - // No indentation. - for (var i = 0, j = nc.length; i < j; i++) { - if (i > 0) - p += "\n"; - p += pp(nc[i], d); - var eoc = p[p.length - 1]; - if (eoc != ";") - p += ";"; - } - - break; - } - - p += "{"; - if (n.id !== undefined) - p += " /* " + n.id + " */"; - p += "\n"; - for (var i = 0, j = nc.length; i < j; i++) { - if (i > 0) - p += "\n"; - p += indent(4, pp(nc[i], d)); - var eoc = p[p.length - 1]; - if (eoc != ";") - p += ";"; - } - p += "\n}"; - break; - - case LET_BLOCK: - p += "let (" + pp(n.variables, d, true) + ") "; - if (n.expression) - p += pp(n.expression, d); - else - p += pp(n.block, d); - break; - - case IF: - p += "if (" + pp(n.condition, d) + ") "; - - var tp = n.thenPart, ep = n.elsePart; - var b = isBlock(tp) || isBlock(ep); - if (!b) - p += "{\n"; - p += (b ? pp(tp, d) : indent(4, pp(tp, d))) + "\n"; - - if (ep) { - if (!b) - p += "} else {\n"; - else - p += " else "; - - p += (b ? pp(ep, d) : indent(4, pp(ep, d))) + "\n"; - } - if (!b) - p += "}"; - break; - - case SWITCH: - p += "switch (" + pp(n.discriminant, d) + ") {\n"; - for (var i = 0, j = n.cases.length; i < j; i++) { - var ca = n.cases[i]; - if (ca.type === CASE) - p += " case " + pp(ca.caseLabel, d) + ":\n"; - else - p += " default:\n"; - ps = pp(ca.statements, d); - p += ps.slice(2, ps.length - 2) + "\n"; - } - p += "}"; - break; - - case FOR: - p += "for (" + pp(n.setup, d) + "; " - + pp(n.condition, d) + "; " - + pp(n.update, d) + ") "; - - var pb = pp(n.body, d); - if (!isBlock(n.body)) - p += "{\n" + indent(4, pb) + ";\n}"; - else if (n.body) - p += pb; - break; - - case WHILE: - p += "while (" + pp(n.condition, d) + ") "; - - var pb = pp(n.body, d); - if (!isBlock(n.body)) - p += "{\n" + indent(4, pb) + ";\n}"; - else - p += pb; - break; - - case FOR_IN: - var u = n.varDecl; - p += n.isEach ? "for each (" : "for ("; - p += (u ? pp(u, d) : pp(n.iterator, d)) + " in " + - pp(n.object, d) + ") "; - - var pb = pp(n.body, d); - if (!isBlock(n.body)) - p += "{\n" + indent(4, pb) + ";\n}"; - else if (n.body) - p += pb; - break; - - case DO: - p += "do " + pp(n.body, d); - p += " while (" + pp(n.condition, d) + ");"; - break; - - case BREAK: - p += "break" + (n.label ? " " + n.label : "") + ";"; - break; - - case CONTINUE: - p += "continue" + (n.label ? " " + n.label : "") + ";"; - break; - - case TRY: - p += "try "; - p += pp(n.tryBlock, d); - for (var i = 0, j = n.catchClauses.length; i < j; i++) { - var t = n.catchClauses[i]; - p += " catch (" + pp(t.varName, d) + - (t.guard ? " if " + pp(t.guard, d) : "") + - ") "; - p += pp(t.block, d); - } - if (n.finallyBlock) { - p += " finally "; - p += pp(n.finallyBlock, d); - } - break; - - case THROW: - p += "throw " + pp(n.exception, d); - break; - - case RETURN: - p += "return"; - if (n.value) - p += " " + pp(n.value, d); - break; - - case YIELD: - p += "yield"; - if (n.value.type) - p += " " + pp(n.value, d); - break; - - case GENERATOR: - p += pp(n.expression, d) + " " + pp(n.tail, d); - break; - - case WITH: - p += "with (" + pp(n.object, d) + ") "; - p += pp(n.body, d); - break; - - case LET: - case VAR: - case CONST: - var nc = n.children; - if (!inLetHead) { - p += tokens[n.type] + " "; - } - for (var i = 0, j = nc.length; i < j; i++) { - if (i > 0) - p += ", "; - var u = nc[i]; - p += pp(u.name, d); - if (u.initializer) - p += " = " + pp(u.initializer, d); - } - break; - - case DEBUGGER: - p += "debugger\n"; - break; - - case SEMICOLON: - if (n.expression) { - p += pp(n.expression, d) + ";"; - } - break; - - case LABEL: - p += n.label + ":\n" + pp(n.statement, d); - break; - - case COMMA: - case LIST: - var nc = n.children; - for (var i = 0, j = nc.length; i < j; i++) { - if (i > 0) - p += ", "; - p += pp(nc[i], d); - } - break; - - case ASSIGN: - var nc = n.children; - var t = n.assignOp; - p += pp(nc[0], d) + " " + (t ? tokens[t] : "") + "=" - + " " + pp(nc[1], d); - break; - - case HOOK: - var nc = n.children; - p += "(" + pp(nc[0], d) + " ? " - + pp(nc[1], d) + " : " - + pp(nc[2], d); - p += ")"; - break; - - case OR: - case AND: - var nc = n.children; - p += "(" + pp(nc[0], d) + " " + tokens[n.type] + " " - + pp(nc[1], d); - p += ")"; - break; - - case BITWISE_OR: - case BITWISE_XOR: - case BITWISE_AND: - case EQ: - case NE: - case STRICT_EQ: - case STRICT_NE: - case LT: - case LE: - case GE: - case GT: - case IN: - case INSTANCEOF: - case LSH: - case RSH: - case URSH: - case PLUS: - case MINUS: - case MUL: - case DIV: - case MOD: - var nc = n.children; - p += "(" + pp(nc[0], d) + " " + tokens[n.type] + " " - + pp(nc[1], d) + ")"; - break; - - case DELETE: - case VOID: - case TYPEOF: - p += tokens[n.type] + " " + pp(n.children[0], d); - break; - - case NOT: - case BITWISE_NOT: - p += tokens[n.type] + pp(n.children[0], d); - break; - - case UNARY_PLUS: - p += "+" + pp(n.children[0], d); - break; - - case UNARY_MINUS: - p += "-" + pp(n.children[0], d); - break; - - case INCREMENT: - case DECREMENT: - if (n.postfix) { - p += pp(n.children[0], d) + tokens[n.type]; - } else { - p += tokens[n.type] + pp(n.children[0], d); - } - break; - - case DOT: - var nc = n.children; - p += pp(nc[0], d) + "." + pp(nc[1], d); - break; - - case INDEX: - var nc = n.children; - p += pp(nc[0], d) + "[" + pp(nc[1], d) + "]"; - break; - - case CALL: - var nc = n.children; - p += pp(nc[0], d) + "(" + pp(nc[1], d) + ")"; - break; - - case NEW: - case NEW_WITH_ARGS: - var nc = n.children; - p += "new " + pp(nc[0], d); - if (nc[1]) - p += "(" + pp(nc[1], d) + ")"; - break; - - case ARRAY_INIT: - p += "["; - var nc = n.children; - for (var i = 0, j = nc.length; i < j; i++) { - if(nc[i]) - p += pp(nc[i], d); - p += "," - } - p += "]"; - break; - - case ARRAY_COMP: - p += "[" + pp (n.expression, d) + " "; - p += pp(n.tail, d); - p += "]"; - break; - - case COMP_TAIL: - var nc = n.children; - for (var i = 0, j = nc.length; i < j; i++) { - if (i > 0) - p += " "; - p += pp(nc[i], d); - } - if (n.guard) - p += " if (" + pp(n.guard, d) + ")"; - break; - - case OBJECT_INIT: - var nc = n.children; - if (nc[0] && nc[0].type === PROPERTY_INIT) - p += "{\n"; - else - p += "{"; - for (var i = 0, j = nc.length; i < j; i++) { - if (i > 0) { - p += ",\n"; - } - - var t = nc[i]; - if (t.type === PROPERTY_INIT) { - var tc = t.children; - var l; - // see if the left needs to be a string - if (typeof tc[0].value === "string" && !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(tc[0].value)) { - l = nodeStr(tc[0]); - } else { - l = pp(tc[0], d); - } - p += indent(4, l) + ": " + - indent(4, pp(tc[1], d)).substring(4); - } else { - p += indent(4, pp(t, d)); - } - } - p += "\n}"; - break; - - case NULL: - p += "null"; - break; - - case THIS: - p += "this"; - break; - - case TRUE: - p += "true"; - break; - - case FALSE: - p += "false"; - break; - - case IDENTIFIER: - case NUMBER: - case REGEXP: - if (n.value.isOctal) p += "0" + n.value.toString(8); - else p += n.value; - break; - - case STRING: - p += nodeStr(n); - break; - - case GROUP: - p += "(" + pp(n.children[0], d) + ")"; - break; - - default: - throw "PANIC: unknown operation " + tokens[n.type] + " " + n.toSource(); - } - - if (n.parenthesized) - p += ")"; - - return p; - } - - return { - pp: pp - }; - -}()); diff --git a/deps/narcissus/lib/jsdefs.js b/deps/narcissus/lib/jsdefs.js deleted file mode 100644 index 8fe3b0c0..00000000 --- a/deps/narcissus/lib/jsdefs.js +++ /dev/null @@ -1,379 +0,0 @@ -/* vim: set sw=4 ts=4 et tw=78: */ -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is the Narcissus JavaScript engine. - * - * The Initial Developer of the Original Code is - * Brendan Eich . - * Portions created by the Initial Developer are Copyright (C) 2004 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * Tom Austin - * Brendan Eich - * Shu-Yu Guo - * Dave Herman - * Dimitris Vardoulakis - * Patrick Walton - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -/* - * Narcissus - JS implemented in JS. - * - * Well-known constants and lookup tables. Many consts are generated from the - * tokens table via eval to minimize redundancy, so consumers must be compiled - * separately to take advantage of the simple switch-case constant propagation - * done by SpiderMonkey. - */ - -(function() { - - var narcissus = { - options: { - version: 185, - }, - hostGlobal: this - }; - Narcissus = narcissus; -})(); - -Narcissus.definitions = (function() { - - var tokens = [ - // End of source. - "END", - - // Operators and punctuators. Some pair-wise order matters, e.g. (+, -) - // and (UNARY_PLUS, UNARY_MINUS). - "\n", ";", - ",", - "=", - "?", ":", "CONDITIONAL", - "||", - "&&", - "|", - "^", - "&", - "==", "!=", "===", "!==", - "<", "<=", ">=", ">", - "<<", ">>", ">>>", - "+", "-", - "*", "/", "%", - "!", "~", "UNARY_PLUS", "UNARY_MINUS", - "++", "--", - ".", - "[", "]", - "{", "}", - "(", ")", - - // Nonterminal tree node type codes. - "SCRIPT", "BLOCK", "LABEL", "FOR_IN", "CALL", "NEW_WITH_ARGS", "INDEX", - "ARRAY_INIT", "OBJECT_INIT", "PROPERTY_INIT", "GETTER", "SETTER", - "GROUP", "LIST", "LET_BLOCK", "ARRAY_COMP", "GENERATOR", "COMP_TAIL", - - // Terminals. - "IDENTIFIER", "NUMBER", "STRING", "REGEXP", - - // Keywords. - "break", - "case", "catch", "const", "continue", - "debugger", "default", "delete", "do", - "else", - "false", "finally", "for", "function", - "if", "in", "instanceof", - "let", - "new", "null", - "return", - "switch", - "this", "throw", "true", "try", "typeof", - "var", "void", - "yield", - "while", "with", - ]; - - var statementStartTokens = [ - "break", - "const", "continue", - "debugger", "do", - "for", - "if", - "return", - "switch", - "throw", "try", - "var", - "yield", - "while", "with", - ]; - - // Operator and punctuator mapping from token to tree node type name. - // NB: because the lexer doesn't backtrack, all token prefixes must themselves - // be valid tokens (e.g. !== is acceptable because its prefixes are the valid - // tokens != and !). - var opTypeNames = { - '\n': "NEWLINE", - ';': "SEMICOLON", - ',': "COMMA", - '?': "HOOK", - ':': "COLON", - '||': "OR", - '&&': "AND", - '|': "BITWISE_OR", - '^': "BITWISE_XOR", - '&': "BITWISE_AND", - '===': "STRICT_EQ", - '==': "EQ", - '=': "ASSIGN", - '!==': "STRICT_NE", - '!=': "NE", - '<<': "LSH", - '<=': "LE", - '<': "LT", - '>>>': "URSH", - '>>': "RSH", - '>=': "GE", - '>': "GT", - '++': "INCREMENT", - '--': "DECREMENT", - '+': "PLUS", - '-': "MINUS", - '*': "MUL", - '/': "DIV", - '%': "MOD", - '!': "NOT", - '~': "BITWISE_NOT", - '.': "DOT", - '[': "LEFT_BRACKET", - ']': "RIGHT_BRACKET", - '{': "LEFT_CURLY", - '}': "RIGHT_CURLY", - '(': "LEFT_PAREN", - ')': "RIGHT_PAREN" - }; - - // Hash of keyword identifier to tokens index. NB: we must null __proto__ to - // avoid toString, etc. namespace pollution. - var keywords = {__proto__: null}; - - // Define const END, etc., based on the token names. Also map name to index. - var tokenIds = {}; - - // Building up a string to be eval'd in different contexts. - var consts = "var "; - for (var i = 0, j = tokens.length; i < j; i++) { - if (i > 0) - consts += ", "; - var t = tokens[i]; - var name; - if (/^[a-z]/.test(t)) { - name = t.toUpperCase(); - keywords[t] = i; - } else { - name = (/^\W/.test(t) ? opTypeNames[t] : t); - } - consts += name + " = " + i; - tokenIds[name] = i; - tokens[t] = i; - } - consts += ";"; - - var isStatementStartCode = {__proto__: null}; - for (i = 0, j = statementStartTokens.length; i < j; i++) - isStatementStartCode[keywords[statementStartTokens[i]]] = true; - - // Map assignment operators to their indexes in the tokens array. - var assignOps = ['|', '^', '&', '<<', '>>', '>>>', '+', '-', '*', '/', '%']; - - for (i = 0, j = assignOps.length; i < j; i++) { - t = assignOps[i]; - assignOps[t] = tokens[t]; - } - - function defineGetter(obj, prop, fn, dontDelete, dontEnum) { - Object.defineProperty(obj, prop, - { get: fn, configurable: !dontDelete, enumerable: !dontEnum }); - } - - function defineProperty(obj, prop, val, dontDelete, readOnly, dontEnum) { - Object.defineProperty(obj, prop, - { value: val, writable: !readOnly, configurable: !dontDelete, - enumerable: !dontEnum }); - } - - // Returns true if fn is a native function. (Note: SpiderMonkey specific.) - function isNativeCode(fn) { - // Relies on the toString method to identify native code. - return ((typeof fn) === "function") && fn.toString().match(/\[native code\]/); - } - - function getPropertyDescriptor(obj, name) { - while (obj) { - if (({}).hasOwnProperty.call(obj, name)) - return Object.getOwnPropertyDescriptor(obj, name); - obj = Object.getPrototypeOf(obj); - } - } - - function getOwnProperties(obj) { - var map = {}; - for (var name in Object.getOwnPropertyNames(obj)) - map[name] = Object.getOwnPropertyDescriptor(obj, name); - return map; - } - - function makePassthruHandler(obj) { - // Handler copied from - // http://wiki.ecmascript.org/doku.php?id=harmony:proxies&s=proxy%20object#examplea_no-op_forwarding_proxy - return { - getOwnPropertyDescriptor: function(name) { - var desc = Object.getOwnPropertyDescriptor(obj, name); - - // a trapping proxy's properties must always be configurable - desc.configurable = true; - return desc; - }, - getPropertyDescriptor: function(name) { - var desc = getPropertyDescriptor(obj, name); - - // a trapping proxy's properties must always be configurable - desc.configurable = true; - return desc; - }, - getOwnPropertyNames: function() { - return Object.getOwnPropertyNames(obj); - }, - defineProperty: function(name, desc) { - Object.defineProperty(obj, name, desc); - }, - "delete": function(name) { return delete obj[name]; }, - fix: function() { - if (Object.isFrozen(obj)) { - return getOwnProperties(obj); - } - - // As long as obj is not frozen, the proxy won't allow itself to be fixed. - return undefined; // will cause a TypeError to be thrown - }, - - has: function(name) { return name in obj; }, - hasOwn: function(name) { return ({}).hasOwnProperty.call(obj, name); }, - get: function(receiver, name) { return obj[name]; }, - - // bad behavior when set fails in non-strict mode - set: function(receiver, name, val) { obj[name] = val; return true; }, - enumerate: function() { - var result = []; - for (name in obj) { result.push(name); }; - return result; - }, - keys: function() { return Object.keys(obj); } - }; - } - - // default function used when looking for a property in the global object - function noPropFound() { return undefined; } - - var hasOwnProperty = ({}).hasOwnProperty; - - function StringMap() { - this.table = Object.create(null, {}); - this.size = 0; - } - - StringMap.prototype = { - has: function(x) { return hasOwnProperty.call(this.table, x); }, - set: function(x, v) { - if (!hasOwnProperty.call(this.table, x)) - this.size++; - this.table[x] = v; - }, - get: function(x) { return this.table[x]; }, - getDef: function(x, thunk) { - if (!hasOwnProperty.call(this.table, x)) { - this.size++; - this.table[x] = thunk(); - } - return this.table[x]; - }, - forEach: function(f) { - var table = this.table; - for (var key in table) - f.call(this, key, table[key]); - }, - toString: function() { return "[object StringMap]" } - }; - - // non-destructive stack - function Stack(elts) { - this.elts = elts || null; - } - - Stack.prototype = { - push: function(x) { - return new Stack({ top: x, rest: this.elts }); - }, - top: function() { - if (!this.elts) - throw new Error("empty stack"); - return this.elts.top; - }, - isEmpty: function() { - return this.top === null; - }, - find: function(test) { - for (var elts = this.elts; elts; elts = elts.rest) { - if (test(elts.top)) - return elts.top; - } - return null; - }, - has: function(x) { - return Boolean(this.find(function(elt) { return elt === x })); - }, - forEach: function(f) { - for (var elts = this.elts; elts; elts = elts.rest) { - f(elts.top); - } - } - }; - - return { - tokens: tokens, - opTypeNames: opTypeNames, - keywords: keywords, - isStatementStartCode: isStatementStartCode, - tokenIds: tokenIds, - consts: consts, - assignOps: assignOps, - defineGetter: defineGetter, - defineProperty: defineProperty, - isNativeCode: isNativeCode, - makePassthruHandler: makePassthruHandler, - noPropFound: noPropFound, - StringMap: StringMap, - Stack: Stack - }; -}()); diff --git a/deps/narcissus/lib/jsexec.js b/deps/narcissus/lib/jsexec.js deleted file mode 100644 index 2dbc9bce..00000000 --- a/deps/narcissus/lib/jsexec.js +++ /dev/null @@ -1,1216 +0,0 @@ -/* -*- Mode: JS; tab-width: 4; indent-tabs-mode: nil; -*- - * vim: set sw=4 ts=4 et tw=78: -/* ***** BEGIN LICENSE BLOCK ***** - * - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is the Narcissus JavaScript engine. - * - * The Initial Developer of the Original Code is - * Brendan Eich . - * Portions created by the Initial Developer are Copyright (C) 2004 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * Tom Austin - * Brendan Eich - * Shu-Yu Guo - * Dave Herman - * Dimitris Vardoulakis - * Patrick Walton - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -/* - * Narcissus - JS implemented in JS. - * - * Execution of parse trees. - * - * Standard classes except for eval, Function, Array, and String are borrowed - * from the host JS environment. Function is metacircular. Array and String - * are reflected via wrapping the corresponding native constructor and adding - * an extra level of prototype-based delegation. - */ - -Narcissus.interpreter = (function() { - - var parser = Narcissus.parser; - var definitions = Narcissus.definitions; - var hostGlobal = Narcissus.hostGlobal; - - // Set constants in the local scope. - eval(definitions.consts); - - const GLOBAL_CODE = 0, EVAL_CODE = 1, FUNCTION_CODE = 2; - - function ExecutionContext(type) { - this.type = type; - } - - function isStackOverflow(e) { - var re = /InternalError: (script stack space quota is exhausted|too much recursion)/; - return re.test(e.toString()); - } - - // The underlying global object for narcissus. - var globalBase = { - // Value properties. - NaN: NaN, Infinity: Infinity, undefined: undefined, - - // Function properties. - eval: function eval(s) { - if (typeof s !== "string") - return s; - - var x = ExecutionContext.current; - var x2 = new ExecutionContext(EVAL_CODE); - x2.thisObject = x.thisObject; - x2.caller = x.caller; - x2.callee = x.callee; - x2.scope = x.scope; - try { - x2.execute(parser.parse(s)); - return x2.result; - } catch (e if e instanceof SyntaxError || isStackOverflow(e)) { - /* - * If we get an internal error during parsing we need to reify - * the exception as a Narcissus THROW. - * - * See bug 152646. - */ - x.result = e; - throw THROW; - } - }, - - // Class constructors. Where ECMA-262 requires C.length === 1, we declare - // a dummy formal parameter. - Function: function Function(dummy) { - var p = "", b = "", n = arguments.length; - if (n) { - var m = n - 1; - if (m) { - p += arguments[0]; - for (var k = 1; k < m; k++) - p += "," + arguments[k]; - } - b += arguments[m]; - } - - // XXX We want to pass a good file and line to the tokenizer. - // Note the anonymous name to maintain parity with Spidermonkey. - var t = new parser.Tokenizer("anonymous(" + p + ") {" + b + "}"); - - // NB: Use the STATEMENT_FORM constant since we don't want to push this - // function onto the fake compilation context. - var f = parser.FunctionDefinition(t, null, false, parser.STATEMENT_FORM); - var s = {object: global, parent: null}; - return newFunction(f,{scope:s}); - }, - Array: function (dummy) { - // Array when called as a function acts as a constructor. - return Array.apply(this, arguments); - }, - String: function String(s) { - // Called as function or constructor: convert argument to string type. - s = arguments.length ? "" + s : ""; - if (this instanceof String) { - // Called as constructor: save the argument as the string value - // of this String object and return this object. - this.value = s; - return this; - } - return s; - }, - - // Don't want to proxy RegExp or some features won't work - RegExp: RegExp, - - // Extensions to ECMA. - load: function load(s) { - if (typeof s !== "string") - return s; - - evaluate(snarf(s), s, 1) - }, - version: function() { return Narcissus.options.version; }, - quit: function() { throw END; } - }; - - var narcissusGlobal = {}; - function resetEnvironment() { - ExecutionContext.current = new ExecutionContext(GLOBAL_CODE); - for (let key in narcissusGlobal) { - delete narcissusGlobal[key]; - } - for (let key in globalBase) { - narcissusGlobal[key] = globalBase[key]; - } - } - resetEnvironment(); - - // Create global handler with needed modifications. - var globalHandler = definitions.makePassthruHandler(narcissusGlobal); - - globalHandler.has = function(name) { - if (name in narcissusGlobal) - return true; - // Hide Narcissus implementation code. - if (name === "Narcissus") - return false; - if (name in hostGlobal) - return true; - return Narcissus.definitions.noPropFound(name); - }; - - globalHandler.get = function(receiver, name) { - if (narcissusGlobal.hasOwnProperty(name)) - return narcissusGlobal[name]; - - var globalProp = hostGlobal[name]; - if (definitions.isNativeCode(globalProp)) { - // Enables native browser functions like 'alert' to work correctly. - return Proxy.createFunction( - definitions.makePassthruHandler(globalProp), - function() { return globalProp.apply(hostGlobal, arguments); }, - function() { - var a = arguments; - switch (a.length) { - case 0: - return new globalProp(); - case 1: - return new globalProp(a[0]); - case 2: - return new globalProp(a[0], a[1]); - case 3: - return new globalProp(a[0], a[1], a[2]); - default: - var argStr = ""; - for (var i = 0; i < a.length; i++) - argStr += 'a[' + i + '],'; - return eval('new ' + name + '(' + argStr.slice(0,-1) + ');'); - } - }); - } - // If globalProp is not found, call the noPropFound hook. - return globalProp ? globalProp : Narcissus.definitions.noPropFound(name); - }; - - var global = Proxy.create(globalHandler); - - // Helper to avoid Object.prototype.hasOwnProperty polluting scope objects. - function hasDirectProperty(o, p) { - return Object.prototype.hasOwnProperty.call(o, p); - } - - // Reflect a host class into the target global environment by delegation. - function reflectClass(name, proto) { - var gctor = global[name]; - definitions.defineProperty(gctor, "prototype", proto, true, true, true); - definitions.defineProperty(proto, "constructor", gctor, false, false, true); - return proto; - } - - // Reflect Array -- note that all Array methods are generic. - reflectClass('Array', new Array); - - // Reflect String, overriding non-generic methods. - var gSp = reflectClass('String', new String); - gSp.toSource = function () { return this.value.toSource(); }; - gSp.toString = function () { return this.value; }; - gSp.valueOf = function () { return this.value; }; - global.String.fromCharCode = String.fromCharCode; - - ExecutionContext.current = null; - - ExecutionContext.prototype = { - caller: null, - callee: null, - scope: {object: global, parent: null}, - thisObject: global, - result: undefined, - target: null, - ecma3OnlyMode: false, - - // Execute a node in this execution context. - execute: function(n) { - var prev = ExecutionContext.current; - ExecutionContext.current = this; - try { - execute(n, this); - } catch (e if e === THROW) { - // Propagate the throw to the previous context if it exists. - if (prev) { - prev.result = this.result; - throw THROW; - } - // Otherwise reflect the throw into host JS. - throw this.result; - } finally { - ExecutionContext.current = prev; - } - } - }; - - function Reference(base, propertyName, node) { - this.base = base; - this.propertyName = propertyName; - this.node = node; - } - - Reference.prototype.toString = function () { return this.node.getSource(); } - - function getValue(v) { - if (v instanceof Reference) { - if (!v.base) { - throw new ReferenceError(v.propertyName + " is not defined", - v.node.filename, v.node.lineno); - } - return v.base[v.propertyName]; - } - return v; - } - - function putValue(v, w, vn) { - if (v instanceof Reference) - return (v.base || global)[v.propertyName] = w; - throw new ReferenceError("Invalid assignment left-hand side", - vn.filename, vn.lineno); - } - - function isPrimitive(v) { - var t = typeof v; - return (t === "object") ? v === null : t !== "function"; - } - - function isObject(v) { - var t = typeof v; - return (t === "object") ? v !== null : t === "function"; - } - - // If r instanceof Reference, v === getValue(r); else v === r. If passed, rn - // is the node whose execute result was r. - function toObject(v, r, rn) { - switch (typeof v) { - case "boolean": - return new global.Boolean(v); - case "number": - return new global.Number(v); - case "string": - return new global.String(v); - case "function": - return v; - case "object": - if (v !== null) - return v; - } - var message = r + " (type " + (typeof v) + ") has no properties"; - throw rn ? new TypeError(message, rn.filename, rn.lineno) - : new TypeError(message); - } - - function execute(n, x) { - var a, c, f, i, j, r, s, t, u, v; - - switch (n.type) { - case FUNCTION: - if (n.functionForm !== parser.DECLARED_FORM) { - if (!n.name || n.functionForm === parser.STATEMENT_FORM) { - v = newFunction(n, x); - if (n.functionForm === parser.STATEMENT_FORM) - definitions.defineProperty(x.scope.object, n.name, v, true); - } else { - t = new Object; - x.scope = {object: t, parent: x.scope}; - try { - v = newFunction(n, x); - definitions.defineProperty(t, n.name, v, true, true); - } finally { - x.scope = x.scope.parent; - } - } - } - break; - - case SCRIPT: - t = x.scope.object; - a = n.funDecls; - for (i = 0, j = a.length; i < j; i++) { - s = a[i].name; - f = newFunction(a[i], x); - definitions.defineProperty(t, s, f, x.type !== EVAL_CODE); - } - a = n.varDecls; - for (i = 0, j = a.length; i < j; i++) { - u = a[i]; - s = u.name; - if (u.readOnly && hasDirectProperty(t, s)) { - throw new TypeError("Redeclaration of const " + s, - u.filename, u.lineno); - } - if (u.readOnly || !hasDirectProperty(t, s)) { - // Does not correctly handle 'const x;' -- see bug 592335. - definitions.defineProperty(t, s, undefined, x.type !== EVAL_CODE, false); - } - } - // FALL THROUGH - - case BLOCK: - c = n.children; - for (i = 0, j = c.length; i < j; i++) - execute(c[i], x); - break; - - case IF: - if (getValue(execute(n.condition, x))) - execute(n.thenPart, x); - else if (n.elsePart) - execute(n.elsePart, x); - break; - - case SWITCH: - s = getValue(execute(n.discriminant, x)); - a = n.cases; - var matchDefault = false; - switch_loop: - for (i = 0, j = a.length; ; i++) { - if (i === j) { - if (n.defaultIndex >= 0) { - i = n.defaultIndex - 1; // no case matched, do default - matchDefault = true; - continue; - } - break; // no default, exit switch_loop - } - t = a[i]; // next case (might be default!) - if (t.type === CASE) { - u = getValue(execute(t.caseLabel, x)); - } else { - if (!matchDefault) // not defaulting, skip for now - continue; - u = s; // force match to do default - } - if (u === s) { - for (;;) { // this loop exits switch_loop - if (t.statements.children.length) { - try { - execute(t.statements, x); - } catch (e if e === BREAK && x.target === n) { - break switch_loop; - } - } - if (++i === j) - break switch_loop; - t = a[i]; - } - // NOT REACHED - } - } - break; - - case FOR: - n.setup && getValue(execute(n.setup, x)); - // FALL THROUGH - case WHILE: - while (!n.condition || getValue(execute(n.condition, x))) { - try { - execute(n.body, x); - } catch (e if e === BREAK && x.target === n) { - break; - } catch (e if e === CONTINUE && x.target === n) { - // Must run the update expression. - } - n.update && getValue(execute(n.update, x)); - } - break; - - case FOR_IN: - u = n.varDecl; - if (u) - execute(u, x); - r = n.iterator; - s = execute(n.object, x); - v = getValue(s); - - // ECMA deviation to track extant browser JS implementation behavior. - t = ((v === null || v === undefined) && !x.ecma3OnlyMode) - ? v - : toObject(v, s, n.object); - a = []; - for (i in t) - a.push(i); - for (i = 0, j = a.length; i < j; i++) { - putValue(execute(r, x), a[i], r); - try { - execute(n.body, x); - } catch (e if e === BREAK && x.target === n) { - break; - } catch (e if e === CONTINUE && x.target === n) { - continue; - } - } - break; - - case DO: - do { - try { - execute(n.body, x); - } catch (e if e === BREAK && x.target === n) { - break; - } catch (e if e === CONTINUE && x.target === n) { - continue; - } - } while (getValue(execute(n.condition, x))); - break; - - case BREAK: - case CONTINUE: - x.target = n.target; - throw n.type; - - case TRY: - try { - execute(n.tryBlock, x); - } catch (e if e === THROW && (j = n.catchClauses.length)) { - e = x.result; - x.result = undefined; - for (i = 0; ; i++) { - if (i === j) { - x.result = e; - throw THROW; - } - t = n.catchClauses[i]; - x.scope = {object: {}, parent: x.scope}; - definitions.defineProperty(x.scope.object, t.varName, e, true); - try { - if (t.guard && !getValue(execute(t.guard, x))) - continue; - execute(t.block, x); - break; - } finally { - x.scope = x.scope.parent; - } - } - } finally { - if (n.finallyBlock) - execute(n.finallyBlock, x); - } - break; - - case THROW: - x.result = getValue(execute(n.exception, x)); - throw THROW; - - case RETURN: - // Check for returns with no return value - x.result = n.value ? getValue(execute(n.value, x)) : undefined; - throw RETURN; - - case WITH: - r = execute(n.object, x); - t = toObject(getValue(r), r, n.object); - x.scope = {object: t, parent: x.scope}; - try { - execute(n.body, x); - } finally { - x.scope = x.scope.parent; - } - break; - - case VAR: - case CONST: - c = n.children; - for (i = 0, j = c.length; i < j; i++) { - u = c[i].initializer; - if (!u) - continue; - t = c[i].name; - for (s = x.scope; s; s = s.parent) { - if (hasDirectProperty(s.object, t)) - break; - } - u = getValue(execute(u, x)); - if (n.type === CONST) - definitions.defineProperty(s.object, t, u, x.type !== EVAL_CODE, true); - else - s.object[t] = u; - } - break; - - case DEBUGGER: - throw "NYI: " + definitions.tokens[n.type]; - - case SEMICOLON: - if (n.expression) - x.result = getValue(execute(n.expression, x)); - break; - - case LABEL: - try { - execute(n.statement, x); - } catch (e if e === BREAK && x.target === n.target) { - } - break; - - case COMMA: - c = n.children; - for (i = 0, j = c.length; i < j; i++) - v = getValue(execute(c[i], x)); - break; - - case ASSIGN: - c = n.children; - r = execute(c[0], x); - t = n.assignOp; - if (t) - u = getValue(r); - v = getValue(execute(c[1], x)); - if (t) { - switch (t) { - case BITWISE_OR: v = u | v; break; - case BITWISE_XOR: v = u ^ v; break; - case BITWISE_AND: v = u & v; break; - case LSH: v = u << v; break; - case RSH: v = u >> v; break; - case URSH: v = u >>> v; break; - case PLUS: v = u + v; break; - case MINUS: v = u - v; break; - case MUL: v = u * v; break; - case DIV: v = u / v; break; - case MOD: v = u % v; break; - } - } - putValue(r, v, c[0]); - break; - - case HOOK: - c = n.children; - v = getValue(execute(c[0], x)) ? getValue(execute(c[1], x)) - : getValue(execute(c[2], x)); - break; - - case OR: - c = n.children; - v = getValue(execute(c[0], x)) || getValue(execute(c[1], x)); - break; - - case AND: - c = n.children; - v = getValue(execute(c[0], x)) && getValue(execute(c[1], x)); - break; - - case BITWISE_OR: - c = n.children; - v = getValue(execute(c[0], x)) | getValue(execute(c[1], x)); - break; - - case BITWISE_XOR: - c = n.children; - v = getValue(execute(c[0], x)) ^ getValue(execute(c[1], x)); - break; - - case BITWISE_AND: - c = n.children; - v = getValue(execute(c[0], x)) & getValue(execute(c[1], x)); - break; - - case EQ: - c = n.children; - v = getValue(execute(c[0], x)) == getValue(execute(c[1], x)); - break; - - case NE: - c = n.children; - v = getValue(execute(c[0], x)) != getValue(execute(c[1], x)); - break; - - case STRICT_EQ: - c = n.children; - v = getValue(execute(c[0], x)) === getValue(execute(c[1], x)); - break; - - case STRICT_NE: - c = n.children; - v = getValue(execute(c[0], x)) !== getValue(execute(c[1], x)); - break; - - case LT: - c = n.children; - v = getValue(execute(c[0], x)) < getValue(execute(c[1], x)); - break; - - case LE: - c = n.children; - v = getValue(execute(c[0], x)) <= getValue(execute(c[1], x)); - break; - - case GE: - c = n.children; - v = getValue(execute(c[0], x)) >= getValue(execute(c[1], x)); - break; - - case GT: - c = n.children; - v = getValue(execute(c[0], x)) > getValue(execute(c[1], x)); - break; - - case IN: - c = n.children; - v = getValue(execute(c[0], x)) in getValue(execute(c[1], x)); - break; - - case INSTANCEOF: - c = n.children; - t = getValue(execute(c[0], x)); - u = getValue(execute(c[1], x)); - if (isObject(u) && typeof u.__hasInstance__ === "function") - v = u.__hasInstance__(t); - else - v = t instanceof u; - break; - - case LSH: - c = n.children; - v = getValue(execute(c[0], x)) << getValue(execute(c[1], x)); - break; - - case RSH: - c = n.children; - v = getValue(execute(c[0], x)) >> getValue(execute(c[1], x)); - break; - - case URSH: - c = n.children; - v = getValue(execute(c[0], x)) >>> getValue(execute(c[1], x)); - break; - - case PLUS: - c = n.children; - v = getValue(execute(c[0], x)) + getValue(execute(c[1], x)); - break; - - case MINUS: - c = n.children; - v = getValue(execute(c[0], x)) - getValue(execute(c[1], x)); - break; - - case MUL: - c = n.children; - v = getValue(execute(c[0], x)) * getValue(execute(c[1], x)); - break; - - case DIV: - c = n.children; - v = getValue(execute(c[0], x)) / getValue(execute(c[1], x)); - break; - - case MOD: - c = n.children; - v = getValue(execute(c[0], x)) % getValue(execute(c[1], x)); - break; - - case DELETE: - t = execute(n.children[0], x); - v = !(t instanceof Reference) || delete t.base[t.propertyName]; - break; - - case VOID: - getValue(execute(n.children[0], x)); - break; - - case TYPEOF: - t = execute(n.children[0], x); - if (t instanceof Reference) - t = t.base ? t.base[t.propertyName] : undefined; - v = typeof t; - break; - - case NOT: - v = !getValue(execute(n.children[0], x)); - break; - - case BITWISE_NOT: - v = ~getValue(execute(n.children[0], x)); - break; - - case UNARY_PLUS: - v = +getValue(execute(n.children[0], x)); - break; - - case UNARY_MINUS: - v = -getValue(execute(n.children[0], x)); - break; - - case INCREMENT: - case DECREMENT: - t = execute(n.children[0], x); - u = Number(getValue(t)); - if (n.postfix) - v = u; - putValue(t, (n.type === INCREMENT) ? ++u : --u, n.children[0]); - if (!n.postfix) - v = u; - break; - - case DOT: - c = n.children; - r = execute(c[0], x); - t = getValue(r); - u = c[1].value; - v = new Reference(toObject(t, r, c[0]), u, n); - break; - - case INDEX: - c = n.children; - r = execute(c[0], x); - t = getValue(r); - u = getValue(execute(c[1], x)); - v = new Reference(toObject(t, r, c[0]), String(u), n); - break; - - case LIST: - // Curse ECMA for specifying that arguments is not an Array object! - v = {}; - c = n.children; - for (i = 0, j = c.length; i < j; i++) { - u = getValue(execute(c[i], x)); - definitions.defineProperty(v, i, u, false, false, true); - } - definitions.defineProperty(v, "length", i, false, false, true); - break; - - case CALL: - c = n.children; - r = execute(c[0], x); - a = execute(c[1], x); - f = getValue(r); - if (isPrimitive(f) || typeof f.__call__ !== "function") { - throw new TypeError(r + " is not callable", c[0].filename, c[0].lineno); - } - t = (r instanceof Reference) ? r.base : null; - if (t instanceof Activation) - t = null; - v = f.__call__(t, a, x); - break; - - case NEW: - case NEW_WITH_ARGS: - c = n.children; - r = execute(c[0], x); - f = getValue(r); - if (n.type === NEW) { - a = {}; - definitions.defineProperty(a, "length", 0, false, false, true); - } else { - a = execute(c[1], x); - } - if (isPrimitive(f) || typeof f.__construct__ !== "function") { - throw new TypeError(r + " is not a constructor", c[0].filename, c[0].lineno); - } - v = f.__construct__(a, x); - break; - - case ARRAY_INIT: - v = []; - c = n.children; - for (i = 0, j = c.length; i < j; i++) { - if (c[i]) - v[i] = getValue(execute(c[i], x)); - } - v.length = j; - break; - - case OBJECT_INIT: - v = {}; - c = n.children; - for (i = 0, j = c.length; i < j; i++) { - t = c[i]; - if (t.type === PROPERTY_INIT) { - let c2 = t.children; - v[c2[0].value] = getValue(execute(c2[1], x)); - } else { - f = newFunction(t, x); - u = (t.type === GETTER) ? '__defineGetter__' - : '__defineSetter__'; - v[u](t.name, thunk(f, x)); - } - } - break; - - case NULL: - v = null; - break; - - case THIS: - v = x.thisObject; - break; - - case TRUE: - v = true; - break; - - case FALSE: - v = false; - break; - - case IDENTIFIER: - for (s = x.scope; s; s = s.parent) { - if (n.value in s.object) - break; - } - v = new Reference(s && s.object, n.value, n); - break; - - case NUMBER: - case STRING: - case REGEXP: - v = n.value; - break; - - case GROUP: - v = execute(n.children[0], x); - break; - - default: - throw "PANIC: unknown operation " + n.type + ": " + uneval(n); - } - - return v; - } - - function Activation(f, a) { - for (var i = 0, j = f.params.length; i < j; i++) - definitions.defineProperty(this, f.params[i], a[i], true); - definitions.defineProperty(this, "arguments", a, true); - } - - // Null Activation.prototype's proto slot so that Object.prototype.* does not - // pollute the scope of heavyweight functions. Also delete its 'constructor' - // property so that it doesn't pollute function scopes. - - Activation.prototype.__proto__ = null; - delete Activation.prototype.constructor; - - function FunctionObject(node, scope) { - this.node = node; - this.scope = scope; - definitions.defineProperty(this, "length", node.params.length, true, true, true); - var proto = {}; - definitions.defineProperty(this, "prototype", proto, true); - definitions.defineProperty(proto, "constructor", this, false, false, true); - } - - function getPropertyDescriptor(obj, name) { - while (obj) { - if (({}).hasOwnProperty.call(obj, name)) - return Object.getOwnPropertyDescriptor(obj, name); - obj = Object.getPrototypeOf(obj); - } - } - - function getOwnProperties(obj) { - var map = {}; - for (var name in Object.getOwnPropertyNames(obj)) - map[name] = Object.getOwnPropertyDescriptor(obj, name); - return map; - } - - // Returns a new function wrapped with a Proxy. - function newFunction(n, x) { - var fobj = new FunctionObject(n, x.scope); - var handler = definitions.makePassthruHandler(fobj); - var p = Proxy.createFunction(handler, - function() { return fobj.__call__(this, arguments, x); }, - function() { return fobj.__construct__(arguments, x); }); - return p; - } - - var FOp = FunctionObject.prototype = { - - // Internal methods. - __call__: function (t, a, x) { - var x2 = new ExecutionContext(FUNCTION_CODE); - x2.thisObject = t || global; - x2.caller = x; - x2.callee = this; - definitions.defineProperty(a, "callee", this, false, false, true); - var f = this.node; - x2.scope = {object: new Activation(f, a), parent: this.scope}; - - try { - x2.execute(f.body); - } catch (e if e === RETURN) { - return x2.result; - } - return undefined; - }, - - __construct__: function (a, x) { - var o = new Object; - var p = this.prototype; - if (isObject(p)) - o.__proto__ = p; - // else o.__proto__ defaulted to Object.prototype - - var v = this.__call__(o, a, x); - if (isObject(v)) - return v; - return o; - }, - - __hasInstance__: function (v) { - if (isPrimitive(v)) - return false; - var p = this.prototype; - if (isPrimitive(p)) { - throw new TypeError("'prototype' property is not an object", - this.node.filename, this.node.lineno); - } - var o; - while ((o = v.__proto__)) { - if (o === p) - return true; - v = o; - } - return false; - }, - - // Standard methods. - toString: function () { - return this.node.getSource(); - }, - - apply: function (t, a) { - // Curse ECMA again! - if (typeof this.__call__ !== "function") { - throw new TypeError("Function.prototype.apply called on" + - " uncallable object"); - } - - if (t === undefined || t === null) - t = global; - else if (typeof t !== "object") - t = toObject(t, t); - - if (a === undefined || a === null) { - a = {}; - definitions.defineProperty(a, "length", 0, false, false, true); - } else if (a instanceof Array) { - var v = {}; - for (var i = 0, j = a.length; i < j; i++) - definitions.defineProperty(v, i, a[i], false, false, true); - definitions.defineProperty(v, "length", i, false, false, true); - a = v; - } else if (!(a instanceof Object)) { - // XXX check for a non-arguments object - throw new TypeError("Second argument to Function.prototype.apply" + - " must be an array or arguments object", - this.node.filename, this.node.lineno); - } - - return this.__call__(t, a, ExecutionContext.current); - }, - - call: function (t) { - // Curse ECMA a third time! - var a = Array.prototype.splice.call(arguments, 1); - return this.apply(t, a); - } - }; - - // Connect Function.prototype and Function.prototype.constructor in global. - reflectClass('Function', FOp); - - // Help native and host-scripted functions be like FunctionObjects. - var Fp = Function.prototype; - var REp = RegExp.prototype; - - if (!('__call__' in Fp)) { - definitions.defineProperty(Fp, "__call__", - function (t, a, x) { - // Curse ECMA yet again! - a = Array.prototype.splice.call(a, 0, a.length); - return this.apply(t, a); - }, true, true, true); - definitions.defineProperty(REp, "__call__", - function (t, a, x) { - a = Array.prototype.splice.call(a, 0, a.length); - return this.exec.apply(this, a); - }, true, true, true); - definitions.defineProperty(Fp, "__construct__", - function (a, x) { - a = Array.prototype.splice.call(a, 0, a.length); - switch (a.length) { - case 0: - return new this(); - case 1: - return new this(a[0]); - case 2: - return new this(a[0], a[1]); - case 3: - return new this(a[0], a[1], a[2]); - default: - var argStr = ""; - for (var i=0; i@"); - line = line.replace(/@(.*\/|\\)?([^\/\\]+:[0-9]+)/, " at $2"); - print(" in " + line); - } - } - } - - // A read-eval-print-loop that roughly tracks the behavior of the js shell. - function repl() { - - // Display a value similarly to the js shell. - function display(x) { - if (typeof x === "object") { - // At the js shell, objects with no |toSource| don't print. - if (x !== null && "toSource" in x) { - try { - print(x.toSource()); - } catch (e) { - } - } else { - print("null"); - } - } else if (typeof x === "string") { - print(uneval(x)); - } else if (typeof x !== "undefined") { - // Since x must be primitive, String can't throw. - print(String(x)); - } - } - - // String conversion that never throws. - function string(x) { - try { - return String(x); - } catch (e) { - return "unknown (can't convert to string)"; - } - } - - var x = new ExecutionContext(GLOBAL_CODE); - - // Line number in/out parameter to parser.parseStdin. - var ln = {value: 0}; - - ExecutionContext.current = x; - for (;;) { - x.result = undefined; - putstr("njs> "); - var src = readline(); - - // If readline receives EOF it returns null. - if (src === null) { - print(""); - break; - } - ++ln.value; - - try { - execute(parser.parseStdin(src, ln), x); - display(x.result); - } catch (e if e === THROW) { - print("uncaught exception: " + string(x.result)); - } catch (e if e === END) { - break; - } catch (e if e instanceof SyntaxError) { - const PREFIX = (e.filename || "stdin") + ":" + e.lineNumber + ": "; - print(PREFIX + e.toString()); - print(PREFIX + e.source); - print(PREFIX + ".".repeat(e.cursor) + "^"); - } catch (e if e instanceof Error) { - print((e.filename || "stdin") + ":" + e.lineNumber + ": " + e.toString()); - if (e.stack) - printStackTrace(e.stack); - } catch (e) { - print("unexpected Narcissus exception (" + e + ")"); - throw e; - } - } - ExecutionContext.current = null; - } - - function test(thunk) { - try { - return thunk(); - } catch (e) { - print(e.fileName + ":" + e.lineNumber + ": " + e.name + ": " + e.message); - printStackTrace(e.stack); - } - } - - return { - // resetEnvironment wipes any properties added externally to global, - // but properties added to globalBase will persist. - global: global, - globalBase: globalBase, - resetEnvironment: resetEnvironment, - evaluate: evaluate, - repl: repl, - test: test - }; - -}()); diff --git a/deps/narcissus/lib/jslex.js b/deps/narcissus/lib/jslex.js deleted file mode 100644 index 667da44e..00000000 --- a/deps/narcissus/lib/jslex.js +++ /dev/null @@ -1,474 +0,0 @@ -/* vim: set sw=4 ts=4 et tw=78: */ -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is the Narcissus JavaScript engine. - * - * The Initial Developer of the Original Code is - * Brendan Eich . - * Portions created by the Initial Developer are Copyright (C) 2004 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * Tom Austin - * Brendan Eich - * Shu-Yu Guo - * Dave Herman - * Dimitris Vardoulakis - * Patrick Walton - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -/* - * Narcissus - JS implemented in JS. - * - * Lexical scanner. - */ - -Narcissus.lexer = (function() { - - var definitions = Narcissus.definitions; - - // Set constants in the local scope. - eval(definitions.consts); - - // Build up a trie of operator tokens. - var opTokens = {}; - for (var op in definitions.opTypeNames) { - if (op === '\n' || op === '.') - continue; - - var node = opTokens; - for (var i = 0; i < op.length; i++) { - var ch = op[i]; - if (!(ch in node)) - node[ch] = {}; - node = node[ch]; - node.op = op; - } - } - - /* - * Tokenizer :: (source, filename, line number) -> Tokenizer - */ - function Tokenizer(s, f, l) { - this.cursor = 0; - this.source = String(s); - this.tokens = []; - this.tokenIndex = 0; - this.lookahead = 0; - this.scanNewlines = false; - this.unexpectedEOF = false; - this.filename = f || ""; - this.lineno = l || 1; - } - - Tokenizer.prototype = { - get done() { - // We need to set scanOperand to true here because the first thing - // might be a regexp. - return this.peek(true) === END; - }, - - get token() { - return this.tokens[this.tokenIndex]; - }, - - match: function (tt, scanOperand) { - return this.get(scanOperand) === tt || this.unget(); - }, - - mustMatch: function (tt) { - if (!this.match(tt)) { - throw this.newSyntaxError("Missing " + - definitions.tokens[tt].toLowerCase()); - } - return this.token; - }, - - forceIdentifier: function() { - if (!this.match(IDENTIFIER)) { - // keywords are valid property names in ES 5 - if (this.get() >= definitions.keywords[0] || this.unget) { - this.token.type = IDENTIFIER; - } - else { - throw this.newSyntaxError("Missing identifier"); - } - } - return this.token; - }, - - peek: function (scanOperand) { - var tt, next; - if (this.lookahead) { - next = this.tokens[(this.tokenIndex + this.lookahead) & 3]; - tt = (this.scanNewlines && next.lineno !== this.lineno) - ? NEWLINE - : next.type; - } else { - tt = this.get(scanOperand); - this.unget(); - } - return tt; - }, - - peekOnSameLine: function (scanOperand) { - this.scanNewlines = true; - var tt = this.peek(scanOperand); - this.scanNewlines = false; - return tt; - }, - - // Eat comments and whitespace. - skip: function () { - var input = this.source; - for (;;) { - var ch = input[this.cursor++]; - var next = input[this.cursor]; - if (ch === '\n' && !this.scanNewlines) { - this.lineno++; - } else if (ch === '/' && next === '*') { - this.cursor++; - for (;;) { - ch = input[this.cursor++]; - if (ch === undefined) - throw this.newSyntaxError("Unterminated comment"); - - if (ch === '*') { - next = input[this.cursor]; - if (next === '/') { - this.cursor++; - break; - } - } else if (ch === '\n') { - this.lineno++; - } - } - } else if (ch === '/' && next === '/') { - this.cursor++; - for (;;) { - ch = input[this.cursor++]; - if (ch === undefined) - return; - - if (ch === '\n') { - this.lineno++; - break; - } - } - } else if (ch !== ' ' && ch !== '\t') { - this.cursor--; - return; - } - } - }, - - // Lex the exponential part of a number, if present. Return true iff an - // exponential part was found. - lexExponent: function() { - var input = this.source; - var next = input[this.cursor]; - if (next === 'e' || next === 'E') { - this.cursor++; - ch = input[this.cursor++]; - if (ch === '+' || ch === '-') - ch = input[this.cursor++]; - - if (ch < '0' || ch > '9') - throw this.newSyntaxError("Missing exponent"); - - do { - ch = input[this.cursor++]; - } while (ch >= '0' && ch <= '9'); - this.cursor--; - - return true; - } - - return false; - }, - - lexZeroNumber: function (ch) { - var token = this.token, input = this.source; - token.type = NUMBER; - - ch = input[this.cursor++]; - if (ch === '.') { - do { - ch = input[this.cursor++]; - } while (ch >= '0' && ch <= '9'); - this.cursor--; - - this.lexExponent(); - token.value = parseFloat(input.substring(token.start, this.cursor)); - } else if (ch === 'x' || ch === 'X') { - do { - ch = input[this.cursor++]; - } while ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || - (ch >= 'A' && ch <= 'F')); - this.cursor--; - - token.value = parseInt(input.substring(token.start, this.cursor)); - } else if (ch >= '0' && ch <= '7') { - do { - ch = input[this.cursor++]; - } while (ch >= '0' && ch <= '7'); - this.cursor--; - - token.value = parseInt(input.substring(token.start, this.cursor), 8); - token.value.isOctal = true; // mark it to decomp as octal so that strict mode catches it - } else { - this.cursor--; - this.lexExponent(); // 0E1, &c. - token.value = 0; - } - }, - - lexNumber: function (ch) { - var token = this.token, input = this.source; - token.type = NUMBER; - - var floating = false; - do { - ch = input[this.cursor++]; - if (ch === '.' && !floating) { - floating = true; - ch = input[this.cursor++]; - } - } while (ch >= '0' && ch <= '9'); - - this.cursor--; - - var exponent = this.lexExponent(); - floating = floating || exponent; - - var str = input.substring(token.start, this.cursor); - token.value = floating ? parseFloat(str) : parseInt(str); - }, - - lexDot: function (ch) { - var token = this.token, input = this.source; - var next = input[this.cursor]; - if (next >= '0' && next <= '9') { - do { - ch = input[this.cursor++]; - } while (ch >= '0' && ch <= '9'); - this.cursor--; - - this.lexExponent(); - - token.type = NUMBER; - token.value = parseFloat(input.substring(token.start, this.cursor)); - } else { - token.type = DOT; - token.assignOp = null; - token.value = '.'; - } - }, - - lexString: function (ch) { - var token = this.token, input = this.source; - token.type = STRING; - - var hasEscapes = false; - var delim = ch; - while ((ch = input[this.cursor++]) !== delim) { - if (this.cursor == input.length) - throw this.newSyntaxError("Unterminated string literal"); - if (ch === '\\') { - hasEscapes = true; - if (input[this.cursor] === '\n') this.lineno++; // fix for escaped newline - if (++this.cursor == input.length) - throw this.newSyntaxError("Unterminated string literal"); - } - } - - token.value = hasEscapes - ? eval(input.substring(token.start, this.cursor)) - : input.substring(token.start + 1, this.cursor - 1); - }, - - lexRegExp: function (ch) { - var token = this.token, input = this.source; - token.type = REGEXP; - - do { - ch = input[this.cursor++]; - if (ch === '\\') { - this.cursor++; - } else if (ch === '[') { - do { - if (ch === undefined) - throw this.newSyntaxError("Unterminated character class"); - - if (ch === '\\') - this.cursor++; - - ch = input[this.cursor++]; - } while (ch !== ']'); - } else if (ch === undefined) { - throw this.newSyntaxError("Unterminated regex"); - } - } while (ch !== '/'); - - do { - ch = input[this.cursor++]; - } while (ch >= 'a' && ch <= 'z'); - - this.cursor--; - - token.value = eval(input.substring(token.start, this.cursor)); - }, - - lexOp: function (ch) { - var token = this.token, input = this.source; - - // A bit ugly, but it seems wasteful to write a trie lookup routine - // for only 3 characters... - var node = opTokens[ch]; - var next = input[this.cursor]; - if (next in node) { - node = node[next]; - this.cursor++; - next = input[this.cursor]; - if (next in node) { - node = node[next]; - this.cursor++; - next = input[this.cursor]; - } - } - - var op = node.op; - if (definitions.assignOps[op] && input[this.cursor] === '=') { - this.cursor++; - token.type = ASSIGN; - token.assignOp = definitions.tokenIds[definitions.opTypeNames[op]]; - op += '='; - } else { - token.type = definitions.tokenIds[definitions.opTypeNames[op]]; - token.assignOp = null; - } - - token.value = op; - }, - - // FIXME: Unicode escape sequences - // FIXME: Unicode identifiers - lexIdent: function (ch) { - var token = this.token, input = this.source; - - do { - ch = input[this.cursor++]; - } while ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || - (ch >= '0' && ch <= '9') || ch === '$' || ch === '_'); - - this.cursor--; // Put the non-word character back. - - var id = input.substring(token.start, this.cursor); - token.type = definitions.keywords[id] || IDENTIFIER; - token.value = id; - }, - - /* - * Tokenizer.get :: void -> token type - * - * Consume input *only* if there is no lookahead. - * Dispatch to the appropriate lexing function depending on the input. - */ - get: function (scanOperand) { - var token; - while (this.lookahead) { - --this.lookahead; - this.tokenIndex = (this.tokenIndex + 1) & 3; - token = this.tokens[this.tokenIndex]; - if (token.type !== NEWLINE || this.scanNewlines) - return token.type; - } - - this.skip(); - - this.tokenIndex = (this.tokenIndex + 1) & 3; - token = this.tokens[this.tokenIndex]; - if (!token) - this.tokens[this.tokenIndex] = token = {}; - - var input = this.source; - if (this.cursor === input.length) - return token.type = END; - - token.start = this.cursor; - token.lineno = this.lineno; - - var ch = input[this.cursor++]; - if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch === '$' || ch === '_') { - this.lexIdent(ch); - } else if (scanOperand && ch === '/') { - this.lexRegExp(ch); - } else if (ch in opTokens) { - this.lexOp(ch); - } else if (ch === '.') { - this.lexDot(ch); - } else if (ch >= '1' && ch <= '9') { - this.lexNumber(ch); - } else if (ch === '0') { - this.lexZeroNumber(ch); - } else if (ch === '"' || ch === "'") { - this.lexString(ch); - } else if (this.scanNewlines && ch === '\n') { - token.type = NEWLINE; - token.value = '\n'; - this.lineno++; - } else { - throw this.newSyntaxError("Illegal token"); - } - - token.end = this.cursor; - return token.type; - }, - - /* - * Tokenizer.unget :: void -> undefined - * - * Match depends on unget returning undefined. - */ - unget: function () { - if (++this.lookahead === 4) throw "PANIC: too much lookahead!"; - this.tokenIndex = (this.tokenIndex - 1) & 3; - }, - - newSyntaxError: function (m) { - var e = new SyntaxError(this.filename + ":" + this.lineno + ":" + m); - e.source = this.source; - e.cursor = this.lookahead - ? this.tokens[(this.tokenIndex + this.lookahead) & 3].start - : this.cursor; - return e; - }, - }; - - return { Tokenizer: Tokenizer }; - -}()); diff --git a/deps/narcissus/lib/jsparse.js b/deps/narcissus/lib/jsparse.js deleted file mode 100644 index b74aefbf..00000000 --- a/deps/narcissus/lib/jsparse.js +++ /dev/null @@ -1,1470 +0,0 @@ -/* -*- Mode: JS; tab-width: 4; indent-tabs-mode: nil; -*- - * vim: set sw=4 ts=4 et tw=78: - * ***** BEGIN LICENSE BLOCK ***** - * - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is the Narcissus JavaScript engine. - * - * The Initial Developer of the Original Code is - * Brendan Eich . - * Portions created by the Initial Developer are Copyright (C) 2004 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * Tom Austin - * Brendan Eich - * Shu-Yu Guo - * Dave Herman - * Dimitris Vardoulakis - * Patrick Walton - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -/* - * Narcissus - JS implemented in JS. - * - * Parser. - */ - -Narcissus.parser = (function() { - - var lexer = Narcissus.lexer; - var definitions = Narcissus.definitions; - - const StringMap = definitions.StringMap; - const Stack = definitions.Stack; - - // Set constants in the local scope. - eval(definitions.consts); - - /* - * pushDestructuringVarDecls :: (node, hoisting node) -> void - * - * Recursively add all destructured declarations to varDecls. - */ - function pushDestructuringVarDecls(n, s) { - for (var i in n) { - var sub = n[i]; - if (sub.type === IDENTIFIER) { - s.varDecls.push(sub); - } else { - pushDestructuringVarDecls(sub, s); - } - } - } - - // NESTING_TOP: top-level - // NESTING_SHALLOW: nested within static forms such as { ... } or labeled statement - // NESTING_DEEP: nested within dynamic forms such as if, loops, etc. - const NESTING_TOP = 0, NESTING_SHALLOW = 1, NESTING_DEEP = 2; - - function StaticContext(parentScript, parentBlock, inFunction, inForLoopInit, nesting) { - this.parentScript = parentScript; - this.parentBlock = parentBlock; - this.inFunction = inFunction; - this.inForLoopInit = inForLoopInit; - this.nesting = nesting; - this.allLabels = new Stack(); - this.currentLabels = new Stack(); - this.labeledTargets = new Stack(); - this.defaultTarget = null; - Narcissus.options.ecma3OnlyMode && (this.ecma3OnlyMode = true); - Narcissus.options.parenFreeMode && (this.parenFreeMode = true); - } - - StaticContext.prototype = { - ecma3OnlyMode: false, - parenFreeMode: false, - // non-destructive update via prototype extension - update: function(ext) { - var desc = {}; - for (var key in ext) { - desc[key] = { - value: ext[key], - writable: true, - enumerable: true, - configurable: true - } - } - return Object.create(this, desc); - }, - pushLabel: function(label) { - return this.update({ currentLabels: this.currentLabels.push(label), - allLabels: this.allLabels.push(label) }); - }, - pushTarget: function(target) { - var isDefaultTarget = target.isLoop || target.type === SWITCH; - if (isDefaultTarget) target.target = this.defaultTarget; - - if (this.currentLabels.isEmpty()) { - return isDefaultTarget - ? this.update({ defaultTarget: target }) - : this; - } - - target.labels = new StringMap(); - this.currentLabels.forEach(function(label) { - target.labels.set(label, true); - }); - return this.update({ currentLabels: new Stack(), - labeledTargets: this.labeledTargets.push(target), - defaultTarget: isDefaultTarget - ? target - : this.defaultTarget }); - }, - nest: function(atLeast) { - var nesting = Math.max(this.nesting, atLeast); - return (nesting !== this.nesting) - ? this.update({ nesting: nesting }) - : this; - } - }; - - /* - * Script :: (tokenizer, boolean) -> node - * - * Parses the toplevel and function bodies. - */ - function Script(t, inFunction) { - var n = new Node(t, scriptInit()); - var x = new StaticContext(n, n, inFunction, false, NESTING_TOP); - Statements(t, x, n); - return n; - } - - // We extend Array slightly with a top-of-stack method. - definitions.defineProperty(Array.prototype, "top", - function() { - return this.length && this[this.length-1]; - }, false, false, true); - - /* - * Node :: (tokenizer, optional init object) -> node - */ - function Node(t, init) { - var token = t.token; - if (token) { - // If init.type exists it will override token.type. - this.type = token.type; - this.value = token.value; - this.lineno = token.lineno; - - // Start and end are file positions for error handling. - this.start = token.start; - this.end = token.end; - } else { - this.lineno = t.lineno; - } - - // Node uses a tokenizer for debugging (getSource, filename getter). - this.tokenizer = t; - this.children = []; - - for (var prop in init) - this[prop] = init[prop]; - } - - var Np = Node.prototype = {}; - Np.constructor = Node; - Np.toSource = Object.prototype.toSource; - - // Always use push to add operands to an expression, to update start and end. - Np.push = function (kid) { - // kid can be null e.g. [1, , 2]. - if (kid !== null) { - if (kid.start < this.start) - this.start = kid.start; - if (this.end < kid.end) - this.end = kid.end; - } - return this.children.push(kid); - } - - Node.indentLevel = 0; - - function tokenString(tt) { - var t = definitions.tokens[tt]; - return /^\W/.test(t) ? definitions.opTypeNames[t] : t.toUpperCase(); - } - - Np.toString = function () { - var a = []; - for (var i in this) { - if (this.hasOwnProperty(i) && i !== 'type' && i !== 'target') - a.push({id: i, value: this[i]}); - } - a.sort(function (a,b) { return (a.id < b.id) ? -1 : 1; }); - const INDENTATION = " "; - var n = ++Node.indentLevel; - var s = "{\n" + INDENTATION.repeat(n) + "type: " + tokenString(this.type); - for (i = 0; i < a.length; i++) - s += ", " + a[i].id + ": " + a[i].value; - //s += ",\n" + INDENTATION.repeat(n) + a[i].id + ": " + a[i].value; - n = --Node.indentLevel; - s += "\n" + INDENTATION.repeat(n) + "}"; - return s; - } - - Np.getSource = function () { - return this.tokenizer.source.slice(this.start, this.end); - }; - - /* - * Helper init objects for common nodes. - */ - - const LOOP_INIT = { isLoop: true }; - - function blockInit() { - return { type: BLOCK, varDecls: [] }; - } - - function scriptInit() { - return { type: SCRIPT, - funDecls: [], - varDecls: [], - modDecls: [], - impDecls: [], - expDecls: [], - loadDeps: [], - hasEmptyReturn: false, - hasReturnWithValue: false, - isGenerator: false }; - } - - definitions.defineGetter(Np, "filename", - function() { - return this.tokenizer.filename; - }); - - definitions.defineGetter(Np, "length", - function() { - throw new Error("Node.prototype.length is gone; " + - "use n.children.length instead"); - }); - - definitions.defineProperty(String.prototype, "repeat", - function(n) { - var s = "", t = this + s; - while (--n >= 0) - s += t; - return s; - }, false, false, true); - - function MaybeLeftParen(t, x) { - if (x.parenFreeMode) - return t.match(LEFT_PAREN) ? LEFT_PAREN : END; - return t.mustMatch(LEFT_PAREN).type; - } - - function MaybeRightParen(t, p) { - if (p === LEFT_PAREN) - t.mustMatch(RIGHT_PAREN); - } - - /* - * Statements :: (tokenizer, compiler context, node) -> void - * - * Parses a sequence of Statements. - */ - function Statements(t, x, n) { - try { - while (!t.done && t.peek(true) !== RIGHT_CURLY) - n.push(Statement(t, x)); - } catch (e) { - if (t.done) - t.unexpectedEOF = true; - throw e; - } - } - - function Block(t, x) { - t.mustMatch(LEFT_CURLY); - var n = new Node(t, blockInit()); - Statements(t, x.update({ parentBlock: n }).pushTarget(n), n); - t.mustMatch(RIGHT_CURLY); - n.end = t.token.end; - return n; - } - - const DECLARED_FORM = 0, EXPRESSED_FORM = 1, STATEMENT_FORM = 2; - - /* - * Statement :: (tokenizer, compiler context) -> node - * - * Parses a Statement. - */ - function Statement(t, x) { - var i, label, n, n2, p, c, ss, tt = t.get(true), tt2, x2, x3; - - // Cases for statements ending in a right curly return early, avoiding the - // common semicolon insertion magic after this switch. - switch (tt) { - case FUNCTION: - // DECLARED_FORM extends funDecls of x, STATEMENT_FORM doesn't. - return FunctionDefinition(t, x, true, - (x.nesting !== NESTING_TOP) - ? STATEMENT_FORM - : DECLARED_FORM); - - case LEFT_CURLY: - n = new Node(t, blockInit()); - Statements(t, x.update({ parentBlock: n }).pushTarget(n).nest(NESTING_SHALLOW), n); - t.mustMatch(RIGHT_CURLY); - n.end = t.token.end; - return n; - - case IF: - n = new Node(t); - n.condition = HeadExpression(t, x); - x2 = x.pushTarget(n).nest(NESTING_DEEP); - n.thenPart = Statement(t, x2); - n.elsePart = t.match(ELSE) ? Statement(t, x2) : null; - return n; - - case SWITCH: - // This allows CASEs after a DEFAULT, which is in the standard. - n = new Node(t, { cases: [], defaultIndex: -1 }); - n.discriminant = HeadExpression(t, x); - x2 = x.pushTarget(n).nest(NESTING_DEEP); - t.mustMatch(LEFT_CURLY); - while ((tt = t.get()) !== RIGHT_CURLY) { - switch (tt) { - case DEFAULT: - if (n.defaultIndex >= 0) - throw t.newSyntaxError("More than one switch default"); - // FALL THROUGH - case CASE: - n2 = new Node(t); - if (tt === DEFAULT) - n.defaultIndex = n.cases.length; - else - n2.caseLabel = Expression(t, x2, COLON); - break; - - default: - throw t.newSyntaxError("Invalid switch case"); - } - t.mustMatch(COLON); - n2.statements = new Node(t, blockInit()); - while ((tt=t.peek(true)) !== CASE && tt !== DEFAULT && - tt !== RIGHT_CURLY) - n2.statements.push(Statement(t, x2)); - n.cases.push(n2); - } - n.end = t.token.end; - return n; - - case FOR: - n = new Node(t, LOOP_INIT); - if (t.match(IDENTIFIER)) { - if (t.token.value === "each") - n.isEach = true; - else - t.unget(); - } - if (!x.parenFreeMode) - t.mustMatch(LEFT_PAREN); - x2 = x.pushTarget(n).nest(NESTING_DEEP); - x3 = x.update({ inForLoopInit: true }); - if ((tt = t.peek()) !== SEMICOLON) { - if (tt === VAR || tt === CONST) { - t.get(); - n2 = Variables(t, x3); - } else if (tt === LET) { - t.get(); - if (t.peek() === LEFT_PAREN) { - n2 = LetBlock(t, x3, false); - } else { - // Let in for head, we need to add an implicit block - // around the rest of the for. - x3.parentBlock = n; - n.varDecls = []; - n2 = Variables(t, x3); - } - } else { - n2 = Expression(t, x3); - } - } - if (n2 && t.match(IN)) { - n.type = FOR_IN; - n.object = Expression(t, x3); - if (n2.type === VAR || n2.type === LET) { - c = n2.children; - - // Destructuring turns one decl into multiples, so either - // there must be only one destructuring or only one - // decl. - if (c.length !== 1 && n2.destructurings.length !== 1) { - throw new SyntaxError("Invalid for..in left-hand side", - t.filename, n2.lineno); - } - if (n2.destructurings.length > 0) { - n.iterator = n2.destructurings[0]; - } else { - n.iterator = c[0]; - } - n.varDecl = n2; - } else { - if (n2.type === ARRAY_INIT || n2.type === OBJECT_INIT) { - n2.destructuredNames = checkDestructuring(t, x3, n2); - } - n.iterator = n2; - } - } else { - n.setup = n2; - t.mustMatch(SEMICOLON); - if (n.isEach) - throw t.newSyntaxError("Invalid for each..in loop"); - n.condition = (t.peek() === SEMICOLON) - ? null - : Expression(t, x3); - t.mustMatch(SEMICOLON); - tt2 = t.peek(); - n.update = (x.parenFreeMode - ? tt2 === LEFT_CURLY || definitions.isStatementStartCode[tt2] - : tt2 === RIGHT_PAREN) - ? null - : Expression(t, x3); - } - if (!x.parenFreeMode) - t.mustMatch(RIGHT_PAREN); - n.body = Statement(t, x2); - n.end = t.token.end; - return n; - - case WHILE: - n = new Node(t, { isLoop: true }); - n.condition = HeadExpression(t, x); - n.body = Statement(t, x.pushTarget(n).nest(NESTING_DEEP)); - n.end = t.token.end; - return n; - - case DO: - n = new Node(t, { isLoop: true }); - n.body = Statement(t, x.pushTarget(n).nest(NESTING_DEEP)); - t.mustMatch(WHILE); - n.condition = HeadExpression(t, x); - if (!x.ecmaStrictMode) { - // - - - - + + + + - + - +
diff --git a/lib/callbacks/builtins.js b/lib/callbacks/builtins.js index 1e0e9548..77172c21 100644 --- a/lib/callbacks/builtins.js +++ b/lib/callbacks/builtins.js @@ -1,370 +1,367 @@ -/*** Generated by streamline 0.10.17 (callbacks) - DO NOT EDIT ***/ var __rt=require('../callbacks/runtime').runtime(__filename, false),__func=__rt.__func,__cb=__rt.__cb; (function(exports) { - - - - - - - - - "use strict"; - var VERSION = 3; - - - - var future = function(fn, args, i) { - var err, result, done, q = [], self = this; - - args = Array.prototype.slice.call(args); - args[i] = function(e, r) { - err = e, result = r, done = true; - (q && q.forEach(function(f) { - f.call(self, e, r); })); - - q = null; }; - - fn.apply(this, args); - return function F(cb) { - if (!cb) { return F }; - if (done) { cb.call(self, err, result); } else { - q.push(cb); }; }; }; - - - - - exports.funnel = function(max) { - max = ((max == null) ? -1 : max); - if ((max === 0)) { max = funnel.defaultSize; }; - if ((typeof max !== "number")) { throw new Error(("bad max number: " + max)) }; - var queue = [], active = 0, closed = false; - - - - var funCb = function(callback, fn) { - if ((callback == null)) { return future(funCb, arguments, 0) }; - - if (((max < 0) || (max == Infinity))) { return fn(callback) }; - - queue.push({ - fn: fn, - cb: callback }); - - - function _doOne() { - var current = queue.splice(0, 1)[0]; - if (!current.cb) { return current.fn() }; - active++; - current.fn(function(err, result) { - active--; - if (!closed) { - current.cb(err, result); - while (((active < max) && (queue.length > 0))) { _doOne();; }; } ; }); }; - - - - - while (((active < max) && (queue.length > 0))) { _doOne();; }; }; - - var fun = __rt.streamlinify(funCb, 0); - - fun.close = function() { - queue = [], closed = true; }; - - return fun; }; - - var funnel = exports.funnel; - funnel.defaultSize = 4; - - function _parallel(options) { - if ((typeof options === "number")) { return options }; - if ((typeof options.parallel === "number")) { return options.parallel }; - return (options.parallel ? -1 : 1); }; - - - if ((Array.prototype.forEach_ && (Array.prototype.forEach_.version_ >= VERSION))) { return }; - - - try { - Object.defineProperty({ }, "x", { }); - } catch (e) { - return; }; - - - var has = Object.prototype.hasOwnProperty; - - - - - - - - - - - - - - - - - - - - - - - - - - delete Array.prototype.forEach_; - Object.defineProperty(Array.prototype, "forEach_", { - configurable: true, - writable: true, - enumerable: false, - value: function value__1(_, options, fn, thisObj) { var par, len, i, __this = this; var __frame = { name: "value__1", line: 124 }; return __func(_, this, arguments, value__1, 0, __frame, function __$value__1() { - if ((typeof options === "function")) { thisObj = fn, fn = options, options = 1; } ; - par = _parallel(options); - thisObj = ((thisObj !== undefined) ? thisObj : __this); - len = __this.length; return (function __$value__1(__then) { - if (((par === 1) || (len <= 1))) { - i = 0; var __2 = false; return (function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$value__1() { __more = false; if (__2) { i++; } else { __2 = true; } ; var __1 = (i < len); if (__1) { return (function __$value__1(__then) { - if (has.call(__this, i)) { return fn.call(thisObj, __cb(_, __frame, 7, 31, __then, true), __this[i], i); } else { __then(); } ; })(function __$value__1() { while (__more) { __loop(); }; __more = true; }); } else { __break(); } ; }); do { __loop(); } while (__more); __more = true; })(__then); } else { - - - return __this.map_(__cb(_, __frame, 10, 9, __then, true), par, fn, thisObj); } ; })(function __$value__1() { return _(null, __this); }); }); } }); - - - - - Array.prototype.forEach_.version_ = VERSION; - - - delete Array.prototype.map_; - Object.defineProperty(Array.prototype, "map_", { - configurable: true, - writable: true, - enumerable: false, - value: function value__2(_, options, fn, thisObj) { var par, len, result, i, fun, __this = this; var __frame = { name: "value__2", line: 147 }; return __func(_, this, arguments, value__2, 0, __frame, function __$value__2() { - if ((typeof options === "function")) { thisObj = fn, fn = options, options = 1; } ; - par = _parallel(options); - thisObj = ((thisObj !== undefined) ? thisObj : __this); - len = __this.length; return (function __$value__2(__then) { - - if (((par === 1) || (len <= 1))) { - result = new Array(len); - i = 0; var __4 = false; return (function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$value__2() { __more = false; if (__4) { i++; } else { __4 = true; } ; var __3 = (i < len); if (__3) { return (function __$value__2(__then) { - if (has.call(__this, i)) { return fn.call(thisObj, __cb(_, __frame, 9, 43, function ___(__0, __1) { result[i] = __1; __then(); }, true), __this[i], i); } else { __then(); } ; })(function __$value__2() { while (__more) { __loop(); }; __more = true; }); } else { __break(); } ; }); do { __loop(); } while (__more); __more = true; })(__then); } else { - - - fun = funnel(par); - result = __this.map(function(elt, i) { - return fun(false, function __1(_) { var __frame = { name: "__1", line: 161 }; return __func(_, this, arguments, __1, 0, __frame, function __$__1() { - return fn.call(thisObj, __cb(_, __frame, 1, 16, _, true), elt, i); }); }); }); - - - i = 0; var __7 = false; return (function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$value__2() { __more = false; if (__7) { i++; } else { __7 = true; } ; var __6 = (i < len); if (__6) { return (function __$value__2(__then) { - if (has.call(__this, i)) { return result[i](__cb(_, __frame, 19, 40, function ___(__0, __2) { result[i] = __2; __then(); }, true)); } else { __then(); } ; })(function __$value__2() { while (__more) { __loop(); }; __more = true; }); } else { __break(); } ; }); do { __loop(); } while (__more); __more = true; })(__then); } ; })(function __$value__2() { - - - return _(null, result); }); }); } }); - - - - - delete Array.prototype.filter_; - Object.defineProperty(Array.prototype, "filter_", { - configurable: true, - writable: true, - enumerable: false, - value: function value__3(_, options, fn, thisObj) { var par, result, len, i, elt, __this = this; var __frame = { name: "value__3", line: 179 }; return __func(_, this, arguments, value__3, 0, __frame, function __$value__3() { - if ((typeof options === "function")) { thisObj = fn, fn = options, options = 1; } ; - par = _parallel(options); - thisObj = ((thisObj !== undefined) ? thisObj : __this); - result = []; - len = __this.length; return (function __$value__3(__then) { - if (((par === 1) || (len <= 1))) { - i = 0; var __4 = false; return (function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$value__3() { __more = false; if (__4) { i++; } else { __4 = true; } ; var __3 = (i < len); if (__3) { return (function __$value__3(__then) { - if (has.call(__this, i)) { - elt = __this[i]; - return fn.call(thisObj, __cb(_, __frame, 10, 13, function ___(__0, __2) { return (function __$value__3(__then) { if (__2) { result.push(elt); __then(); } else { __then(); } ; })(__then); }, true), elt); } else { __then(); } ; })(function __$value__3() { while (__more) { __loop(); }; __more = true; }); } else { __break(); } ; }); do { __loop(); } while (__more); __more = true; })(__then); } else { - - - - return __this.map_(__cb(_, __frame, 14, 9, __then, true), par, function __1(_, elt) { var __frame = { name: "__1", line: 193 }; return __func(_, this, arguments, __1, 0, __frame, function __$__1() { - return fn.call(thisObj, __cb(_, __frame, 1, 12, function ___(__0, __1) { return (function __$__1(__then) { if (__1) { result.push(elt); __then(); } else { __then(); } ; })(_); }, true), elt); }); - }, thisObj); } ; })(function __$value__3() { - - return _(null, result); }); }); } }); - - - - - delete Array.prototype.every_; - Object.defineProperty(Array.prototype, "every_", { - configurable: true, - writable: true, - enumerable: false, - value: function value__4(_, options, fn, thisObj) { var par, len, i, fun, futures, __this = this; var __frame = { name: "value__4", line: 207 }; return __func(_, this, arguments, value__4, 0, __frame, function __$value__4() { - if ((typeof options === "function")) { thisObj = fn, fn = options, options = 1; } ; - par = _parallel(options); - thisObj = ((thisObj !== undefined) ? thisObj : __this); - len = __this.length; return (function __$value__4(__then) { - if (((par === 1) || (len <= 1))) { - i = 0; var __6 = false; return (function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$value__4() { __more = false; if (__6) { i++; } else { __6 = true; } ; var __5 = (i < len); if (__5) { return (function __$value__4(_) { - - var __1 = has.call(__this, i); if (!__1) { return _(null, __1); } ; return fn.call(thisObj, __cb(_, __frame, 8, 34, function ___(__0, __3) { var __2 = !__3; return _(null, __2); }, true), __this[i]); })(__cb(_, __frame, -206, 17, function ___(__0, __3) { return (function __$value__4(__then) { if (__3) { return _(null, false); } else { __then(); } ; })(function __$value__4() { while (__more) { __loop(); }; __more = true; }); }, true)); } else { __break(); } ; }); do { __loop(); } while (__more); __more = true; })(__then); } else { - - - fun = funnel(par); - futures = __this.map(function(elt) { - return fun(false, function __1(_) { var __frame = { name: "__1", line: 220 }; return __func(_, this, arguments, __1, 0, __frame, function __$__1() { - return fn.call(thisObj, __cb(_, __frame, 1, 16, _, true), elt); }); }); }); - - - i = 0; var __9 = false; return (function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$value__4() { __more = false; if (__9) { i++; } else { __9 = true; } ; var __8 = (i < len); if (__8) { return (function __$value__4(_) { - var __2 = has.call(__this, i); if (!__2) { return _(null, __2); } ; return futures[i](__cb(_, __frame, 18, 31, function ___(__0, __4) { var __3 = !__4; return _(null, __3); }, true)); })(__cb(_, __frame, -206, 17, function ___(__0, __4) { return (function __$value__4(__then) { if (__4) { - fun.close(); - return _(null, false); } else { __then(); } ; })(function __$value__4() { while (__more) { __loop(); }; __more = true; }); }, true)); } else { __break(); } ; }); do { __loop(); } while (__more); __more = true; })(__then); } ; })(function __$value__4() { - - - - return _(null, true); }); }); } }); - - - - - delete Array.prototype.some_; - Object.defineProperty(Array.prototype, "some_", { - configurable: true, - writable: true, - enumerable: false, - value: function value__5(_, options, fn, thisObj) { var par, len, i, fun, futures, __this = this; var __frame = { name: "value__5", line: 241 }; return __func(_, this, arguments, value__5, 0, __frame, function __$value__5() { - if ((typeof options === "function")) { thisObj = fn, fn = options, options = 1; } ; - par = _parallel(options); - thisObj = ((thisObj !== undefined) ? thisObj : __this); - len = __this.length; return (function __$value__5(__then) { - if (((par === 1) || (len <= 1))) { - i = 0; var __6 = false; return (function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$value__5() { __more = false; if (__6) { i++; } else { __6 = true; } ; var __5 = (i < len); if (__5) { return (function __$value__5(_) { - var __1 = has.call(__this, i); if (!__1) { return _(null, __1); } ; return fn.call(thisObj, __cb(_, __frame, 7, 33, _, true), __this[i]); })(__cb(_, __frame, -240, 17, function ___(__0, __3) { return (function __$value__5(__then) { if (__3) { return _(null, true); } else { __then(); } ; })(function __$value__5() { while (__more) { __loop(); }; __more = true; }); }, true)); } else { __break(); } ; }); do { __loop(); } while (__more); __more = true; })(__then); } else { - - - fun = funnel(par); - futures = __this.map(function(elt) { - return fun(false, function __1(_) { var __frame = { name: "__1", line: 253 }; return __func(_, this, arguments, __1, 0, __frame, function __$__1() { - return fn.call(thisObj, __cb(_, __frame, 1, 16, _, true), elt); }); }); }); - - - i = 0; var __9 = false; return (function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$value__5() { __more = false; if (__9) { i++; } else { __9 = true; } ; var __8 = (i < len); if (__8) { return (function __$value__5(_) { - var __2 = has.call(__this, i); if (!__2) { return _(null, __2); } ; return futures[i](__cb(_, __frame, 17, 30, _, true)); })(__cb(_, __frame, -240, 17, function ___(__0, __4) { return (function __$value__5(__then) { if (__4) { - fun.close(); - return _(null, true); } else { __then(); } ; })(function __$value__5() { while (__more) { __loop(); }; __more = true; }); }, true)); } else { __break(); } ; }); do { __loop(); } while (__more); __more = true; })(__then); } ; })(function __$value__5() { - - - - return _(null, false); }); }); } }); - - - - - delete Array.prototype.reduce_; - Object.defineProperty(Array.prototype, "reduce_", { - configurable: true, - writable: true, - enumerable: false, - value: function value__6(_, fn, v, thisObj) { var len, i, __this = this; var __frame = { name: "value__6", line: 274 }; return __func(_, this, arguments, value__6, 0, __frame, function __$value__6() { - thisObj = ((thisObj !== undefined) ? thisObj : __this); - len = __this.length; - i = 0; var __3 = false; return (function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$value__6() { __more = false; if (__3) { i++; } else { __3 = true; } ; var __2 = (i < len); if (__2) { return (function __$value__6(__then) { - if (has.call(__this, i)) { return fn.call(thisObj, __cb(_, __frame, 4, 34, function ___(__0, __1) { v = __1; __then(); }, true), v, __this[i], i, __this); } else { __then(); } ; })(function __$value__6() { while (__more) { __loop(); }; __more = true; }); } else { __break(); } ; }); do { __loop(); } while (__more); __more = true; })(function __$value__6() { - - return _(null, v); }); }); } }); - - - - - delete Array.prototype.reduceRight_; - Object.defineProperty(Array.prototype, "reduceRight_", { - configurable: true, - writable: true, - enumerable: false, - value: function value__7(_, fn, v, thisObj) { var len, i, __this = this; var __frame = { name: "value__7", line: 290 }; return __func(_, this, arguments, value__7, 0, __frame, function __$value__7() { - thisObj = ((thisObj !== undefined) ? thisObj : __this); - len = __this.length; - i = (len - 1); var __3 = false; return (function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$value__7() { __more = false; if (__3) { i--; } else { __3 = true; } ; var __2 = (i >= 0); if (__2) { return (function __$value__7(__then) { - if (has.call(__this, i)) { return fn.call(thisObj, __cb(_, __frame, 4, 34, function ___(__0, __1) { v = __1; __then(); }, true), v, __this[i], i, __this); } else { __then(); } ; })(function __$value__7() { while (__more) { __loop(); }; __more = true; }); } else { __break(); } ; }); do { __loop(); } while (__more); __more = true; })(function __$value__7() { - - return _(null, v); }); }); } }); - - - - - - - delete Array.prototype.sort_; - Object.defineProperty(Array.prototype, "sort_", { - configurable: true, - writable: true, - enumerable: false, - value: function value__8(_, compare, beg, end) { var array, __this = this; - - - - - function _qsort(_, beg, end) { var tmp, mid, o, nbeg, nend; var __frame = { name: "_qsort", line: 313 }; return __func(_, this, arguments, _qsort, 0, __frame, function __$_qsort() { - if ((beg >= end)) { return _(null); } ; return (function __$_qsort(__then) { - - if ((end == (beg + 1))) { - return compare(__cb(_, __frame, 4, 9, function ___(__0, __4) { var __3 = (__4 > 0); return (function __$_qsort(__then) { if (__3) { - tmp = array[beg]; - array[beg] = array[end]; - array[end] = tmp; __then(); } else { __then(); } ; })(function __$_qsort() { return _(null); }); }, true), array[beg], array[end]); } else { __then(); } ; })(function __$_qsort() { - - - - - mid = Math.floor((((beg + end)) / 2)); - o = array[mid]; - nbeg = beg; - nend = end; return (function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$_qsort() { __more = false; - - var __6 = (nbeg <= nend); if (__6) { return (function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$_qsort() { __more = false; return (function __$_qsort(_) { return (function __$_qsort(_) { - var __1 = (nbeg < end); if (!__1) { return _(null, __1); } ; return compare(__cb(_, __frame, 18, 26, function ___(__0, __3) { var __2 = (__3 < 0); return _(null, __2); }, true), array[nbeg], o); })(__cb(_, __frame, -312, 17, _, true)); })(__cb(_, __frame, -312, 17, function ___(__0, __7) { if (__7) { nbeg++; while (__more) { __loop(); }; __more = true; } else { __break(); } ; }, true)); }); do { __loop(); } while (__more); __more = true; })(function __$_qsort() { return (function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$_qsort() { __more = false; return (function __$_qsort(_) { return (function __$_qsort(_) { - var __2 = (beg < nend); if (!__2) { return _(null, __2); } ; return compare(__cb(_, __frame, 19, 26, function ___(__0, __4) { var __3 = (__4 < 0); return _(null, __3); }, true), o, array[nend]); })(__cb(_, __frame, -312, 17, _, true)); })(__cb(_, __frame, -312, 17, function ___(__0, __9) { if (__9) { nend--; while (__more) { __loop(); }; __more = true; } else { __break(); } ; }, true)); }); do { __loop(); } while (__more); __more = true; })(function __$_qsort() { - - if ((nbeg <= nend)) { - tmp = array[nbeg]; - array[nbeg] = array[nend]; - array[nend] = tmp; - nbeg++; - nend--; } ; while (__more) { __loop(); }; __more = true; }); }); } else { __break(); } ; }); do { __loop(); } while (__more); __more = true; })(function __$_qsort() { return (function __$_qsort(__then) { - - - - if ((nbeg < end)) { return _qsort(__cb(_, __frame, 30, 20, __then, true), nbeg, end); } else { __then(); } ; })(function __$_qsort() { return (function __$_qsort(__then) { - if ((beg < nend)) { return _qsort(__cb(_, __frame, 31, 20, __then, true), beg, nend); } else { __then(); } ; })(_); }); }); }); }); }; var __frame = { name: "value__8", line: 308 }; return __func(_, this, arguments, value__8, 0, __frame, function __$value__8() { array = __this; beg = (beg || 0); end = ((end == null) ? (array.length - 1) : end); - - return _qsort(__cb(_, __frame, 38, 3, function __$value__8() { - return _(null, array); }, true), beg, end); }); } }); - - - - - - - - - - - - delete Function.prototype.apply_; - Object.defineProperty(Function.prototype, "apply_", { - configurable: true, - writable: true, - enumerable: false, - value: function(callback, thisObj, args, index) { - args = Array.prototype.slice.call(args, 0); - args.splice((((index != null) && (index >= 0)) ? index : args.length), 0, callback); - return this.apply(thisObj, args); } }); - - -})(((typeof exports !== "undefined") ? exports : (Streamline.builtins = (Streamline.builtins || {})))); +/*** Generated by streamline 0.10.17 (callbacks) - DO NOT EDIT ***/ var __rt=require('../callbacks/runtime').runtime(__filename, false),__func=__rt.__func,__cb=__rt.__cb; + + + + + + + + (function (exports) { + 'use strict'; + var VERSION = 3; + + + + var future = function (fn, args, i) { + var err, result, done, q = [], self = this; + + args = Array.prototype.slice.call(args); + args[i] = function (e, r) { + err = e, result = r, done = true; + q && q.forEach(function (f) { + f.call(self, e, r); }); + + q = null; }; + + fn.apply(this, args); + return function F(cb) { + if (!cb) return F; + if (done) cb.call(self, err, result); else q.push(cb); }; }; + + + + + + exports.funnel = function (max) { + max = max == null ? -1 : max; + if (max === 0) max = funnel.defaultSize; + if (typeof max !== 'number') throw new Error('bad max number: ' + max); + var queue = [], active = 0, closed = false; + + + + var funCb = function (callback, fn) { + if (callback == null) return future(funCb, arguments, 0); + + if (max < 0 || max == Infinity) return fn(callback); + + queue.push({ fn: fn, cb: callback }); + + + + + function _doOne() { + var current = queue.splice(0, 1)[0]; + if (!current.cb) return current.fn(); + active++; + current.fn(function (err, result) { + active--; + if (!closed) { + current.cb(err, result); + while (active < max && queue.length > 0) _doOne(); } }); } + + + + + while (active < max && queue.length > 0) _doOne(); }; + + var fun = __rt.streamlinify(funCb, 0); + + fun.close = function () { + queue = [], closed = true; }; + + return fun; }; + + var funnel = exports.funnel; + funnel.defaultSize = 4; + + function _parallel(options) { + if (typeof options === 'number') return options; + if (typeof options.parallel === 'number') return options.parallel; + return options.parallel ? -1 : 1; } + + + if (Array.prototype.forEach_ && Array.prototype.forEach_.version_ >= VERSION) return; + + + try { + Object.defineProperty({}, 'x', {}); } catch (e) { + + return; } + + + var has = Object.prototype.hasOwnProperty; + + + + + + + + + + + + + + + + + + + + + + + + + + delete Array.prototype.forEach_; + Object.defineProperty(Array.prototype, 'forEach_', { configurable: true, writable: true, enumerable: false, value: function value__1(_, options, fn, thisObj) { + + + + var par, len, i, __this = this; var __frame = { name: 'value__1', line: 124 }; return __func(_, this, arguments, value__1, 0, __frame, function __$value__1() { + if (typeof options === 'function') { thisObj = fn, fn = options, options = 1; } par = _parallel(options); + + thisObj = thisObj !== undefined ? thisObj : __this; len = __this.length; + + return function __$value__1(__then) { if (par === 1 || len <= 1) { i = 0; + var __2 = false; return function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$value__1() { __more = false; if (__2) { i++; } else { __2 = true; } var __1 = i < len; if (__1) { + return function __$value__1(__then) { if (has.call(__this, i)) { return fn.call(thisObj, __cb(_, __frame, 7, 0, __then, true, false), __this[i], i); } else { __then(); } }(function __$value__1() { while (__more) { __loop(); } __more = true; }); } else { __break(); } }); do { __loop(); } while (__more); __more = true; }(__then); } else { + + + return __this.map_(__cb(_, __frame, 10, 0, __then, true, false), par, fn, thisObj); } }(function __$value__1() { + + return _(null, __this); }); }); } }); + + + Array.prototype.forEach_.version_ = VERSION; + + + delete Array.prototype.map_; + Object.defineProperty(Array.prototype, 'map_', { configurable: true, writable: true, enumerable: false, value: function value__2(_, options, fn, thisObj) { + + + + var par, len, result, i, fun, __this = this; var __frame = { name: 'value__2', line: 147 }; return __func(_, this, arguments, value__2, 0, __frame, function __$value__2() { + if (typeof options === 'function') { thisObj = fn, fn = options, options = 1; } par = _parallel(options); + + thisObj = thisObj !== undefined ? thisObj : __this; len = __this.length; + + + return function __$value__2(__then) { if (par === 1 || len <= 1) { + result = new Array(len); i = 0; + var __4 = false; return function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$value__2() { __more = false; if (__4) { i++; } else { __4 = true; } var __3 = i < len; if (__3) { + return function __$value__2(__then) { if (has.call(__this, i)) { return fn.call(thisObj, __cb(_, __frame, 9, 0, function ___(__0, __1) { result[i] = __1; __then(); }, true, false), __this[i], i); } else { __then(); } }(function __$value__2() { while (__more) { __loop(); } __more = true; }); } else { __break(); } }); do { __loop(); } while (__more); __more = true; }(__then); } else { + + fun = funnel(par); + + result = __this.map(function (elt, i) { + return fun(false, function __1(_) { var __frame = { name: '__1', line: 161 }; return __func(_, this, arguments, __1, 0, __frame, function __$__1() { + return fn.call(thisObj, __cb(_, __frame, 1, 0, _, true, false), elt, i); }); }); }); i = 0; + + + var __7 = false; return function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$value__2() { __more = false; if (__7) { i++; } else { __7 = true; } var __6 = i < len; if (__6) { + return function __$value__2(__then) { if (has.call(__this, i)) { return result[i](__cb(_, __frame, 19, 0, function ___(__0, __2) { result[i] = __2; __then(); }, true, false)); } else { __then(); } }(function __$value__2() { while (__more) { __loop(); } __more = true; }); } else { __break(); } }); do { __loop(); } while (__more); __more = true; }(__then); } }(function __$value__2() { + + + return _(null, result); }); }); } }); + + + + + delete Array.prototype.filter_; + Object.defineProperty(Array.prototype, 'filter_', { configurable: true, writable: true, enumerable: false, value: function value__3(_, options, fn, thisObj) { + + + + var par, result, len, i, elt, __this = this; var __frame = { name: 'value__3', line: 179 }; return __func(_, this, arguments, value__3, 0, __frame, function __$value__3() { + if (typeof options === 'function') { thisObj = fn, fn = options, options = 1; } par = _parallel(options); + + thisObj = thisObj !== undefined ? thisObj : __this; result = []; + len = __this.length; + + return function __$value__3(__then) { if (par === 1 || len <= 1) { i = 0; + var __5 = false; return function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$value__3() { __more = false; if (__5) { i++; } else { __5 = true; } var __4 = i < len; if (__4) { + return function __$value__3(__then) { if (has.call(__this, i)) { elt = __this[i]; + + return fn.call(thisObj, __cb(_, __frame, 10, 0, function ___(__0, __3) { var __2 = __3; return function __$value__3(__then) { if (__2) { result.push(elt); __then(); } else { __then(); } }(__then); }, true, false), elt); } else { __then(); } }(function __$value__3() { while (__more) { __loop(); } __more = true; }); } else { __break(); } }); do { __loop(); } while (__more); __more = true; }(__then); } else { + + + + return __this.map_(__cb(_, __frame, 14, 0, __then, true, false), par, function __1(_, elt) { var __frame = { name: '__1', line: 193 }; return __func(_, this, arguments, __1, 0, __frame, function __$__1() { + return fn.call(thisObj, __cb(_, __frame, 1, 0, function ___(__0, __2) { var __1 = __2; return function __$__1(__then) { if (__1) { result.push(elt); __then(); } else { __then(); } }(_); }, true, false), elt); }); }, thisObj); } }(function __$value__3() { + + + return _(null, result); }); }); } }); + + + + + delete Array.prototype.every_; + Object.defineProperty(Array.prototype, 'every_', { configurable: true, writable: true, enumerable: false, value: function value__4(_, options, fn, thisObj) { + + + + var par, len, i, fun, futures, __this = this; var __frame = { name: 'value__4', line: 207 }; return __func(_, this, arguments, value__4, 0, __frame, function __$value__4() { + if (typeof options === 'function') { thisObj = fn, fn = options, options = 1; } par = _parallel(options); + + thisObj = thisObj !== undefined ? thisObj : __this; len = __this.length; + + return function __$value__4(__then) { if (par === 1 || len <= 1) { i = 0; + var __8 = false; return function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$value__4() { __more = false; if (__8) { i++; } else { __8 = true; } var __7 = i < len; if (__7) { + + return function __$value__4(_) { var __1 = has.call(__this, i); if (!__1) { return _(null, __1); } return fn.call(thisObj, __cb(_, __frame, 8, 0, function ___(__0, __3) { var __2 = !__3; return _(null, __2); }, true, false), __this[i]); }(__cb(_, __frame, 0, 0, function ___(__0, __4) { var __3 = __4; return function __$value__4(__then) { if (__3) { return _(null, false); } else { __then(); } }(function __$value__4() { while (__more) { __loop(); } __more = true; }); }, true, false)); } else { __break(); } }); do { __loop(); } while (__more); __more = true; }(__then); } else { + + fun = funnel(par); + futures = __this.map(function (elt) { + + return fun(false, function __1(_) { var __frame = { name: '__1', line: 220 }; return __func(_, this, arguments, __1, 0, __frame, function __$__1() { + return fn.call(thisObj, __cb(_, __frame, 1, 0, _, true, false), elt); }); }); }); i = 0; + + + var __11 = false; return function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$value__4() { __more = false; if (__11) { i++; } else { __11 = true; } var __10 = i < len; if (__10) { + return function __$value__4(_) { var __2 = has.call(__this, i); if (!__2) { return _(null, __2); } return futures[i](__cb(_, __frame, 18, 0, function ___(__0, __4) { var __3 = !__4; return _(null, __3); }, true, false)); }(__cb(_, __frame, 0, 0, function ___(__0, __6) { var __5 = __6; return function __$value__4(__then) { if (__5) { + fun.close(); + return _(null, false); } else { __then(); } }(function __$value__4() { while (__more) { __loop(); } __more = true; }); }, true, false)); } else { __break(); } }); do { __loop(); } while (__more); __more = true; }(__then); } }(function __$value__4() { + + + + return _(null, true); }); }); } }); + + + + + delete Array.prototype.some_; + Object.defineProperty(Array.prototype, 'some_', { configurable: true, writable: true, enumerable: false, value: function value__5(_, options, fn, thisObj) { + + + + var par, len, i, fun, futures, __this = this; var __frame = { name: 'value__5', line: 241 }; return __func(_, this, arguments, value__5, 0, __frame, function __$value__5() { + if (typeof options === 'function') { thisObj = fn, fn = options, options = 1; } par = _parallel(options); + + thisObj = thisObj !== undefined ? thisObj : __this; len = __this.length; + + return function __$value__5(__then) { if (par === 1 || len <= 1) { i = 0; + var __8 = false; return function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$value__5() { __more = false; if (__8) { i++; } else { __8 = true; } var __7 = i < len; if (__7) { + return function __$value__5(_) { var __1 = has.call(__this, i); if (!__1) { return _(null, __1); } return fn.call(thisObj, __cb(_, __frame, 7, 0, _, true, false), __this[i]); }(__cb(_, __frame, 0, 0, function ___(__0, __4) { var __3 = __4; return function __$value__5(__then) { if (__3) { return _(null, true); } else { __then(); } }(function __$value__5() { while (__more) { __loop(); } __more = true; }); }, true, false)); } else { __break(); } }); do { __loop(); } while (__more); __more = true; }(__then); } else { + + fun = funnel(par); + futures = __this.map(function (elt) { + + return fun(false, function __1(_) { var __frame = { name: '__1', line: 253 }; return __func(_, this, arguments, __1, 0, __frame, function __$__1() { + return fn.call(thisObj, __cb(_, __frame, 1, 0, _, true, false), elt); }); }); }); i = 0; + + + var __11 = false; return function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$value__5() { __more = false; if (__11) { i++; } else { __11 = true; } var __10 = i < len; if (__10) { + return function __$value__5(_) { var __2 = has.call(__this, i); if (!__2) { return _(null, __2); } return futures[i](__cb(_, __frame, 17, 0, _, true, false)); }(__cb(_, __frame, 0, 0, function ___(__0, __6) { var __5 = __6; return function __$value__5(__then) { if (__5) { + fun.close(); + return _(null, true); } else { __then(); } }(function __$value__5() { while (__more) { __loop(); } __more = true; }); }, true, false)); } else { __break(); } }); do { __loop(); } while (__more); __more = true; }(__then); } }(function __$value__5() { + + + + return _(null, false); }); }); } }); + + + + + delete Array.prototype.reduce_; + Object.defineProperty(Array.prototype, 'reduce_', { configurable: true, writable: true, enumerable: false, value: function value__6(_, fn, v, thisObj) { + + + + var len, i, __this = this; var __frame = { name: 'value__6', line: 274 }; return __func(_, this, arguments, value__6, 0, __frame, function __$value__6() { + thisObj = thisObj !== undefined ? thisObj : __this; len = __this.length; + i = 0; + var __3 = false; return function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$value__6() { __more = false; if (__3) { i++; } else { __3 = true; } var __2 = i < len; if (__2) { + return function __$value__6(__then) { if (has.call(__this, i)) { return fn.call(thisObj, __cb(_, __frame, 4, 0, function ___(__0, __1) { v = __1; __then(); }, true, false), v, __this[i], i, __this); } else { __then(); } }(function __$value__6() { while (__more) { __loop(); } __more = true; }); } else { __break(); } }); do { __loop(); } while (__more); __more = true; }(function __$value__6() { + + return _(null, v); }); }); } }); + + + + + delete Array.prototype.reduceRight_; + Object.defineProperty(Array.prototype, 'reduceRight_', { configurable: true, writable: true, enumerable: false, value: function value__7(_, fn, v, thisObj) { + + + + var len, i, __this = this; var __frame = { name: 'value__7', line: 290 }; return __func(_, this, arguments, value__7, 0, __frame, function __$value__7() { + thisObj = thisObj !== undefined ? thisObj : __this; len = __this.length; + i = len - 1; + var __3 = false; return function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$value__7() { __more = false; if (__3) { i--; } else { __3 = true; } var __2 = i >= 0; if (__2) { + return function __$value__7(__then) { if (has.call(__this, i)) { return fn.call(thisObj, __cb(_, __frame, 4, 0, function ___(__0, __1) { v = __1; __then(); }, true, false), v, __this[i], i, __this); } else { __then(); } }(function __$value__7() { while (__more) { __loop(); } __more = true; }); } else { __break(); } }); do { __loop(); } while (__more); __more = true; }(function __$value__7() { + + return _(null, v); }); }); } }); + + + + + + + delete Array.prototype.sort_; + Object.defineProperty(Array.prototype, 'sort_', { configurable: true, writable: true, enumerable: false, value: function value__8(_, compare, beg, end) { + + + + var array, __this = this; + + + + + function _qsort(_, beg, end) { var tmp, mid, o, nbeg, nend; var __frame = { name: '_qsort', line: 313 }; return __func(_, this, arguments, _qsort, 0, __frame, function __$_qsort() { + if (beg >= end) { return _(null); } + + return function __$_qsort(__then) { if (end == beg + 1) { + return compare(__cb(_, __frame, 4, 0, function ___(__0, __4) { var __3 = __4 > 0; return function __$_qsort(__then) { if (__3) { tmp = array[beg]; + + array[beg] = array[end]; + array[end] = tmp; __then(); } else { __then(); } }(function __$_qsort() { + + return _(null); }); }, true, false), array[beg], array[end]); } else { __then(); } }(function __$_qsort() { mid = Math.floor((beg + end) / 2); + + + o = array[mid]; + nbeg = beg; + nend = end; + return function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$_qsort() { __more = false; var __6 = nbeg <= nend; + + if (__6) { return function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$_qsort() { __more = false; return function __$_qsort(_) { + return function __$_qsort(_) { var __1 = nbeg < end; if (!__1) { return _(null, __1); } return compare(__cb(_, __frame, 18, 0, function ___(__0, __3) { var __2 = __3 < 0; return _(null, __2); }, true, false), array[nbeg], o); }(__cb(_, __frame, 0, 0, _, true, false)); }(__cb(_, __frame, 0, 0, function ___(__0, __7) { if (__7) { nbeg++; while (__more) { __loop(); } __more = true; } else { __break(); } }, true, false)); }); do { __loop(); } while (__more); __more = true; }(function __$_qsort() { return function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$_qsort() { __more = false; return function __$_qsort(_) { + return function __$_qsort(_) { var __2 = beg < nend; if (!__2) { return _(null, __2); } return compare(__cb(_, __frame, 19, 0, function ___(__0, __4) { var __3 = __4 < 0; return _(null, __3); }, true, false), o, array[nend]); }(__cb(_, __frame, 0, 0, _, true, false)); }(__cb(_, __frame, 0, 0, function ___(__0, __9) { if (__9) { nend--; while (__more) { __loop(); } __more = true; } else { __break(); } }, true, false)); }); do { __loop(); } while (__more); __more = true; }(function __$_qsort() { + + if (nbeg <= nend) { tmp = array[nbeg]; + + array[nbeg] = array[nend]; + array[nend] = tmp; + nbeg++; + nend--; } while (__more) { __loop(); } __more = true; }); }); } else { __break(); } }); do { __loop(); } while (__more); __more = true; }(function __$_qsort() { + + + + return function __$_qsort(__then) { if (nbeg < end) { return _qsort(__cb(_, __frame, 30, 0, __then, true, false), nbeg, end); } else { __then(); } }(function __$_qsort() { + return function __$_qsort(__then) { if (beg < nend) { return _qsort(__cb(_, __frame, 31, 0, __then, true, false), beg, nend); } else { __then(); } }(_); }); }); }); }); } var __frame = { name: 'value__8', line: 308 }; return __func(_, this, arguments, value__8, 0, __frame, function __$value__8() { array = __this; beg = beg || 0; end = end == null ? array.length - 1 : end; + + return _qsort(__cb(_, __frame, 38, 0, function __$value__8() { + return _(null, array); }, true, false), beg, end); }); } }); + + + + + + + + + + + + delete Function.prototype.apply_; + Object.defineProperty(Function.prototype, 'apply_', { configurable: true, writable: true, enumerable: false, value: function (callback, thisObj, args, index) { + + + + + args = Array.prototype.slice.call(args, 0); + args.splice(index != null && index >= 0 ? index : args.length, 0, callback); + return this.apply(thisObj, args); } }); }(typeof exports !== 'undefined' ? exports : Streamline.builtins = Streamline.builtins || {})); \ No newline at end of file diff --git a/lib/callbacks/compile.js b/lib/callbacks/compile.js index ba3f88f8..8046d1b5 100644 --- a/lib/callbacks/compile.js +++ b/lib/callbacks/compile.js @@ -1,423 +1,423 @@ -/*** Generated by streamline 0.10.17 (callbacks) - DO NOT EDIT ***/ "use strict"; var __rt=require('../callbacks/runtime').runtime(__filename, false),__func=__rt.__func,__cb=__rt.__cb,__catch=__rt.__catch,__tryCatch=__rt.__tryCatch; var fs = require("fs"); - - - - - - - - -var fspath = require("path"); -var compileSync = require("../compiler/compileSync"); - -var _exists = __rt.streamlinify(function(cb, fname) { - fs.exists(fname, function(result) { - cb(null, result); }); - -}, 0); - -function mtime(_, fname) { var __frame = { name: "mtime", line: 19 }; return __func(_, this, arguments, mtime, 0, __frame, function __$mtime() { return (function __$mtime(_) { - return _exists(__cb(_, __frame, 1, 8, function ___(__0, __1) { var __2 = __1; return (function __$mtime(__then) { if (__2) { return fs.stat(fname, __cb(_, __frame, 1, 31, function ___(__0, __4) { var __3 = __4.mtime; return _(null, __3); }, true)); } else { __then(); } ; })(function __$mtime() { return _(null, 0); }); }, true), fname); })(__cb(_, __frame, -18, 6, _, true)); });}; - - -var _0755 = parseInt("0755", 8); - -function _getTransform(options) { - - var req = require; - if (options.generators) { - if (options.fast) { return req("../generators-fast/transform"); } else { - return req("../generators/transform") }; } - else if (options.fibers) { - if (options.fast) { return req("../fibers-fast/transform"); } else { - return req("../fibers/transform") }; } - else { - return require("../callbacks/transform"); } ;}; - - - -function _banner(version, options) { - - var optStr = (options.oldStyleFutures ? " --old-style-futures" : ""); - if (options.promise) { optStr += (" --promise-" + options.promise); }; - if (options.standalone) { optStr += " --standalone"; }; - if (options.aggressive) { optStr += " --aggressive"; }; - return ((("/*** Generated by streamline " + version) + optStr) + " - DO NOT EDIT ***/");}; - - -function _extend(obj, other) { - for (var i in other) { - obj[i] = other[i]; }; - - return obj;}; - - -function _transform(transform, source, options) { - options.source = source; - options.callback = (options.callback || "_"); - options.lines = (options.lines || "preserve"); - return transform.transform(source, options);}; - - -function parseShebang(content) { - if (((content[0] === "#") && (content[1] === "!"))) { - var n = content.indexOf("\n"); - var le = "\n"; - if ((n != -1)) { - var shebang = content.substr(0, n); - if ((shebang[(shebang.length - 1)] == "\r")) { - le = "\r\n"; - shebang = shebang.substr(0, (shebang.length - 1)); } ; - - content = content.substr((n + 1)); - return [shebang,content,le,]; } ; } ; - - - return ["",content,"",];}; - - -function mkdirp(_, path) { var __frame = { name: "mkdirp", line: 79 }; return __func(_, this, arguments, mkdirp, 0, __frame, function __$mkdirp() { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$mkdirp() { - - return fs.mkdir(path, _0755, __cb(_, __frame, 2, 5, __then, true)); }); })(function ___(err, __result) { __catch(function __$mkdirp() { if (err) { return (function __$mkdirp(__then) { - - if ((err.code == "EEXIST")) { - return fs.stat(path, __cb(_, __frame, 5, 10, function ___(__0, __2) { var __1 = __2.isDirectory(); return (function __$mkdirp(__then) { if (__1) { return _(null); } else { __then(); } ; })(function __$mkdirp() { - - - return _(err); }); }, true)); } else { __then(); } ; })(function __$mkdirp() { return (function __$mkdirp(__then) { - - if ((err.code == "ENOENT")) { - return mkdirp(__cb(_, __frame, 11, 3, function __$mkdirp() { - return fs.mkdir(path, _0755, __cb(_, __frame, 12, 6, function __$mkdirp() { return _(null); }, true)); }, true), fspath.join(path, "..")); } else { __then(); } ; })(function __$mkdirp() { - - - return _(err); }); }); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$mkdirp() { _(); }); }); });}; - - - -function outputFile(_, inFile, options) { var dirname, outDir, stripped; var __frame = { name: "outputFile", line: 98 }; return __func(_, this, arguments, outputFile, 0, __frame, function __$outputFile() { - dirname = fspath.dirname(inFile); - - if (options.outputDir) { - if (options.baseDir) { - outDir = fspath.join(options.outputDir, fspath.relative(options.baseDir, dirname)); } - else { - outDir = options.outputDir; } ; } - - else { - outDir = dirname; } ; - - return mkdirp(__cb(_, __frame, 12, 1, function __$outputFile() { - stripped = fspath.basename(inFile, fspath.extname(inFile)); - return _(null, fspath.join(outDir, (stripped + ".js"))); }, true), outDir); });}; - - -function fixSourceMap(sourceMap) { - var keys = { }; - sourceMap._mappings._array = sourceMap._mappings._array.filter(function(mapping) { - if (!mapping.originalLine) { return false }; - var key = ((mapping.originalLine + "/") + mapping.originalColumn); - if (keys[key]) { return false }; - keys[key] = true; - return true; });}; - - - - -exports.compileFile = function exports_compileFile__1(_, path, options) { var ext, language, basename, relpath, dstName, dirname, mtimeSrc, mtimeDst, transform, banner, content, shebangparse, shebang, le, coffee, transformed, sourceMap, mapFile, mapPath; var __frame = { name: "exports_compileFile__1", line: 127 }; return __func(_, this, arguments, exports_compileFile__1, 0, __frame, function __$exports_compileFile__1() { - options = _extend({ }, (options || { })); - ext = fspath.extname(path); - language = ext.substring(2); - basename = fspath.basename(path, ext); - relpath = fspath.relative(".", path); - return outputFile(__cb(_, __frame, 6, 15, function ___(__0, __2) { dstName = __2; - dirname = fspath.dirname(dstName); - - return mtime(__cb(_, __frame, 9, 16, function ___(__0, __3) { mtimeSrc = __3; - return mtime(__cb(_, __frame, 10, 16, function ___(__0, __4) { mtimeDst = __4; - transform = _getTransform(options); - - banner = _banner(transform.version, options); - options.sourceName = relpath; - return fs.readFile(path, "utf8", __cb(_, __frame, 15, 18, function ___(__0, __5) { content = __5; - shebangparse = parseShebang(content); - shebang = shebangparse[0]; - le = shebangparse[2]; - content = shebangparse[1]; - - if ((language === "coffee")) { - coffee = require("../util/require")("coffee-script"); - if (options.sourceMap) { - content = coffee.compile(content, { - filename: relpath, - sourceFiles: [relpath,], - sourceMap: 1 }); - - options.prevMap = new (require("source-map").SourceMapConsumer)(content.v3SourceMap); - content = content.js; } - else { - content = coffee.compile(content, { - filename: path }); } ; } ; - - - - - if (options.sourceMap) { - options.lines = "sourcemap"; } ; - - - banner = ((shebang + le) + banner); return (function __$exports_compileFile__1(_) { - var __1 = mtimeDst; if (!__1) { return _(null, __1); } ; return fs.readFile(dstName, "utf8", __cb(_, __frame, 43, 34, _, true)); })(__cb(_, __frame, -126, 6, function ___(__0, __6) { transformed = __6; - if ((((transformed && (mtimeSrc < mtimeDst)) && (transformed.substring(0, banner.length) == banner)) && !options.force)) { - return _(null, transformed); } ; - - if (options.verbose) { - console.log(("streamline: creating: " + dstName)); } ; - - transformed = _transform(transform, content, options); - - mapFile = (options.sourceMapFile || fspath.join(dirname, (basename + ".map"))); - if ((typeof transformed == "string")) { - transformed = (banner + transformed); - if (options.prevMap) { - transformed += (("\n//# sourceMappingURL=" + ((options.sourceMapFile || ((basename + ".map"))))) + "\n"); - sourceMap = require("source-map").SourceMapGenerator.fromSourceMap(options.prevMap); - options.prevMap = null; } ; } - - else { - transformed.prepend(banner); - if (options.sourceMap) { - transformed.add((("\n//# sourceMappingURL=" + ((options.sourceMapFile || ((basename + ".map"))))) + "\n")); - mapPath = fspath.dirname(mapFile); - sourceMap = transformed.toStringWithSourceMap({ - file: fspath.relative(mapPath, dstName), - sourceRoot: fspath.relative(mapPath, ".") }); - - transformed = sourceMap.code; - sourceMap = sourceMap.map; - fixSourceMap(sourceMap); } ; } ; return (function __$exports_compileFile__1(__then) { - - - if (options.noWrite) { - return _(null, { - transformed: transformed, - sourceMap: sourceMap }); } else { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$exports_compileFile__1() { - - - - - - return fs.writeFile(dstName, transformed, "utf8", __cb(_, __frame, 83, 6, __then, true)); }); })(function ___(ex, __result) { __catch(function __$exports_compileFile__1() { if (ex) { __then(); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$exports_compileFile__1() { return (function __$exports_compileFile__1(__then) { - - if (options.sourceMap) { - if (options.prevMap) { - sourceMap.applySourceMap(options.prevMap, options.sourceName); } ; return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$exports_compileFile__1() { - - - if (options.verbose) { console.log(("streamline: creating: " + mapFile)); } ; - return fs.writeFile(mapFile, sourceMap.toString(), "utf8", __cb(_, __frame, 91, 7, __then, true)); }); })(function ___(ex, __result) { __catch(function __$exports_compileFile__1() { if (ex) { __then(); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, __then); }); } else { __then(); } ; })(__then); }); }); } ; })(_); }, true)); }, true)); }, true), dstName); }, true), path); }, true), path, options); });}; - - - - - - - - - - -exports.loadFile = function exports_loadFile__2(_, path, options) { var ext, basename, dirname, js, transform, banner, content, shebangparse, shebang, le, matches; var __frame = { name: "exports_loadFile__2", line: 229 }; return __func(_, this, arguments, exports_loadFile__2, 0, __frame, function __$exports_loadFile__2() { - options = _extend({ }, (options || { })); - - ext = fspath.extname(path); return (function __$exports_loadFile__2(__then) { - if (((ext !== ".js") && (ext !== "._js"))) { - - return _exists(__cb(_, __frame, 6, 6, function ___(__0, __1) { return (function __$exports_loadFile__2(__then) { if (__1) { path = (path + (ext = "._js")); __then(); } else { - return _exists(__cb(_, __frame, 7, 11, function ___(__0, __2) { return (function __$exports_loadFile__2(__then) { if (__2) { path = (path + (ext = ".js")); __then(); } else { return _(null); } ; })(__then); }, true), (path + ".js")); } ; })(__then); }, true), (path + "._js")); } else { __then(); } ; })(function __$exports_loadFile__2() { - - - basename = fspath.basename(path, ext); - dirname = fspath.dirname(path); - - js = (((dirname + "/") + basename) + ext); - options.lines = (options.lines || "preserve"); - - transform = _getTransform(options); - banner = _banner(transform.version, options); - options.sourceName = js; - return fs.readFile(js, "utf8", __cb(_, __frame, 19, 18, function ___(__0, __3) { content = __3; - shebangparse = parseShebang(content); - shebang = shebangparse[0]; - le = shebangparse[2]; - content = shebangparse[1]; - - banner = ((shebang + le) + banner); return (function __$exports_loadFile__2(__then) { - - if ((ext === "._js")) { - return cachedTransform(__cb(_, __frame, 28, 9, _, true), content, path, transform, banner, options); } else { - - return _(null, content); } ; })(_); }, true)); }); });}; - - - -exports.transformModule = compileSync.transformModule; - -function cacheRoot(options) { - if (options.cacheDir) { return options.cacheDir }; - if (((process.env.HOME === undefined) && (process.env.HOMEDRIVE === undefined))) { throw new Error("HOME not found, unable to store Streamline callback cache") }; - return (((process.env.HOME || ((process.env.HOMEDRIVE + process.env.HOMEPATH)).replace(/\\/g, "/"))) + "/.streamline");}; - - -var dirMode = parseInt("777", 8); - -function mkdirs(_, path) { var p, i, segs, seg; var __frame = { name: "mkdirs", line: 273 }; return __func(_, this, arguments, mkdirs, 0, __frame, function __$mkdirs() { - p = ""; - i = 0; - segs = path.split("/").slice(0, -1); return (function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$mkdirs() { __more = false; - var __3 = (i < segs.length); if (__3) { - seg = segs[i]; - p += (((i++ ? "/" : "")) + seg); - return _exists(__cb(_, __frame, 7, 7, function ___(__0, __2) { var __1 = !__2; return (function __$mkdirs(__then) { if (__1) { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$mkdirs() { - - return fs.mkdir(p, dirMode, __cb(_, __frame, 9, 7, __then, true)); }); })(function ___(err, __result) { __catch(function __$mkdirs() { if (err) { - - if (((i > 1) && (err.code !== "EEXIST"))) { - return _(err); } ; __then(); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, __then); }); } else { __then(); } ; })(function __$mkdirs() { while (__more) { __loop(); }; __more = true; }); }, true), p); } else { __break(); } ; }); do { __loop(); } while (__more); __more = true; })(_); });}; - - - - - - -function subdir(options) { - var d = (options.generators ? "generators" : (options.fibers ? "fibers" : "callbacks")); - if (options.fast) { d += "-fast"; }; - if (options.aggressive) { d += "-aggressive"; }; - return d;}; - - -function cachedTransform(_, content, path, transform, banner, options) { var i, dir, f, transformed; var __frame = { name: "cachedTransform", line: 299 }; return __func(_, this, arguments, cachedTransform, 0, __frame, function __$cachedTransform() { - path = path.replace(/\\/g, "/"); return (function __$cachedTransform(__then) { - if (options.cache) { - i = path.indexOf("node_modules/"); - if ((i < 0)) { i = path.lastIndexOf("/"); } else { - i += "node_modules".length; } ; - - dir = ((cacheRoot(options) + "/") + subdir(options)); - dir += ("/" + path.substring(0, i).replace(/[\/\:]/g, "__")); - f = (dir + path.substring(i)); - return mkdirs(__cb(_, __frame, 10, 2, function __$cachedTransform() { - - return mtime(__cb(_, __frame, 12, 6, function ___(__0, __2) { return mtime(__cb(_, __frame, 12, 20, function ___(__0, __3) { var __1 = (__2 > __3); return (function __$cachedTransform(__then) { if (__1) { - return fs.readFile(f, "utf8", __cb(_, __frame, 13, 20, function ___(__0, __4) { transformed = __4; - if ((transformed.substring(0, banner.length) === banner)) { return _(null, transformed); } ; __then(); }, true)); } else { __then(); } ; })(__then); }, true), path); }, true), f); }, true), f); } else { __then(); } ; })(function __$cachedTransform() { - - - - if (options.verbose) { console.log(("streamline: transforming: " + path)); } ; - options.lines = (options.lines || "sourcemap"); - transformed = (banner + _transform(transform, content, options)); return (function __$cachedTransform(__then) { - if ((options.cache && (path.indexOf("/tmp--") < 0))) { return fs.writeFile(f, transformed, "utf8", __cb(_, __frame, 21, 53, __then, true)); } else { __then(); } ; })(function __$cachedTransform() { - return _(null, transformed); }); }); });}; - - -exports.cachedTransformSync = compileSync.cachedTransformSync; - -function compileCoffee(_, path, options) { var jsPath, mapPath, outDir, coffeeOpts, source, coffee, compiled, js; var __frame = { name: "compileCoffee", line: 326 }; return __func(_, this, arguments, compileCoffee, 0, __frame, function __$compileCoffee() { - return outputFile(__cb(_, __frame, 1, 14, function ___(__0, __2) { jsPath = __2; - mapPath = jsPath.replace(/\.js$/, ".map"); - outDir = fspath.dirname(jsPath); - coffeeOpts = { - filename: path, - sourceMap: options.sourceMap, - jsPath: jsPath, - sourceRoot: fspath.relative(outDir, "."), - sourceFiles: [fspath.relative(".", path),], - generatedFile: fspath.basename(jsPath) }; return (function __$compileCoffee(_) { - - var __1 = options.force; if (__1) { return _(null, __1); } ; return mtime(__cb(_, __frame, 12, 22, function ___(__0, __3) { return mtime(__cb(_, __frame, 12, 39, function ___(__0, __4) { var __2 = (__3 > __4); return _(null, __2); }, true), jsPath); }, true), path); })(__cb(_, __frame, -325, 6, function ___(__0, __3) { return (function __$compileCoffee(__then) { if (__3) { - return fs.readFile(path, "utf8", __cb(_, __frame, 13, 18, function ___(__0, __4) { source = __4; - coffee = require("../util/require")("coffee-script"); - compiled = coffee.compile(source, coffeeOpts); - if (options.verbose) { console.log(((("streamline: coffee compiling: " + path) + " to ") + jsPath)); } ; - - if (options.sourceMap) { - js = (((compiled.js + "\n//# sourceMappingURL=") + fspath.basename(mapPath)) + "\n"); } - else { - js = compiled; } ; return (function __$compileCoffee(__then) { - - if (options.noWrite) { - return _(null, { - transformed: js, - sourceMap: compiled.v3SourceMap }); } else { - - - - return fs.writeFile(jsPath, js, "utf8", __cb(_, __frame, 30, 6, function __$compileCoffee() { return (function __$compileCoffee(__then) { - if (options.sourceMap) { - return fs.writeFile(mapPath, compiled.v3SourceMap, "utf8", __cb(_, __frame, 32, 7, __then, true)); } else { __then(); } ; })(__then); }, true)); } ; })(__then); }, true)); } else { __then(); } ; })(_); }, true)); }, true), path, options); });}; - - - - - - -function _getCompiler(path) { - var ext = fspath.extname(path); - if (((ext === "._js") || (ext === "._coffee"))) { - return exports.compileFile; } - else if (((ext === ".coffee") && (path[((path.length - ext.length) - 1)] !== "_"))) { - return compileCoffee; } - else { } ;}; - - - - - - -exports.transform = function exports_transform__3(_, path, options) { var compiler; var __frame = { name: "exports_transform__3", line: 378 }; return __func(_, this, arguments, exports_transform__3, 0, __frame, function __$exports_transform__3() { - options = _extend({ - noWrite: true - }, (options || { })); - compiler = _getCompiler(path); return (function __$exports_transform__3(__then) { - if (compiler) { return compiler(__cb(_, __frame, 5, 15, __then, true), path, options); } else { __then(); } ; })(_); });}; - - - - - - - - -exports.compile = function exports_compile__4(_, paths, options) { var failed, transform, cwd; - function _compile(_, path, base, options) { var stat, compiler; var __frame = { name: "_compile", line: 393 }; return __func(_, this, arguments, _compile, 0, __frame, function __$_compile() { - return fs.stat(path, __cb(_, __frame, 1, 16, function ___(__0, __2) { stat = __2; return (function __$_compile(__then) { - if (stat.isDirectory()) { - base = (base || path); - return fs.readdir(path, __cb(_, __frame, 4, 6, function ___(__0, __3) { return __3.forEach_(__cb(_, __frame, 4, 24, __then, true), function __1(_, f) { var __frame = { name: "__1", line: 397 }; return __func(_, this, arguments, __1, 0, __frame, function __$__1() { - return _compile(__cb(_, __frame, 1, 4, function __$__1() { _(); }, true), ((path + "/") + f), base, options); }); }); }, true)); } else { return (function __$_compile(__then) { - - if (stat.isFile()) { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$_compile() { - - base = (base || fspath.dirname(path)); - options.baseDir = base; - compiler = _getCompiler(path); return (function __$_compile(__then) { - if (compiler) { return compiler(__cb(_, __frame, 12, 18, __then, true), path, options); } else { __then(); } ; })(__then); }); })(function ___(ex, __result) { __catch(function __$_compile() { if (ex) { - - console.error(ex.stack); - failed++; __then(); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, __then); }); } else { __then(); } ; })(__then); } ; })(_); }, true)); }); }; var __frame = { name: "exports_compile__4", line: 392 }; return __func(_, this, arguments, exports_compile__4, 0, __frame, function __$exports_compile__4() { - - - - - - failed = 0; - options = (options || { }); - transform = _getTransform(options); - if (options.verbose) { console.log(("transform version: " + transform.version)); } ; - if ((!paths || (paths.length == 0))) { return _(new Error("cannot compile: no files specified")); } ; - cwd = process.cwd(); - return paths.forEach_(__cb(_, __frame, 28, 7, function __$exports_compile__4() { - - - if (failed) { return _(new Error((("errors found in " + failed) + " files"))); } ; _(); }, true), function __1(_, path) { var __frame = { name: "__1", line: 420 }; return __func(_, this, arguments, __1, 0, __frame, function __$__1() { return _compile(__cb(_, __frame, 1, 2, function __$__1() { _(); }, true), fspath.resolve(cwd, path), null, options); }); }); });}; +/*** Generated by streamline 0.10.17 (callbacks) - DO NOT EDIT ***/ "use strict"; var __rt=require('../callbacks/runtime').runtime(__filename, false),__func=__rt.__func,__cb=__rt.__cb,__catch=__rt.__catch,__tryCatch=__rt.__tryCatch; + + + + + + + + var fs = require('fs'); + var fspath = require('path'); + var compileSync = require('../compiler/compileSync'); + + var _exists = __rt.streamlinify(function (cb, fname) { + fs.exists(fname, function (result) { + cb(null, result); }); }, 0); + + + + function mtime(_, fname) { var __frame = { name: 'mtime', line: 19 }; return __func(_, this, arguments, mtime, 0, __frame, function __$mtime() { + return function __$mtime(_) { return _exists(__cb(_, __frame, 1, 0, function ___(__0, __2) { var __1 = __2; return function __$mtime(__then) { if (__1) { return fs.stat(fname, __cb(_, __frame, 1, 0, function ___(__0, __4) { var __3 = __4.mtime; return _(null, __3); }, true, false)); } else { __then(); } }(function __$mtime() { return _(null, 0); }); }, true, false), fname); }(__cb(_, __frame, 0, 0, _, true, false)); }); } + + + var _0755 = parseInt('0755', 8); + + function _getTransform(options) { + + var req = require; + if (options.generators) { + if (options.fast) return req('../generators-fast/transform'); else return req('../generators/transform'); } else if (options.fibers) { + + + if (options.fast) return req('../fibers-fast/transform'); else return req('../fibers/transform'); } else { + + + return require('../callbacks/transform'); } } + + + + function _banner(version, options) { + + var optStr = options.oldStyleFutures ? ' --old-style-futures' : ''; + if (options.promise) optStr += ' --promise-' + options.promise; + if (options.standalone) optStr += ' --standalone'; + if (options.aggressive) optStr += ' --aggressive'; + return '/*** Generated by streamline ' + version + optStr + ' - DO NOT EDIT ***/'; } + + + function _extend(obj, other) { + for (var i in other) { + obj[i] = other[i]; } + + return obj; } + + + function _transform(transform, source, options) { + options.source = source; + options.callback = options.callback || '_'; + options.lines = options.lines || 'preserve'; + return transform.transform(source, options); } + + + function parseShebang(content) { + if (content[0] === '#' && content[1] === '!') { + var n = content.indexOf('\n'); + var le = '\n'; + if (n != -1) { + var shebang = content.substr(0, n); + if (shebang[shebang.length - 1] == '\r') { + le = '\r\n'; + shebang = shebang.substr(0, shebang.length - 1); } + + content = content.substr(n + 1); + return [ shebang, content, le ]; } } + + + return [ '', content, '' ]; } + + + function mkdirp(_, path) { var __frame = { name: 'mkdirp', line: 79 }; return __func(_, this, arguments, mkdirp, 0, __frame, function __$mkdirp() { + return function ___(__then) { (function ___(_) { __tryCatch(_, function __$mkdirp() { + return fs.mkdir(path, _0755, __cb(_, __frame, 2, 0, __then, true, false)); }); }(function ___(err, __result) { + __catch(function __$mkdirp() { if (err) { + return function __$mkdirp(__then) { if (err.code == 'EEXIST') { + return fs.stat(path, __cb(_, __frame, 5, 0, function ___(__0, __2) { var __1 = __2.isDirectory(); return function __$mkdirp(__then) { if (__1) { + return _(null); } else { __then(); } }(function __$mkdirp() { + + return _(err); }); }, true, false)); } else { __then(); } }(function __$mkdirp() { + + return function __$mkdirp(__then) { if (err.code == 'ENOENT') { + return mkdirp(__cb(_, __frame, 11, 0, function __$mkdirp() { + return fs.mkdir(path, _0755, __cb(_, __frame, 12, 0, function __$mkdirp() { + return _(null); }, true, false)); }, true, false), fspath.join(path, '..')); } else { __then(); } }(function __$mkdirp() { + + return _(err); }); }); } else { _(null, __result); } }, _); })); }(function ___() { __tryCatch(_, function __$mkdirp() { _(); }); }); }); } + + + + function outputFile(_, inFile, options) { var dirname, outDir, stripped; var __frame = { name: 'outputFile', line: 98 }; return __func(_, this, arguments, outputFile, 0, __frame, function __$outputFile() { dirname = fspath.dirname(inFile); + + + if (options.outputDir) { + if (options.baseDir) { + outDir = fspath.join(options.outputDir, fspath.relative(options.baseDir, dirname)); } else { + + outDir = options.outputDir; } } else { + + + outDir = dirname; } + + return mkdirp(__cb(_, __frame, 12, 0, function __$outputFile() { stripped = fspath.basename(inFile, fspath.extname(inFile)); + + return _(null, fspath.join(outDir, stripped + '.js')); }, true, false), outDir); }); } + + + function fixSourceMap(sourceMap) { + var keys = {}; + sourceMap._mappings._array = sourceMap._mappings._array.filter(function (mapping) { + if (!mapping.originalLine) return false; + var key = mapping.originalLine + '/' + mapping.originalColumn; + if (keys[key]) return false; + keys[key] = true; + return true; }); } + + + + + exports.compileFile = function exports_compileFile__1(_, path, options) { var ext, language, basename, relpath, dstName, dirname, mtimeSrc, mtimeDst, transform, banner, content, shebangparse, shebang, le, coffee, transformed, sourceMap, mapFile, mapPath; var __frame = { name: 'exports_compileFile__1', line: 127 }; return __func(_, this, arguments, exports_compileFile__1, 0, __frame, function __$exports_compileFile__1() { + options = _extend({}, options || {}); ext = fspath.extname(path); + language = ext.substring(2); + basename = fspath.basename(path, ext); + relpath = fspath.relative('.', path); + + return outputFile(__cb(_, __frame, 6, 0, function ___(__0, __2) { dstName = __2; dirname = fspath.dirname(dstName); + + + return mtime(__cb(_, __frame, 9, 0, function ___(__0, __3) { mtimeSrc = __3; + return mtime(__cb(_, __frame, 10, 0, function ___(__0, __4) { mtimeDst = __4; transform = _getTransform(options); + banner = _banner(transform.version, options); + + + options.sourceName = relpath; + return fs.readFile(path, 'utf8', __cb(_, __frame, 15, 0, function ___(__0, __5) { content = __5; shebangparse = parseShebang(content); + shebang = shebangparse[0]; + le = shebangparse[2]; + + content = shebangparse[1]; + + if (language === 'coffee') { coffee = require('../util/require')('coffee-script'); + + if (options.sourceMap) { + content = coffee.compile(content, { filename: relpath, sourceFiles: [relpath], sourceMap: 1 }); + + + + + options.prevMap = new (require('source-map')).SourceMapConsumer(content.v3SourceMap); + content = content.js; } else { + + content = coffee.compile(content, { filename: path }); } } + + + + + + if (options.sourceMap) { + options.lines = 'sourcemap'; } + + + banner = shebang + le + banner; + return function __$exports_compileFile__1(_) { var __1 = mtimeDst; if (!__1) { return _(null, __1); } return fs.readFile(dstName, 'utf8', __cb(_, __frame, 43, 0, _, true, false)); }(__cb(_, __frame, 0, 0, function ___(__0, __6) { transformed = __6; + if (transformed && mtimeSrc < mtimeDst && transformed.substring(0, banner.length) == banner && !options.force) { + return _(null, transformed); } + + if (options.verbose) { + console.log('streamline: creating: ' + dstName); } transformed = _transform(transform, content, options); + + mapFile = options.sourceMapFile || fspath.join(dirname, basename + '.map'); + + + if (typeof transformed == 'string') { + transformed = banner + transformed; + if (options.prevMap) { + transformed += '\n//# sourceMappingURL=' + (options.sourceMapFile || basename + '.map') + '\n'; + sourceMap = require('source-map').SourceMapGenerator.fromSourceMap(options.prevMap); + options.prevMap = null; } } else { + + + transformed.prepend(banner); + if (options.sourceMap) { + transformed.add('\n//# sourceMappingURL=' + (options.sourceMapFile || basename + '.map') + '\n'); mapPath = fspath.dirname(mapFile); + + sourceMap = transformed.toStringWithSourceMap({ file: fspath.relative(mapPath, dstName), sourceRoot: fspath.relative(mapPath, '.') }); + + + + transformed = sourceMap.code; + sourceMap = sourceMap.map; + fixSourceMap(sourceMap); } } + + + return function __$exports_compileFile__1(__then) { if (options.noWrite) { + return _(null, { transformed: transformed, sourceMap: sourceMap }); } else { + + + + + + + return function ___(__then) { (function ___(_) { __tryCatch(_, function __$exports_compileFile__1() { + return fs.writeFile(dstName, transformed, 'utf8', __cb(_, __frame, 83, 0, __then, true, false)); }); }(function ___(ex, __result) { + __catch(function __$exports_compileFile__1() { if (ex) { __then(); } else { _(null, __result); } }, _); })); }(function ___() { __tryCatch(_, function __$exports_compileFile__1() { + return function __$exports_compileFile__1(__then) { if (options.sourceMap) { + if (options.prevMap) { + sourceMap.applySourceMap(options.prevMap, options.sourceName); } + + return function ___(__then) { (function ___(_) { __tryCatch(_, function __$exports_compileFile__1() { + if (options.verbose) { console.log('streamline: creating: ' + mapFile); } + return fs.writeFile(mapFile, sourceMap.toString(), 'utf8', __cb(_, __frame, 91, 0, __then, true, false)); }); }(function ___(ex, __result) { + __catch(function __$exports_compileFile__1() { if (ex) { __then(); } else { _(null, __result); } }, _); })); }(function ___() { __tryCatch(_, __then); }); } else { __then(); } }(__then); }); }); } }(_); }, true, false)); }, true, false)); }, true, false), dstName); }, true, false), path); }, true, false), path, options); }); }; + + + + + + + + + + exports.loadFile = function exports_loadFile__2(_, path, options) { var ext, basename, dirname, js, transform, banner, content, shebangparse, shebang, le, matches; var __frame = { name: 'exports_loadFile__2', line: 229 }; return __func(_, this, arguments, exports_loadFile__2, 0, __frame, function __$exports_loadFile__2() { + options = _extend({}, options || {}); ext = fspath.extname(path); + + + return function __$exports_loadFile__2(__then) { if (ext !== '.js' && ext !== '._js') { + + return _exists(__cb(_, __frame, 6, 0, function ___(__0, __2) { var __1 = __2; return function __$exports_loadFile__2(__then) { if (__1) { path = path + (ext = '._js'); __then(); } else { + return _exists(__cb(_, __frame, 7, 0, function ___(__0, __4) { var __3 = __4; return function __$exports_loadFile__2(__then) { if (__3) { path = path + (ext = '.js'); __then(); } else { + return _(null); } }(__then); }, true, false), path + '.js'); } }(__then); }, true, false), path + '._js'); } else { __then(); } }(function __$exports_loadFile__2() { basename = fspath.basename(path, ext); + + dirname = fspath.dirname(path); + js = dirname + '/' + basename + ext; + + + options.lines = options.lines || 'preserve'; transform = _getTransform(options); + + banner = _banner(transform.version, options); + + options.sourceName = js; + return fs.readFile(js, 'utf8', __cb(_, __frame, 19, 0, function ___(__0, __5) { content = __5; shebangparse = parseShebang(content); + shebang = shebangparse[0]; + le = shebangparse[2]; + + content = shebangparse[1]; + + banner = shebang + le + banner; + + return function __$exports_loadFile__2(__then) { if (ext === '._js') { + return cachedTransform(__cb(_, __frame, 28, 0, _, true, false), content, path, transform, banner, options); } else { + + return _(null, content); } }(_); }, true, false)); }); }); }; + + + + exports.transformModule = compileSync.transformModule; + + function cacheRoot(options) { + if (options.cacheDir) return options.cacheDir; + if (process.env.HOME === undefined && process.env.HOMEDRIVE === undefined) throw new Error('HOME not found, unable to store Streamline callback cache'); + return (process.env.HOME || (process.env.HOMEDRIVE + process.env.HOMEPATH).replace(/\\/g, '/')) + '/.streamline'; } + + + var dirMode = parseInt('777', 8); + + function mkdirs(_, path) { var p, i, segs, seg; var __frame = { name: 'mkdirs', line: 273 }; return __func(_, this, arguments, mkdirs, 0, __frame, function __$mkdirs() { p = ''; + i = 0; + segs = path.split('/').slice(0, -1); + return function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$mkdirs() { __more = false; var __3 = i < segs.length; + if (__3) { seg = segs[i]; + + p += (i++ ? '/' : '') + seg; + return _exists(__cb(_, __frame, 7, 0, function ___(__0, __2) { var __1 = !__2; return function __$mkdirs(__then) { if (__1) { + return function ___(__then) { (function ___(_) { __tryCatch(_, function __$mkdirs() { + return fs.mkdir(p, dirMode, __cb(_, __frame, 9, 0, __then, true, false)); }); }(function ___(err, __result) { + __catch(function __$mkdirs() { if (err) { + if (i > 1 && err.code !== 'EEXIST') { + return _(err); } __then(); } else { _(null, __result); } }, _); })); }(function ___() { __tryCatch(_, __then); }); } else { __then(); } }(function __$mkdirs() { while (__more) { __loop(); } __more = true; }); }, true, false), p); } else { __break(); } }); do { __loop(); } while (__more); __more = true; }(_); }); } + + + + + + + function subdir(options) { + var d = options.generators ? 'generators' : options.fibers ? 'fibers' : 'callbacks'; + if (options.fast) d += '-fast'; + if (options.aggressive) d += '-aggressive'; + return d; } + + + function cachedTransform(_, content, path, transform, banner, options) { var i, dir, f, transformed; var __frame = { name: 'cachedTransform', line: 299 }; return __func(_, this, arguments, cachedTransform, 0, __frame, function __$cachedTransform() { + path = path.replace(/\\/g, '/'); + return function __$cachedTransform(__then) { if (options.cache) { i = path.indexOf('node_modules/'); + + if (i < 0) { i = path.lastIndexOf('/'); } else { + i += 'node_modules'.length; } dir = cacheRoot(options) + '/' + subdir(options); + + + dir += '/' + path.substring(0, i).replace(/[\/\:]/g, '__'); f = dir + path.substring(i); + + return mkdirs(__cb(_, __frame, 10, 0, function __$cachedTransform() { + + return mtime(__cb(_, __frame, 12, 0, function ___(__0, __2) { return mtime(__cb(_, __frame, 12, 0, function ___(__0, __3) { var __1 = __2 > __3; return function __$cachedTransform(__then) { if (__1) { + return fs.readFile(f, 'utf8', __cb(_, __frame, 13, 0, function ___(__0, __4) { transformed = __4; + if (transformed.substring(0, banner.length) === banner) { return _(null, transformed); } __then(); }, true, false)); } else { __then(); } }(__then); }, true, false), path); }, true, false), f); }, true, false), f); } else { __then(); } }(function __$cachedTransform() { + + + + if (options.verbose) { console.log('streamline: transforming: ' + path); } + options.lines = options.lines || 'sourcemap'; + transformed = banner + _transform(transform, content, options); + return function __$cachedTransform(__then) { if (options.cache && path.indexOf('/tmp--') < 0) { return fs.writeFile(f, transformed, 'utf8', __cb(_, __frame, 21, 0, __then, true, false)); } else { __then(); } }(function __$cachedTransform() { + return _(null, transformed); }); }); }); } + + + exports.cachedTransformSync = compileSync.cachedTransformSync; + + function compileCoffee(_, path, options) { var jsPath, mapPath, outDir, coffeeOpts, source, coffee, compiled, js; var __frame = { name: 'compileCoffee', line: 326 }; return __func(_, this, arguments, compileCoffee, 0, __frame, function __$compileCoffee() { + return outputFile(__cb(_, __frame, 1, 0, function ___(__0, __2) { jsPath = __2; mapPath = jsPath.replace(/\.js$/, '.map'); + outDir = fspath.dirname(jsPath); + coffeeOpts = { filename: path, sourceMap: options.sourceMap, jsPath: jsPath, sourceRoot: fspath.relative(outDir, '.'), sourceFiles: [fspath.relative('.', path)], generatedFile: fspath.basename(jsPath) }; + + + + + + + + + return function __$compileCoffee(_) { var __1 = options.force; if (__1) { return _(null, __1); } return mtime(__cb(_, __frame, 12, 0, function ___(__0, __3) { return mtime(__cb(_, __frame, 12, 0, function ___(__0, __4) { var __2 = __3 > __4; return _(null, __2); }, true, false), jsPath); }, true, false), path); }(__cb(_, __frame, 0, 0, function ___(__0, __4) { var __3 = __4; return function __$compileCoffee(__then) { if (__3) { + return fs.readFile(path, 'utf8', __cb(_, __frame, 13, 0, function ___(__0, __5) { source = __5; coffee = require('../util/require')('coffee-script'); + compiled = coffee.compile(source, coffeeOpts); + + if (options.verbose) { console.log('streamline: coffee compiling: ' + path + ' to ' + jsPath); } + + if (options.sourceMap) { + js = compiled.js + '\n//# sourceMappingURL=' + fspath.basename(mapPath) + '\n'; } else { + + js = compiled; } + + return function __$compileCoffee(__then) { if (options.noWrite) { + return _(null, { transformed: js, sourceMap: compiled.v3SourceMap }); } else { + + + + + + return fs.writeFile(jsPath, js, 'utf8', __cb(_, __frame, 30, 0, function __$compileCoffee() { + return function __$compileCoffee(__then) { if (options.sourceMap) { + return fs.writeFile(mapPath, compiled.v3SourceMap, 'utf8', __cb(_, __frame, 32, 0, __then, true, false)); } else { __then(); } }(__then); }, true, false)); } }(__then); }, true, false)); } else { __then(); } }(_); }, true, false)); }, true, false), path, options); }); } + + + + + + + function _getCompiler(path) { + var ext = fspath.extname(path); + if (ext === '._js' || ext === '._coffee') { + return exports.compileFile; } else if (ext === '.coffee' && path[path.length - ext.length - 1] !== '_') { + + return compileCoffee; } else { } } + + + + + + + + exports.transform = function exports_transform__3(_, path, options) { var compiler; var __frame = { name: 'exports_transform__3', line: 378 }; return __func(_, this, arguments, exports_transform__3, 0, __frame, function __$exports_transform__3() { + options = _extend({ noWrite: true }, options || {}); + + compiler = _getCompiler(path); + + return function __$exports_transform__3(__then) { if (compiler) { return compiler(__cb(_, __frame, 5, 0, __then, true, false), path, options); } else { __then(); } }(_); }); }; + + + + + + + + + exports.compile = function exports_compile__4(_, paths, options) { var failed, transform, cwd; + function _compile(_, path, base, options) { var stat, compiler; var __frame = { name: '_compile', line: 393 }; return __func(_, this, arguments, _compile, 0, __frame, function __$_compile() { + return fs.stat(path, __cb(_, __frame, 1, 0, function ___(__0, __2) { stat = __2; + return function __$_compile(__then) { if (stat.isDirectory()) { + base = base || path; + return fs.readdir(path, __cb(_, __frame, 4, 0, function ___(__0, __3) { return __3.forEach_(__cb(_, __frame, 4, 0, __then, true, false), function __1(_, f) { var __frame = { name: '__1', line: 397 }; return __func(_, this, arguments, __1, 0, __frame, function __$__1() { + return _compile(__cb(_, __frame, 1, 0, function __$__1() { _(); }, true, false), path + '/' + f, base, options); }); }); }, true, false)); } else { + + return function __$_compile(__then) { if (stat.isFile()) { + return function ___(__then) { (function ___(_) { __tryCatch(_, function __$_compile() { + base = base || fspath.dirname(path); + options.baseDir = base; compiler = _getCompiler(path); + + return function __$_compile(__then) { if (compiler) { return compiler(__cb(_, __frame, 12, 0, __then, true, false), path, options); } else { __then(); } }(__then); }); }(function ___(ex, __result) { + __catch(function __$_compile() { if (ex) { + console.error(ex.stack); + failed++; __then(); } else { _(null, __result); } }, _); })); }(function ___() { __tryCatch(_, __then); }); } else { __then(); } }(__then); } }(_); }, true, false)); }); } var __frame = { name: 'exports_compile__4', line: 392 }; return __func(_, this, arguments, exports_compile__4, 0, __frame, function __$exports_compile__4() { failed = 0; + + + + + + + options = options || {}; transform = _getTransform(options); + + if (options.verbose) { console.log('transform version: ' + transform.version); } + if (!paths || paths.length == 0) { return _(new Error('cannot compile: no files specified')); } cwd = process.cwd(); + + return paths.forEach_(__cb(_, __frame, 28, 0, function __$exports_compile__4() { + + + if (failed) { return _(new Error('errors found in ' + failed + ' files')); } _(); }, true, false), function __1(_, path) { var __frame = { name: '__1', line: 420 }; return __func(_, this, arguments, __1, 0, __frame, function __$__1() { return _compile(__cb(_, __frame, 1, 0, function __$__1() { _(); }, true, false), fspath.resolve(cwd, path), null, options); }); }); }); }; diff --git a/lib/callbacks/escodegen-browser.js b/lib/callbacks/escodegen-browser.js new file mode 100644 index 00000000..b248fb78 --- /dev/null +++ b/lib/callbacks/escodegen-browser.js @@ -0,0 +1,3558 @@ +"use strict"; +// template to expose escodegen server side +(function() { + // load utils.code + var modules = {}; + var mod = {}; + (function(module) { + /* + Copyright (C) 2013-2014 Yusuke Suzuki + Copyright (C) 2014 Ivan Nikulin + + 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 HOLDERS AND CONTRIBUTORS "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 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 () { + 'use strict'; + + var Regex, NON_ASCII_WHITESPACES; + + // See `tools/generate-identifier-regex.js`. + Regex = { + NonAsciiIdentifierStart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]'), + NonAsciiIdentifierPart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0\u08A2-\u08AC\u08E4-\u08FE\u0900-\u0963\u0966-\u096F\u0971-\u0977\u0979-\u097F\u0981-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C82\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191C\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1D00-\u1DE6\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA697\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7B\uAA80-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE26\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]') + }; + + function isDecimalDigit(ch) { + return (ch >= 48 && ch <= 57); // 0..9 + } + + function isHexDigit(ch) { + return isDecimalDigit(ch) || // 0..9 + (97 <= ch && ch <= 102) || // a..f + (65 <= ch && ch <= 70); // A..F + } + + function isOctalDigit(ch) { + return (ch >= 48 && ch <= 55); // 0..7 + } + + // 7.2 White Space + + NON_ASCII_WHITESPACES = [ + 0x1680, 0x180E, + 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, + 0x202F, 0x205F, + 0x3000, + 0xFEFF + ]; + + function isWhiteSpace(ch) { + return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) || + (ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0); + } + + // 7.3 Line Terminators + + function isLineTerminator(ch) { + return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029); + } + + // 7.6 Identifier Names and Identifiers + + function isIdentifierStart(ch) { + return (ch >= 97 && ch <= 122) || // a..z + (ch >= 65 && ch <= 90) || // A..Z + (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) + (ch === 92) || // \ (backslash) + ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))); + } + + function isIdentifierPart(ch) { + return (ch >= 97 && ch <= 122) || // a..z + (ch >= 65 && ch <= 90) || // A..Z + (ch >= 48 && ch <= 57) || // 0..9 + (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) + (ch === 92) || // \ (backslash) + ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))); + } + + module.exports = { + isDecimalDigit: isDecimalDigit, + isHexDigit: isHexDigit, + isOctalDigit: isOctalDigit, + isWhiteSpace: isWhiteSpace, + isLineTerminator: isLineTerminator, + isIdentifierStart: isIdentifierStart, + isIdentifierPart: isIdentifierPart + }; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ + + })(mod); + modules.esutils = { + code: mod.exports, + }; + + // load estraverse + (function(exports) { + /* + Copyright (C) 2012-2013 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat + + 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 HOLDERS AND CONTRIBUTORS "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 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. +*/ +/*jslint vars:false, bitwise:true*/ +/*jshint indent:4*/ +/*global exports:true, define:true*/ +(function (root, factory) { + 'use strict'; + + // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, + // and plain browser loading, + if (typeof define === 'function' && define.amd) { + define(['exports'], factory); + } else if (typeof exports !== 'undefined') { + factory(exports); + } else { + factory((root.estraverse = {})); + } +}(this, function clone(exports) { + 'use strict'; + + var Syntax, + isArray, + VisitorOption, + VisitorKeys, + objectCreate, + objectKeys, + BREAK, + SKIP, + REMOVE; + + function ignoreJSHintError() { } + + isArray = Array.isArray; + if (!isArray) { + isArray = function isArray(array) { + return Object.prototype.toString.call(array) === '[object Array]'; + }; + } + + function deepCopy(obj) { + var ret = {}, key, val; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + val = obj[key]; + if (typeof val === 'object' && val !== null) { + ret[key] = deepCopy(val); + } else { + ret[key] = val; + } + } + } + return ret; + } + + function shallowCopy(obj) { + var ret = {}, key; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + ignoreJSHintError(shallowCopy); + + // based on LLVM libc++ upper_bound / lower_bound + // MIT License + + function upperBound(array, func) { + var diff, len, i, current; + + len = array.length; + i = 0; + + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + len = diff; + } else { + i = current + 1; + len -= diff + 1; + } + } + return i; + } + + function lowerBound(array, func) { + var diff, len, i, current; + + len = array.length; + i = 0; + + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + i = current + 1; + len -= diff + 1; + } else { + len = diff; + } + } + return i; + } + ignoreJSHintError(lowerBound); + + objectCreate = Object.create || (function () { + function F() { } + + return function (o) { + F.prototype = o; + return new F(); + }; + })(); + + objectKeys = Object.keys || function (o) { + var keys = [], key; + for (key in o) { + keys.push(key); + } + return keys; + }; + + function extend(to, from) { + objectKeys(from).forEach(function (key) { + to[key] = from[key]; + }); + return to; + } + + Syntax = { + AssignmentExpression: 'AssignmentExpression', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7. + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7. + ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7. + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DebuggerStatement: 'DebuggerStatement', + DirectiveStatement: 'DirectiveStatement', + DoWhileStatement: 'DoWhileStatement', + EmptyStatement: 'EmptyStatement', + ExportBatchSpecifier: 'ExportBatchSpecifier', + ExportDeclaration: 'ExportDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + ForOfStatement: 'ForOfStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7. + Identifier: 'Identifier', + IfStatement: 'IfStatement', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MethodDefinition: 'MethodDefinition', + ModuleSpecifier: 'ModuleSpecifier', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + Program: 'Program', + Property: 'Property', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; + + VisitorKeys = { + AssignmentExpression: ['left', 'right'], + ArrayExpression: ['elements'], + ArrayPattern: ['elements'], + ArrowFunctionExpression: ['params', 'defaults', 'rest', 'body'], + AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7. + BlockStatement: ['body'], + BinaryExpression: ['left', 'right'], + BreakStatement: ['label'], + CallExpression: ['callee', 'arguments'], + CatchClause: ['param', 'body'], + ClassBody: ['body'], + ClassDeclaration: ['id', 'body', 'superClass'], + ClassExpression: ['id', 'body', 'superClass'], + ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7. + ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + ConditionalExpression: ['test', 'consequent', 'alternate'], + ContinueStatement: ['label'], + DebuggerStatement: [], + DirectiveStatement: [], + DoWhileStatement: ['body', 'test'], + EmptyStatement: [], + ExportBatchSpecifier: [], + ExportDeclaration: ['declaration', 'specifiers', 'source'], + ExportSpecifier: ['id', 'name'], + ExpressionStatement: ['expression'], + ForStatement: ['init', 'test', 'update', 'body'], + ForInStatement: ['left', 'right', 'body'], + ForOfStatement: ['left', 'right', 'body'], + FunctionDeclaration: ['id', 'params', 'defaults', 'rest', 'body'], + FunctionExpression: ['id', 'params', 'defaults', 'rest', 'body'], + GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + Identifier: [], + IfStatement: ['test', 'consequent', 'alternate'], + ImportDeclaration: ['specifiers', 'source'], + ImportDefaultSpecifier: ['id'], + ImportNamespaceSpecifier: ['id'], + ImportSpecifier: ['id', 'name'], + Literal: [], + LabeledStatement: ['label', 'body'], + LogicalExpression: ['left', 'right'], + MemberExpression: ['object', 'property'], + MethodDefinition: ['key', 'value'], + ModuleSpecifier: [], + NewExpression: ['callee', 'arguments'], + ObjectExpression: ['properties'], + ObjectPattern: ['properties'], + Program: ['body'], + Property: ['key', 'value'], + ReturnStatement: ['argument'], + SequenceExpression: ['expressions'], + SpreadElement: ['argument'], + SwitchStatement: ['discriminant', 'cases'], + SwitchCase: ['test', 'consequent'], + TaggedTemplateExpression: ['tag', 'quasi'], + TemplateElement: [], + TemplateLiteral: ['quasis', 'expressions'], + ThisExpression: [], + ThrowStatement: ['argument'], + TryStatement: ['block', 'handlers', 'handler', 'guardedHandlers', 'finalizer'], + UnaryExpression: ['argument'], + UpdateExpression: ['argument'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + WhileStatement: ['test', 'body'], + WithStatement: ['object', 'body'], + YieldExpression: ['argument'] + }; + + // unique id + BREAK = {}; + SKIP = {}; + REMOVE = {}; + + VisitorOption = { + Break: BREAK, + Skip: SKIP, + Remove: REMOVE + }; + + function Reference(parent, key) { + this.parent = parent; + this.key = key; + } + + Reference.prototype.replace = function replace(node) { + this.parent[this.key] = node; + }; + + Reference.prototype.remove = function remove() { + if (isArray(this.parent)) { + this.parent.splice(this.key, 1); + return true; + } else { + this.replace(null); + return false; + } + }; + + function Element(node, path, wrap, ref) { + this.node = node; + this.path = path; + this.wrap = wrap; + this.ref = ref; + } + + function Controller() { } + + // API: + // return property path array from root to current node + Controller.prototype.path = function path() { + var i, iz, j, jz, result, element; + + function addToPath(result, path) { + if (isArray(path)) { + for (j = 0, jz = path.length; j < jz; ++j) { + result.push(path[j]); + } + } else { + result.push(path); + } + } + + // root node + if (!this.__current.path) { + return null; + } + + // first node is sentinel, second node is root element + result = []; + for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { + element = this.__leavelist[i]; + addToPath(result, element.path); + } + addToPath(result, this.__current.path); + return result; + }; + + // API: + // return type of current node + Controller.prototype.type = function () { + var node = this.current(); + return node.type || this.__current.wrap; + }; + + // API: + // return array of parent elements + Controller.prototype.parents = function parents() { + var i, iz, result; + + // first node is sentinel + result = []; + for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { + result.push(this.__leavelist[i].node); + } + + return result; + }; + + // API: + // return current node + Controller.prototype.current = function current() { + return this.__current.node; + }; + + Controller.prototype.__execute = function __execute(callback, element) { + var previous, result; + + result = undefined; + + previous = this.__current; + this.__current = element; + this.__state = null; + if (callback) { + result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); + } + this.__current = previous; + + return result; + }; + + // API: + // notify control skip / break + Controller.prototype.notify = function notify(flag) { + this.__state = flag; + }; + + // API: + // skip child nodes of current node + Controller.prototype.skip = function () { + this.notify(SKIP); + }; + + // API: + // break traversals + Controller.prototype['break'] = function () { + this.notify(BREAK); + }; + + // API: + // remove node + Controller.prototype.remove = function () { + this.notify(REMOVE); + }; + + Controller.prototype.__initialize = function(root, visitor) { + this.visitor = visitor; + this.root = root; + this.__worklist = []; + this.__leavelist = []; + this.__current = null; + this.__state = null; + this.__fallback = visitor.fallback === 'iteration'; + this.__keys = VisitorKeys; + if (visitor.keys) { + this.__keys = extend(objectCreate(this.__keys), visitor.keys); + } + }; + + function isNode(node) { + if (node == null) { + return false; + } + return typeof node === 'object' && typeof node.type === 'string'; + } + + function isProperty(nodeType, key) { + return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; + } + + Controller.prototype.traverse = function traverse(root, visitor) { + var worklist, + leavelist, + element, + node, + nodeType, + ret, + key, + current, + current2, + candidates, + candidate, + sentinel; + + this.__initialize(root, visitor); + + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + worklist.push(new Element(root, null, null, null)); + leavelist.push(new Element(null, null, null, null)); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + ret = this.__execute(visitor.leave, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + continue; + } + + if (element.node) { + + ret = this.__execute(visitor.enter, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + + worklist.push(sentinel); + leavelist.push(element); + + if (this.__state === SKIP || ret === SKIP) { + continue; + } + + node = element.node; + nodeType = element.wrap || node.type; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = objectKeys(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + if (isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', null); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, null); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, null)); + } + } + } + } + }; + + Controller.prototype.replace = function replace(root, visitor) { + function removeElem(element) { + var i, + key, + nextElem, + parent; + + if (element.ref.remove()) { + // When the reference is an element of an array. + key = element.ref.key; + parent = element.ref.parent; + + // If removed from array, then decrease following items' keys. + i = worklist.length; + while (i--) { + nextElem = worklist[i]; + if (nextElem.ref && nextElem.ref.parent === parent) { + if (nextElem.ref.key < key) { + break; + } + --nextElem.ref.key; + } + } + } + } + + var worklist, + leavelist, + node, + nodeType, + target, + element, + current, + current2, + candidates, + candidate, + sentinel, + outer, + key; + + this.__initialize(root, visitor); + + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + outer = { + root: root + }; + element = new Element(root, null, null, new Reference(outer, 'root')); + worklist.push(element); + leavelist.push(element); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + target = this.__execute(visitor.leave, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + } + + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + } + + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + continue; + } + + target = this.__execute(visitor.enter, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + element.node = target; + } + + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + element.node = null; + } + + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + + // node may be null + node = element.node; + if (!node) { + continue; + } + + worklist.push(sentinel); + leavelist.push(element); + + if (this.__state === SKIP || target === SKIP) { + continue; + } + + nodeType = element.wrap || node.type; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = objectKeys(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + if (isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, new Reference(node, key))); + } + } + } + + return outer.root; + }; + + function traverse(root, visitor) { + var controller = new Controller(); + return controller.traverse(root, visitor); + } + + function replace(root, visitor) { + var controller = new Controller(); + return controller.replace(root, visitor); + } + + function extendCommentRange(comment, tokens) { + var target; + + target = upperBound(tokens, function search(token) { + return token.range[0] > comment.range[0]; + }); + + comment.extendedRange = [comment.range[0], comment.range[1]]; + + if (target !== tokens.length) { + comment.extendedRange[1] = tokens[target].range[0]; + } + + target -= 1; + if (target >= 0) { + comment.extendedRange[0] = tokens[target].range[1]; + } + + return comment; + } + + function attachComments(tree, providedComments, tokens) { + // At first, we should calculate extended comment ranges. + var comments = [], comment, len, i, cursor; + + if (!tree.range) { + throw new Error('attachComments needs range information'); + } + + // tokens array is empty, we attach comments to tree as 'leadingComments' + if (!tokens.length) { + if (providedComments.length) { + for (i = 0, len = providedComments.length; i < len; i += 1) { + comment = deepCopy(providedComments[i]); + comment.extendedRange = [0, tree.range[0]]; + comments.push(comment); + } + tree.leadingComments = comments; + } + return tree; + } + + for (i = 0, len = providedComments.length; i < len; i += 1) { + comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); + } + + // This is based on John Freeman's implementation. + cursor = 0; + traverse(tree, { + enter: function (node) { + var comment; + + while (cursor < comments.length) { + comment = comments[cursor]; + if (comment.extendedRange[1] > node.range[0]) { + break; + } + + if (comment.extendedRange[1] === node.range[0]) { + if (!node.leadingComments) { + node.leadingComments = []; + } + node.leadingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + cursor = 0; + traverse(tree, { + leave: function (node) { + var comment; + + while (cursor < comments.length) { + comment = comments[cursor]; + if (node.range[1] < comment.extendedRange[0]) { + break; + } + + if (node.range[1] === comment.extendedRange[0]) { + if (!node.trailingComments) { + node.trailingComments = []; + } + node.trailingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + return tree; + } + + exports.version = '1.8.1-dev'; + exports.Syntax = Syntax; + exports.traverse = traverse; + exports.replace = replace; + exports.attachComments = attachComments; + exports.VisitorKeys = VisitorKeys; + exports.VisitorOption = VisitorOption; + exports.Controller = Controller; + exports.cloneEnvironment = function () { return clone({}); }; + + return exports; +})); +/* vim: set sw=4 ts=4 et tw=80 : */ + + })(modules.estraverse = {}); + + modules['./package.json'] = { + "name": "streamline", + "description": "Asynchronous Javascript for dummies", + "version": "0.10.17", + "homepage": "http://github.com/Sage/streamlinejs", + "repository": { + "type": "git", + "url": "git://github.com/Sage/streamlinejs.git" + }, + "engines": { + "node": ">=0.10.0" + }, + "dependencies": { + "esprima": "^2.0.0", + "escodegen": "^1.6.1", + "source-map": "~0.1.43" + }, + "optionalDependencies": { + "fibers": "^1.0.1", + "galaxy": "^0.1.11" + }, + "author": "Bruno Jouhier", + "directories": { + "lib": "./lib", + "bin": "./bin" + }, + "main": "index.js" +} +; + + (function(require, exports) { + /* + Copyright (C) 2012-2014 Yusuke Suzuki + Copyright (C) 2015 Ingvar Stepanyan + Copyright (C) 2014 Ivan Nikulin + Copyright (C) 2012-2013 Michael Ficarra + Copyright (C) 2012-2013 Mathias Bynens + Copyright (C) 2013 Irakli Gozalishvili + Copyright (C) 2012 Robert Gust-Bardon + Copyright (C) 2012 John Freeman + Copyright (C) 2011-2012 Ariya Hidayat + Copyright (C) 2012 Joost-Wim Boekesteijn + Copyright (C) 2012 Kris Kowal + Copyright (C) 2012 Arpad Borsos + + 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 HOLDERS AND CONTRIBUTORS "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 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. +*/ + +/*global exports:true, require:true, global:true*/ +(function () { + 'use strict'; + + var Syntax, + Precedence, + BinaryPrecedence, + SourceNode, + estraverse, + esutils, + isArray, + base, + indent, + json, + renumber, + hexadecimal, + quotes, + escapeless, + newline, + space, + parentheses, + semicolons, + safeConcatenation, + directive, + extra, + parse, + sourceMap, + sourceCode, + preserveBlankLines, + FORMAT_MINIFY, + FORMAT_DEFAULTS; + + estraverse = require('estraverse'); + esutils = require('esutils'); + + Syntax = estraverse.Syntax; + + // Generation is done by generateExpression. + function isExpression(node) { + return CodeGenerator.Expression.hasOwnProperty(node.type); + } + + // Generation is done by generateStatement. + function isStatement(node) { + return CodeGenerator.Statement.hasOwnProperty(node.type); + } + + Precedence = { + Sequence: 0, + Yield: 1, + Await: 1, + Assignment: 1, + Conditional: 2, + ArrowFunction: 2, + LogicalOR: 3, + LogicalAND: 4, + BitwiseOR: 5, + BitwiseXOR: 6, + BitwiseAND: 7, + Equality: 8, + Relational: 9, + BitwiseSHIFT: 10, + Additive: 11, + Multiplicative: 12, + Unary: 13, + Postfix: 14, + Call: 15, + New: 16, + TaggedTemplate: 17, + Member: 18, + Primary: 19 + }; + + BinaryPrecedence = { + '||': Precedence.LogicalOR, + '&&': Precedence.LogicalAND, + '|': Precedence.BitwiseOR, + '^': Precedence.BitwiseXOR, + '&': Precedence.BitwiseAND, + '==': Precedence.Equality, + '!=': Precedence.Equality, + '===': Precedence.Equality, + '!==': Precedence.Equality, + 'is': Precedence.Equality, + 'isnt': Precedence.Equality, + '<': Precedence.Relational, + '>': Precedence.Relational, + '<=': Precedence.Relational, + '>=': Precedence.Relational, + 'in': Precedence.Relational, + 'instanceof': Precedence.Relational, + '<<': Precedence.BitwiseSHIFT, + '>>': Precedence.BitwiseSHIFT, + '>>>': Precedence.BitwiseSHIFT, + '+': Precedence.Additive, + '-': Precedence.Additive, + '*': Precedence.Multiplicative, + '%': Precedence.Multiplicative, + '/': Precedence.Multiplicative + }; + + //Flags + var F_ALLOW_IN = 1, + F_ALLOW_CALL = 1 << 1, + F_ALLOW_UNPARATH_NEW = 1 << 2, + F_FUNC_BODY = 1 << 3, + F_DIRECTIVE_CTX = 1 << 4, + F_SEMICOLON_OPT = 1 << 5; + + //Expression flag sets + //NOTE: Flag order: + // F_ALLOW_IN + // F_ALLOW_CALL + // F_ALLOW_UNPARATH_NEW + var E_FTT = F_ALLOW_CALL | F_ALLOW_UNPARATH_NEW, + E_TTF = F_ALLOW_IN | F_ALLOW_CALL, + E_TTT = F_ALLOW_IN | F_ALLOW_CALL | F_ALLOW_UNPARATH_NEW, + E_TFF = F_ALLOW_IN, + E_FFT = F_ALLOW_UNPARATH_NEW, + E_TFT = F_ALLOW_IN | F_ALLOW_UNPARATH_NEW; + + //Statement flag sets + //NOTE: Flag order: + // F_ALLOW_IN + // F_FUNC_BODY + // F_DIRECTIVE_CTX + // F_SEMICOLON_OPT + var S_TFFF = F_ALLOW_IN, + S_TFFT = F_ALLOW_IN | F_SEMICOLON_OPT, + S_FFFF = 0x00, + S_TFTF = F_ALLOW_IN | F_DIRECTIVE_CTX, + S_TTFF = F_ALLOW_IN | F_FUNC_BODY; + + function getDefaultOptions() { + // default options + return { + indent: null, + base: null, + parse: null, + comment: false, + format: { + indent: { + style: ' ', + base: 0, + adjustMultilineComment: false + }, + newline: '\n', + space: ' ', + json: false, + renumber: false, + hexadecimal: false, + quotes: 'single', + escapeless: false, + compact: false, + parentheses: true, + semicolons: true, + safeConcatenation: false, + preserveBlankLines: false + }, + moz: { + comprehensionExpressionStartsWithAssignment: false, + starlessGenerator: false + }, + sourceMap: null, + sourceMapRoot: null, + sourceMapWithCode: false, + directive: false, + raw: true, + verbatim: null, + sourceCode: null + }; + } + + function stringRepeat(str, num) { + var result = ''; + + for (num |= 0; num > 0; num >>>= 1, str += str) { + if (num & 1) { + result += str; + } + } + + return result; + } + + isArray = Array.isArray; + if (!isArray) { + isArray = function isArray(array) { + return Object.prototype.toString.call(array) === '[object Array]'; + }; + } + + function hasLineTerminator(str) { + return (/[\r\n]/g).test(str); + } + + function endsWithLineTerminator(str) { + var len = str.length; + return len && esutils.code.isLineTerminator(str.charCodeAt(len - 1)); + } + + function merge(target, override) { + var key; + for (key in override) { + if (override.hasOwnProperty(key)) { + target[key] = override[key]; + } + } + return target; + } + + function updateDeeply(target, override) { + var key, val; + + function isHashObject(target) { + return typeof target === 'object' && target instanceof Object && !(target instanceof RegExp); + } + + for (key in override) { + if (override.hasOwnProperty(key)) { + val = override[key]; + if (isHashObject(val)) { + if (isHashObject(target[key])) { + updateDeeply(target[key], val); + } else { + target[key] = updateDeeply({}, val); + } + } else { + target[key] = val; + } + } + } + return target; + } + + function generateNumber(value) { + var result, point, temp, exponent, pos; + + if (value !== value) { + throw new Error('Numeric literal whose value is NaN'); + } + if (value < 0 || (value === 0 && 1 / value < 0)) { + throw new Error('Numeric literal whose value is negative'); + } + + if (value === 1 / 0) { + return json ? 'null' : renumber ? '1e400' : '1e+400'; + } + + result = '' + value; + if (!renumber || result.length < 3) { + return result; + } + + point = result.indexOf('.'); + if (!json && result.charCodeAt(0) === 0x30 /* 0 */ && point === 1) { + point = 0; + result = result.slice(1); + } + temp = result; + result = result.replace('e+', 'e'); + exponent = 0; + if ((pos = temp.indexOf('e')) > 0) { + exponent = +temp.slice(pos + 1); + temp = temp.slice(0, pos); + } + if (point >= 0) { + exponent -= temp.length - point - 1; + temp = +(temp.slice(0, point) + temp.slice(point + 1)) + ''; + } + pos = 0; + while (temp.charCodeAt(temp.length + pos - 1) === 0x30 /* 0 */) { + --pos; + } + if (pos !== 0) { + exponent -= pos; + temp = temp.slice(0, pos); + } + if (exponent !== 0) { + temp += 'e' + exponent; + } + if ((temp.length < result.length || + (hexadecimal && value > 1e12 && Math.floor(value) === value && (temp = '0x' + value.toString(16)).length < result.length)) && + +temp === value) { + result = temp; + } + + return result; + } + + // Generate valid RegExp expression. + // This function is based on https://github.com/Constellation/iv Engine + + function escapeRegExpCharacter(ch, previousIsBackslash) { + // not handling '\' and handling \u2028 or \u2029 to unicode escape sequence + if ((ch & ~1) === 0x2028) { + return (previousIsBackslash ? 'u' : '\\u') + ((ch === 0x2028) ? '2028' : '2029'); + } else if (ch === 10 || ch === 13) { // \n, \r + return (previousIsBackslash ? '' : '\\') + ((ch === 10) ? 'n' : 'r'); + } + return String.fromCharCode(ch); + } + + function generateRegExp(reg) { + var match, result, flags, i, iz, ch, characterInBrack, previousIsBackslash; + + result = reg.toString(); + + if (reg.source) { + // extract flag from toString result + match = result.match(/\/([^/]*)$/); + if (!match) { + return result; + } + + flags = match[1]; + result = ''; + + characterInBrack = false; + previousIsBackslash = false; + for (i = 0, iz = reg.source.length; i < iz; ++i) { + ch = reg.source.charCodeAt(i); + + if (!previousIsBackslash) { + if (characterInBrack) { + if (ch === 93) { // ] + characterInBrack = false; + } + } else { + if (ch === 47) { // / + result += '\\'; + } else if (ch === 91) { // [ + characterInBrack = true; + } + } + result += escapeRegExpCharacter(ch, previousIsBackslash); + previousIsBackslash = ch === 92; // \ + } else { + // if new RegExp("\\\n') is provided, create /\n/ + result += escapeRegExpCharacter(ch, previousIsBackslash); + // prevent like /\\[/]/ + previousIsBackslash = false; + } + } + + return '/' + result + '/' + flags; + } + + return result; + } + + function escapeAllowedCharacter(code, next) { + var hex; + + if (code === 0x08 /* \b */) { + return '\\b'; + } + + if (code === 0x0C /* \f */) { + return '\\f'; + } + + if (code === 0x09 /* \t */) { + return '\\t'; + } + + hex = code.toString(16).toUpperCase(); + if (json || code > 0xFF) { + return '\\u' + '0000'.slice(hex.length) + hex; + } else if (code === 0x0000 && !esutils.code.isDecimalDigit(next)) { + return '\\0'; + } else if (code === 0x000B /* \v */) { // '\v' + return '\\x0B'; + } else { + return '\\x' + '00'.slice(hex.length) + hex; + } + } + + function escapeDisallowedCharacter(code) { + if (code === 0x5C /* \ */) { + return '\\\\'; + } + + if (code === 0x0A /* \n */) { + return '\\n'; + } + + if (code === 0x0D /* \r */) { + return '\\r'; + } + + if (code === 0x2028) { + return '\\u2028'; + } + + if (code === 0x2029) { + return '\\u2029'; + } + + throw new Error('Incorrectly classified character'); + } + + function escapeDirective(str) { + var i, iz, code, quote; + + quote = quotes === 'double' ? '"' : '\''; + for (i = 0, iz = str.length; i < iz; ++i) { + code = str.charCodeAt(i); + if (code === 0x27 /* ' */) { + quote = '"'; + break; + } else if (code === 0x22 /* " */) { + quote = '\''; + break; + } else if (code === 0x5C /* \ */) { + ++i; + } + } + + return quote + str + quote; + } + + function escapeString(str) { + var result = '', i, len, code, singleQuotes = 0, doubleQuotes = 0, single, quote; + + for (i = 0, len = str.length; i < len; ++i) { + code = str.charCodeAt(i); + if (code === 0x27 /* ' */) { + ++singleQuotes; + } else if (code === 0x22 /* " */) { + ++doubleQuotes; + } else if (code === 0x2F /* / */ && json) { + result += '\\'; + } else if (esutils.code.isLineTerminator(code) || code === 0x5C /* \ */) { + result += escapeDisallowedCharacter(code); + continue; + } else if ((json && code < 0x20 /* SP */) || !(json || escapeless || (code >= 0x20 /* SP */ && code <= 0x7E /* ~ */))) { + result += escapeAllowedCharacter(code, str.charCodeAt(i + 1)); + continue; + } + result += String.fromCharCode(code); + } + + single = !(quotes === 'double' || (quotes === 'auto' && doubleQuotes < singleQuotes)); + quote = single ? '\'' : '"'; + + if (!(single ? singleQuotes : doubleQuotes)) { + return quote + result + quote; + } + + str = result; + result = quote; + + for (i = 0, len = str.length; i < len; ++i) { + code = str.charCodeAt(i); + if ((code === 0x27 /* ' */ && single) || (code === 0x22 /* " */ && !single)) { + result += '\\'; + } + result += String.fromCharCode(code); + } + + return result + quote; + } + + /** + * flatten an array to a string, where the array can contain + * either strings or nested arrays + */ + function flattenToString(arr) { + var i, iz, elem, result = ''; + for (i = 0, iz = arr.length; i < iz; ++i) { + elem = arr[i]; + result += isArray(elem) ? flattenToString(elem) : elem; + } + return result; + } + + /** + * convert generated to a SourceNode when source maps are enabled. + */ + function toSourceNodeWhenNeeded(generated, node) { + if (!sourceMap) { + // with no source maps, generated is either an + // array or a string. if an array, flatten it. + // if a string, just return it + if (isArray(generated)) { + return flattenToString(generated); + } else { + return generated; + } + } + if (node == null) { + if (generated instanceof SourceNode) { + return generated; + } else { + node = {}; + } + } + if (node.loc == null) { + return new SourceNode(null, null, sourceMap, generated, node.name || null); + } + return new SourceNode(node.loc.start.line, node.loc.start.column, (sourceMap === true ? node.loc.source || null : sourceMap), generated, node.name || null); + } + + function noEmptySpace() { + return (space) ? space : ' '; + } + + function join(left, right) { + var leftSource, + rightSource, + leftCharCode, + rightCharCode; + + leftSource = toSourceNodeWhenNeeded(left).toString(); + if (leftSource.length === 0) { + return [right]; + } + + rightSource = toSourceNodeWhenNeeded(right).toString(); + if (rightSource.length === 0) { + return [left]; + } + + leftCharCode = leftSource.charCodeAt(leftSource.length - 1); + rightCharCode = rightSource.charCodeAt(0); + + if ((leftCharCode === 0x2B /* + */ || leftCharCode === 0x2D /* - */) && leftCharCode === rightCharCode || + esutils.code.isIdentifierPart(leftCharCode) && esutils.code.isIdentifierPart(rightCharCode) || + leftCharCode === 0x2F /* / */ && rightCharCode === 0x69 /* i */) { // infix word operators all start with `i` + return [left, noEmptySpace(), right]; + } else if (esutils.code.isWhiteSpace(leftCharCode) || esutils.code.isLineTerminator(leftCharCode) || + esutils.code.isWhiteSpace(rightCharCode) || esutils.code.isLineTerminator(rightCharCode)) { + return [left, right]; + } + return [left, space, right]; + } + + function addIndent(stmt) { + return [base, stmt]; + } + + function withIndent(fn) { + var previousBase; + previousBase = base; + base += indent; + fn(base); + base = previousBase; + } + + function calculateSpaces(str) { + var i; + for (i = str.length - 1; i >= 0; --i) { + if (esutils.code.isLineTerminator(str.charCodeAt(i))) { + break; + } + } + return (str.length - 1) - i; + } + + function adjustMultilineComment(value, specialBase) { + var array, i, len, line, j, spaces, previousBase, sn; + + array = value.split(/\r\n|[\r\n]/); + spaces = Number.MAX_VALUE; + + // first line doesn't have indentation + for (i = 1, len = array.length; i < len; ++i) { + line = array[i]; + j = 0; + while (j < line.length && esutils.code.isWhiteSpace(line.charCodeAt(j))) { + ++j; + } + if (spaces > j) { + spaces = j; + } + } + + if (typeof specialBase !== 'undefined') { + // pattern like + // { + // var t = 20; /* + // * this is comment + // */ + // } + previousBase = base; + if (array[1][spaces] === '*') { + specialBase += ' '; + } + base = specialBase; + } else { + if (spaces & 1) { + // /* + // * + // */ + // If spaces are odd number, above pattern is considered. + // We waste 1 space. + --spaces; + } + previousBase = base; + } + + for (i = 1, len = array.length; i < len; ++i) { + sn = toSourceNodeWhenNeeded(addIndent(array[i].slice(spaces))); + array[i] = sourceMap ? sn.join('') : sn; + } + + base = previousBase; + + return array.join('\n'); + } + + function generateComment(comment, specialBase) { + if (comment.type === 'Line') { + if (endsWithLineTerminator(comment.value)) { + return '//' + comment.value; + } else { + // Always use LineTerminator + var result = '//' + comment.value; + if (!preserveBlankLines) { + result += '\n'; + } + return result; + } + } + if (extra.format.indent.adjustMultilineComment && /[\n\r]/.test(comment.value)) { + return adjustMultilineComment('/*' + comment.value + '*/', specialBase); + } + return '/*' + comment.value + '*/'; + } + + function addComments(stmt, result) { + var i, len, comment, save, tailingToStatement, specialBase, fragment, + extRange, range, prevRange, prefix, infix, suffix, count; + + if (stmt.leadingComments && stmt.leadingComments.length > 0) { + save = result; + + if (preserveBlankLines) { + comment = stmt.leadingComments[0]; + result = []; + + extRange = comment.extendedRange; + range = comment.range; + + prefix = sourceCode.substring(extRange[0], range[0]); + count = (prefix.match(/\n/g) || []).length; + if (count > 0) { + result.push(stringRepeat('\n', count)); + result.push(addIndent(generateComment(comment))); + } else { + result.push(prefix); + result.push(generateComment(comment)); + } + + prevRange = range; + + for (i = 1, len = stmt.leadingComments.length; i < len; i++) { + comment = stmt.leadingComments[i]; + range = comment.range; + + infix = sourceCode.substring(prevRange[1], range[0]); + count = (infix.match(/\n/g) || []).length; + result.push(stringRepeat('\n', count)); + result.push(addIndent(generateComment(comment))); + + prevRange = range; + } + + suffix = sourceCode.substring(range[1], extRange[1]); + count = (suffix.match(/\n/g) || []).length; + result.push(stringRepeat('\n', count)); + } else { + comment = stmt.leadingComments[0]; + result = []; + if (safeConcatenation && stmt.type === Syntax.Program && stmt.body.length === 0) { + result.push('\n'); + } + result.push(generateComment(comment)); + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push('\n'); + } + + for (i = 1, len = stmt.leadingComments.length; i < len; ++i) { + comment = stmt.leadingComments[i]; + fragment = [generateComment(comment)]; + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + fragment.push('\n'); + } + result.push(addIndent(fragment)); + } + } + + result.push(addIndent(save)); + } + + if (stmt.trailingComments) { + + if (preserveBlankLines) { + comment = stmt.trailingComments[0]; + extRange = comment.extendedRange; + range = comment.range; + + prefix = sourceCode.substring(extRange[0], range[0]); + count = (prefix.match(/\n/g) || []).length; + + if (count > 0) { + result.push(stringRepeat('\n', count)); + result.push(addIndent(generateComment(comment))); + } else { + result.push(prefix); + result.push(generateComment(comment)); + } + } else { + tailingToStatement = !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString()); + specialBase = stringRepeat(' ', calculateSpaces(toSourceNodeWhenNeeded([base, result, indent]).toString())); + for (i = 0, len = stmt.trailingComments.length; i < len; ++i) { + comment = stmt.trailingComments[i]; + if (tailingToStatement) { + // We assume target like following script + // + // var t = 20; /** + // * This is comment of t + // */ + if (i === 0) { + // first case + result = [result, indent]; + } else { + result = [result, specialBase]; + } + result.push(generateComment(comment, specialBase)); + } else { + result = [result, addIndent(generateComment(comment))]; + } + if (i !== len - 1 && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result = [result, '\n']; + } + } + } + } + + return result; + } + + function generateBlankLines(start, end, result) { + var j, newlineCount = 0; + + for (j = start; j < end; j++) { + if (sourceCode[j] === '\n') { + newlineCount++; + } + } + + for (j = 1; j < newlineCount; j++) { + result.push(newline); + } + } + + function parenthesize(text, current, should) { + if (current < should) { + return ['(', text, ')']; + } + return text; + } + + function generateVerbatimString(string) { + var i, iz, result; + result = string.split(/\r\n|\n/); + for (i = 1, iz = result.length; i < iz; i++) { + result[i] = newline + base + result[i]; + } + return result; + } + + function generateVerbatim(expr, precedence) { + var verbatim, result, prec; + verbatim = expr[extra.verbatim]; + + if (typeof verbatim === 'string') { + result = parenthesize(generateVerbatimString(verbatim), Precedence.Sequence, precedence); + } else { + // verbatim is object + result = generateVerbatimString(verbatim.content); + prec = (verbatim.precedence != null) ? verbatim.precedence : Precedence.Sequence; + result = parenthesize(result, prec, precedence); + } + + return toSourceNodeWhenNeeded(result, expr); + } + + function CodeGenerator() { + } + + // Helpers. + + CodeGenerator.prototype.maybeBlock = function(stmt, flags) { + var result, noLeadingComment, that = this; + + noLeadingComment = !extra.comment || !stmt.leadingComments; + + if (stmt.type === Syntax.BlockStatement && noLeadingComment) { + return [space, this.generateStatement(stmt, flags)]; + } + + if (stmt.type === Syntax.EmptyStatement && noLeadingComment) { + return ';'; + } + + withIndent(function () { + result = [ + newline, + addIndent(that.generateStatement(stmt, flags)) + ]; + }); + + return result; + }; + + CodeGenerator.prototype.maybeBlockSuffix = function (stmt, result) { + var ends = endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString()); + if (stmt.type === Syntax.BlockStatement && (!extra.comment || !stmt.leadingComments) && !ends) { + return [result, space]; + } + if (ends) { + return [result, base]; + } + return [result, newline, base]; + }; + + function generateIdentifier(node) { + return toSourceNodeWhenNeeded(node.name, node); + } + + function generateAsyncPrefix(node, spaceRequired) { + return node.async ? 'async' + (spaceRequired ? noEmptySpace() : space) : ''; + } + + function generateStarSuffix(node) { + var isGenerator = node.generator && !extra.moz.starlessGenerator; + return isGenerator ? '*' + space : ''; + } + + function generateMethodPrefix(prop) { + var func = prop.value; + if (func.async) { + return generateAsyncPrefix(func, !prop.computed); + } else { + // avoid space before method name + return generateStarSuffix(func) ? '*' : ''; + } + } + + CodeGenerator.prototype.generatePattern = function (node, precedence, flags) { + if (node.type === Syntax.Identifier) { + return generateIdentifier(node); + } + return this.generateExpression(node, precedence, flags); + }; + + CodeGenerator.prototype.generateFunctionParams = function (node) { + var i, iz, result, hasDefault; + + hasDefault = false; + + if (node.type === Syntax.ArrowFunctionExpression && + !node.rest && (!node.defaults || node.defaults.length === 0) && + node.params.length === 1 && node.params[0].type === Syntax.Identifier) { + // arg => { } case + result = [generateAsyncPrefix(node, true), generateIdentifier(node.params[0])]; + } else { + result = node.type === Syntax.ArrowFunctionExpression ? [generateAsyncPrefix(node, false)] : []; + result.push('('); + if (node.defaults) { + hasDefault = true; + } + for (i = 0, iz = node.params.length; i < iz; ++i) { + if (hasDefault && node.defaults[i]) { + // Handle default values. + result.push(this.generateAssignment(node.params[i], node.defaults[i], '=', Precedence.Assignment, E_TTT)); + } else { + result.push(this.generatePattern(node.params[i], Precedence.Assignment, E_TTT)); + } + if (i + 1 < iz) { + result.push(',' + space); + } + } + + if (node.rest) { + if (node.params.length) { + result.push(',' + space); + } + result.push('...'); + result.push(generateIdentifier(node.rest)); + } + + result.push(')'); + } + + return result; + }; + + CodeGenerator.prototype.generateFunctionBody = function (node) { + var result, expr; + + result = this.generateFunctionParams(node); + + if (node.type === Syntax.ArrowFunctionExpression) { + result.push(space); + result.push('=>'); + } + + if (node.expression) { + result.push(space); + expr = this.generateExpression(node.body, Precedence.Assignment, E_TTT); + if (expr.toString().charAt(0) === '{') { + expr = ['(', expr, ')']; + } + result.push(expr); + } else { + result.push(this.maybeBlock(node.body, S_TTFF)); + } + + return result; + }; + + CodeGenerator.prototype.generateIterationForStatement = function (operator, stmt, flags) { + var result = ['for' + space + '('], that = this; + withIndent(function () { + if (stmt.left.type === Syntax.VariableDeclaration) { + withIndent(function () { + result.push(stmt.left.kind + noEmptySpace()); + result.push(that.generateStatement(stmt.left.declarations[0], S_FFFF)); + }); + } else { + result.push(that.generateExpression(stmt.left, Precedence.Call, E_TTT)); + } + + result = join(result, operator); + result = [join( + result, + that.generateExpression(stmt.right, Precedence.Sequence, E_TTT) + ), ')']; + }); + result.push(this.maybeBlock(stmt.body, flags)); + return result; + }; + + CodeGenerator.prototype.generatePropertyKey = function (expr, computed) { + var result = []; + + if (computed) { + result.push('['); + } + + result.push(this.generateExpression(expr, Precedence.Sequence, E_TTT)); + if (computed) { + result.push(']'); + } + + return result; + }; + + CodeGenerator.prototype.generateAssignment = function (left, right, operator, precedence, flags) { + if (Precedence.Assignment < precedence) { + flags |= F_ALLOW_IN; + } + + return parenthesize( + [ + this.generateExpression(left, Precedence.Call, flags), + space + operator + space, + this.generateExpression(right, Precedence.Assignment, flags) + ], + Precedence.Assignment, + precedence + ); + }; + + CodeGenerator.prototype.semicolon = function (flags) { + if (!semicolons && flags & F_SEMICOLON_OPT) { + return ''; + } + return ';'; + }; + + // Statements. + + CodeGenerator.Statement = { + + BlockStatement: function (stmt, flags) { + var range, content, result = ['{', newline], that = this; + + withIndent(function () { + // handle functions without any code + if (stmt.body.length === 0 && preserveBlankLines) { + range = stmt.range; + if (range[1] - range[0] > 2) { + content = sourceCode.substring(range[0] + 1, range[1] - 1); + if (content[0] === '\n') { + result = ['{']; + } + result.push(content); + } + } + + var i, iz, fragment, bodyFlags; + bodyFlags = S_TFFF; + if (flags & F_FUNC_BODY) { + bodyFlags |= F_DIRECTIVE_CTX; + } + + for (i = 0, iz = stmt.body.length; i < iz; ++i) { + if (preserveBlankLines) { + // handle spaces before the first line + if (i === 0) { + if (stmt.body[0].leadingComments) { + range = stmt.body[0].leadingComments[0].extendedRange; + content = sourceCode.substring(range[0], range[1]); + if (content[0] === '\n') { + result = ['{']; + } + } + if (!stmt.body[0].leadingComments) { + generateBlankLines(stmt.range[0], stmt.body[0].range[0], result); + } + } + + // handle spaces between lines + if (i > 0) { + if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) { + generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result); + } + } + } + + if (i === iz - 1) { + bodyFlags |= F_SEMICOLON_OPT; + } + + if (stmt.body[i].leadingComments && preserveBlankLines) { + fragment = that.generateStatement(stmt.body[i], bodyFlags); + } else { + fragment = addIndent(that.generateStatement(stmt.body[i], bodyFlags)); + } + + result.push(fragment); + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + if (preserveBlankLines && i < iz - 1) { + // don't add a new line if there are leading coments + // in the next statement + if (!stmt.body[i + 1].leadingComments) { + result.push(newline); + } + } else { + result.push(newline); + } + } + + if (preserveBlankLines) { + // handle spaces after the last line + if (i === iz - 1) { + if (!stmt.body[i].trailingComments) { + generateBlankLines(stmt.body[i].range[1], stmt.range[1], result); + } + } + } + } + }); + + result.push(addIndent('}')); + return result; + }, + + BreakStatement: function (stmt, flags) { + if (stmt.label) { + return 'break ' + stmt.label.name + this.semicolon(flags); + } + return 'break' + this.semicolon(flags); + }, + + ContinueStatement: function (stmt, flags) { + if (stmt.label) { + return 'continue ' + stmt.label.name + this.semicolon(flags); + } + return 'continue' + this.semicolon(flags); + }, + + ClassBody: function (stmt, flags) { + var result = [ '{', newline], that = this; + + withIndent(function (indent) { + var i, iz; + + for (i = 0, iz = stmt.body.length; i < iz; ++i) { + result.push(indent); + result.push(that.generateExpression(stmt.body[i], Precedence.Sequence, E_TTT)); + if (i + 1 < iz) { + result.push(newline); + } + } + }); + + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + result.push(base); + result.push('}'); + return result; + }, + + ClassDeclaration: function (stmt, flags) { + var result, fragment; + result = ['class ' + stmt.id.name]; + if (stmt.superClass) { + fragment = join('extends', this.generateExpression(stmt.superClass, Precedence.Assignment, E_TTT)); + result = join(result, fragment); + } + result.push(space); + result.push(this.generateStatement(stmt.body, S_TFFT)); + return result; + }, + + DirectiveStatement: function (stmt, flags) { + if (extra.raw && stmt.raw) { + return stmt.raw + this.semicolon(flags); + } + return escapeDirective(stmt.directive) + this.semicolon(flags); + }, + + DoWhileStatement: function (stmt, flags) { + // Because `do 42 while (cond)` is Syntax Error. We need semicolon. + var result = join('do', this.maybeBlock(stmt.body, S_TFFF)); + result = this.maybeBlockSuffix(stmt.body, result); + return join(result, [ + 'while' + space + '(', + this.generateExpression(stmt.test, Precedence.Sequence, E_TTT), + ')' + this.semicolon(flags) + ]); + }, + + CatchClause: function (stmt, flags) { + var result, that = this; + withIndent(function () { + var guard; + + result = [ + 'catch' + space + '(', + that.generateExpression(stmt.param, Precedence.Sequence, E_TTT), + ')' + ]; + + if (stmt.guard) { + guard = that.generateExpression(stmt.guard, Precedence.Sequence, E_TTT); + result.splice(2, 0, ' if ', guard); + } + }); + result.push(this.maybeBlock(stmt.body, S_TFFF)); + return result; + }, + + DebuggerStatement: function (stmt, flags) { + return 'debugger' + this.semicolon(flags); + }, + + EmptyStatement: function (stmt, flags) { + return ';'; + }, + + ExportDeclaration: function (stmt, flags) { + var result = [ 'export' ], bodyFlags, that = this; + + bodyFlags = (flags & F_SEMICOLON_OPT) ? S_TFFT : S_TFFF; + + // export default HoistableDeclaration[Default] + // export default AssignmentExpression[In] ; + if (stmt['default']) { + result = join(result, 'default'); + if (isStatement(stmt.declaration)) { + result = join(result, this.generateStatement(stmt.declaration, bodyFlags)); + } else { + result = join(result, this.generateExpression(stmt.declaration, Precedence.Assignment, E_TTT) + this.semicolon(flags)); + } + return result; + } + + // export VariableStatement + // export Declaration[Default] + if (stmt.declaration) { + return join(result, this.generateStatement(stmt.declaration, bodyFlags)); + } + + // export * FromClause ; + // export ExportClause[NoReference] FromClause ; + // export ExportClause ; + if (stmt.specifiers) { + if (stmt.specifiers.length === 0) { + result = join(result, '{' + space + '}'); + } else if (stmt.specifiers[0].type === Syntax.ExportBatchSpecifier) { + result = join(result, this.generateExpression(stmt.specifiers[0], Precedence.Sequence, E_TTT)); + } else { + result = join(result, '{'); + withIndent(function (indent) { + var i, iz; + result.push(newline); + for (i = 0, iz = stmt.specifiers.length; i < iz; ++i) { + result.push(indent); + result.push(that.generateExpression(stmt.specifiers[i], Precedence.Sequence, E_TTT)); + if (i + 1 < iz) { + result.push(',' + newline); + } + } + }); + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + result.push(base + '}'); + } + + if (stmt.source) { + result = join(result, [ + 'from' + space, + // ModuleSpecifier + this.generateExpression(stmt.source, Precedence.Sequence, E_TTT), + this.semicolon(flags) + ]); + } else { + result.push(this.semicolon(flags)); + } + } + return result; + }, + + ExpressionStatement: function (stmt, flags) { + var result, fragment; + + function isClassPrefixed(fragment) { + var code; + if (fragment.slice(0, 5) !== 'class') { + return false; + } + code = fragment.charCodeAt(5); + return code === 0x7B /* '{' */ || esutils.code.isWhiteSpace(code) || esutils.code.isLineTerminator(code); + } + + function isFunctionPrefixed(fragment) { + var code; + if (fragment.slice(0, 8) !== 'function') { + return false; + } + code = fragment.charCodeAt(8); + return code === 0x28 /* '(' */ || esutils.code.isWhiteSpace(code) || code === 0x2A /* '*' */ || esutils.code.isLineTerminator(code); + } + + function isAsyncPrefixed(fragment) { + var code, i, iz; + if (fragment.slice(0, 5) !== 'async') { + return false; + } + if (!esutils.code.isWhiteSpace(fragment.charCodeAt(5))) { + return false; + } + for (i = 6, iz = fragment.length; i < iz; ++i) { + if (!esutils.code.isWhiteSpace(fragment.charCodeAt(i))) { + break; + } + } + if (i === iz) { + return false; + } + if (fragment.slice(i, i + 8) !== 'function') { + return false; + } + code = fragment.charCodeAt(i + 8); + return code === 0x28 /* '(' */ || esutils.code.isWhiteSpace(code) || code === 0x2A /* '*' */ || esutils.code.isLineTerminator(code); + } + + result = [this.generateExpression(stmt.expression, Precedence.Sequence, E_TTT)]; + // 12.4 '{', 'function', 'class' is not allowed in this position. + // wrap expression with parentheses + fragment = toSourceNodeWhenNeeded(result).toString(); + if (fragment.charCodeAt(0) === 0x7B /* '{' */ || // ObjectExpression + isClassPrefixed(fragment) || + isFunctionPrefixed(fragment) || + isAsyncPrefixed(fragment) || + (directive && (flags & F_DIRECTIVE_CTX) && stmt.expression.type === Syntax.Literal && typeof stmt.expression.value === 'string')) { + result = ['(', result, ')' + this.semicolon(flags)]; + } else { + result.push(this.semicolon(flags)); + } + return result; + }, + + ImportDeclaration: function (stmt, flags) { + // ES6: 15.2.1 valid import declarations: + // - import ImportClause FromClause ; + // - import ModuleSpecifier ; + var result, cursor, that = this; + + // If no ImportClause is present, + // this should be `import ModuleSpecifier` so skip `from` + // ModuleSpecifier is StringLiteral. + if (stmt.specifiers.length === 0) { + // import ModuleSpecifier ; + return [ + 'import', + space, + // ModuleSpecifier + this.generateExpression(stmt.source, Precedence.Sequence, E_TTT), + this.semicolon(flags) + ]; + } + + // import ImportClause FromClause ; + result = [ + 'import' + ]; + cursor = 0; + + // ImportedBinding + if (stmt.specifiers[cursor].type === Syntax.ImportDefaultSpecifier) { + result = join(result, [ + this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT) + ]); + ++cursor; + } + + if (stmt.specifiers[cursor]) { + if (cursor !== 0) { + result.push(','); + } + + if (stmt.specifiers[cursor].type === Syntax.ImportNamespaceSpecifier) { + // NameSpaceImport + result = join(result, [ + space, + this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT) + ]); + } else { + // NamedImports + result.push(space + '{'); + + if ((stmt.specifiers.length - cursor) === 1) { + // import { ... } from "..."; + result.push(space); + result.push(this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT)); + result.push(space + '}' + space); + } else { + // import { + // ..., + // ..., + // } from "..."; + withIndent(function (indent) { + var i, iz; + result.push(newline); + for (i = cursor, iz = stmt.specifiers.length; i < iz; ++i) { + result.push(indent); + result.push(that.generateExpression(stmt.specifiers[i], Precedence.Sequence, E_TTT)); + if (i + 1 < iz) { + result.push(',' + newline); + } + } + }); + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + result.push(base + '}' + space); + } + } + } + + result = join(result, [ + 'from' + space, + // ModuleSpecifier + this.generateExpression(stmt.source, Precedence.Sequence, E_TTT), + this.semicolon(flags) + ]); + return result; + }, + + VariableDeclarator: function (stmt, flags) { + var itemFlags = (flags & F_ALLOW_IN) ? E_TTT : E_FTT; + if (stmt.init) { + return [ + this.generateExpression(stmt.id, Precedence.Assignment, itemFlags), + space, + '=', + space, + this.generateExpression(stmt.init, Precedence.Assignment, itemFlags) + ]; + } + return this.generatePattern(stmt.id, Precedence.Assignment, itemFlags); + }, + + VariableDeclaration: function (stmt, flags) { + // VariableDeclarator is typed as Statement, + // but joined with comma (not LineTerminator). + // So if comment is attached to target node, we should specialize. + var result, i, iz, node, bodyFlags, that = this; + + result = [ stmt.kind ]; + + bodyFlags = (flags & F_ALLOW_IN) ? S_TFFF : S_FFFF; + + function block() { + node = stmt.declarations[0]; + if (extra.comment && node.leadingComments) { + result.push('\n'); + result.push(addIndent(that.generateStatement(node, bodyFlags))); + } else { + result.push(noEmptySpace()); + result.push(that.generateStatement(node, bodyFlags)); + } + + for (i = 1, iz = stmt.declarations.length; i < iz; ++i) { + node = stmt.declarations[i]; + if (extra.comment && node.leadingComments) { + result.push(',' + newline); + result.push(addIndent(that.generateStatement(node, bodyFlags))); + } else { + result.push(',' + space); + result.push(that.generateStatement(node, bodyFlags)); + } + } + } + + if (stmt.declarations.length > 1) { + withIndent(block); + } else { + block(); + } + + result.push(this.semicolon(flags)); + + return result; + }, + + ThrowStatement: function (stmt, flags) { + return [join( + 'throw', + this.generateExpression(stmt.argument, Precedence.Sequence, E_TTT) + ), this.semicolon(flags)]; + }, + + TryStatement: function (stmt, flags) { + var result, i, iz, guardedHandlers; + + result = ['try', this.maybeBlock(stmt.block, S_TFFF)]; + result = this.maybeBlockSuffix(stmt.block, result); + + if (stmt.handlers) { + // old interface + for (i = 0, iz = stmt.handlers.length; i < iz; ++i) { + result = join(result, this.generateStatement(stmt.handlers[i], S_TFFF)); + if (stmt.finalizer || i + 1 !== iz) { + result = this.maybeBlockSuffix(stmt.handlers[i].body, result); + } + } + } else { + guardedHandlers = stmt.guardedHandlers || []; + + for (i = 0, iz = guardedHandlers.length; i < iz; ++i) { + result = join(result, this.generateStatement(guardedHandlers[i], S_TFFF)); + if (stmt.finalizer || i + 1 !== iz) { + result = this.maybeBlockSuffix(guardedHandlers[i].body, result); + } + } + + // new interface + if (stmt.handler) { + if (isArray(stmt.handler)) { + for (i = 0, iz = stmt.handler.length; i < iz; ++i) { + result = join(result, this.generateStatement(stmt.handler[i], S_TFFF)); + if (stmt.finalizer || i + 1 !== iz) { + result = this.maybeBlockSuffix(stmt.handler[i].body, result); + } + } + } else { + result = join(result, this.generateStatement(stmt.handler, S_TFFF)); + if (stmt.finalizer) { + result = this.maybeBlockSuffix(stmt.handler.body, result); + } + } + } + } + if (stmt.finalizer) { + result = join(result, ['finally', this.maybeBlock(stmt.finalizer, S_TFFF)]); + } + return result; + }, + + SwitchStatement: function (stmt, flags) { + var result, fragment, i, iz, bodyFlags, that = this; + withIndent(function () { + result = [ + 'switch' + space + '(', + that.generateExpression(stmt.discriminant, Precedence.Sequence, E_TTT), + ')' + space + '{' + newline + ]; + }); + if (stmt.cases) { + bodyFlags = S_TFFF; + for (i = 0, iz = stmt.cases.length; i < iz; ++i) { + if (i === iz - 1) { + bodyFlags |= F_SEMICOLON_OPT; + } + fragment = addIndent(this.generateStatement(stmt.cases[i], bodyFlags)); + result.push(fragment); + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + result.push(newline); + } + } + } + result.push(addIndent('}')); + return result; + }, + + SwitchCase: function (stmt, flags) { + var result, fragment, i, iz, bodyFlags, that = this; + withIndent(function () { + if (stmt.test) { + result = [ + join('case', that.generateExpression(stmt.test, Precedence.Sequence, E_TTT)), + ':' + ]; + } else { + result = ['default:']; + } + + i = 0; + iz = stmt.consequent.length; + if (iz && stmt.consequent[0].type === Syntax.BlockStatement) { + fragment = that.maybeBlock(stmt.consequent[0], S_TFFF); + result.push(fragment); + i = 1; + } + + if (i !== iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + + bodyFlags = S_TFFF; + for (; i < iz; ++i) { + if (i === iz - 1 && flags & F_SEMICOLON_OPT) { + bodyFlags |= F_SEMICOLON_OPT; + } + fragment = addIndent(that.generateStatement(stmt.consequent[i], bodyFlags)); + result.push(fragment); + if (i + 1 !== iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + result.push(newline); + } + } + }); + return result; + }, + + IfStatement: function (stmt, flags) { + var result, bodyFlags, semicolonOptional, that = this; + withIndent(function () { + result = [ + 'if' + space + '(', + that.generateExpression(stmt.test, Precedence.Sequence, E_TTT), + ')' + ]; + }); + semicolonOptional = flags & F_SEMICOLON_OPT; + bodyFlags = S_TFFF; + if (semicolonOptional) { + bodyFlags |= F_SEMICOLON_OPT; + } + if (stmt.alternate) { + result.push(this.maybeBlock(stmt.consequent, S_TFFF)); + result = this.maybeBlockSuffix(stmt.consequent, result); + if (stmt.alternate.type === Syntax.IfStatement) { + result = join(result, ['else ', this.generateStatement(stmt.alternate, bodyFlags)]); + } else { + result = join(result, join('else', this.maybeBlock(stmt.alternate, bodyFlags))); + } + } else { + result.push(this.maybeBlock(stmt.consequent, bodyFlags)); + } + return result; + }, + + ForStatement: function (stmt, flags) { + var result, that = this; + withIndent(function () { + result = ['for' + space + '(']; + if (stmt.init) { + if (stmt.init.type === Syntax.VariableDeclaration) { + result.push(that.generateStatement(stmt.init, S_FFFF)); + } else { + // F_ALLOW_IN becomes false. + result.push(that.generateExpression(stmt.init, Precedence.Sequence, E_FTT)); + result.push(';'); + } + } else { + result.push(';'); + } + + if (stmt.test) { + result.push(space); + result.push(that.generateExpression(stmt.test, Precedence.Sequence, E_TTT)); + result.push(';'); + } else { + result.push(';'); + } + + if (stmt.update) { + result.push(space); + result.push(that.generateExpression(stmt.update, Precedence.Sequence, E_TTT)); + result.push(')'); + } else { + result.push(')'); + } + }); + + result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF)); + return result; + }, + + ForInStatement: function (stmt, flags) { + return this.generateIterationForStatement('in', stmt, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF); + }, + + ForOfStatement: function (stmt, flags) { + return this.generateIterationForStatement('of', stmt, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF); + }, + + LabeledStatement: function (stmt, flags) { + return [stmt.label.name + ':', this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF)]; + }, + + Program: function (stmt, flags) { + var result, fragment, i, iz, bodyFlags; + iz = stmt.body.length; + result = [safeConcatenation && iz > 0 ? '\n' : '']; + bodyFlags = S_TFTF; + for (i = 0; i < iz; ++i) { + if (!safeConcatenation && i === iz - 1) { + bodyFlags |= F_SEMICOLON_OPT; + } + + if (preserveBlankLines) { + // handle spaces before the first line + if (i === 0) { + if (!stmt.body[0].leadingComments) { + generateBlankLines(stmt.range[0], stmt.body[i].range[0], result); + } + } + + // handle spaces between lines + if (i > 0) { + if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) { + generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result); + } + } + } + + fragment = addIndent(this.generateStatement(stmt.body[i], bodyFlags)); + result.push(fragment); + if (i + 1 < iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + if (preserveBlankLines) { + if (!stmt.body[i + 1].leadingComments) { + result.push(newline); + } + } else { + result.push(newline); + } + } + + if (preserveBlankLines) { + // handle spaces after the last line + if (i === iz - 1) { + if (!stmt.body[i].trailingComments) { + generateBlankLines(stmt.body[i].range[1], stmt.range[1], result); + } + } + } + } + return result; + }, + + FunctionDeclaration: function (stmt, flags) { + return [ + generateAsyncPrefix(stmt, true), + 'function', + generateStarSuffix(stmt) || noEmptySpace(), + generateIdentifier(stmt.id), + this.generateFunctionBody(stmt) + ]; + }, + + ReturnStatement: function (stmt, flags) { + if (stmt.argument) { + return [join( + 'return', + this.generateExpression(stmt.argument, Precedence.Sequence, E_TTT) + ), this.semicolon(flags)]; + } + return ['return' + this.semicolon(flags)]; + }, + + WhileStatement: function (stmt, flags) { + var result, that = this; + withIndent(function () { + result = [ + 'while' + space + '(', + that.generateExpression(stmt.test, Precedence.Sequence, E_TTT), + ')' + ]; + }); + result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF)); + return result; + }, + + WithStatement: function (stmt, flags) { + var result, that = this; + withIndent(function () { + result = [ + 'with' + space + '(', + that.generateExpression(stmt.object, Precedence.Sequence, E_TTT), + ')' + ]; + }); + result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF)); + return result; + } + + }; + + merge(CodeGenerator.prototype, CodeGenerator.Statement); + + // Expressions. + + CodeGenerator.Expression = { + + SequenceExpression: function (expr, precedence, flags) { + var result, i, iz; + if (Precedence.Sequence < precedence) { + flags |= F_ALLOW_IN; + } + result = []; + for (i = 0, iz = expr.expressions.length; i < iz; ++i) { + result.push(this.generateExpression(expr.expressions[i], Precedence.Assignment, flags)); + if (i + 1 < iz) { + result.push(',' + space); + } + } + return parenthesize(result, Precedence.Sequence, precedence); + }, + + AssignmentExpression: function (expr, precedence, flags) { + return this.generateAssignment(expr.left, expr.right, expr.operator, precedence, flags); + }, + + ArrowFunctionExpression: function (expr, precedence, flags) { + return parenthesize(this.generateFunctionBody(expr), Precedence.ArrowFunction, precedence); + }, + + ConditionalExpression: function (expr, precedence, flags) { + if (Precedence.Conditional < precedence) { + flags |= F_ALLOW_IN; + } + return parenthesize( + [ + this.generateExpression(expr.test, Precedence.LogicalOR, flags), + space + '?' + space, + this.generateExpression(expr.consequent, Precedence.Assignment, flags), + space + ':' + space, + this.generateExpression(expr.alternate, Precedence.Assignment, flags) + ], + Precedence.Conditional, + precedence + ); + }, + + LogicalExpression: function (expr, precedence, flags) { + return this.BinaryExpression(expr, precedence, flags); + }, + + BinaryExpression: function (expr, precedence, flags) { + var result, currentPrecedence, fragment, leftSource; + currentPrecedence = BinaryPrecedence[expr.operator]; + + if (currentPrecedence < precedence) { + flags |= F_ALLOW_IN; + } + + fragment = this.generateExpression(expr.left, currentPrecedence, flags); + + leftSource = fragment.toString(); + + if (leftSource.charCodeAt(leftSource.length - 1) === 0x2F /* / */ && esutils.code.isIdentifierPart(expr.operator.charCodeAt(0))) { + result = [fragment, noEmptySpace(), expr.operator]; + } else { + result = join(fragment, expr.operator); + } + + fragment = this.generateExpression(expr.right, currentPrecedence + 1, flags); + + if (expr.operator === '/' && fragment.toString().charAt(0) === '/' || + expr.operator.slice(-1) === '<' && fragment.toString().slice(0, 3) === '!--') { + // If '/' concats with '/' or `<` concats with `!--`, it is interpreted as comment start + result.push(noEmptySpace()); + result.push(fragment); + } else { + result = join(result, fragment); + } + + if (expr.operator === 'in' && !(flags & F_ALLOW_IN)) { + return ['(', result, ')']; + } + return parenthesize(result, currentPrecedence, precedence); + }, + + CallExpression: function (expr, precedence, flags) { + var result, i, iz; + // F_ALLOW_UNPARATH_NEW becomes false. + result = [this.generateExpression(expr.callee, Precedence.Call, E_TTF)]; + result.push('('); + for (i = 0, iz = expr['arguments'].length; i < iz; ++i) { + result.push(this.generateExpression(expr['arguments'][i], Precedence.Assignment, E_TTT)); + if (i + 1 < iz) { + result.push(',' + space); + } + } + result.push(')'); + + if (!(flags & F_ALLOW_CALL)) { + return ['(', result, ')']; + } + return parenthesize(result, Precedence.Call, precedence); + }, + + NewExpression: function (expr, precedence, flags) { + var result, length, i, iz, itemFlags; + length = expr['arguments'].length; + + // F_ALLOW_CALL becomes false. + // F_ALLOW_UNPARATH_NEW may become false. + itemFlags = (flags & F_ALLOW_UNPARATH_NEW && !parentheses && length === 0) ? E_TFT : E_TFF; + + result = join( + 'new', + this.generateExpression(expr.callee, Precedence.New, itemFlags) + ); + + if (!(flags & F_ALLOW_UNPARATH_NEW) || parentheses || length > 0) { + result.push('('); + for (i = 0, iz = length; i < iz; ++i) { + result.push(this.generateExpression(expr['arguments'][i], Precedence.Assignment, E_TTT)); + if (i + 1 < iz) { + result.push(',' + space); + } + } + result.push(')'); + } + + return parenthesize(result, Precedence.New, precedence); + }, + + MemberExpression: function (expr, precedence, flags) { + var result, fragment; + + // F_ALLOW_UNPARATH_NEW becomes false. + result = [this.generateExpression(expr.object, Precedence.Call, (flags & F_ALLOW_CALL) ? E_TTF : E_TFF)]; + + if (expr.computed) { + result.push('['); + result.push(this.generateExpression(expr.property, Precedence.Sequence, flags & F_ALLOW_CALL ? E_TTT : E_TFT)); + result.push(']'); + } else { + if (expr.object.type === Syntax.Literal && typeof expr.object.value === 'number') { + fragment = toSourceNodeWhenNeeded(result).toString(); + // When the following conditions are all true, + // 1. No floating point + // 2. Don't have exponents + // 3. The last character is a decimal digit + // 4. Not hexadecimal OR octal number literal + // we should add a floating point. + if ( + fragment.indexOf('.') < 0 && + !/[eExX]/.test(fragment) && + esutils.code.isDecimalDigit(fragment.charCodeAt(fragment.length - 1)) && + !(fragment.length >= 2 && fragment.charCodeAt(0) === 48) // '0' + ) { + result.push('.'); + } + } + result.push('.'); + result.push(generateIdentifier(expr.property)); + } + + return parenthesize(result, Precedence.Member, precedence); + }, + + UnaryExpression: function (expr, precedence, flags) { + var result, fragment, rightCharCode, leftSource, leftCharCode; + fragment = this.generateExpression(expr.argument, Precedence.Unary, E_TTT); + + if (space === '') { + result = join(expr.operator, fragment); + } else { + result = [expr.operator]; + if (expr.operator.length > 2) { + // delete, void, typeof + // get `typeof []`, not `typeof[]` + result = join(result, fragment); + } else { + // Prevent inserting spaces between operator and argument if it is unnecessary + // like, `!cond` + leftSource = toSourceNodeWhenNeeded(result).toString(); + leftCharCode = leftSource.charCodeAt(leftSource.length - 1); + rightCharCode = fragment.toString().charCodeAt(0); + + if (((leftCharCode === 0x2B /* + */ || leftCharCode === 0x2D /* - */) && leftCharCode === rightCharCode) || + (esutils.code.isIdentifierPart(leftCharCode) && esutils.code.isIdentifierPart(rightCharCode))) { + result.push(noEmptySpace()); + result.push(fragment); + } else { + result.push(fragment); + } + } + } + return parenthesize(result, Precedence.Unary, precedence); + }, + + YieldExpression: function (expr, precedence, flags) { + var result; + if (expr.delegate) { + result = 'yield*'; + } else { + result = 'yield'; + } + if (expr.argument) { + result = join( + result, + this.generateExpression(expr.argument, Precedence.Yield, E_TTT) + ); + } + return parenthesize(result, Precedence.Yield, precedence); + }, + + AwaitExpression: function (expr, precedence, flags) { + var result = join( + expr.delegate ? 'await*' : 'await', + this.generateExpression(expr.argument, Precedence.Await, E_TTT) + ); + return parenthesize(result, Precedence.Await, precedence); + }, + + UpdateExpression: function (expr, precedence, flags) { + if (expr.prefix) { + return parenthesize( + [ + expr.operator, + this.generateExpression(expr.argument, Precedence.Unary, E_TTT) + ], + Precedence.Unary, + precedence + ); + } + return parenthesize( + [ + this.generateExpression(expr.argument, Precedence.Postfix, E_TTT), + expr.operator + ], + Precedence.Postfix, + precedence + ); + }, + + FunctionExpression: function (expr, precedence, flags) { + var result = [ + generateAsyncPrefix(expr, true), + 'function' + ]; + if (expr.id) { + result.push(generateStarSuffix(expr) || noEmptySpace()); + result.push(generateIdentifier(expr.id)); + } else { + result.push(generateStarSuffix(expr) || space); + } + result.push(this.generateFunctionBody(expr)); + return result; + }, + + ExportBatchSpecifier: function (expr, precedence, flags) { + return '*'; + }, + + ArrayPattern: function (expr, precedence, flags) { + return this.ArrayExpression(expr, precedence, flags); + }, + + ArrayExpression: function (expr, precedence, flags) { + var result, multiline, that = this; + if (!expr.elements.length) { + return '[]'; + } + multiline = expr.elements.length > 1; + result = ['[', multiline ? newline : '']; + withIndent(function (indent) { + var i, iz; + for (i = 0, iz = expr.elements.length; i < iz; ++i) { + if (!expr.elements[i]) { + if (multiline) { + result.push(indent); + } + if (i + 1 === iz) { + result.push(','); + } + } else { + result.push(multiline ? indent : ''); + result.push(that.generateExpression(expr.elements[i], Precedence.Assignment, E_TTT)); + } + if (i + 1 < iz) { + result.push(',' + (multiline ? newline : space)); + } + } + }); + if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + result.push(multiline ? base : ''); + result.push(']'); + return result; + }, + + ClassExpression: function (expr, precedence, flags) { + var result, fragment; + result = ['class']; + if (expr.id) { + result = join(result, this.generateExpression(expr.id, Precedence.Sequence, E_TTT)); + } + if (expr.superClass) { + fragment = join('extends', this.generateExpression(expr.superClass, Precedence.Assignment, E_TTT)); + result = join(result, fragment); + } + result.push(space); + result.push(this.generateStatement(expr.body, S_TFFT)); + return result; + }, + + MethodDefinition: function (expr, precedence, flags) { + var result, fragment; + if (expr['static']) { + result = ['static' + space]; + } else { + result = []; + } + if (expr.kind === 'get' || expr.kind === 'set') { + fragment = [ + join(expr.kind, this.generatePropertyKey(expr.key, expr.computed)), + this.generateFunctionBody(expr.value) + ]; + } else { + fragment = [ + generateMethodPrefix(expr), + this.generatePropertyKey(expr.key, expr.computed), + this.generateFunctionBody(expr.value) + ]; + } + return join(result, fragment); + }, + + Property: function (expr, precedence, flags) { + if (expr.kind === 'get' || expr.kind === 'set') { + return [ + expr.kind, noEmptySpace(), + this.generatePropertyKey(expr.key, expr.computed), + this.generateFunctionBody(expr.value) + ]; + } + + if (expr.shorthand) { + return this.generatePropertyKey(expr.key, expr.computed); + } + + if (expr.method) { + return [ + generateMethodPrefix(expr), + this.generatePropertyKey(expr.key, expr.computed), + this.generateFunctionBody(expr.value) + ]; + } + return [ + this.generatePropertyKey(expr.key, expr.computed), + ':' + space, + this.generateExpression(expr.value, Precedence.Assignment, E_TTT) + ]; + }, + + ObjectExpression: function (expr, precedence, flags) { + var multiline, result, fragment, that = this; + + if (!expr.properties.length) { + return '{}'; + } + multiline = expr.properties.length > 1; + + withIndent(function () { + fragment = that.generateExpression(expr.properties[0], Precedence.Sequence, E_TTT); + }); + + if (!multiline) { + // issues 4 + // Do not transform from + // dejavu.Class.declare({ + // method2: function () {} + // }); + // to + // dejavu.Class.declare({method2: function () { + // }}); + if (!hasLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + return [ '{', space, fragment, space, '}' ]; + } + } + + withIndent(function (indent) { + var i, iz; + result = [ '{', newline, indent, fragment ]; + + if (multiline) { + result.push(',' + newline); + for (i = 1, iz = expr.properties.length; i < iz; ++i) { + result.push(indent); + result.push(that.generateExpression(expr.properties[i], Precedence.Sequence, E_TTT)); + if (i + 1 < iz) { + result.push(',' + newline); + } + } + } + }); + + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + result.push(base); + result.push('}'); + return result; + }, + + ObjectPattern: function (expr, precedence, flags) { + var result, i, iz, multiline, property, that = this; + if (!expr.properties.length) { + return '{}'; + } + + multiline = false; + if (expr.properties.length === 1) { + property = expr.properties[0]; + if (property.value.type !== Syntax.Identifier) { + multiline = true; + } + } else { + for (i = 0, iz = expr.properties.length; i < iz; ++i) { + property = expr.properties[i]; + if (!property.shorthand) { + multiline = true; + break; + } + } + } + result = ['{', multiline ? newline : '' ]; + + withIndent(function (indent) { + var i, iz; + for (i = 0, iz = expr.properties.length; i < iz; ++i) { + result.push(multiline ? indent : ''); + result.push(that.generateExpression(expr.properties[i], Precedence.Sequence, E_TTT)); + if (i + 1 < iz) { + result.push(',' + (multiline ? newline : space)); + } + } + }); + + if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + result.push(multiline ? base : ''); + result.push('}'); + return result; + }, + + ThisExpression: function (expr, precedence, flags) { + return 'this'; + }, + + Identifier: function (expr, precedence, flags) { + return generateIdentifier(expr); + }, + + ImportDefaultSpecifier: function (expr, precedence, flags) { + return generateIdentifier(expr.id); + }, + + ImportNamespaceSpecifier: function (expr, precedence, flags) { + var result = ['*']; + if (expr.id) { + result.push(space + 'as' + noEmptySpace() + generateIdentifier(expr.id)); + } + return result; + }, + + ImportSpecifier: function (expr, precedence, flags) { + return this.ExportSpecifier(expr, precedence, flags); + }, + + ExportSpecifier: function (expr, precedence, flags) { + var result = [ expr.id.name ]; + if (expr.name) { + result.push(noEmptySpace() + 'as' + noEmptySpace() + generateIdentifier(expr.name)); + } + return result; + }, + + Literal: function (expr, precedence, flags) { + var raw; + if (expr.hasOwnProperty('raw') && parse && extra.raw) { + try { + raw = parse(expr.raw).body[0].expression; + if (raw.type === Syntax.Literal) { + if (raw.value === expr.value) { + return expr.raw; + } + } + } catch (e) { + // not use raw property + } + } + + if (expr.value === null) { + return 'null'; + } + + if (typeof expr.value === 'string') { + return escapeString(expr.value); + } + + if (typeof expr.value === 'number') { + return generateNumber(expr.value); + } + + if (typeof expr.value === 'boolean') { + return expr.value ? 'true' : 'false'; + } + + return generateRegExp(expr.value); + }, + + GeneratorExpression: function (expr, precedence, flags) { + return this.ComprehensionExpression(expr, precedence, flags); + }, + + ComprehensionExpression: function (expr, precedence, flags) { + // GeneratorExpression should be parenthesized with (...), ComprehensionExpression with [...] + // Due to https://bugzilla.mozilla.org/show_bug.cgi?id=883468 position of expr.body can differ in Spidermonkey and ES6 + + var result, i, iz, fragment, that = this; + result = (expr.type === Syntax.GeneratorExpression) ? ['('] : ['[']; + + if (extra.moz.comprehensionExpressionStartsWithAssignment) { + fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT); + result.push(fragment); + } + + if (expr.blocks) { + withIndent(function () { + for (i = 0, iz = expr.blocks.length; i < iz; ++i) { + fragment = that.generateExpression(expr.blocks[i], Precedence.Sequence, E_TTT); + if (i > 0 || extra.moz.comprehensionExpressionStartsWithAssignment) { + result = join(result, fragment); + } else { + result.push(fragment); + } + } + }); + } + + if (expr.filter) { + result = join(result, 'if' + space); + fragment = this.generateExpression(expr.filter, Precedence.Sequence, E_TTT); + result = join(result, [ '(', fragment, ')' ]); + } + + if (!extra.moz.comprehensionExpressionStartsWithAssignment) { + fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT); + + result = join(result, fragment); + } + + result.push((expr.type === Syntax.GeneratorExpression) ? ')' : ']'); + return result; + }, + + ComprehensionBlock: function (expr, precedence, flags) { + var fragment; + if (expr.left.type === Syntax.VariableDeclaration) { + fragment = [ + expr.left.kind, noEmptySpace(), + this.generateStatement(expr.left.declarations[0], S_FFFF) + ]; + } else { + fragment = this.generateExpression(expr.left, Precedence.Call, E_TTT); + } + + fragment = join(fragment, expr.of ? 'of' : 'in'); + fragment = join(fragment, this.generateExpression(expr.right, Precedence.Sequence, E_TTT)); + + return [ 'for' + space + '(', fragment, ')' ]; + }, + + SpreadElement: function (expr, precedence, flags) { + return [ + '...', + this.generateExpression(expr.argument, Precedence.Assignment, E_TTT) + ]; + }, + + TaggedTemplateExpression: function (expr, precedence, flags) { + var itemFlags = E_TTF; + if (!(flags & F_ALLOW_CALL)) { + itemFlags = E_TFF; + } + var result = [ + this.generateExpression(expr.tag, Precedence.Call, itemFlags), + this.generateExpression(expr.quasi, Precedence.Primary, E_FFT) + ]; + return parenthesize(result, Precedence.TaggedTemplate, precedence); + }, + + TemplateElement: function (expr, precedence, flags) { + // Don't use "cooked". Since tagged template can use raw template + // representation. So if we do so, it breaks the script semantics. + return expr.value.raw; + }, + + TemplateLiteral: function (expr, precedence, flags) { + var result, i, iz; + result = [ '`' ]; + for (i = 0, iz = expr.quasis.length; i < iz; ++i) { + result.push(this.generateExpression(expr.quasis[i], Precedence.Primary, E_TTT)); + if (i + 1 < iz) { + result.push('${' + space); + result.push(this.generateExpression(expr.expressions[i], Precedence.Sequence, E_TTT)); + result.push(space + '}'); + } + } + result.push('`'); + return result; + }, + + ModuleSpecifier: function (expr, precedence, flags) { + return this.Literal(expr, precedence, flags); + } + + }; + + merge(CodeGenerator.prototype, CodeGenerator.Expression); + + CodeGenerator.prototype.generateExpression = function (expr, precedence, flags) { + var result, type; + + type = expr.type || Syntax.Property; + + if (extra.verbatim && expr.hasOwnProperty(extra.verbatim)) { + return generateVerbatim(expr, precedence); + } + + result = this[type](expr, precedence, flags); + + + if (extra.comment) { + result = addComments(expr,result); + } + return toSourceNodeWhenNeeded(result, expr); + }; + + CodeGenerator.prototype.generateStatement = function (stmt, flags) { + var result, + fragment; + + result = this[stmt.type](stmt, flags); + + // Attach comments + + if (extra.comment) { + result = addComments(stmt, result); + } + + fragment = toSourceNodeWhenNeeded(result).toString(); + if (stmt.type === Syntax.Program && !safeConcatenation && newline === '' && fragment.charAt(fragment.length - 1) === '\n') { + result = sourceMap ? toSourceNodeWhenNeeded(result).replaceRight(/\s+$/, '') : fragment.replace(/\s+$/, ''); + } + + return toSourceNodeWhenNeeded(result, stmt); + }; + + function generateInternal(node) { + var codegen; + + codegen = new CodeGenerator(); + if (isStatement(node)) { + return codegen.generateStatement(node, S_TFFF); + } + + if (isExpression(node)) { + return codegen.generateExpression(node, Precedence.Sequence, E_TTT); + } + + throw new Error('Unknown node type: ' + node.type); + } + + function generate(node, options) { + var defaultOptions = getDefaultOptions(), result, pair; + + if (options != null) { + // Obsolete options + // + // `options.indent` + // `options.base` + // + // Instead of them, we can use `option.format.indent`. + if (typeof options.indent === 'string') { + defaultOptions.format.indent.style = options.indent; + } + if (typeof options.base === 'number') { + defaultOptions.format.indent.base = options.base; + } + options = updateDeeply(defaultOptions, options); + indent = options.format.indent.style; + if (typeof options.base === 'string') { + base = options.base; + } else { + base = stringRepeat(indent, options.format.indent.base); + } + } else { + options = defaultOptions; + indent = options.format.indent.style; + base = stringRepeat(indent, options.format.indent.base); + } + json = options.format.json; + renumber = options.format.renumber; + hexadecimal = json ? false : options.format.hexadecimal; + quotes = json ? 'double' : options.format.quotes; + escapeless = options.format.escapeless; + newline = options.format.newline; + space = options.format.space; + if (options.format.compact) { + newline = space = indent = base = ''; + } + parentheses = options.format.parentheses; + semicolons = options.format.semicolons; + safeConcatenation = options.format.safeConcatenation; + directive = options.directive; + parse = json ? null : options.parse; + sourceMap = options.sourceMap; + sourceCode = options.sourceCode; + preserveBlankLines = options.format.preserveBlankLines && sourceCode !== null; + extra = options; + + if (sourceMap) { + if (!exports.browser) { + // We assume environment is node.js + // And prevent from including source-map by browserify + SourceNode = require('source-map').SourceNode; + } else { + SourceNode = global.sourceMap.SourceNode; + } + } + + result = generateInternal(node); + + if (!sourceMap) { + pair = {code: result.toString(), map: null}; + return options.sourceMapWithCode ? pair : pair.code; + } + + + pair = result.toStringWithSourceMap({ + file: options.file, + sourceRoot: options.sourceMapRoot + }); + + if (options.sourceContent) { + pair.map.setSourceContent(options.sourceMap, + options.sourceContent); + } + + if (options.sourceMapWithCode) { + return pair; + } + + return pair.map.toString(); + } + + FORMAT_MINIFY = { + indent: { + style: '', + base: 0 + }, + renumber: true, + hexadecimal: true, + quotes: 'auto', + escapeless: true, + compact: true, + parentheses: false, + semicolons: false + }; + + FORMAT_DEFAULTS = getDefaultOptions().format; + + exports.version = require('./package.json').version; + exports.generate = generate; + exports.attachComments = estraverse.attachComments; + exports.Precedence = updateDeeply({}, Precedence); + exports.browser = false; + exports.FORMAT_MINIFY = FORMAT_MINIFY; + exports.FORMAT_DEFAULTS = FORMAT_DEFAULTS; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ + + })(function(path) { + if (!modules[path]) throw new Error("unexpected require: " + path); + return modules[path]; + }, window.escodegen = { + browser: true, + }); +})(); diff --git a/lib/callbacks/escodegen-build.js b/lib/callbacks/escodegen-build.js new file mode 100644 index 00000000..0c62a0cf --- /dev/null +++ b/lib/callbacks/escodegen-build.js @@ -0,0 +1,10 @@ +"use strict"; + +var fs = require('fs'); +var fsp = require('path'); + +var templ = fs.readFileSync(fsp.join(__dirname, 'escodegen-template.js'), 'utf8'); +templ = templ.replace(/\{\{'([^']*)'\}\}/g, function(all, path) { + return fs.readFileSync(fsp.join(__dirname, path), 'utf8'); +}); +fs.writeFileSync(fsp.join(__dirname, 'escodegen-browser.js'), templ, 'utf8'); \ No newline at end of file diff --git a/lib/callbacks/escodegen-template.js b/lib/callbacks/escodegen-template.js new file mode 100644 index 00000000..b1854fb7 --- /dev/null +++ b/lib/callbacks/escodegen-template.js @@ -0,0 +1,29 @@ +"use strict"; +// template to expose escodegen server side +(function() { + // load utils.code + var modules = {}; + var mod = {}; + (function(module) { + {{'../../node_modules/escodegen/node_modules/esutils/lib/code.js'}} + })(mod); + modules.esutils = { + code: mod.exports, + }; + + // load estraverse + (function(exports) { + {{'../../node_modules/escodegen/node_modules/estraverse/estraverse.js'}} + })(modules.estraverse = {}); + + modules['./package.json'] = {{'../../package.json'}}; + + (function(require, exports) { + {{'../../node_modules/escodegen/escodegen.js'}} + })(function(path) { + if (!modules[path]) throw new Error("unexpected require: " + path); + return modules[path]; + }, window.escodegen = { + browser: true, + }); +})(); diff --git a/lib/callbacks/flows.js b/lib/callbacks/flows.js index 3ad524df..39e84d5b 100644 --- a/lib/callbacks/flows.js +++ b/lib/callbacks/flows.js @@ -1,380 +1,375 @@ -/*** Generated by streamline 0.10.17 (callbacks) - DO NOT EDIT ***/ var __rt=require('../callbacks/runtime').runtime(__filename, false),__func=__rt.__func,__cb=__rt.__cb; (function(exports) { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "use strict"; - var globals = require("../globals"); - var dir = ("../" + globals.runtime); - var builtins = require((dir + "/builtins")); - - - - - - - - - exports.each = function exports_each__1(_, array, fn, thisObj) { var __frame = { name: "exports_each__1", line: 45 }; return __func(_, this, arguments, exports_each__1, 0, __frame, function __$exports_each__1() { return (function __$exports_each__1(_) { - var __1 = ((array && array.length)); return (function __$exports_each__1(__then) { if (__1) { return array.forEach_(__cb(_, __frame, 1, 41, _, true), fn, thisObj); } else { __then(); } ; })(function __$exports_each__1() { return _(null, undefined); }); })(__cb(_, __frame, -44, 17, _, true)); }); }; - - - - - exports.map = function exports_map__2(_, array, fn, thisObj) { var __frame = { name: "exports_map__2", line: 51 }; return __func(_, this, arguments, exports_map__2, 0, __frame, function __$exports_map__2() { return (function __$exports_map__2(_) { - var __1 = array; return (function __$exports_map__2(__then) { if (__1) { return array.map_(__cb(_, __frame, 1, 23, _, true), fn, thisObj); } else { __then(); } ; })(function __$exports_map__2() { return _(null, array); }); })(__cb(_, __frame, -50, 17, _, true)); }); }; - - - - - exports.filter = function exports_filter__3(_, array, fn, thisObj) { var __frame = { name: "exports_filter__3", line: 57 }; return __func(_, this, arguments, exports_filter__3, 0, __frame, function __$exports_filter__3() { return (function __$exports_filter__3(_) { - var __1 = array; return (function __$exports_filter__3(__then) { if (__1) { return array.filter_(__cb(_, __frame, 1, 23, _, true), fn, thisObj); } else { __then(); } ; })(function __$exports_filter__3() { return _(null, array); }); })(__cb(_, __frame, -56, 17, _, true)); }); }; - - - - - exports.every = function exports_every__4(_, array, fn, thisObj) { var __frame = { name: "exports_every__4", line: 63 }; return __func(_, this, arguments, exports_every__4, 0, __frame, function __$exports_every__4() { return (function __$exports_every__4(_) { - var __1 = array; return (function __$exports_every__4(__then) { if (__1) { return array.every_(__cb(_, __frame, 1, 23, _, true), fn, thisObj); } else { __then(); } ; })(function __$exports_every__4() { return _(null, undefined); }); })(__cb(_, __frame, -62, 17, _, true)); }); }; - - - - - exports.some = function exports_some__5(_, array, fn, thisObj) { var __frame = { name: "exports_some__5", line: 69 }; return __func(_, this, arguments, exports_some__5, 0, __frame, function __$exports_some__5() { return (function __$exports_some__5(_) { - var __1 = array; return (function __$exports_some__5(__then) { if (__1) { return array.some_(__cb(_, __frame, 1, 23, _, true), fn, thisObj); } else { __then(); } ; })(function __$exports_some__5() { return _(null, undefined); }); })(__cb(_, __frame, -68, 17, _, true)); }); }; - - - - - exports.reduce = function exports_reduce__6(_, array, fn, v, thisObj) { var __frame = { name: "exports_reduce__6", line: 75 }; return __func(_, this, arguments, exports_reduce__6, 0, __frame, function __$exports_reduce__6() { return (function __$exports_reduce__6(_) { - var __1 = array; return (function __$exports_reduce__6(__then) { if (__1) { return array.reduce_(__cb(_, __frame, 1, 23, _, true), fn, v, thisObj); } else { __then(); } ; })(function __$exports_reduce__6() { return _(null, v); }); })(__cb(_, __frame, -74, 17, _, true)); }); }; - - - - - exports.reduceRight = function exports_reduceRight__7(_, array, fn, v, thisObj) { var __frame = { name: "exports_reduceRight__7", line: 81 }; return __func(_, this, arguments, exports_reduceRight__7, 0, __frame, function __$exports_reduceRight__7() { return (function __$exports_reduceRight__7(_) { - var __1 = array; return (function __$exports_reduceRight__7(__then) { if (__1) { return array.reduceRight_(__cb(_, __frame, 1, 23, _, true), fn, v, thisObj); } else { __then(); } ; })(function __$exports_reduceRight__7() { return _(null, v); }); })(__cb(_, __frame, -80, 17, _, true)); }); }; - - - - - - - - exports.sort = function exports_sort__8(_, array, compare, beg, end) { var __frame = { name: "exports_sort__8", line: 90 }; return __func(_, this, arguments, exports_sort__8, 0, __frame, function __$exports_sort__8() { return (function __$exports_sort__8(_) { - var __1 = array; return (function __$exports_sort__8(__then) { if (__1) { return array.sort_(__cb(_, __frame, 1, 23, _, true), compare, beg, end); } else { __then(); } ; })(function __$exports_sort__8() { return _(null, array); }); })(__cb(_, __frame, -89, 17, _, true)); }); }; - - - - - - - - - exports.eachKey = function exports_eachKey__9(_, obj, fn, thisObj) { var __frame = { name: "exports_eachKey__9", line: 100 }; return __func(_, this, arguments, exports_eachKey__9, 0, __frame, function __$exports_eachKey__9() { - return ((obj ? Object.keys(obj) : [])).forEach_(__cb(_, __frame, 1, 39, _, true), function __1(_, elt) { var __frame = { name: "__1", line: 101 }; return __func(_, this, arguments, __1, 0, __frame, function __$__1() { - return fn.call(thisObj, __cb(_, __frame, 1, 6, function __$__1() { _(); }, true), elt, obj[elt]); }); }); }); }; - - - - exports.spray = function(fns, max) { - return new function() { - - - var funnel = exports.funnel(max); - this.collect = function collect__1(_, count, trim) { var __this = this; var __frame = { name: "collect__1", line: 111 }; return __func(_, this, arguments, collect__1, 0, __frame, function __$collect__1() { - - - - - - - - - - - - - - - - - return (function(callback) { if ((typeof (callback) != "function")) { throw new Error("invalid call to collect: no callback") }; var results = (trim ? [] : new Array(fns.length)); count = ((count < 0) ? fns.length : Math.min(count, fns.length)); if ((count == 0)) { return callback(null, results) }; var collected = 0; for (var i = 0; (i < fns.length); i++) { (function(i) { funnel(function(err, result) { if (err) { return callback(err) }; if (trim) { results.push(result); } else { results[i] = result; }; if ((++collected == count)) { return callback(null, results) }; }, fns[i]); })(i); }; }).call(__this, __cb(_, __frame, 17, 7, _, true)); }); }; - - this.collectOne = function collectOne__2(_) { var result, __this = this; var __frame = { name: "collectOne__2", line: 130 }; return __func(_, this, arguments, collectOne__2, 0, __frame, function __$collectOne__2() { - return __this.collect(__cb(_, __frame, 1, 22, function ___(__0, __1) { result = __1; - return _(null, (result && result[0])); }, true), 1, true); }); }; - - this.collectAll = function collectAll__3(_) { var __this = this; var __frame = { name: "collectAll__3", line: 134 }; return __func(_, this, arguments, collectAll__3, 0, __frame, function __$collectAll__3() { - return __this.collect(__cb(_, __frame, 1, 16, _, true), -1, false); }); }; }; }; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - exports.funnel = builtins.funnel; - - - - - - - - - exports.handshake = function() { - var callback = null, notified = false; - return { - wait: __rt.streamlinify(function(cb) { - if (callback) { throw new Error("already waiting") }; - if (notified) { exports.setImmediate(cb); } else { - callback = cb; }; - notified = false; - }, 0), - notify: function() { - if (!callback) { notified = true; } else { - exports.setImmediate(callback); }; - callback = null; } }; }; - - - - - - - - - - - - - - exports.queue = function(options) { - options = (options || { }); - var max = ((options.max != null) ? options.max : -1); - var callback = null, q = [], pendingWrites = []; - return { - read: __rt.streamlinify(function(cb) { - if (callback) { throw new Error("already getting") }; - if ((q.length > 0)) { - var item = q.shift(); - - if ((q.length === 0)) { q = []; }; - exports.setImmediate(function() { - cb(null, item); }); - - if ((pendingWrites.length > 0)) { - var wr = pendingWrites.shift(); - exports.setImmediate(function() { - wr[0](null, wr[1]); }); } ; } - - - else { - callback = cb; } ; - - }, 0), - write: __rt.streamlinify(function(cb, item) { - if (this.put(item)) { - exports.setImmediate(function() { - cb(); }); } - - else { - pendingWrites.push([cb,item,]); } ; - - }, 0), - put: function(item, force) { - if (!callback) { - if ((((max >= 0) && (q.length >= max)) && !force)) { return false }; - q.push(item); } - else { - var cb = callback; - callback = null; - exports.setImmediate(function() { - cb(null, item); }); } ; - - - return true; }, - - end: function() { - this.put(undefined, true); } }; }; - - - - - - - - - exports.collect = function exports_collect__10(_, futures) { var __frame = { name: "exports_collect__10", line: 258 }; return __func(_, this, arguments, exports_collect__10, 0, __frame, function __$exports_collect__10() { return (function __$exports_collect__10(_) { - var __2 = futures; if (!__2) { return _(null, __2); } ; return futures.map_(__cb(_, __frame, 1, 28, _, true), function __1(_, future) { var __frame = { name: "__1", line: 259 }; return __func(_, this, arguments, __1, 0, __frame, function __$__1() { - return future(__cb(_, __frame, 1, 10, _, true)); }); }); })(__cb(_, __frame, -257, 17, _, true)); }); }; - - - - - var globals = require("../globals"); - exports.setContext = function(ctx) { - var old = globals.context; - globals.context = ctx; - return old; }; - - exports.getContext = function() { - return globals.context; }; - - - - - - - - - exports.trampoline = __rt.streamlinify(function(cb, fn, thisObj) { - fn = globals.withContext(fn, globals.context); - exports.setImmediate(function() { - fn.call(thisObj, cb); }); - - }, 0); - - - - - exports.setImmediate = ((typeof setImmediate === "function") ? setImmediate : function(fn) { - setTimeout(fn, 0); }); - - - - - - - var nextTick = (((typeof process === "object") && (typeof process.nextTick === "function")) ? process.nextTick : function(cb) { - cb(); }); - - - - exports.nextTick = function exports_nextTick__11(_) { var __frame = { name: "exports_nextTick__11", line: 304 }; return __func(_, this, arguments, exports_nextTick__11, 0, __frame, function __$exports_nextTick__11() { - return nextTick(__cb(_, __frame, 1, 2, function __$exports_nextTick__11() { _(); }, true)); }); }; - - - - - exports.setTimeout = function(fn, millis) { - - - - var max = 2147483647; - if ((millis > max)) { - return setTimeout(function() { - exports.setTimeout(fn, (millis - max)); - }, max); } - else { - return setTimeout(function() { - fn(false); - }, millis); } ; }; - - - - - exports.setInterval = function(fn, millis) { - return setInterval(function() { - fn(false); - }, millis); }; - - - - - - exports.sleep = function exports_sleep__12(_, millis) { var __frame = { name: "exports_sleep__12", line: 336 }; return __func(_, this, arguments, exports_sleep__12, 0, __frame, function __$exports_sleep__12() { - return setTimeout(__cb(_, __frame, 1, 9, _, true), millis); }); }; - - - exports.eventHandler = function(fn) { - return function() { - var that = this; - var args = Array.prototype.slice(arguments, 0); - return (function __1(_) { var __frame = { name: "__1", line: 344 }; return __func(_, this, arguments, __1, 0, __frame, function __$__1() { - return fn.apply_(__cb(_, __frame, 1, 14, _, true), that, args, 0); }); - })(function(err) { - if (err) { throw err }; }); }; }; - - - - - - exports.apply = function apply(_, fn, thisObj, args, index) { var __frame = { name: "apply", line: 353 }; return __func(_, this, arguments, apply, 0, __frame, function __$apply() { - return fn.apply_(__cb(_, __frame, 1, 12, _, true), thisObj, args, index); }); }; - - - - - - - exports.callWithTimeout = __rt.streamlinify(function(cb, fn, millis) { - var tid = setTimeout(function() { - if (cb) { - var ex = new Error("timeout"); - ex.code = "ETIMEOUT"; - ex.errno = "ETIMEOUT"; - cb(ex); - cb = null; } ; - - }, millis); - fn(function(err, result) { - if (cb) { - clearTimeout(tid); - cb(err, result); - cb = null; } ; }); - - - }, 0); - -})(((typeof exports !== "undefined") ? exports : (Streamline.flows = (Streamline.flows || {})))); +/*** Generated by streamline 0.10.17 (callbacks) - DO NOT EDIT ***/ var __rt=require('../callbacks/runtime').runtime(__filename, false),__func=__rt.__func,__cb=__rt.__cb; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + (function (exports) { + 'use strict'; + var globals = require('../globals'); + var dir = '../' + globals.runtime; + var builtins = require(dir + '/builtins'); + + + + + + + + + exports.each = function exports_each__1(_, array, fn, thisObj) { var __frame = { name: 'exports_each__1', line: 45 }; return __func(_, this, arguments, exports_each__1, 0, __frame, function __$exports_each__1() { + return function __$exports_each__1(_) { var __1 = array && array.length; return function __$exports_each__1(__then) { if (__1) { return array.forEach_(__cb(_, __frame, 1, 0, _, true, false), fn, thisObj); } else { __then(); } }(function __$exports_each__1() { return _(null, undefined); }); }(__cb(_, __frame, 0, 0, _, true, false)); }); }; + + + + + exports.map = function exports_map__2(_, array, fn, thisObj) { var __frame = { name: 'exports_map__2', line: 51 }; return __func(_, this, arguments, exports_map__2, 0, __frame, function __$exports_map__2() { + return function __$exports_map__2(_) { var __1 = array; return function __$exports_map__2(__then) { if (__1) { return array.map_(__cb(_, __frame, 1, 0, _, true, false), fn, thisObj); } else { __then(); } }(function __$exports_map__2() { return _(null, array); }); }(__cb(_, __frame, 0, 0, _, true, false)); }); }; + + + + + exports.filter = function exports_filter__3(_, array, fn, thisObj) { var __frame = { name: 'exports_filter__3', line: 57 }; return __func(_, this, arguments, exports_filter__3, 0, __frame, function __$exports_filter__3() { + return function __$exports_filter__3(_) { var __1 = array; return function __$exports_filter__3(__then) { if (__1) { return array.filter_(__cb(_, __frame, 1, 0, _, true, false), fn, thisObj); } else { __then(); } }(function __$exports_filter__3() { return _(null, array); }); }(__cb(_, __frame, 0, 0, _, true, false)); }); }; + + + + + exports.every = function exports_every__4(_, array, fn, thisObj) { var __frame = { name: 'exports_every__4', line: 63 }; return __func(_, this, arguments, exports_every__4, 0, __frame, function __$exports_every__4() { + return function __$exports_every__4(_) { var __1 = array; return function __$exports_every__4(__then) { if (__1) { return array.every_(__cb(_, __frame, 1, 0, _, true, false), fn, thisObj); } else { __then(); } }(function __$exports_every__4() { return _(null, undefined); }); }(__cb(_, __frame, 0, 0, _, true, false)); }); }; + + + + + exports.some = function exports_some__5(_, array, fn, thisObj) { var __frame = { name: 'exports_some__5', line: 69 }; return __func(_, this, arguments, exports_some__5, 0, __frame, function __$exports_some__5() { + return function __$exports_some__5(_) { var __1 = array; return function __$exports_some__5(__then) { if (__1) { return array.some_(__cb(_, __frame, 1, 0, _, true, false), fn, thisObj); } else { __then(); } }(function __$exports_some__5() { return _(null, undefined); }); }(__cb(_, __frame, 0, 0, _, true, false)); }); }; + + + + + exports.reduce = function exports_reduce__6(_, array, fn, v, thisObj) { var __frame = { name: 'exports_reduce__6', line: 75 }; return __func(_, this, arguments, exports_reduce__6, 0, __frame, function __$exports_reduce__6() { + return function __$exports_reduce__6(_) { var __1 = array; return function __$exports_reduce__6(__then) { if (__1) { return array.reduce_(__cb(_, __frame, 1, 0, _, true, false), fn, v, thisObj); } else { __then(); } }(function __$exports_reduce__6() { return _(null, v); }); }(__cb(_, __frame, 0, 0, _, true, false)); }); }; + + + + + exports.reduceRight = function exports_reduceRight__7(_, array, fn, v, thisObj) { var __frame = { name: 'exports_reduceRight__7', line: 81 }; return __func(_, this, arguments, exports_reduceRight__7, 0, __frame, function __$exports_reduceRight__7() { + return function __$exports_reduceRight__7(_) { var __1 = array; return function __$exports_reduceRight__7(__then) { if (__1) { return array.reduceRight_(__cb(_, __frame, 1, 0, _, true, false), fn, v, thisObj); } else { __then(); } }(function __$exports_reduceRight__7() { return _(null, v); }); }(__cb(_, __frame, 0, 0, _, true, false)); }); }; + + + + + + + + exports.sort = function exports_sort__8(_, array, compare, beg, end) { var __frame = { name: 'exports_sort__8', line: 90 }; return __func(_, this, arguments, exports_sort__8, 0, __frame, function __$exports_sort__8() { + return function __$exports_sort__8(_) { var __1 = array; return function __$exports_sort__8(__then) { if (__1) { return array.sort_(__cb(_, __frame, 1, 0, _, true, false), compare, beg, end); } else { __then(); } }(function __$exports_sort__8() { return _(null, array); }); }(__cb(_, __frame, 0, 0, _, true, false)); }); }; + + + + + + + + + exports.eachKey = function exports_eachKey__9(_, obj, fn, thisObj) { var __frame = { name: 'exports_eachKey__9', line: 100 }; return __func(_, this, arguments, exports_eachKey__9, 0, __frame, function __$exports_eachKey__9() { + return (obj ? Object.keys(obj) : []).forEach_(__cb(_, __frame, 1, 0, _, true, false), function __1(_, elt) { var __frame = { name: '__1', line: 101 }; return __func(_, this, arguments, __1, 0, __frame, function __$__1() { + return fn.call(thisObj, __cb(_, __frame, 1, 0, function __$__1() { _(); }, true, false), elt, obj[elt]); }); }); }); }; + + + + exports.spray = function (fns, max) { + return new function () { + + + var funnel = exports.funnel(max); + this.collect = function collect__1(_, count, trim) { var __this = this; var __frame = { name: 'collect__1', line: 111 }; return __func(_, this, arguments, collect__1, 0, __frame, function __$collect__1() { + return function (callback) { + if (typeof callback != 'function') throw new Error('invalid call to collect: no callback'); + var results = trim ? [] : new Array(fns.length); + count = count < 0 ? fns.length : Math.min(count, fns.length); + if (count == 0) return callback(null, results); + var collected = 0; + for (var i = 0; i < fns.length; i++) { + (function (i) { + funnel(function (err, result) { + if (err) return callback(err); + if (trim) results.push(result); else results[i] = result; + + if (++collected == count) return callback(null, results); }, fns[i]); }(i)); } }.call(__this, __cb(_, __frame, 17, 0, _, true, false)); }); }; + + + + + + this.collectOne = function collectOne__2(_) { var result, __this = this; var __frame = { name: 'collectOne__2', line: 130 }; return __func(_, this, arguments, collectOne__2, 0, __frame, function __$collectOne__2() { + return __this.collect(__cb(_, __frame, 1, 0, function ___(__0, __1) { result = __1; + return _(null, result && result[0]); }, true, false), 1, true); }); }; + + this.collectAll = function collectAll__3(_) { var __this = this; var __frame = { name: 'collectAll__3', line: 134 }; return __func(_, this, arguments, collectAll__3, 0, __frame, function __$collectAll__3() { + return __this.collect(__cb(_, __frame, 1, 0, _, true, false), -1, false); }); }; }(); }; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + exports.funnel = builtins.funnel; + + + + + + + + + exports.handshake = function () { + var callback = null, notified = false; + return { wait: __rt.streamlinify(function (cb) { + + if (callback) throw new Error('already waiting'); + if (notified) exports.setImmediate(cb); else callback = cb; + + notified = false; }, 0), notify: function () { + + + if (!callback) notified = true; else exports.setImmediate(callback); + + callback = null; } }; }; + + + + + + + + + + + + + + exports.queue = function (options) { + options = options || {}; + var max = options.max != null ? options.max : -1; + var callback = null, q = [], pendingWrites = []; + return { read: __rt.streamlinify(function (cb) { + + if (callback) throw new Error('already getting'); + if (q.length > 0) { + var item = q.shift(); + + if (q.length === 0) q = []; + exports.setImmediate(function () { + cb(null, item); }); + + if (pendingWrites.length > 0) { + var wr = pendingWrites.shift(); + exports.setImmediate(function () { + wr[0](null, wr[1]); }); } } else { + + + + callback = cb; } }, 0), write: __rt.streamlinify(function (cb, item) { + + + + if (this.put(item)) { + exports.setImmediate(function () { + cb(); }); } else { + + + pendingWrites.push([ cb, item ]); } }, 0), put: function (item, force) { + + + + if (!callback) { + if (max >= 0 && q.length >= max && !force) return false; + q.push(item); } else { + + var cb = callback; + callback = null; + exports.setImmediate(function () { + cb(null, item); }); } + + + return true; }, end: function () { + + + this.put(undefined, true); } }; }; + + + + + + + + + exports.collect = function exports_collect__10(_, futures) { var __frame = { name: 'exports_collect__10', line: 258 }; return __func(_, this, arguments, exports_collect__10, 0, __frame, function __$exports_collect__10() { + return function __$exports_collect__10(_) { var __2 = futures; if (!__2) { return _(null, __2); } return futures.map_(__cb(_, __frame, 1, 0, _, true, false), function __1(_, future) { var __frame = { name: '__1', line: 259 }; return __func(_, this, arguments, __1, 0, __frame, function __$__1() { + return future(__cb(_, __frame, 1, 0, _, true, false)); }); }); }(__cb(_, __frame, 0, 0, _, true, false)); }); }; + + + + + var globals = require('../globals'); + exports.setContext = function (ctx) { + var old = globals.context; + globals.context = ctx; + return old; }; + + exports.getContext = function () { + return globals.context; }; + + + + + + + + + exports.trampoline = __rt.streamlinify(function (cb, fn, thisObj) { + fn = globals.withContext(fn, globals.context); + exports.setImmediate(function () { + fn.call(thisObj, cb); }); }, 0); + + + + + + + exports.setImmediate = typeof setImmediate === 'function' ? setImmediate : function (fn) { + setTimeout(fn, 0); }; + + + + + + + var nextTick = typeof process === 'object' && typeof process.nextTick === 'function' ? process.nextTick : function (cb) { + cb(); }; + + + + exports.nextTick = function exports_nextTick__11(_) { var __frame = { name: 'exports_nextTick__11', line: 304 }; return __func(_, this, arguments, exports_nextTick__11, 0, __frame, function __$exports_nextTick__11() { + return nextTick(__cb(_, __frame, 1, 0, function __$exports_nextTick__11() { _(); }, true, false)); }); }; + + + + + exports.setTimeout = function (fn, millis) { + + + + var max = 2147483647; + if (millis > max) { + return setTimeout(function () { + exports.setTimeout(fn, millis - max); }, max); } else { + + + return setTimeout(function () { + fn(false); }, millis); } }; + + + + + + exports.setInterval = function (fn, millis) { + return setInterval(function () { + fn(false); }, millis); }; + + + + + + + exports.sleep = function exports_sleep__12(_, millis) { var __frame = { name: 'exports_sleep__12', line: 336 }; return __func(_, this, arguments, exports_sleep__12, 0, __frame, function __$exports_sleep__12() { + return setTimeout(__cb(_, __frame, 1, 0, _, true, false), millis); }); }; + + + exports.eventHandler = function (fn) { + return function () { + var that = this; + var args = Array.prototype.slice(arguments, 0); + return function __1(_) { var __frame = { name: '__1', line: 344 }; return __func(_, this, arguments, __1, 0, __frame, function __$__1() { + return fn.apply_(__cb(_, __frame, 1, 0, _, true, false), that, args, 0); }); }(function (err) { + + if (err) throw err; }); }; }; + + + + + + exports.apply = function apply(_, fn, thisObj, args, index) { var __frame = { name: 'apply', line: 353 }; return __func(_, this, arguments, apply, 0, __frame, function __$apply() { + return fn.apply_(__cb(_, __frame, 1, 0, _, true, false), thisObj, args, index); }); }; + + + + + + + exports.callWithTimeout = __rt.streamlinify(function (cb, fn, millis) { + var tid = setTimeout(function () { + if (cb) { + var ex = new Error('timeout'); + ex.code = 'ETIMEOUT'; + ex.errno = 'ETIMEOUT'; + cb(ex); + cb = null; } }, millis); + + + fn(function (err, result) { + if (cb) { + clearTimeout(tid); + cb(err, result); + cb = null; } }); }, 0); }(typeof exports !== 'undefined' ? exports : Streamline.flows = Streamline.flows || {})); \ No newline at end of file diff --git a/lib/callbacks/transform.js b/lib/callbacks/transform.js index deae9da3..fff3fb47 100644 --- a/lib/callbacks/transform.js +++ b/lib/callbacks/transform.js @@ -32,12 +32,13 @@ if (typeof exports !== 'undefined') { var esprima = require('esprima'); var escodegen = require('escodegen'); } else { - // see later + var esprima = window.esprima; + var escodegen = window.escodegen; }(function(exports) { "use strict"; /// * `version = transform.version` /// current version of the transformation algorithm. - exports.version = require("../version").version + " (callbacks - esprima)"; + exports.version = require("../version").version + " (callbacks)"; var Syntax = esprima.Syntax; // ES6 forms that we don't transform yet diff --git a/lib/compiler/build.sh b/lib/compiler/build.sh index 60df6383..3bff424e 100755 --- a/lib/compiler/build.sh +++ b/lib/compiler/build.sh @@ -37,13 +37,10 @@ bin/_node -lp -v -f -o $TEST/callbacks/ -c $TEST/flows-test._js bin/_node --generators -v -f -o $TEST/generators/ -c $TEST/*._js cat lib/callbacks/require-stub.js \ - deps/narcissus/lib/jsdefs.js \ - deps/narcissus/lib/jslex.js \ - deps/narcissus/lib/jsparse.js \ - deps/narcissus/lib/jsdecomp.js \ + node_modules/esprima/esprima.js \ + lib/callbacks/escodegen-browser.js \ lib/version.js \ lib/util/source-map.js \ - lib/callbacks/format.js \ lib/callbacks/transform.js \ lib/util/future.js \ lib/callbacks/runtime.js \ diff --git a/lib/fibers-fast/builtins.js b/lib/fibers-fast/builtins.js index 147c8268..1a76e923 100644 --- a/lib/fibers-fast/builtins.js +++ b/lib/fibers-fast/builtins.js @@ -1,4 +1,4 @@ -/*** Generated by streamline 0.10.17 (fibers-fast) --aggressive - DO NOT EDIT ***/var fstreamline__ = require("../fibers-fast/runtime");(function(){})(); fstreamline__.create((function(_) { /** +/*** Generated by streamline 0.10.17 (fibers-fast) --aggressive - DO NOT EDIT ***/var fstreamline__ = require("../fibers-fast/runtime");(function(){})(); fstreamline__.create(function(_) { /** * Copyright (c) 2012 Bruno Jouhier * MIT License */ @@ -158,7 +158,7 @@ } else { var fun = funnel(par); result = this.map(function(elt, i) { - return fstreamline__.spin(null, fun, [false, function(_) { + return fstreamline__.spin(null, fun, [false , function(_) { return fn.call(thisObj, _, elt, i); }], 0); }); @@ -217,7 +217,7 @@ } else { var fun = funnel(par); var futures = this.map(function(elt) { - return fstreamline__.spin(null, fun, [false, function(_) { + return fstreamline__.spin(null, fun, [false , function(_) { return fn.call(thisObj, _, elt); }], 0); }); @@ -250,7 +250,7 @@ } else { var fun = funnel(par); var futures = this.map(function(elt) { - return fstreamline__.spin(null, fun, [false, function(_) { + return fstreamline__.spin(null, fun, [false , function(_) { return fn.call(thisObj, _, elt); }], 0); }); @@ -368,6 +368,6 @@ } }); })(typeof exports !== 'undefined' ? exports : (Streamline.builtins = Streamline.builtins || {})); -}),0)( function(err) { +},0)( function(err) { if (err) throw err; }); diff --git a/lib/fibers-fast/flows.js b/lib/fibers-fast/flows.js index 37d4e709..647a0b4b 100644 --- a/lib/fibers-fast/flows.js +++ b/lib/fibers-fast/flows.js @@ -1,4 +1,4 @@ -/*** Generated by streamline 0.10.17 (fibers-fast) --aggressive - DO NOT EDIT ***/var fstreamline__ = require("../fibers-fast/runtime");(function(){})(); fstreamline__.create((function(_) { /** +/*** Generated by streamline 0.10.17 (fibers-fast) --aggressive - DO NOT EDIT ***/var fstreamline__ = require("../fibers-fast/runtime");(function(){})(); fstreamline__.create(function(_) { /** * Copyright (c) 2011 Bruno Jouhier * * Permission is hereby granted, free of charge, to any person @@ -122,10 +122,10 @@ if (trim) results.push(result); else results[i] = result; if (++collected == count) return callback(null, results); - }, fns[i]) + } , fns[i]) })(i); } - }), "call", [this, _], 1) + }, "call", [this, _], 1) } this.collectOne = function(_) { var result = this.collect(_, 1, true); @@ -281,7 +281,7 @@ exports.trampoline = fstreamline__.star(function(cb, fn, thisObj) { fn = globals.withContext(fn, globals.context); exports.setImmediate(function() { - fstreamline__.createBound(fn,'call',1)(thisObj, cb); + fstreamline__.createBound(fn,'call',1)(thisObj , cb); }); }, 0); @@ -341,9 +341,9 @@ return function() { var that = this; var args = Array.prototype.slice(arguments, 0); - return fstreamline__.create((function(_) { + return fstreamline__.create(function(_) { return fn.apply_(_, that, args, 0); - }),0)( function(err) { + },0)( function(err) { if (err) throw err; }); }; @@ -379,6 +379,6 @@ })(typeof exports !== 'undefined' ? exports : (Streamline.flows = Streamline.flows || {})); -}),0)( function(err) { +},0)( function(err) { if (err) throw err; }); diff --git a/lib/fibers-fast/transform.js b/lib/fibers-fast/transform.js index c9d4b19c..0470eb9a 100644 --- a/lib/fibers-fast/transform.js +++ b/lib/fibers-fast/transform.js @@ -23,11 +23,11 @@ if (typeof exports !== 'undefined') { } (function(exports) { exports.transform = transform; - exports.version = require("../version").version + " (fibers-fast --esprima)"; + exports.version = require("../version").version + " (fibers-fast)"; // hack to fix #123 exports.transform.version = exports.version; -var Walker = require('../fibers/walker-esprima'); +var Walker = require('../fibers/walker'); function aggressiveReplace(source) { // arr.forEach_(_, function(_, item) {...}) --> arr.forEach(function(item, __, _) {...}) diff --git a/lib/fibers/builtins.js b/lib/fibers/builtins.js index c23c8975..4042c4c4 100644 --- a/lib/fibers/builtins.js +++ b/lib/fibers/builtins.js @@ -128,10 +128,10 @@ var len = this.length; if (par === 1 || len <= 1) { for (var i = 0; i < len; i++) { - if (has.call(this, i)) fstreamline__.invoke(fn, "call", [thisObj, _, this[i], i], 1); + if (has.call(this, i)) fstreamline__.invoke(fn, "call", [thisObj , _ , this[i] , i], 1); } } else { - fstreamline__.invoke(this, "map_", [_, par, fn, thisObj], 0); + fstreamline__.invoke(this, "map_", [_ , par , fn , thisObj], 0); } return this; }, 0,__filename,124) @@ -153,13 +153,13 @@ if (par === 1 || len <= 1) { result = new Array(len); for (var i = 0; i < len; i++) { - if (has.call(this, i)) result[i] = fstreamline__.invoke(fn, "call", [thisObj, _, this[i], i], 1); + if (has.call(this, i)) result[i] = fstreamline__.invoke(fn, "call", [thisObj , _ , this[i] , i], 1); } } else { var fun = funnel(par); result = this.map(function(elt, i) { return fun(false, fstreamline__.create(function(_) { - return fstreamline__.invoke(fn, "call", [thisObj, _, elt, i], 1); + return fstreamline__.invoke(fn, "call", [thisObj , _ , elt , i], 1); }, 0,__filename,161)); }); for (var i = 0; i < len; i++) { @@ -186,13 +186,13 @@ for (var i = 0; i < len; i++) { if (has.call(this, i)) { var elt = this[i]; - if (fstreamline__.invoke(fn, "call", [thisObj, _, elt], 1)) result.push(elt); + if (fstreamline__.invoke(fn, "call", [thisObj , _ , elt], 1)) result.push(elt); } } } else { - fstreamline__.invoke(this, "map_", [_, par, fstreamline__.create(function(_, elt) { - if (fstreamline__.invoke(fn, "call", [thisObj, _, elt], 1)) result.push(elt); - }, 0,__filename,193), thisObj], 0); + fstreamline__.invoke(this, "map_", [_ , par , fstreamline__.create(function(_, elt) { + if (fstreamline__.invoke(fn, "call", [thisObj , _ , elt], 1)) result.push(elt); + }, 0,__filename,193) , thisObj], 0); } return result; }, 0,__filename,179) @@ -212,13 +212,13 @@ if (par === 1 || len <= 1) { for (var i = 0; i < len; i++) { - if (has.call(this, i) && !fstreamline__.invoke(fn, "call", [thisObj, _, this[i]], 1)) return false; + if (has.call(this, i) && !fstreamline__.invoke(fn, "call", [thisObj , _ , this[i]], 1)) return false; } } else { var fun = funnel(par); var futures = this.map(function(elt) { return fun(false, fstreamline__.create(function(_) { - return fstreamline__.invoke(fn, "call", [thisObj, _, elt], 1); + return fstreamline__.invoke(fn, "call", [thisObj , _ , elt], 1); }, 0,__filename,220)); }); for (var i = 0; i < len; i++) { @@ -245,13 +245,13 @@ var len = this.length; if (par === 1 || len <= 1) { for (var i = 0; i < len; i++) { - if (has.call(this, i) && fstreamline__.invoke(fn, "call", [thisObj, _, this[i]], 1)) return true; + if (has.call(this, i) && fstreamline__.invoke(fn, "call", [thisObj , _ , this[i]], 1)) return true; } } else { var fun = funnel(par); var futures = this.map(function(elt) { return fun(false, fstreamline__.create(function(_) { - return fstreamline__.invoke(fn, "call", [thisObj, _, elt], 1); + return fstreamline__.invoke(fn, "call", [thisObj , _ , elt], 1); }, 0,__filename,253)); }); for (var i = 0; i < len; i++) { @@ -275,7 +275,7 @@ thisObj = thisObj !== undefined ? thisObj : this; var len = this.length; for (var i = 0; i < len; i++) { - if (has.call(this, i)) v = fstreamline__.invoke(fn, "call", [thisObj, _, v, this[i], i, this], 1); + if (has.call(this, i)) v = fstreamline__.invoke(fn, "call", [thisObj , _ , v , this[i] , i , this], 1); } return v; }, 0,__filename,274) @@ -291,7 +291,7 @@ thisObj = thisObj !== undefined ? thisObj : this; var len = this.length; for (var i = len - 1; i >= 0; i--) { - if (has.call(this, i)) v = fstreamline__.invoke(fn, "call", [thisObj, _, v, this[i], i, this], 1); + if (has.call(this, i)) v = fstreamline__.invoke(fn, "call", [thisObj , _ , v , this[i] , i , this], 1); } return v; }, 0,__filename,290) @@ -314,7 +314,7 @@ if (beg >= end) return; if (end == beg + 1) { - if (fstreamline__.invoke(null, compare, [_, array[beg], array[end]], 0) > 0) { + if (fstreamline__.invoke(null, compare, [_ , array[beg] , array[end]], 0) > 0) { var tmp = array[beg]; array[beg] = array[end]; array[end] = tmp; @@ -328,8 +328,8 @@ var nend = end; while (nbeg <= nend) { - while (nbeg < end && fstreamline__.invoke(null, compare, [_, array[nbeg], o], 0) < 0) nbeg++; - while (beg < nend && fstreamline__.invoke(null, compare, [_, o, array[nend]], 0) < 0) nend--; + while (nbeg < end && fstreamline__.invoke(null, compare, [_ , array[nbeg] , o], 0) < 0) nbeg++; + while (beg < nend && fstreamline__.invoke(null, compare, [_ , o , array[nend]], 0) < 0) nend--; if (nbeg <= nend) { var tmp = array[nbeg]; @@ -340,10 +340,10 @@ } } - if (nbeg < end) (_qsort_.fstreamlineFunction || 0)(_, nbeg, end); - if (beg < nend) (_qsort_.fstreamlineFunction || 0)(_, beg, nend); + if (nbeg < end) (_qsort_.fstreamlineFunction || 0)(_ , nbeg , end); + if (beg < nend) (_qsort_.fstreamlineFunction || 0)(_ , beg , nend); } - (_qsort_.fstreamlineFunction || 0)(_, beg, end); + (_qsort_.fstreamlineFunction || 0)(_ , beg , end); return array; }, 0,__filename,308) }); diff --git a/lib/fibers/flows.js b/lib/fibers/flows.js index e12bded5..07c710ae 100644 --- a/lib/fibers/flows.js +++ b/lib/fibers/flows.js @@ -43,43 +43,43 @@ /// applies `fn` sequentially to the elements of `array`. /// `fn` is called as `fn(_, elt, i)`. exports.each = fstreamline__.create(function(_, array, fn, thisObj) { - return (array && array.length) ? fstreamline__.invoke(array, "forEach_", [_, fn, thisObj], 0) : undefined; + return (array && array.length) ? fstreamline__.invoke(array, "forEach_", [_ , fn , thisObj], 0) : undefined; }, 0,__filename,45); /// * `result = flows.map(_, array, fn, [thisObj])` /// transforms `array` by applying `fn` to each element in turn. /// `fn` is called as `fn(_, elt, i)`. exports.map = fstreamline__.create(function(_, array, fn, thisObj) { - return array ? fstreamline__.invoke(array, "map_", [_, fn, thisObj], 0) : array; + return array ? fstreamline__.invoke(array, "map_", [_ , fn , thisObj], 0) : array; }, 0,__filename,51); /// * `result = flows.filter(_, array, fn, [thisObj])` /// generates a new array that only contains the elements that satisfy the `fn` predicate. /// `fn` is called as `fn(_, elt)`. exports.filter = fstreamline__.create(function(_, array, fn, thisObj) { - return array ? fstreamline__.invoke(array, "filter_", [_, fn, thisObj], 0) : array; + return array ? fstreamline__.invoke(array, "filter_", [_ , fn , thisObj], 0) : array; }, 0,__filename,57); /// * `bool = flows.every(_, array, fn, [thisObj])` /// returns true if `fn` is true on every element (if `array` is empty too). /// `fn` is called as `fn(_, elt)`. exports.every = fstreamline__.create(function(_, array, fn, thisObj) { - return array ? fstreamline__.invoke(array, "every_", [_, fn, thisObj], 0) : undefined; + return array ? fstreamline__.invoke(array, "every_", [_ , fn , thisObj], 0) : undefined; }, 0,__filename,63); /// * `bool = flows.some(_, array, fn, [thisObj])` /// returns true if `fn` is true for at least one element. /// `fn` is called as `fn(_, elt)`. exports.some = fstreamline__.create(function(_, array, fn, thisObj) { - return array ? fstreamline__.invoke(array, "some_", [_, fn, thisObj], 0) : undefined; + return array ? fstreamline__.invoke(array, "some_", [_ , fn , thisObj], 0) : undefined; }, 0,__filename,69); /// * `result = flows.reduce(_, array, fn, val, [thisObj])` /// reduces by applying `fn` to each element. /// `fn` is called as `val = fn(_, val, elt, i, array)`. exports.reduce = fstreamline__.create(function(_, array, fn, v, thisObj) { - return array ? fstreamline__.invoke(array, "reduce_", [_, fn, v, thisObj], 0) : v; + return array ? fstreamline__.invoke(array, "reduce_", [_ , fn , v , thisObj], 0) : v; }, 0,__filename,75); /// * `result = flows.reduceRight(_, array, fn, val, [thisObj])` /// reduces from end to start by applying `fn` to each element. /// `fn` is called as `val = fn(_, val, elt, i, array)`. exports.reduceRight = fstreamline__.create(function(_, array, fn, v, thisObj) { - return array ? fstreamline__.invoke(array, "reduceRight_", [_, fn, v, thisObj], 0) : v; + return array ? fstreamline__.invoke(array, "reduceRight_", [_ , fn , v , thisObj], 0) : v; }, 0,__filename,81); /// * `array = flows.sort(_, array, compare, [beg], [end])` @@ -88,7 +88,7 @@ /// /// Note: this function _changes_ the original array (and returns it) exports.sort = fstreamline__.create(function(_, array, compare, beg, end) { - return array ? fstreamline__.invoke(array, "sort_", [_, compare, beg, end], 0) : array; + return array ? fstreamline__.invoke(array, "sort_", [_ , compare , beg , end], 0) : array; }, 0,__filename,90); /// /// ## Object utility (obsolete) @@ -98,8 +98,8 @@ /// * `flows.eachKey(_, obj, fn)` /// calls `fn(_, key, obj[key])` for every `key` in `obj`. exports.eachKey = fstreamline__.create(function(_, obj, fn, thisObj) { - return fstreamline__.invoke((obj ? Object.keys(obj) : []), "forEach_", [_, fstreamline__.create(function(_, elt) { - fstreamline__.invoke(fn, "call", [thisObj, _, elt, obj[elt]], 1); + return fstreamline__.invoke(obj ? Object.keys(obj) : [], "forEach_", [_ , fstreamline__.create(function(_, elt) { + fstreamline__.invoke(fn, "call", [thisObj , _ , elt , obj[elt]], 1); }, 0,__filename,101)], 0); }, 0,__filename,100); // deprecated -- don't document @@ -109,7 +109,7 @@ function() { var funnel = exports.funnel(max); this.collect = fstreamline__.create(function(_, count, trim) { - return fstreamline__.invoke((function(callback) { + return fstreamline__.invoke(function(callback) { if (typeof(callback) != "function") throw new Error("invalid call to collect: no callback"); var results = trim ? [] : new Array(fns.length); count = count < 0 ? fns.length : Math.min(count, fns.length); @@ -125,14 +125,14 @@ }, fns[i]); })(i); } - }), "call", [this, _], 1); + }, "call", [this , _], 1); }, 0,__filename,111); this.collectOne = fstreamline__.create(function(_) { - var result = fstreamline__.invoke(this, "collect", [_, 1, true], 0); + var result = fstreamline__.invoke(this, "collect", [_ , 1 , true], 0); return result && result[0]; }, 0,__filename,130); this.collectAll = fstreamline__.create(function(_) { - return fstreamline__.invoke(this, "collect", [_, -1, false], 0); + return fstreamline__.invoke(this, "collect", [_ , -1 , false], 0); }, 0,__filename,134); }; @@ -256,7 +256,7 @@ /// * `results = flows.collect(_, futures)` /// collects the results of an array of futures exports.collect = fstreamline__.create(function(_, futures) { - return futures && fstreamline__.invoke(futures, "map_", [_, fstreamline__.create(function(_, future) { + return futures && fstreamline__.invoke(futures, "map_", [_ , fstreamline__.create(function(_, future) { return fstreamline__.invoke(null, future, [_], 0); }, 0,__filename,259)], 0); }, 0,__filename,258); @@ -334,16 +334,16 @@ /// * `flows.sleep(_, millis)` /// Sleeps `millis` ms. exports.sleep = fstreamline__.create(function(_, millis) { - return fstreamline__.invoke(null, setTimeout, [_, millis], 0); + return fstreamline__.invoke(null, setTimeout, [_ , millis], 0); }, 0,__filename,336); exports.eventHandler = function(fn) { return function() { var that = this; var args = Array.prototype.slice(arguments, 0); - return fstreamline__.create((function(_) { - return fstreamline__.invoke(fn, "apply_", [_, that, args, 0], 0); - }), 0,__filename,344)( function(err) { + return (fstreamline__.create(function(_) { + return fstreamline__.invoke(fn, "apply_", [_ , that , args , 0], 0); + }, 0,__filename,344))( function(err) { if (err) throw err; }); }; @@ -351,7 +351,7 @@ // Obsolete. Use `fn.apply_` instead. exports.apply = fstreamline__.create(function apply(_, fn, thisObj, args, index) { - return fstreamline__.invoke(fn, "apply_", [_, thisObj, args, index], 0); + return fstreamline__.invoke(fn, "apply_", [_ , thisObj , args , index], 0); }, 0,__filename,353); /// diff --git a/lib/fibers/transform.js b/lib/fibers/transform.js index 42a35143..86fce561 100644 --- a/lib/fibers/transform.js +++ b/lib/fibers/transform.js @@ -23,11 +23,11 @@ if (typeof exports !== 'undefined') { } (function(exports) { exports.transform = transform; - exports.version = require("../version").version + " (fibers --esprima)"; + exports.version = require("../version").version + " (fibers)"; // hack to fix #123 exports.transform.version = exports.version; -var Walker = require('../fibers/walker-esprima'); +var Walker = require('../fibers/walker'); // TODO ensure `foo(_)` calls have a bounding fiber. streamline is smart enough to allow this: // ~function() { foo(_) }(); diff --git a/lib/fibers/walker-esprima.js b/lib/fibers/walker-esprima.js deleted file mode 100644 index a5ea171f..00000000 --- a/lib/fibers/walker-esprima.js +++ /dev/null @@ -1,289 +0,0 @@ -// Copyright 2011 Marcel Laverdet -"use strict"; -if (typeof exports !== 'undefined') { - module.exports = Walker; -} else { - Streamline.walker = Walker; -} - -/** - * It seems that Narcissus lacks a reasonable node walker. This implements a simple walker which - * lets you walk a tree linearly, in terms of source code, and only subscribe to the parts that - * you're interested in. - */ -function Walker(visitors) { - return function walk(node) { - var type = node.type; - if (type === undefined) { - throw new Error('Trying to walk unknown node!'); - } - switch (type) { - case 'AssignmentExpression': - if (visitors[type]) { - visitors[type].call(node, node.left, node.right); - } else { - walk(node.left); - walk(node.right); - } - break; - - case 'ArrayExpression': - if (visitors[type]) { - visitors[type].call(node, node.elements); - } else { - node.elements.map(walk); - } - break; - - case 'ArrowFunctionExpression': - throw new Error("NIY"); - - case 'BinaryExpression': - case 'LogicalExpression': - if (visitors[type]) { - visitors[type].call(node, node.operator, node.left, node.right); - } else { - walk(node.left); - walk(node.right); - } - break; - - case 'BlockStatement': - case 'Program': - if (visitors[type]) { - visitors[type].call(node, node.body); - } else { - node.body.map(walk); - } - break; - - case 'BreakStatement': - case 'ContinueStatement': - if (visitors[type]) { - visitors[type].call(node, node.label && node.label.name); - } - break; - - case 'CallExpression': - case 'NewExpression': - if (visitors[type]) { - visitors[type].call(node, node.callee, node.arguments); - } else { - walk(node.callee); - node.arguments.map(walk); - } - break; - - case 'CatchClause': - if (visitors[type]) { - visitors[type].call(node, node.body); - } else { - walk(node.body); - } - break; - - case 'ConditionalExpression': - case 'IfStatement': - if (visitors[type]) { - visitors[type].call(node, node.test, node.consequent, node.alternate); - } else { - walk(node.test); - walk(node.consequent); - node.alternate && walk(node.alternate); - } - break; - - case 'DebuggerStatement': - case 'EmptyStatement': - case 'ThisExpression': - if (visitors[type]) { - visitors[type].call(node); - } - break; - - case 'DoWhileStatement': - if (visitors[type]) { - visitors[type].call(node, node.test, node.body); - } else { - walk(node.body); - walk(node.test); - } - break; - - case 'ExpressionStatement': - if (visitors[type]) { - visitors[type].call(node, node.expression); - } else { - node.expression && walk(node.expression); - } - break; - - case 'ForStatement': - if (visitors[type]) { - visitors[type].call(node, node.init, node.test, node.update, node.body); - } else { - node.init && walk(node.init); - node.test && walk(node.test); - node.update && walk(node.update); - walk(node.body); - } - break; - - case 'ForInStatement': - if (visitors[type]) { - visitors[type].call(node, node.left, node.right, node.body); - } else { - walk(node.left); - walk(node.right); - walk(node.body); - } - break; - - case 'FunctionDeclaration': - case 'FunctionExpression': - if (visitors[type] || visitors['Function']) { - (visitors[type] || visitors['Function']).call(node, node.id && node.id.name, node.params, node.body.body); - } else { - node.body.body.map(walk); - } - break; - - case 'Identifier': - if (visitors[type]) { - visitors[type].call(node, node.name); - } - break; - - case 'LabeledStatement': - if (visitors[type]) { - visitors[type].call(node, node.label.id, node.body); - } else { - walk(node.body); - } - break; - - case 'Literal': - if (visitors[type]) { - visitors[type].call(node, node.value); - } - break; - - case 'MemberExpression': - if (visitors[type]) { - visitors[type].call(node, node.object, node.property); - } else { - walk(node.object); - } - break; - - case 'ObjectExpression': - if (visitors[type]) { - visitors[type].call(node, node.properties); - } else { - node.properties.map(walk); - } - break; - - case 'Property': - if (visitors[type]) { - visitors[type].call(node, node.key, node.value); - } else { - walk(node.value); - } - break; - - case 'ReturnStatement': - case 'ThrowStatement': - if (visitors[type]) { - visitors[type].call(node, node.argument); - } else { - node.argument && walk(node.argument); - } - break; - - case 'SequenceExpression': - if (visitors[type]) { - visitors[type].call(node, node.expressions); - } else { - node.expressions.map(walk); - } - break; - - case 'SwitchCase': - if (visitors[type]) { - visitors[type].call(node, node.test, node.consequent); - } else { - node.test && walk(node.test); - node.consequent.map(walk); - Walker.insideCase = false; - } - break; - - case 'SwitchStatement': - if (visitors[type]) { - visitors[type].call(node, node.discriminant, node.cases); - } else { - walk(node.discriminant); - node.cases.map(walk); - } - break; - - case 'TryStatement': - if (visitors[type]) { - visitors[type].call(node, node.block, node.handlers, node.finalizer); - } else { - walk(node.block); - node.handlers.map(walk); - node.finalizer && walk(node.finalizer); - } - break; - - case 'UnaryExpression': - case 'UpdateExpression': - if (visitors[type]) { - visitors[type].call(node, node.operator, node.argument); - } else { - walk(node.argument); - } - break; - - case 'VariableDeclaration': - if (visitors[type]) { - visitors[type].call(node, node.declarations); - } else { - node.declarations.map(walk); - } - break; - - case 'VariableDeclarator': - if (visitors[type]) { - visitors[type].call(node, node.id.name, node.init); - } else { - node.init && walk(node.init); - } - break; - - case 'WhileStatement': - if (visitors[type]) { - visitors[type].call(node, node.test, node.body); - } else { - walk(node.test); - walk(node.body); - } - break; - - case 'WithStatement': - if (visitors[type]) { - visitors[type].call(node, node.object, node.body); - } else { - walk(node.object); - walk(node.body); - } - break; - - - default: - throw new Error("unhandled node type: " + node.type); - } - }; -} diff --git a/lib/fibers/walker.js b/lib/fibers/walker.js index 767549c7..a5ea171f 100644 --- a/lib/fibers/walker.js +++ b/lib/fibers/walker.js @@ -2,10 +2,8 @@ "use strict"; if (typeof exports !== 'undefined') { module.exports = Walker; - var t = require('../../deps/narcissus').definitions.tokenIds; } else { Streamline.walker = Walker; - var t = Narcissus.definitions.tokenIds; } /** @@ -14,233 +12,278 @@ if (typeof exports !== 'undefined') { * you're interested in. */ function Walker(visitors) { - for (var ii in visitors) { - visitors[t[ii.toUpperCase()]] = visitors[ii]; - } return function walk(node) { var type = node.type; if (type === undefined) { throw new Error('Trying to walk unknown node!'); } switch (type) { - case t.FUNCTION: - case t.GETTER: - case t.SETTER: + case 'AssignmentExpression': if (visitors[type]) { - visitors[type].call(node, node.name, node.params, node.body.children); + visitors[type].call(node, node.left, node.right); } else { - node.body.children.map(walk); + walk(node.left); + walk(node.right); } break; - case t.LET_BLOCK: + case 'ArrayExpression': if (visitors[type]) { - visitors[type].call(node, node.variables, node.expression || node.block); + visitors[type].call(node, node.elements); } else { - walk(node.variables); - walk(node.expression || node.block); + node.elements.map(walk); } break; - case t.IF: + case 'ArrowFunctionExpression': + throw new Error("NIY"); + + case 'BinaryExpression': + case 'LogicalExpression': if (visitors[type]) { - visitors[type].call(node, node.condition, node.thenPart, node.elsePart); + visitors[type].call(node, node.operator, node.left, node.right); } else { - walk(node.condition); - walk(node.thenPart); - node.elsePart && walk(node.elsePart); + walk(node.left); + walk(node.right); } break; - case t.SWITCH: + case 'BlockStatement': + case 'Program': if (visitors[type]) { - visitors[type].call(node, node.discriminant, node.cases); + visitors[type].call(node, node.body); } else { - walk(node.discriminant); - node.cases.map(walk); + node.body.map(walk); + } + break; + + case 'BreakStatement': + case 'ContinueStatement': + if (visitors[type]) { + visitors[type].call(node, node.label && node.label.name); } break; - case t.CASE: - case t.DEFAULT: + case 'CallExpression': + case 'NewExpression': if (visitors[type]) { - visitors[type].call(node, node.caselabel, node.statements); + visitors[type].call(node, node.callee, node.arguments); } else { - node.caseLabel && walk(node.caseLabel); - walk(node.statements); - Walker.insideCase = false; + walk(node.callee); + node.arguments.map(walk); } break; - case t.FOR: + case 'CatchClause': if (visitors[type]) { - visitors[type].call(node, node.setup, node.condition, node.update, node.body); + visitors[type].call(node, node.body); } else { - node.setup && walk(node.setup); - node.condition && walk(node.condition); - node.update && walk(node.update); walk(node.body); } break; - case t.WHILE: + case 'ConditionalExpression': + case 'IfStatement': if (visitors[type]) { - visitors[type].call(node, node.condition, node.body); + visitors[type].call(node, node.test, node.consequent, node.alternate); } else { - walk(node.condition); - walk(node.body); + walk(node.test); + walk(node.consequent); + node.alternate && walk(node.alternate); + } + break; + + case 'DebuggerStatement': + case 'EmptyStatement': + case 'ThisExpression': + if (visitors[type]) { + visitors[type].call(node); } break; - case t.FOR_IN: + case 'DoWhileStatement': if (visitors[type]) { - visitors[type].call(node, node.varDecl || node.iterator, node.object, node.body); + visitors[type].call(node, node.test, node.body); } else { - walk(node.varDecl || node.iterator); - walk(node.object); walk(node.body); + walk(node.test); } break; - case t.DO: + case 'ExpressionStatement': if (visitors[type]) { - visitors[type].call(node, node.condition, node.body); + visitors[type].call(node, node.expression); } else { - walk(node.body); - walk(node.condition); + node.expression && walk(node.expression); } break; - case t.TRY: + case 'ForStatement': if (visitors[type]) { - visitors[type].call(node, node.tryBlock, node.catchClauses, node.finallyBlock); + visitors[type].call(node, node.init, node.test, node.update, node.body); } else { - walk(node.tryBlock); - node.catchClauses.map(walk); - node.finallyBlock && walk(node.finallyBlock); + node.init && walk(node.init); + node.test && walk(node.test); + node.update && walk(node.update); + walk(node.body); } break; - case t.CATCH: + case 'ForInStatement': if (visitors[type]) { - visitors[type].call(node, node.block); + visitors[type].call(node, node.left, node.right, node.body); } else { - walk(node.block); + walk(node.left); + walk(node.right); + walk(node.body); + } + break; + + case 'FunctionDeclaration': + case 'FunctionExpression': + if (visitors[type] || visitors['Function']) { + (visitors[type] || visitors['Function']).call(node, node.id && node.id.name, node.params, node.body.body); + } else { + node.body.body.map(walk); + } + break; + + case 'Identifier': + if (visitors[type]) { + visitors[type].call(node, node.name); } break; - case t.THROW: + case 'LabeledStatement': if (visitors[type]) { - visitors[type].call(node, node.exception); + visitors[type].call(node, node.label.id, node.body); } else { - walk(node.exception); + walk(node.body); } break; - case t.RETURN: - case t.YIELD: + case 'Literal': if (visitors[type]) { visitors[type].call(node, node.value); + } + break; + + case 'MemberExpression': + if (visitors[type]) { + visitors[type].call(node, node.object, node.property); } else { - node.value && walk(node.value); + walk(node.object); } break; - case t.GENERATOR: + case 'ObjectExpression': if (visitors[type]) { - visitors[type].call(node, node.expression, node.tail); + visitors[type].call(node, node.properties); } else { - walk(node.expression); - walk(node.tail); + node.properties.map(walk); } break; - case t.WITH: + case 'Property': if (visitors[type]) { - visitors[type].call(node, node.object, node.body); + visitors[type].call(node, node.key, node.value); } else { - walk(node.object); - walk(node.body); + walk(node.value); } break; - case t.SEMICOLON: + case 'ReturnStatement': + case 'ThrowStatement': if (visitors[type]) { - visitors[type].call(node, node.expression); + visitors[type].call(node, node.argument); } else { - node.expression && walk(node.expression); + node.argument && walk(node.argument); } break; + case 'SequenceExpression': + if (visitors[type]) { + visitors[type].call(node, node.expressions); + } else { + node.expressions.map(walk); + } break; - case t.LABEL: + case 'SwitchCase': if (visitors[type]) { - visitors[type].call(node, node.label, node.statement); + visitors[type].call(node, node.test, node.consequent); } else { - walk(node.statement); + node.test && walk(node.test); + node.consequent.map(walk); + Walker.insideCase = false; } break; - case t.ARRAY_COMP: + case 'SwitchStatement': if (visitors[type]) { - visitors[type].call(node, node.expression, node.tail); + visitors[type].call(node, node.discriminant, node.cases); } else { - walk(node.expression); - walk(node.tail); + walk(node.discriminant); + node.cases.map(walk); } break; - case t.COMP_TAIL: + case 'TryStatement': if (visitors[type]) { - visitors[type].call(node, node.guard, node.children); + visitors[type].call(node, node.block, node.handlers, node.finalizer); } else { - walk(node.children); - walk(node.guard); + walk(node.block); + node.handlers.map(walk); + node.finalizer && walk(node.finalizer); } break; - case t.IDENTIFIER: + case 'UnaryExpression': + case 'UpdateExpression': if (visitors[type]) { - visitors[type].call(node, node.value, node.initializer); + visitors[type].call(node, node.operator, node.argument); } else { - node.initializer && walk(node.initializer); + walk(node.argument); } break; - case t.NUMBER: - case t.REGEXP: - case t.STRING: + case 'VariableDeclaration': if (visitors[type]) { - visitors[type].call(node, node.value); + visitors[type].call(node, node.declarations); + } else { + node.declarations.map(walk); } break; - case t.CALL: - case t.NEW_WITH_ARGS: + case 'VariableDeclarator': if (visitors[type]) { - visitors[type].call(node, node.children[0], node.children[1].children); + visitors[type].call(node, node.id.name, node.init); } else { - node.children.map(walk); + node.init && walk(node.init); } break; - case t.NOT: - case t.VOID: + case 'WhileStatement': if (visitors[type]) { - visitors[type].call(node, node.children[0]); + visitors[type].call(node, node.test, node.body); } else { - node.children.map(walk); + walk(node.test); + walk(node.body); } break; - default: + case 'WithStatement': if (visitors[type]) { - visitors[type].call(node); + visitors[type].call(node, node.object, node.body); } else { - node.children && node.children.map(walk); + walk(node.object); + walk(node.body); } break; + + + default: + throw new Error("unhandled node type: " + node.type); } }; } diff --git a/lib/generators-fast/builtins.js b/lib/generators-fast/builtins.js index 071e78e9..d422a242 100644 --- a/lib/generators-fast/builtins.js +++ b/lib/generators-fast/builtins.js @@ -1,4 +1,4 @@ -/*** Generated by streamline 0.10.17 (generators-fast) - DO NOT EDIT ***/var galaxy = require("../generators-fast/runtime");(function(){})();galaxy.unstar((function*(_) { /** +/*** Generated by streamline 0.10.17 (generators-fast) - DO NOT EDIT ***/var galaxy = require("../generators-fast/runtime");(function(){})();galaxy.unstar(function*(_) { /** * Copyright (c) 2012 Bruno Jouhier * MIT License */ @@ -158,7 +158,7 @@ } else { var fun = funnel(par); result = this.map(function(elt, i) { - return galaxy.spin.call(this, fun(false, function*(_) { + return galaxy.spin.call(this, fun(false , function*(_) { return (yield fn.call(thisObj, _, elt, i)); }), 0); }); @@ -217,7 +217,7 @@ } else { var fun = funnel(par); var futures = this.map(function(elt) { - return galaxy.spin.call(this, fun(false, function*(_) { + return galaxy.spin.call(this, fun(false , function*(_) { return (yield fn.call(thisObj, _, elt)); }), 0); }); @@ -250,7 +250,7 @@ } else { var fun = funnel(par); var futures = this.map(function(elt) { - return galaxy.spin.call(this, fun(false, function*(_) { + return galaxy.spin.call(this, fun(false , function*(_) { return (yield fn.call(thisObj, _, elt)); }), 0); }); @@ -368,6 +368,6 @@ } }); })(typeof exports !== 'undefined' ? exports : (Streamline.builtins = Streamline.builtins || {})); -}),0)( function(err) { +},0)( function(err) { if (err) throw err; }); diff --git a/lib/generators-fast/flows.js b/lib/generators-fast/flows.js index 775148f6..98c921e8 100644 --- a/lib/generators-fast/flows.js +++ b/lib/generators-fast/flows.js @@ -1,4 +1,4 @@ -/*** Generated by streamline 0.10.17 (generators-fast) - DO NOT EDIT ***/var galaxy = require("../generators-fast/runtime");(function(){})();galaxy.unstar((function*(_) { /** +/*** Generated by streamline 0.10.17 (generators-fast) - DO NOT EDIT ***/var galaxy = require("../generators-fast/runtime");(function(){})();galaxy.unstar(function*(_) { /** * Copyright (c) 2011 Bruno Jouhier * * Permission is hereby granted, free of charge, to any person @@ -122,10 +122,10 @@ if (trim) results.push(result); else results[i] = result; if (++collected == count) return callback(null, results); - }, fns[i]); + } , fns[i]); })(i); } - }), "call", [this, _], 1)); + }, "call", [this, _], 1)); }; this.collectOne = function*(_) { var result = (yield this.collect(_, 1, true)); @@ -281,7 +281,7 @@ exports.trampoline = galaxy.star(function(cb, fn, thisObj) { fn = globals.withContext(fn, globals.context); exports.setImmediate(function() { - galaxy.unstarBound(fn,'call',1)(thisObj, cb); + galaxy.unstarBound(fn,'call',1)(thisObj , cb); }); }, 0); @@ -341,9 +341,9 @@ return function() { var that = this; var args = Array.prototype.slice(arguments, 0); - return galaxy.unstar((function*(_) { + return galaxy.unstar(function*(_) { return (yield fn.apply_(_, that, args, 0)); - }),0)( function(err) { + },0)( function(err) { if (err) throw err; }); }; @@ -379,6 +379,6 @@ })(typeof exports !== 'undefined' ? exports : (Streamline.flows = Streamline.flows || {})); -}),0)( function(err) { +},0)( function(err) { if (err) throw err; }); diff --git a/lib/generators-fast/transform.js b/lib/generators-fast/transform.js index f4d6c215..d990d345 100644 --- a/lib/generators-fast/transform.js +++ b/lib/generators-fast/transform.js @@ -23,11 +23,11 @@ if (typeof exports !== 'undefined') { } (function(exports) { exports.transform = transform; - exports.version = require("../version").version + " (generators-fast --esprima)"; + exports.version = require("../version").version + " (generators-fast)"; // hack to fix #123 exports.transform.version = exports.version; -var Walker = require('../fibers/walker-esprima'); +var Walker = require('../fibers/walker'); try { eval("(function*(){})"); diff --git a/lib/generators/builtins.js b/lib/generators/builtins.js index 93d3d53b..097d8777 100644 --- a/lib/generators/builtins.js +++ b/lib/generators/builtins.js @@ -128,10 +128,10 @@ var len = this.length; if (par === 1 || len <= 1) { for (var i = 0; i < len; i++) { - if (has.call(this, i)) (yield galaxy.invoke(fn, "call", [thisObj, _, this[i], i], 1)); + if (has.call(this, i)) (yield galaxy.invoke(fn, "call", [thisObj , _ , this[i] , i], 1)); } } else { - (yield galaxy.invoke(this, "map_", [_, par, fn, thisObj], 0)); + (yield galaxy.invoke(this, "map_", [_ , par , fn , thisObj], 0)); } return this; }, 0) @@ -153,13 +153,13 @@ if (par === 1 || len <= 1) { result = new Array(len); for (var i = 0; i < len; i++) { - if (has.call(this, i)) result[i] = (yield galaxy.invoke(fn, "call", [thisObj, _, this[i], i], 1)); + if (has.call(this, i)) result[i] = (yield galaxy.invoke(fn, "call", [thisObj , _ , this[i] , i], 1)); } } else { var fun = funnel(par); result = this.map(function(elt, i) { return fun(false, galaxy.unstar(function*(_) { - return (yield galaxy.invoke(fn, "call", [thisObj, _, elt, i], 1)); + return (yield galaxy.invoke(fn, "call", [thisObj , _ , elt , i], 1)); }, 0)); }); for (var i = 0; i < len; i++) { @@ -186,13 +186,13 @@ for (var i = 0; i < len; i++) { if (has.call(this, i)) { var elt = this[i]; - if ((yield galaxy.invoke(fn, "call", [thisObj, _, elt], 1))) result.push(elt); + if ((yield galaxy.invoke(fn, "call", [thisObj , _ , elt], 1))) result.push(elt); } } } else { - (yield galaxy.invoke(this, "map_", [_, par, galaxy.unstar(function*(_, elt) { - if ((yield galaxy.invoke(fn, "call", [thisObj, _, elt], 1))) result.push(elt); - }, 0), thisObj], 0)); + (yield galaxy.invoke(this, "map_", [_ , par , galaxy.unstar(function*(_, elt) { + if ((yield galaxy.invoke(fn, "call", [thisObj , _ , elt], 1))) result.push(elt); + }, 0) , thisObj], 0)); } return result; }, 0) @@ -212,13 +212,13 @@ if (par === 1 || len <= 1) { for (var i = 0; i < len; i++) { - if (has.call(this, i) && !(yield galaxy.invoke(fn, "call", [thisObj, _, this[i]], 1))) return false; + if (has.call(this, i) && !(yield galaxy.invoke(fn, "call", [thisObj , _ , this[i]], 1))) return false; } } else { var fun = funnel(par); var futures = this.map(function(elt) { return fun(false, galaxy.unstar(function*(_) { - return (yield galaxy.invoke(fn, "call", [thisObj, _, elt], 1)); + return (yield galaxy.invoke(fn, "call", [thisObj , _ , elt], 1)); }, 0)); }); for (var i = 0; i < len; i++) { @@ -245,13 +245,13 @@ var len = this.length; if (par === 1 || len <= 1) { for (var i = 0; i < len; i++) { - if (has.call(this, i) && (yield galaxy.invoke(fn, "call", [thisObj, _, this[i]], 1))) return true; + if (has.call(this, i) && (yield galaxy.invoke(fn, "call", [thisObj , _ , this[i]], 1))) return true; } } else { var fun = funnel(par); var futures = this.map(function(elt) { return fun(false, galaxy.unstar(function*(_) { - return (yield galaxy.invoke(fn, "call", [thisObj, _, elt], 1)); + return (yield galaxy.invoke(fn, "call", [thisObj , _ , elt], 1)); }, 0)); }); for (var i = 0; i < len; i++) { @@ -275,7 +275,7 @@ thisObj = thisObj !== undefined ? thisObj : this; var len = this.length; for (var i = 0; i < len; i++) { - if (has.call(this, i)) v = (yield galaxy.invoke(fn, "call", [thisObj, _, v, this[i], i, this], 1)); + if (has.call(this, i)) v = (yield galaxy.invoke(fn, "call", [thisObj , _ , v , this[i] , i , this], 1)); } return v; }, 0) @@ -291,7 +291,7 @@ thisObj = thisObj !== undefined ? thisObj : this; var len = this.length; for (var i = len - 1; i >= 0; i--) { - if (has.call(this, i)) v = (yield galaxy.invoke(fn, "call", [thisObj, _, v, this[i], i, this], 1)); + if (has.call(this, i)) v = (yield galaxy.invoke(fn, "call", [thisObj , _ , v , this[i] , i , this], 1)); } return v; }, 0) @@ -314,7 +314,7 @@ if (beg >= end) return; if (end == beg + 1) { - if ((yield galaxy.invoke(null, compare, [_, array[beg], array[end]], 0)) > 0) { + if ((yield galaxy.invoke(null, compare, [_ , array[beg] , array[end]], 0)) > 0) { var tmp = array[beg]; array[beg] = array[end]; array[end] = tmp; @@ -328,8 +328,8 @@ var nend = end; while (nbeg <= nend) { - while (nbeg < end && (yield galaxy.invoke(null, compare, [_, array[nbeg], o], 0)) < 0) nbeg++; - while (beg < nend && (yield galaxy.invoke(null, compare, [_, o, array[nend]], 0)) < 0) nend--; + while (nbeg < end && (yield galaxy.invoke(null, compare, [_ , array[nbeg] , o], 0)) < 0) nbeg++; + while (beg < nend && (yield galaxy.invoke(null, compare, [_ , o , array[nend]], 0)) < 0) nend--; if (nbeg <= nend) { var tmp = array[nbeg]; @@ -340,10 +340,10 @@ } } - if (nbeg < end) (yield _qsort(_, nbeg, end)); - if (beg < nend) (yield _qsort(_, beg, nend)); + if (nbeg < end) (yield _qsort(_ , nbeg , end)); + if (beg < nend) (yield _qsort(_ , beg , nend)); } - (yield _qsort(_, beg, end)); + (yield _qsort(_ , beg , end)); return array; }, 0) }); diff --git a/lib/generators/flows.js b/lib/generators/flows.js index e87455d1..75e0fac1 100644 --- a/lib/generators/flows.js +++ b/lib/generators/flows.js @@ -43,43 +43,43 @@ /// applies `fn` sequentially to the elements of `array`. /// `fn` is called as `fn(_, elt, i)`. exports.each = galaxy.unstar(function*(_, array, fn, thisObj) { - return (array && array.length) ? (yield galaxy.invoke(array, "forEach_", [_, fn, thisObj], 0)) : undefined; + return (array && array.length) ? (yield galaxy.invoke(array, "forEach_", [_ , fn , thisObj], 0)) : undefined; }, 0); /// * `result = flows.map(_, array, fn, [thisObj])` /// transforms `array` by applying `fn` to each element in turn. /// `fn` is called as `fn(_, elt, i)`. exports.map = galaxy.unstar(function*(_, array, fn, thisObj) { - return array ? (yield galaxy.invoke(array, "map_", [_, fn, thisObj], 0)) : array; + return array ? (yield galaxy.invoke(array, "map_", [_ , fn , thisObj], 0)) : array; }, 0); /// * `result = flows.filter(_, array, fn, [thisObj])` /// generates a new array that only contains the elements that satisfy the `fn` predicate. /// `fn` is called as `fn(_, elt)`. exports.filter = galaxy.unstar(function*(_, array, fn, thisObj) { - return array ? (yield galaxy.invoke(array, "filter_", [_, fn, thisObj], 0)) : array; + return array ? (yield galaxy.invoke(array, "filter_", [_ , fn , thisObj], 0)) : array; }, 0); /// * `bool = flows.every(_, array, fn, [thisObj])` /// returns true if `fn` is true on every element (if `array` is empty too). /// `fn` is called as `fn(_, elt)`. exports.every = galaxy.unstar(function*(_, array, fn, thisObj) { - return array ? (yield galaxy.invoke(array, "every_", [_, fn, thisObj], 0)) : undefined; + return array ? (yield galaxy.invoke(array, "every_", [_ , fn , thisObj], 0)) : undefined; }, 0); /// * `bool = flows.some(_, array, fn, [thisObj])` /// returns true if `fn` is true for at least one element. /// `fn` is called as `fn(_, elt)`. exports.some = galaxy.unstar(function*(_, array, fn, thisObj) { - return array ? (yield galaxy.invoke(array, "some_", [_, fn, thisObj], 0)) : undefined; + return array ? (yield galaxy.invoke(array, "some_", [_ , fn , thisObj], 0)) : undefined; }, 0); /// * `result = flows.reduce(_, array, fn, val, [thisObj])` /// reduces by applying `fn` to each element. /// `fn` is called as `val = fn(_, val, elt, i, array)`. exports.reduce = galaxy.unstar(function*(_, array, fn, v, thisObj) { - return array ? (yield galaxy.invoke(array, "reduce_", [_, fn, v, thisObj], 0)) : v; + return array ? (yield galaxy.invoke(array, "reduce_", [_ , fn , v , thisObj], 0)) : v; }, 0); /// * `result = flows.reduceRight(_, array, fn, val, [thisObj])` /// reduces from end to start by applying `fn` to each element. /// `fn` is called as `val = fn(_, val, elt, i, array)`. exports.reduceRight = galaxy.unstar(function*(_, array, fn, v, thisObj) { - return array ? (yield galaxy.invoke(array, "reduceRight_", [_, fn, v, thisObj], 0)) : v; + return array ? (yield galaxy.invoke(array, "reduceRight_", [_ , fn , v , thisObj], 0)) : v; }, 0); /// * `array = flows.sort(_, array, compare, [beg], [end])` @@ -88,7 +88,7 @@ /// /// Note: this function _changes_ the original array (and returns it) exports.sort = galaxy.unstar(function*(_, array, compare, beg, end) { - return array ? (yield galaxy.invoke(array, "sort_", [_, compare, beg, end], 0)) : array; + return array ? (yield galaxy.invoke(array, "sort_", [_ , compare , beg , end], 0)) : array; }, 0); /// /// ## Object utility (obsolete) @@ -98,8 +98,8 @@ /// * `flows.eachKey(_, obj, fn)` /// calls `fn(_, key, obj[key])` for every `key` in `obj`. exports.eachKey = galaxy.unstar(function*(_, obj, fn, thisObj) { - return (yield galaxy.invoke((obj ? Object.keys(obj) : []), "forEach_", [_, galaxy.unstar(function*(_, elt) { - (yield galaxy.invoke(fn, "call", [thisObj, _, elt, obj[elt]], 1)); + return (yield galaxy.invoke(obj ? Object.keys(obj) : [], "forEach_", [_ , galaxy.unstar(function*(_, elt) { + (yield galaxy.invoke(fn, "call", [thisObj , _ , elt , obj[elt]], 1)); }, 0)], 0)); }, 0); // deprecated -- don't document @@ -109,7 +109,7 @@ function() { var funnel = exports.funnel(max); this.collect = galaxy.unstar(function*(_, count, trim) { - return (yield galaxy.invoke((function(callback) { + return (yield galaxy.invoke(function(callback) { if (typeof(callback) != "function") throw new Error("invalid call to collect: no callback"); var results = trim ? [] : new Array(fns.length); count = count < 0 ? fns.length : Math.min(count, fns.length); @@ -125,14 +125,14 @@ }, fns[i]); })(i); } - }), "call", [this, _], 1)); + }, "call", [this , _], 1)); }, 0); this.collectOne = galaxy.unstar(function*(_) { - var result = (yield galaxy.invoke(this, "collect", [_, 1, true], 0)); + var result = (yield galaxy.invoke(this, "collect", [_ , 1 , true], 0)); return result && result[0]; }, 0); this.collectAll = galaxy.unstar(function*(_) { - return (yield galaxy.invoke(this, "collect", [_, -1, false], 0)); + return (yield galaxy.invoke(this, "collect", [_ , -1 , false], 0)); }, 0); }; @@ -256,7 +256,7 @@ /// * `results = flows.collect(_, futures)` /// collects the results of an array of futures exports.collect = galaxy.unstar(function*(_, futures) { - return futures && (yield galaxy.invoke(futures, "map_", [_, galaxy.unstar(function*(_, future) { + return futures && (yield galaxy.invoke(futures, "map_", [_ , galaxy.unstar(function*(_, future) { return (yield galaxy.invoke(null, future, [_], 0)); }, 0)], 0)); }, 0); @@ -334,16 +334,16 @@ /// * `flows.sleep(_, millis)` /// Sleeps `millis` ms. exports.sleep = galaxy.unstar(function*(_, millis) { - return (yield galaxy.invoke(null, setTimeout, [_, millis], 0)); + return (yield galaxy.invoke(null, setTimeout, [_ , millis], 0)); }, 0); exports.eventHandler = function(fn) { return function() { var that = this; var args = Array.prototype.slice(arguments, 0); - return galaxy.unstar((function*(_) { - return (yield galaxy.invoke(fn, "apply_", [_, that, args, 0], 0)); - }), 0)( function(err) { + return (galaxy.unstar(function*(_) { + return (yield galaxy.invoke(fn, "apply_", [_ , that , args , 0], 0)); + }, 0))( function(err) { if (err) throw err; }); }; @@ -351,7 +351,7 @@ // Obsolete. Use `fn.apply_` instead. exports.apply = galaxy.unstar(function* apply(_, fn, thisObj, args, index) { - return (yield galaxy.invoke(fn, "apply_", [_, thisObj, args, index], 0)); + return (yield galaxy.invoke(fn, "apply_", [_ , thisObj , args , index], 0)); }, 0); /// diff --git a/lib/generators/require-stub.js b/lib/generators/require-stub.js index 28ea87e2..fcaf2a3a 100644 --- a/lib/generators/require-stub.js +++ b/lib/generators/require-stub.js @@ -6,13 +6,14 @@ window.Streamline = { globals: {} }; function require(str) { if (/^\.\.\//.test(str)) str = "streamline/lib" + str.substring(2); if (str == "streamline/lib/util/flows") return Streamline.flows; + else if (str == "streamline/lib/globals") return Streamline.globals; + else if (str == "streamline/lib/version") return Streamline.version; else if (str == "streamline/lib/fibers/walker") return Streamline.walker; - else if (str == "streamline/lib/fibers/transform") return Streamline; else if (str == "streamline/lib/generators/runtime") return Streamline.runtime; else if (str == "streamline/lib/generators/transform") return Streamline; else if (str == "streamline/lib/generators/builtins") return Streamline.builtins; - else if (str == "streamline/lib/globals") return Streamline.globals; else if (str == "streamline/lib/util/future") return Streamline.future; - else if (str == "streamline/lib/callbacks/transform") return Streamline; // hack for eval test + else if (str == "galaxy") return galaxy; + else if (str == "galaxy-stack") return null; else alert("cannot require " + str) } diff --git a/lib/generators/runtime.js b/lib/generators/runtime.js index a94cafcf..0966e1b6 100644 --- a/lib/generators/runtime.js +++ b/lib/generators/runtime.js @@ -1,13 +1,17 @@ -module.exports = require('galaxy'); -var globals = module.exports.globals = require('../globals'); -module.exports.globals.runtime = 'generators'; +if (typeof exports !== 'undefined') { + exports = module.exports = Object.create(require('galaxy')); +} else { + exports = (Streamline.runtime = Streamline.runtime || Object.create(require('galaxy'))); +} +var globals = exports.globals = require('../globals'); +exports.globals.runtime = 'generators'; require("../generators/builtins"); var fut = require("../util/future"); -module.exports.streamlinify = fut.streamlinify; +exports.streamlinify = fut.streamlinify; -var unstar = module.exports.unstar; +var unstar = exports.unstar; -module.exports.unstar = function(fn, options, entering) { +exports.unstar = function(fn, options, entering) { if (typeof options === "number") options = { callbackIndex: options, }; @@ -18,4 +22,4 @@ module.exports.unstar = function(fn, options, entering) { return unstar(fn, options, entering); } -module.exports.then = module.exports.star(fut.then, 2); +exports.then = exports.star(fut.then, 2); diff --git a/lib/generators/transform.js b/lib/generators/transform.js index 24e46db4..3af233a0 100644 --- a/lib/generators/transform.js +++ b/lib/generators/transform.js @@ -21,7 +21,7 @@ if (typeof exports !== 'undefined') { } (function(exports) { exports.transform = transform; - exports.version = require("../version").version + " (generators --esprima)"; + exports.version = require("../version").version + " (generators)"; // hack to fix #123 exports.transform.version = exports.version; @@ -31,7 +31,7 @@ if (typeof exports !== 'undefined') { console.log("warning: generators not supported or not enabled by your JS engine"); } - var Walker = require('../fibers/walker-esprima'); + var Walker = require('../fibers/walker'); // TODO ensure `foo(_)` calls have a bounding fiber. streamline is smart enough to allow this: // ~function() { foo(_) }(); diff --git a/lib/streams/client/streams.js b/lib/streams/client/streams.js index cb086bc3..656f70a1 100644 --- a/lib/streams/client/streams.js +++ b/lib/streams/client/streams.js @@ -1,142 +1,142 @@ -/*** Generated by streamline 0.10.17 (callbacks) - DO NOT EDIT ***/ "use strict"; var __rt=require('../callbacks/runtime').runtime(__filename, false),__func=__rt.__func,__cb=__rt.__cb; function DataBuffer(options) { - - - - - - - - - - - - - - var _chunks = []; - - this.read = function read__1(_, len) { var chunks, total, chunk; var __frame = { name: "read__1", line: 17 }; return __func(_, this, arguments, read__1, 0, __frame, function __$read__1() { - if ((len < 0)) { len = Infinity; } ; - if ((len == 0)) { return _(null, ""); } ; - chunks = []; - total = 0; - while ((total < len)) { - chunk = _chunks.splice(0, 1)[0]; - if (!chunk) { return _(null, ((chunks.length == 0) ? null : chunks.join(""))); } ; - if (((total + chunk.length) <= len)) { - chunks.push(chunk); - total += chunk.length; } - else { - chunks.push(chunk.substring(0, (len - total))); - _chunks.splice(0, 0, chunk.substring((len - total))); - total = len; } ; }; - - - return _(null, chunks.join("")); }); }; - - - - - this.readAll = function readAll__2(_) { var __this = this; var __frame = { name: "readAll__2", line: 39 }; return __func(_, this, arguments, readAll__2, 0, __frame, function __$readAll__2() { - return __this.read(__cb(_, __frame, 1, 14, _, true), -1); }); }; - - - - - this.unread = function(chunk) { - _chunks.splice(0, 0, chunk); - return this; }; - - - this.write = function write__3(_, data, enc) { var __this = this; var __frame = { name: "write__3", line: 50 }; return __func(_, this, arguments, write__3, 0, __frame, function __$write__3() { - _chunks.push(data); return _(null, __this); }); }; - - - - this.end = function(data, enc) { - if (data) { _chunks.push(data); }; - return this; }; - - - this.contents = function() { - return _chunks.join(""); };}; - - - -function HttpError(statusCode, message) { - this.statusCode = statusCode; - this.message = message; - this.stack = new Error().stack;}; - - -function _fixHttpClientOptions(options) { - if (!options) { throw new Error("request error: no options") }; - if ((typeof options === "string")) { options = { - url: options }; }; - - return options;}; - - - - - - - - - - - - - - - - - - - - - -function HttpClientRequest(options) { - options = _fixHttpClientOptions(options); - DataBuffer.call(this, options); - var _xhr; - this.response = function(callback) { - if (!callback) { return __future.call(this, this.response, arguments, 0) }; - $.ajax({ - url: options.url, - headers: options.headers, - type: options.method, - data: this.contents(), - dataType: "text", - - beforeSend: function(xhr) { - _xhr = xhr; }, - - success: function(data, statusText, xhr) { - callback(null, new HttpClientResponse(data, xhr)); }, - - error: function(xhr, statusText, message) { - if ((statusText == "error")) { callback(new HttpError(xhr.status, ((statusText + ": ") + message))); } else { - callback(new HttpError(400, ((statusText + ": ") + message))); }; } }); }; - - - - this.abort = function() { - (_xhr && _xhr.abort()); - _xhr = null; };}; - - - -function HttpClientResponse(data, xhr) { - DataBuffer.call(this); - this.end(data); - this.statusCode = xhr.status; - this.headers = { }; - var self = this; - xhr.getAllResponseHeaders().replace(/\r\n/g, "\n").split("\n").forEach(function(header) { - var pair = header.split(":"); - self.headers[pair[0].toLowerCase()] = (pair[1] && pair[1].trim()); });}; - - - -exports.httpRequest = function(options) { - return new HttpClientRequest(options);}; +/*** Generated by streamline 0.10.17 (callbacks) - DO NOT EDIT ***/ "use strict"; var __rt=require('../callbacks/runtime').runtime(__filename, false),__func=__rt.__func,__cb=__rt.__cb; + + + + + + + + + + + + + function DataBuffer(options) { + var _chunks = []; + + this.read = function read__1(_, len) { var chunks, total, chunk; var __frame = { name: 'read__1', line: 17 }; return __func(_, this, arguments, read__1, 0, __frame, function __$read__1() { + if (len < 0) { len = Infinity; } + if (len == 0) { return _(null, ''); } chunks = []; + total = 0; + + while (total < len) { chunk = _chunks.splice(0, 1)[0]; + + if (!chunk) { return _(null, chunks.length == 0 ? null : chunks.join('')); } + if (total + chunk.length <= len) { + chunks.push(chunk); + total += chunk.length; } else { + + chunks.push(chunk.substring(0, len - total)); + _chunks.splice(0, 0, chunk.substring(len - total)); + total = len; } } + + + return _(null, chunks.join('')); }); }; + + + + + this.readAll = function readAll__2(_) { var __this = this; var __frame = { name: 'readAll__2', line: 39 }; return __func(_, this, arguments, readAll__2, 0, __frame, function __$readAll__2() { + return __this.read(__cb(_, __frame, 1, 0, _, true, false), -1); }); }; + + + + + this.unread = function (chunk) { + _chunks.splice(0, 0, chunk); + return this; }; + + + this.write = function write__3(_, data, enc) { var __this = this; var __frame = { name: 'write__3', line: 50 }; return __func(_, this, arguments, write__3, 0, __frame, function __$write__3() { + _chunks.push(data); + return _(null, __this); }); }; + + + this.end = function (data, enc) { + if (data) _chunks.push(data); + return this; }; + + + this.contents = function () { + return _chunks.join(''); }; } + + + + function HttpError(statusCode, message) { + this.statusCode = statusCode; + this.message = message; + this.stack = new Error().stack; } + + + function _fixHttpClientOptions(options) { + if (!options) throw new Error('request error: no options'); + if (typeof options === 'string') options = { url: options }; + + + return options; } + + + + + + + + + + + + + + + + + + + + + + function HttpClientRequest(options) { + options = _fixHttpClientOptions(options); + DataBuffer.call(this, options); + var _xhr; + this.response = function (callback) { + if (!callback) return __future.call(this, this.response, arguments, 0); + $.ajax({ url: options.url, headers: options.headers, type: options.method, data: this.contents(), dataType: 'text', beforeSend: function (xhr) { + + + + + + + + _xhr = xhr; }, success: function (data, statusText, xhr) { + + + callback(null, new HttpClientResponse(data, xhr)); }, error: function (xhr, statusText, message) { + + + if (statusText == 'error') callback(new HttpError(xhr.status, statusText + ': ' + message)); else callback(new HttpError(400, statusText + ': ' + message)); } }); }; + + + + + this.abort = function () { + _xhr && _xhr.abort(); + _xhr = null; }; } + + + + function HttpClientResponse(data, xhr) { + DataBuffer.call(this); + this.end(data); + this.statusCode = xhr.status; + this.headers = {}; + var self = this; + xhr.getAllResponseHeaders().replace(/\r\n/g, '\n').split('\n').forEach(function (header) { + var pair = header.split(':'); + self.headers[pair[0].toLowerCase()] = pair[1] && pair[1].trim(); }); } + + + + exports.httpRequest = function (options) { + return new HttpClientRequest(options); }; \ No newline at end of file diff --git a/lib/transform-all.js b/lib/transform-all.js index 5f8a9145..88fd547a 100644 --- a/lib/transform-all.js +++ b/lib/transform-all.js @@ -15,2858 +15,7720 @@ function require(str) { else if (str == "streamline/lib/util/source-map") return Streamline.sourceMap.exports; else alert("cannot require " + str) } -/* vim: set sw=4 ts=4 et tw=78: */ -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is the Narcissus JavaScript engine. - * - * The Initial Developer of the Original Code is - * Brendan Eich . - * Portions created by the Initial Developer are Copyright (C) 2004 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * Tom Austin - * Brendan Eich - * Shu-Yu Guo - * Dave Herman - * Dimitris Vardoulakis - * Patrick Walton - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - /* - * Narcissus - JS implemented in JS. - * - * Well-known constants and lookup tables. Many consts are generated from the - * tokens table via eval to minimize redundancy, so consumers must be compiled - * separately to take advantage of the simple switch-case constant propagation - * done by SpiderMonkey. - */ + Copyright (C) 2013 Ariya Hidayat + Copyright (C) 2013 Thaddee Tyl + Copyright (C) 2013 Mathias Bynens + Copyright (C) 2012 Ariya Hidayat + Copyright (C) 2012 Mathias Bynens + Copyright (C) 2012 Joost-Wim Boekesteijn + Copyright (C) 2012 Kris Kowal + Copyright (C) 2012 Yusuke Suzuki + Copyright (C) 2012 Arpad Borsos + Copyright (C) 2011 Ariya Hidayat + + 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 HOLDERS AND CONTRIBUTORS "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 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 (root, factory) { + 'use strict'; + + // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, + // Rhino, and plain browser loading. + + /* istanbul ignore next */ + if (typeof define === 'function' && define.amd) { + define(['exports'], factory); + } else if (typeof exports !== 'undefined') { + factory(exports); + } else { + factory((root.esprima = {})); + } +}(this, function (exports) { + 'use strict'; + + var Token, + TokenName, + FnExprTokens, + Syntax, + PlaceHolders, + PropertyKind, + Messages, + Regex, + source, + strict, + index, + lineNumber, + lineStart, + length, + lookahead, + state, + extra; + + Token = { + BooleanLiteral: 1, + EOF: 2, + Identifier: 3, + Keyword: 4, + NullLiteral: 5, + NumericLiteral: 6, + Punctuator: 7, + StringLiteral: 8, + RegularExpression: 9 + }; -(function() { + TokenName = {}; + TokenName[Token.BooleanLiteral] = 'Boolean'; + TokenName[Token.EOF] = ''; + TokenName[Token.Identifier] = 'Identifier'; + TokenName[Token.Keyword] = 'Keyword'; + TokenName[Token.NullLiteral] = 'Null'; + TokenName[Token.NumericLiteral] = 'Numeric'; + TokenName[Token.Punctuator] = 'Punctuator'; + TokenName[Token.StringLiteral] = 'String'; + TokenName[Token.RegularExpression] = 'RegularExpression'; + + // A function following one of those tokens is an expression. + FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new', + 'return', 'case', 'delete', 'throw', 'void', + // assignment operators + '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=', + '&=', '|=', '^=', ',', + // binary/unary operators + '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&', + '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=', + '<=', '<', '>', '!=', '!==']; + + Syntax = { + AssignmentExpression: 'AssignmentExpression', + ArrayExpression: 'ArrayExpression', + ArrowFunctionExpression: 'ArrowFunctionExpression', + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DoWhileStatement: 'DoWhileStatement', + DebuggerStatement: 'DebuggerStatement', + EmptyStatement: 'EmptyStatement', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + Identifier: 'Identifier', + IfStatement: 'IfStatement', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + Program: 'Program', + Property: 'Property', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement' + }; - var narcissus = { - options: { - version: 185, - }, - hostGlobal: this + PlaceHolders = { + ArrowParameterPlaceHolder: { + type: 'ArrowParameterPlaceHolder' + } }; - Narcissus = narcissus; -})(); -Narcissus.definitions = (function() { - - var tokens = [ - // End of source. - "END", - - // Operators and punctuators. Some pair-wise order matters, e.g. (+, -) - // and (UNARY_PLUS, UNARY_MINUS). - "\n", ";", - ",", - "=", - "?", ":", "CONDITIONAL", - "||", - "&&", - "|", - "^", - "&", - "==", "!=", "===", "!==", - "<", "<=", ">=", ">", - "<<", ">>", ">>>", - "+", "-", - "*", "/", "%", - "!", "~", "UNARY_PLUS", "UNARY_MINUS", - "++", "--", - ".", - "[", "]", - "{", "}", - "(", ")", - - // Nonterminal tree node type codes. - "SCRIPT", "BLOCK", "LABEL", "FOR_IN", "CALL", "NEW_WITH_ARGS", "INDEX", - "ARRAY_INIT", "OBJECT_INIT", "PROPERTY_INIT", "GETTER", "SETTER", - "GROUP", "LIST", "LET_BLOCK", "ARRAY_COMP", "GENERATOR", "COMP_TAIL", - - // Terminals. - "IDENTIFIER", "NUMBER", "STRING", "REGEXP", - - // Keywords. - "break", - "case", "catch", "const", "continue", - "debugger", "default", "delete", "do", - "else", - "false", "finally", "for", "function", - "if", "in", "instanceof", - "let", - "new", "null", - "return", - "switch", - "this", "throw", "true", "try", "typeof", - "var", "void", - "yield", - "while", "with", - ]; + PropertyKind = { + Data: 1, + Get: 2, + Set: 4 + }; - var statementStartTokens = [ - "break", - "const", "continue", - "debugger", "do", - "for", - "if", - "return", - "switch", - "throw", "try", - "var", - "yield", - "while", "with", - ]; + // Error messages should be identical to V8. + Messages = { + UnexpectedToken: 'Unexpected token %0', + UnexpectedNumber: 'Unexpected number', + UnexpectedString: 'Unexpected string', + UnexpectedIdentifier: 'Unexpected identifier', + UnexpectedReserved: 'Unexpected reserved word', + UnexpectedEOS: 'Unexpected end of input', + NewlineAfterThrow: 'Illegal newline after throw', + InvalidRegExp: 'Invalid regular expression', + UnterminatedRegExp: 'Invalid regular expression: missing /', + InvalidLHSInAssignment: 'Invalid left-hand side in assignment', + InvalidLHSInForIn: 'Invalid left-hand side in for-in', + MultipleDefaultsInSwitch: 'More than one default clause in switch statement', + NoCatchOrFinally: 'Missing catch or finally after try', + UnknownLabel: 'Undefined label \'%0\'', + Redeclaration: '%0 \'%1\' has already been declared', + IllegalContinue: 'Illegal continue statement', + IllegalBreak: 'Illegal break statement', + IllegalReturn: 'Illegal return statement', + StrictModeWith: 'Strict mode code may not include a with statement', + StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', + StrictVarName: 'Variable name may not be eval or arguments in strict mode', + StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', + StrictParamDupe: 'Strict mode function may not have duplicate parameter names', + StrictFunctionName: 'Function name may not be eval or arguments in strict mode', + StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', + StrictDelete: 'Delete of an unqualified identifier in strict mode.', + StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode', + AccessorDataProperty: 'Object literal may not have data and accessor property with the same name', + AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name', + StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', + StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', + StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', + StrictReservedWord: 'Use of future reserved word in strict mode' + }; - // Operator and punctuator mapping from token to tree node type name. - // NB: because the lexer doesn't backtrack, all token prefixes must themselves - // be valid tokens (e.g. !== is acceptable because its prefixes are the valid - // tokens != and !). - var opTypeNames = { - '\n': "NEWLINE", - ';': "SEMICOLON", - ',': "COMMA", - '?': "HOOK", - ':': "COLON", - '||': "OR", - '&&': "AND", - '|': "BITWISE_OR", - '^': "BITWISE_XOR", - '&': "BITWISE_AND", - '===': "STRICT_EQ", - '==': "EQ", - '=': "ASSIGN", - '!==': "STRICT_NE", - '!=': "NE", - '<<': "LSH", - '<=': "LE", - '<': "LT", - '>>>': "URSH", - '>>': "RSH", - '>=': "GE", - '>': "GT", - '++': "INCREMENT", - '--': "DECREMENT", - '+': "PLUS", - '-': "MINUS", - '*': "MUL", - '/': "DIV", - '%': "MOD", - '!': "NOT", - '~': "BITWISE_NOT", - '.': "DOT", - '[': "LEFT_BRACKET", - ']': "RIGHT_BRACKET", - '{': "LEFT_CURLY", - '}': "RIGHT_CURLY", - '(': "LEFT_PAREN", - ')': "RIGHT_PAREN" + // See also tools/generate-unicode-regex.py. + Regex = { + NonAsciiIdentifierStart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]'), + NonAsciiIdentifierPart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]') }; - // Hash of keyword identifier to tokens index. NB: we must null __proto__ to - // avoid toString, etc. namespace pollution. - var keywords = {__proto__: null}; - - // Define const END, etc., based on the token names. Also map name to index. - var tokenIds = {}; - - // Building up a string to be eval'd in different contexts. - var consts = "var "; - for (var i = 0, j = tokens.length; i < j; i++) { - if (i > 0) - consts += ", "; - var t = tokens[i]; - var name; - if (/^[a-z]/.test(t)) { - name = t.toUpperCase(); - keywords[t] = i; - } else { - name = (/^\W/.test(t) ? opTypeNames[t] : t); + // Ensure the condition is true, otherwise throw an error. + // This is only to have a better contract semantic, i.e. another safety net + // to catch a logic error. The condition shall be fulfilled in normal case. + // Do NOT use this to enforce a certain condition on any user input. + + function assert(condition, message) { + /* istanbul ignore if */ + if (!condition) { + throw new Error('ASSERT: ' + message); } - consts += name + " = " + i; - tokenIds[name] = i; - tokens[t] = i; } - consts += ";"; - - var isStatementStartCode = {__proto__: null}; - for (i = 0, j = statementStartTokens.length; i < j; i++) - isStatementStartCode[keywords[statementStartTokens[i]]] = true; - // Map assignment operators to their indexes in the tokens array. - var assignOps = ['|', '^', '&', '<<', '>>', '>>>', '+', '-', '*', '/', '%']; - - for (i = 0, j = assignOps.length; i < j; i++) { - t = assignOps[i]; - assignOps[t] = tokens[t]; + function isDecimalDigit(ch) { + return (ch >= 0x30 && ch <= 0x39); // 0..9 } - function defineGetter(obj, prop, fn, dontDelete, dontEnum) { - Object.defineProperty(obj, prop, - { get: fn, configurable: !dontDelete, enumerable: !dontEnum }); + function isHexDigit(ch) { + return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; } - function defineProperty(obj, prop, val, dontDelete, readOnly, dontEnum) { - Object.defineProperty(obj, prop, - { value: val, writable: !readOnly, configurable: !dontDelete, - enumerable: !dontEnum }); + function isOctalDigit(ch) { + return '01234567'.indexOf(ch) >= 0; } - // Returns true if fn is a native function. (Note: SpiderMonkey specific.) - function isNativeCode(fn) { - // Relies on the toString method to identify native code. - return ((typeof fn) === "function") && fn.toString().match(/\[native code\]/); - } - function getPropertyDescriptor(obj, name) { - while (obj) { - if (({}).hasOwnProperty.call(obj, name)) - return Object.getOwnPropertyDescriptor(obj, name); - obj = Object.getPrototypeOf(obj); - } - } + // 7.2 White Space - function getOwnProperties(obj) { - var map = {}; - for (var name in Object.getOwnPropertyNames(obj)) - map[name] = Object.getOwnPropertyDescriptor(obj, name); - return map; + function isWhiteSpace(ch) { + return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) || + (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0); } - function makePassthruHandler(obj) { - // Handler copied from - // http://wiki.ecmascript.org/doku.php?id=harmony:proxies&s=proxy%20object#examplea_no-op_forwarding_proxy - return { - getOwnPropertyDescriptor: function(name) { - var desc = Object.getOwnPropertyDescriptor(obj, name); - - // a trapping proxy's properties must always be configurable - desc.configurable = true; - return desc; - }, - getPropertyDescriptor: function(name) { - var desc = getPropertyDescriptor(obj, name); - - // a trapping proxy's properties must always be configurable - desc.configurable = true; - return desc; - }, - getOwnPropertyNames: function() { - return Object.getOwnPropertyNames(obj); - }, - defineProperty: function(name, desc) { - Object.defineProperty(obj, name, desc); - }, - "delete": function(name) { return delete obj[name]; }, - fix: function() { - if (Object.isFrozen(obj)) { - return getOwnProperties(obj); - } + // 7.3 Line Terminators - // As long as obj is not frozen, the proxy won't allow itself to be fixed. - return undefined; // will cause a TypeError to be thrown - }, + function isLineTerminator(ch) { + return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029); + } - has: function(name) { return name in obj; }, - hasOwn: function(name) { return ({}).hasOwnProperty.call(obj, name); }, - get: function(receiver, name) { return obj[name]; }, + // 7.6 Identifier Names and Identifiers - // bad behavior when set fails in non-strict mode - set: function(receiver, name, val) { obj[name] = val; return true; }, - enumerate: function() { - var result = []; - for (name in obj) { result.push(name); }; - return result; - }, - keys: function() { return Object.keys(obj); } - }; + function isIdentifierStart(ch) { + return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) + (ch >= 0x41 && ch <= 0x5A) || // A..Z + (ch >= 0x61 && ch <= 0x7A) || // a..z + (ch === 0x5C) || // \ (backslash) + ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))); } - // default function used when looking for a property in the global object - function noPropFound() { return undefined; } - - var hasOwnProperty = ({}).hasOwnProperty; + function isIdentifierPart(ch) { + return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) + (ch >= 0x41 && ch <= 0x5A) || // A..Z + (ch >= 0x61 && ch <= 0x7A) || // a..z + (ch >= 0x30 && ch <= 0x39) || // 0..9 + (ch === 0x5C) || // \ (backslash) + ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))); + } - function StringMap() { - this.table = Object.create(null, {}); - this.size = 0; + // 7.6.1.2 Future Reserved Words + + function isFutureReservedWord(id) { + switch (id) { + case 'class': + case 'enum': + case 'export': + case 'extends': + case 'import': + case 'super': + return true; + default: + return false; + } } - StringMap.prototype = { - has: function(x) { return hasOwnProperty.call(this.table, x); }, - set: function(x, v) { - if (!hasOwnProperty.call(this.table, x)) - this.size++; - this.table[x] = v; - }, - get: function(x) { return this.table[x]; }, - getDef: function(x, thunk) { - if (!hasOwnProperty.call(this.table, x)) { - this.size++; - this.table[x] = thunk(); - } - return this.table[x]; - }, - forEach: function(f) { - var table = this.table; - for (var key in table) - f.call(this, key, table[key]); - }, - toString: function() { return "[object StringMap]" } - }; + function isStrictModeReservedWord(id) { + switch (id) { + case 'implements': + case 'interface': + case 'package': + case 'private': + case 'protected': + case 'public': + case 'static': + case 'yield': + case 'let': + return true; + default: + return false; + } + } - // non-destructive stack - function Stack(elts) { - this.elts = elts || null; + function isRestrictedWord(id) { + return id === 'eval' || id === 'arguments'; } - Stack.prototype = { - push: function(x) { - return new Stack({ top: x, rest: this.elts }); - }, - top: function() { - if (!this.elts) - throw new Error("empty stack"); - return this.elts.top; - }, - isEmpty: function() { - return this.top === null; - }, - find: function(test) { - for (var elts = this.elts; elts; elts = elts.rest) { - if (test(elts.top)) - return elts.top; - } - return null; - }, - has: function(x) { - return Boolean(this.find(function(elt) { return elt === x })); - }, - forEach: function(f) { - for (var elts = this.elts; elts; elts = elts.rest) { - f(elts.top); - } - } - }; + // 7.6.1.1 Keywords - return { - tokens: tokens, - opTypeNames: opTypeNames, - keywords: keywords, - isStatementStartCode: isStatementStartCode, - tokenIds: tokenIds, - consts: consts, - assignOps: assignOps, - defineGetter: defineGetter, - defineProperty: defineProperty, - isNativeCode: isNativeCode, - makePassthruHandler: makePassthruHandler, - noPropFound: noPropFound, - StringMap: StringMap, - Stack: Stack - }; -}()); -/* vim: set sw=4 ts=4 et tw=78: */ -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is the Narcissus JavaScript engine. - * - * The Initial Developer of the Original Code is - * Brendan Eich . - * Portions created by the Initial Developer are Copyright (C) 2004 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * Tom Austin - * Brendan Eich - * Shu-Yu Guo - * Dave Herman - * Dimitris Vardoulakis - * Patrick Walton - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ + function isKeyword(id) { + if (strict && isStrictModeReservedWord(id)) { + return true; + } -/* - * Narcissus - JS implemented in JS. - * - * Lexical scanner. - */ + // 'const' is specialized as Keyword in V8. + // 'yield' and 'let' are for compatibility with SpiderMonkey and ES.next. + // Some others are from future reserved words. + + switch (id.length) { + case 2: + return (id === 'if') || (id === 'in') || (id === 'do'); + case 3: + return (id === 'var') || (id === 'for') || (id === 'new') || + (id === 'try') || (id === 'let'); + case 4: + return (id === 'this') || (id === 'else') || (id === 'case') || + (id === 'void') || (id === 'with') || (id === 'enum'); + case 5: + return (id === 'while') || (id === 'break') || (id === 'catch') || + (id === 'throw') || (id === 'const') || (id === 'yield') || + (id === 'class') || (id === 'super'); + case 6: + return (id === 'return') || (id === 'typeof') || (id === 'delete') || + (id === 'switch') || (id === 'export') || (id === 'import'); + case 7: + return (id === 'default') || (id === 'finally') || (id === 'extends'); + case 8: + return (id === 'function') || (id === 'continue') || (id === 'debugger'); + case 10: + return (id === 'instanceof'); + default: + return false; + } + } -Narcissus.lexer = (function() { + // 7.4 Comments - var definitions = Narcissus.definitions; + function addComment(type, value, start, end, loc) { + var comment; - // Set constants in the local scope. - eval(definitions.consts); + assert(typeof start === 'number', 'Comment must have valid position'); - // Build up a trie of operator tokens. - var opTokens = {}; - for (var op in definitions.opTypeNames) { - if (op === '\n' || op === '.') - continue; + // Because the way the actual token is scanned, often the comments + // (if any) are skipped twice during the lexical analysis. + // Thus, we need to skip adding a comment if the comment array already + // handled it. + if (state.lastCommentStart >= start) { + return; + } + state.lastCommentStart = start; - var node = opTokens; - for (var i = 0; i < op.length; i++) { - var ch = op[i]; - if (!(ch in node)) - node[ch] = {}; - node = node[ch]; - node.op = op; + comment = { + type: type, + value: value + }; + if (extra.range) { + comment.range = [start, end]; + } + if (extra.loc) { + comment.loc = loc; + } + extra.comments.push(comment); + if (extra.attachComment) { + extra.leadingComments.push(comment); + extra.trailingComments.push(comment); } } - /* - * Tokenizer :: (source, filename, line number) -> Tokenizer - */ - function Tokenizer(s, f, l) { - this.cursor = 0; - this.source = String(s); - this.tokens = []; - this.tokenIndex = 0; - this.lookahead = 0; - this.scanNewlines = false; - this.unexpectedEOF = false; - this.filename = f || ""; - this.lineno = l || 1; - } - - Tokenizer.prototype = { - get done() { - // We need to set scanOperand to true here because the first thing - // might be a regexp. - return this.peek(true) === END; - }, - - get token() { - return this.tokens[this.tokenIndex]; - }, + function skipSingleLineComment(offset) { + var start, loc, ch, comment; - match: function (tt, scanOperand) { - return this.get(scanOperand) === tt || this.unget(); - }, + start = index - offset; + loc = { + start: { + line: lineNumber, + column: index - lineStart - offset + } + }; - mustMatch: function (tt) { - if (!this.match(tt)) { - throw this.newSyntaxError("Missing " + - definitions.tokens[tt].toLowerCase()); + while (index < length) { + ch = source.charCodeAt(index); + ++index; + if (isLineTerminator(ch)) { + if (extra.comments) { + comment = source.slice(start + offset, index - 1); + loc.end = { + line: lineNumber, + column: index - lineStart - 1 + }; + addComment('Line', comment, start, index - 1, loc); + } + if (ch === 13 && source.charCodeAt(index) === 10) { + ++index; + } + ++lineNumber; + lineStart = index; + return; } - return this.token; - }, + } - forceIdentifier: function() { - if (!this.match(IDENTIFIER)) { - // keywords are valid property names in ES 5 - if (this.get() >= definitions.keywords[0] || this.unget) { - this.token.type = IDENTIFIER; - } - else { - throw this.newSyntaxError("Missing identifier"); - } - } - return this.token; - }, + if (extra.comments) { + comment = source.slice(start + offset, index); + loc.end = { + line: lineNumber, + column: index - lineStart + }; + addComment('Line', comment, start, index, loc); + } + } - peek: function (scanOperand) { - var tt, next; - if (this.lookahead) { - next = this.tokens[(this.tokenIndex + this.lookahead) & 3]; - tt = (this.scanNewlines && next.lineno !== this.lineno) - ? NEWLINE - : next.type; - } else { - tt = this.get(scanOperand); - this.unget(); - } - return tt; - }, + function skipMultiLineComment() { + var start, loc, ch, comment; - peekOnSameLine: function (scanOperand) { - this.scanNewlines = true; - var tt = this.peek(scanOperand); - this.scanNewlines = false; - return tt; - }, + if (extra.comments) { + start = index - 2; + loc = { + start: { + line: lineNumber, + column: index - lineStart - 2 + } + }; + } - // Eat comments and whitespace. - skip: function () { - var input = this.source; - for (;;) { - var ch = input[this.cursor++]; - var next = input[this.cursor]; - if (ch === '\n' && !this.scanNewlines) { - this.lineno++; - } else if (ch === '/' && next === '*') { - this.cursor++; - for (;;) { - ch = input[this.cursor++]; - if (ch === undefined) - throw this.newSyntaxError("Unterminated comment"); - - if (ch === '*') { - next = input[this.cursor]; - if (next === '/') { - this.cursor++; - break; - } - } else if (ch === '\n') { - this.lineno++; - } - } - } else if (ch === '/' && next === '/') { - this.cursor++; - for (;;) { - ch = input[this.cursor++]; - if (ch === undefined) - return; - - if (ch === '\n') { - this.lineno++; - break; - } + while (index < length) { + ch = source.charCodeAt(index); + if (isLineTerminator(ch)) { + if (ch === 0x0D && source.charCodeAt(index + 1) === 0x0A) { + ++index; + } + ++lineNumber; + ++index; + lineStart = index; + if (index >= length) { + throwUnexpectedToken(); + } + } else if (ch === 0x2A) { + // Block comment ends with '*/'. + if (source.charCodeAt(index + 1) === 0x2F) { + ++index; + ++index; + if (extra.comments) { + comment = source.slice(start + 2, index - 2); + loc.end = { + line: lineNumber, + column: index - lineStart + }; + addComment('Block', comment, start, index, loc); } - } else if (ch !== ' ' && ch !== '\t') { - this.cursor--; return; } + ++index; + } else { + ++index; } - }, + } - // Lex the exponential part of a number, if present. Return true iff an - // exponential part was found. - lexExponent: function() { - var input = this.source; - var next = input[this.cursor]; - if (next === 'e' || next === 'E') { - this.cursor++; - ch = input[this.cursor++]; - if (ch === '+' || ch === '-') - ch = input[this.cursor++]; - - if (ch < '0' || ch > '9') - throw this.newSyntaxError("Missing exponent"); - - do { - ch = input[this.cursor++]; - } while (ch >= '0' && ch <= '9'); - this.cursor--; + throwUnexpectedToken(); + } - return true; - } + function skipComment() { + var ch, start; - return false; - }, + start = (index === 0); + while (index < length) { + ch = source.charCodeAt(index); - lexZeroNumber: function (ch) { - var token = this.token, input = this.source; - token.type = NUMBER; - - ch = input[this.cursor++]; - if (ch === '.') { - do { - ch = input[this.cursor++]; - } while (ch >= '0' && ch <= '9'); - this.cursor--; - - this.lexExponent(); - token.value = parseFloat(input.substring(token.start, this.cursor)); - } else if (ch === 'x' || ch === 'X') { - do { - ch = input[this.cursor++]; - } while ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || - (ch >= 'A' && ch <= 'F')); - this.cursor--; - - token.value = parseInt(input.substring(token.start, this.cursor)); - } else if (ch >= '0' && ch <= '7') { - do { - ch = input[this.cursor++]; - } while (ch >= '0' && ch <= '7'); - this.cursor--; - - token.value = parseInt(input.substring(token.start, this.cursor), 8); - token.value.isOctal = true; // mark it to decomp as octal so that strict mode catches it + if (isWhiteSpace(ch)) { + ++index; + } else if (isLineTerminator(ch)) { + ++index; + if (ch === 0x0D && source.charCodeAt(index) === 0x0A) { + ++index; + } + ++lineNumber; + lineStart = index; + start = true; + } else if (ch === 0x2F) { // U+002F is '/' + ch = source.charCodeAt(index + 1); + if (ch === 0x2F) { + ++index; + ++index; + skipSingleLineComment(2); + start = true; + } else if (ch === 0x2A) { // U+002A is '*' + ++index; + ++index; + skipMultiLineComment(); + } else { + break; + } + } else if (start && ch === 0x2D) { // U+002D is '-' + // U+003E is '>' + if ((source.charCodeAt(index + 1) === 0x2D) && (source.charCodeAt(index + 2) === 0x3E)) { + // '-->' is a single-line comment + index += 3; + skipSingleLineComment(3); + } else { + break; + } + } else if (ch === 0x3C) { // U+003C is '<' + if (source.slice(index + 1, index + 4) === '!--') { + ++index; // `<` + ++index; // `!` + ++index; // `-` + ++index; // `-` + skipSingleLineComment(4); + } else { + break; + } } else { - this.cursor--; - this.lexExponent(); // 0E1, &c. - token.value = 0; + break; } - }, - - lexNumber: function (ch) { - var token = this.token, input = this.source; - token.type = NUMBER; - - var floating = false; - do { - ch = input[this.cursor++]; - if (ch === '.' && !floating) { - floating = true; - ch = input[this.cursor++]; - } - } while (ch >= '0' && ch <= '9'); + } + } - this.cursor--; + function scanHexEscape(prefix) { + var i, len, ch, code = 0; - var exponent = this.lexExponent(); - floating = floating || exponent; + len = (prefix === 'u') ? 4 : 2; + for (i = 0; i < len; ++i) { + if (index < length && isHexDigit(source[index])) { + ch = source[index++]; + code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); + } else { + return ''; + } + } + return String.fromCharCode(code); + } - var str = input.substring(token.start, this.cursor); - token.value = floating ? parseFloat(str) : parseInt(str); - }, + function scanUnicodeCodePointEscape() { + var ch, code, cu1, cu2; - lexDot: function (ch) { - var token = this.token, input = this.source; - var next = input[this.cursor]; - if (next >= '0' && next <= '9') { - do { - ch = input[this.cursor++]; - } while (ch >= '0' && ch <= '9'); - this.cursor--; + ch = source[index]; + code = 0; - this.lexExponent(); + // At least, one hex digit is required. + if (ch === '}') { + throwUnexpectedToken(); + } - token.type = NUMBER; - token.value = parseFloat(input.substring(token.start, this.cursor)); - } else { - token.type = DOT; - token.assignOp = null; - token.value = '.'; + while (index < length) { + ch = source[index++]; + if (!isHexDigit(ch)) { + break; } - }, - - lexString: function (ch) { - var token = this.token, input = this.source; - token.type = STRING; + code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); + } - var hasEscapes = false; - var delim = ch; - while ((ch = input[this.cursor++]) !== delim) { - if (this.cursor == input.length) - throw this.newSyntaxError("Unterminated string literal"); - if (ch === '\\') { - hasEscapes = true; - if (input[this.cursor] === '\n') this.lineno++; // fix for escaped newline - if (++this.cursor == input.length) - throw this.newSyntaxError("Unterminated string literal"); - } - } + if (code > 0x10FFFF || ch !== '}') { + throwUnexpectedToken(); + } - token.value = hasEscapes - ? eval(input.substring(token.start, this.cursor)) - : input.substring(token.start + 1, this.cursor - 1); - }, + // UTF-16 Encoding + if (code <= 0xFFFF) { + return String.fromCharCode(code); + } + cu1 = ((code - 0x10000) >> 10) + 0xD800; + cu2 = ((code - 0x10000) & 1023) + 0xDC00; + return String.fromCharCode(cu1, cu2); + } - lexRegExp: function (ch) { - var token = this.token, input = this.source; - token.type = REGEXP; + function getEscapedIdentifier() { + var ch, id; - do { - ch = input[this.cursor++]; - if (ch === '\\') { - this.cursor++; - } else if (ch === '[') { - do { - if (ch === undefined) - throw this.newSyntaxError("Unterminated character class"); + ch = source.charCodeAt(index++); + id = String.fromCharCode(ch); - if (ch === '\\') - this.cursor++; + // '\u' (U+005C, U+0075) denotes an escaped character. + if (ch === 0x5C) { + if (source.charCodeAt(index) !== 0x75) { + throwUnexpectedToken(); + } + ++index; + ch = scanHexEscape('u'); + if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) { + throwUnexpectedToken(); + } + id = ch; + } - ch = input[this.cursor++]; - } while (ch !== ']'); - } else if (ch === undefined) { - throw this.newSyntaxError("Unterminated regex"); + while (index < length) { + ch = source.charCodeAt(index); + if (!isIdentifierPart(ch)) { + break; + } + ++index; + id += String.fromCharCode(ch); + + // '\u' (U+005C, U+0075) denotes an escaped character. + if (ch === 0x5C) { + id = id.substr(0, id.length - 1); + if (source.charCodeAt(index) !== 0x75) { + throwUnexpectedToken(); } - } while (ch !== '/'); - - do { - ch = input[this.cursor++]; - } while (ch >= 'a' && ch <= 'z'); + ++index; + ch = scanHexEscape('u'); + if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) { + throwUnexpectedToken(); + } + id += ch; + } + } - this.cursor--; + return id; + } - token.value = eval(input.substring(token.start, this.cursor)); - }, + function getIdentifier() { + var start, ch; - lexOp: function (ch) { - var token = this.token, input = this.source; - - // A bit ugly, but it seems wasteful to write a trie lookup routine - // for only 3 characters... - var node = opTokens[ch]; - var next = input[this.cursor]; - if (next in node) { - node = node[next]; - this.cursor++; - next = input[this.cursor]; - if (next in node) { - node = node[next]; - this.cursor++; - next = input[this.cursor]; - } - } - - var op = node.op; - if (definitions.assignOps[op] && input[this.cursor] === '=') { - this.cursor++; - token.type = ASSIGN; - token.assignOp = definitions.tokenIds[definitions.opTypeNames[op]]; - op += '='; + start = index++; + while (index < length) { + ch = source.charCodeAt(index); + if (ch === 0x5C) { + // Blackslash (U+005C) marks Unicode escape sequence. + index = start; + return getEscapedIdentifier(); + } + if (isIdentifierPart(ch)) { + ++index; } else { - token.type = definitions.tokenIds[definitions.opTypeNames[op]]; - token.assignOp = null; + break; } + } - token.value = op; - }, - - // FIXME: Unicode escape sequences - // FIXME: Unicode identifiers - lexIdent: function (ch) { - var token = this.token, input = this.source; + return source.slice(start, index); + } - do { - ch = input[this.cursor++]; - } while ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || - (ch >= '0' && ch <= '9') || ch === '$' || ch === '_'); + function scanIdentifier() { + var start, id, type; - this.cursor--; // Put the non-word character back. + start = index; - var id = input.substring(token.start, this.cursor); - token.type = definitions.keywords[id] || IDENTIFIER; - token.value = id; - }, + // Backslash (U+005C) starts an escaped character. + id = (source.charCodeAt(index) === 0x5C) ? getEscapedIdentifier() : getIdentifier(); - /* - * Tokenizer.get :: void -> token type - * - * Consume input *only* if there is no lookahead. - * Dispatch to the appropriate lexing function depending on the input. - */ - get: function (scanOperand) { - var token; - while (this.lookahead) { - --this.lookahead; - this.tokenIndex = (this.tokenIndex + 1) & 3; - token = this.tokens[this.tokenIndex]; - if (token.type !== NEWLINE || this.scanNewlines) - return token.type; - } - - this.skip(); - - this.tokenIndex = (this.tokenIndex + 1) & 3; - token = this.tokens[this.tokenIndex]; - if (!token) - this.tokens[this.tokenIndex] = token = {}; - - var input = this.source; - if (this.cursor === input.length) - return token.type = END; - - token.start = this.cursor; - token.lineno = this.lineno; - - var ch = input[this.cursor++]; - if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch === '$' || ch === '_') { - this.lexIdent(ch); - } else if (scanOperand && ch === '/') { - this.lexRegExp(ch); - } else if (ch in opTokens) { - this.lexOp(ch); - } else if (ch === '.') { - this.lexDot(ch); - } else if (ch >= '1' && ch <= '9') { - this.lexNumber(ch); - } else if (ch === '0') { - this.lexZeroNumber(ch); - } else if (ch === '"' || ch === "'") { - this.lexString(ch); - } else if (this.scanNewlines && ch === '\n') { - token.type = NEWLINE; - token.value = '\n'; - this.lineno++; - } else { - throw this.newSyntaxError("Illegal token"); - } + // There is no keyword or literal with only one character. + // Thus, it must be an identifier. + if (id.length === 1) { + type = Token.Identifier; + } else if (isKeyword(id)) { + type = Token.Keyword; + } else if (id === 'null') { + type = Token.NullLiteral; + } else if (id === 'true' || id === 'false') { + type = Token.BooleanLiteral; + } else { + type = Token.Identifier; + } - token.end = this.cursor; - return token.type; - }, + return { + type: type, + value: id, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } - /* - * Tokenizer.unget :: void -> undefined - * - * Match depends on unget returning undefined. - */ - unget: function () { - if (++this.lookahead === 4) throw "PANIC: too much lookahead!"; - this.tokenIndex = (this.tokenIndex - 1) & 3; - }, - newSyntaxError: function (m) { - var e = new SyntaxError(this.filename + ":" + this.lineno + ":" + m); - e.source = this.source; - e.cursor = this.lookahead - ? this.tokens[(this.tokenIndex + this.lookahead) & 3].start - : this.cursor; - return e; - }, - }; + // 7.7 Punctuators + + function scanPunctuator() { + var start = index, + code = source.charCodeAt(index), + code2, + ch1 = source[index], + ch2, + ch3, + ch4; + + switch (code) { + + // Check for most common single-character punctuators. + case 0x2E: // . dot + case 0x28: // ( open bracket + case 0x29: // ) close bracket + case 0x3B: // ; semicolon + case 0x2C: // , comma + case 0x7B: // { open curly brace + case 0x7D: // } close curly brace + case 0x5B: // [ + case 0x5D: // ] + case 0x3A: // : + case 0x3F: // ? + case 0x7E: // ~ + ++index; + if (extra.tokenize) { + if (code === 0x28) { + extra.openParenToken = extra.tokens.length; + } else if (code === 0x7B) { + extra.openCurlyToken = extra.tokens.length; + } + } + return { + type: Token.Punctuator, + value: String.fromCharCode(code), + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + + default: + code2 = source.charCodeAt(index + 1); + + // '=' (U+003D) marks an assignment or comparison operator. + if (code2 === 0x3D) { + switch (code) { + case 0x2B: // + + case 0x2D: // - + case 0x2F: // / + case 0x3C: // < + case 0x3E: // > + case 0x5E: // ^ + case 0x7C: // | + case 0x25: // % + case 0x26: // & + case 0x2A: // * + index += 2; + return { + type: Token.Punctuator, + value: String.fromCharCode(code) + String.fromCharCode(code2), + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + + case 0x21: // ! + case 0x3D: // = + index += 2; + + // !== and === + if (source.charCodeAt(index) === 0x3D) { + ++index; + } + return { + type: Token.Punctuator, + value: source.slice(start, index), + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + } + } - return { Tokenizer: Tokenizer }; + // 4-character punctuator: >>>= -}()); -/* -*- Mode: JS; tab-width: 4; indent-tabs-mode: nil; -*- - * vim: set sw=4 ts=4 et tw=78: - * ***** BEGIN LICENSE BLOCK ***** - * - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is the Narcissus JavaScript engine. - * - * The Initial Developer of the Original Code is - * Brendan Eich . - * Portions created by the Initial Developer are Copyright (C) 2004 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * Tom Austin - * Brendan Eich - * Shu-Yu Guo - * Dave Herman - * Dimitris Vardoulakis - * Patrick Walton - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ + ch4 = source.substr(index, 4); -/* - * Narcissus - JS implemented in JS. - * - * Parser. - */ + if (ch4 === '>>>=') { + index += 4; + return { + type: Token.Punctuator, + value: ch4, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } -Narcissus.parser = (function() { + // 3-character punctuators: === !== >>> <<= >>= - var lexer = Narcissus.lexer; - var definitions = Narcissus.definitions; + ch3 = ch4.substr(0, 3); - const StringMap = definitions.StringMap; - const Stack = definitions.Stack; + if (ch3 === '>>>' || ch3 === '<<=' || ch3 === '>>=') { + index += 3; + return { + type: Token.Punctuator, + value: ch3, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } - // Set constants in the local scope. - eval(definitions.consts); + // Other 2-character punctuators: ++ -- << >> && || + ch2 = ch3.substr(0, 2); + + if ((ch1 === ch2[1] && ('+-<>&|'.indexOf(ch1) >= 0)) || ch2 === '=>') { + index += 2; + return { + type: Token.Punctuator, + value: ch2, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } - /* - * pushDestructuringVarDecls :: (node, hoisting node) -> void - * - * Recursively add all destructured declarations to varDecls. - */ - function pushDestructuringVarDecls(n, s) { - for (var i in n) { - var sub = n[i]; - if (sub.type === IDENTIFIER) { - s.varDecls.push(sub); - } else { - pushDestructuringVarDecls(sub, s); - } + // 1-character punctuators: < > = ! + - * % & | ^ / + + if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) { + ++index; + return { + type: Token.Punctuator, + value: ch1, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; } + + throwUnexpectedToken(); } - // NESTING_TOP: top-level - // NESTING_SHALLOW: nested within static forms such as { ... } or labeled statement - // NESTING_DEEP: nested within dynamic forms such as if, loops, etc. - const NESTING_TOP = 0, NESTING_SHALLOW = 1, NESTING_DEEP = 2; + // 7.8.3 Numeric Literals - function StaticContext(parentScript, parentBlock, inFunction, inForLoopInit, nesting) { - this.parentScript = parentScript; - this.parentBlock = parentBlock; - this.inFunction = inFunction; - this.inForLoopInit = inForLoopInit; - this.nesting = nesting; - this.allLabels = new Stack(); - this.currentLabels = new Stack(); - this.labeledTargets = new Stack(); - this.defaultTarget = null; - Narcissus.options.ecma3OnlyMode && (this.ecma3OnlyMode = true); - Narcissus.options.parenFreeMode && (this.parenFreeMode = true); - } + function scanHexLiteral(start) { + var number = ''; - StaticContext.prototype = { - ecma3OnlyMode: false, - parenFreeMode: false, - // non-destructive update via prototype extension - update: function(ext) { - var desc = {}; - for (var key in ext) { - desc[key] = { - value: ext[key], - writable: true, - enumerable: true, - configurable: true - } + while (index < length) { + if (!isHexDigit(source[index])) { + break; } - return Object.create(this, desc); - }, - pushLabel: function(label) { - return this.update({ currentLabels: this.currentLabels.push(label), - allLabels: this.allLabels.push(label) }); - }, - pushTarget: function(target) { - var isDefaultTarget = target.isLoop || target.type === SWITCH; - if (isDefaultTarget) target.target = this.defaultTarget; + number += source[index++]; + } - if (this.currentLabels.isEmpty()) { - return isDefaultTarget - ? this.update({ defaultTarget: target }) - : this; - } + if (number.length === 0) { + throwUnexpectedToken(); + } - target.labels = new StringMap(); - this.currentLabels.forEach(function(label) { - target.labels.set(label, true); - }); - return this.update({ currentLabels: new Stack(), - labeledTargets: this.labeledTargets.push(target), - defaultTarget: isDefaultTarget - ? target - : this.defaultTarget }); - }, - nest: function(atLeast) { - var nesting = Math.max(this.nesting, atLeast); - return (nesting !== this.nesting) - ? this.update({ nesting: nesting }) - : this; + if (isIdentifierStart(source.charCodeAt(index))) { + throwUnexpectedToken(); } - }; - /* - * Script :: (tokenizer, boolean) -> node - * - * Parses the toplevel and function bodies. - */ - function Script(t, inFunction) { - var n = new Node(t, scriptInit()); - var x = new StaticContext(n, n, inFunction, false, NESTING_TOP); - Statements(t, x, n); - return n; + return { + type: Token.NumericLiteral, + value: parseInt('0x' + number, 16), + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; } - // We extend Array slightly with a top-of-stack method. - definitions.defineProperty(Array.prototype, "top", - function() { - return this.length && this[this.length-1]; - }, false, false, true); + function scanBinaryLiteral(start) { + var ch, number; - /* - * Node :: (tokenizer, optional init object) -> node - */ - function Node(t, init) { - var token = t.token; - if (token) { - // If init.type exists it will override token.type. - this.type = token.type; - this.value = token.value; - this.lineno = token.lineno; + number = ''; - // Start and end are file positions for error handling. - this.start = token.start; - this.end = token.end; - } else { - this.lineno = t.lineno; + while (index < length) { + ch = source[index]; + if (ch !== '0' && ch !== '1') { + break; + } + number += source[index++]; } - // Node uses a tokenizer for debugging (getSource, filename getter). - this.tokenizer = t; - this.children = []; - - for (var prop in init) - this[prop] = init[prop]; - } - - var Np = Node.prototype = {}; - Np.constructor = Node; - Np.toSource = Object.prototype.toSource; - - // Always use push to add operands to an expression, to update start and end. - Np.push = function (kid) { - // kid can be null e.g. [1, , 2]. - if (kid !== null) { - if (kid.start < this.start) - this.start = kid.start; - if (this.end < kid.end) - this.end = kid.end; + if (number.length === 0) { + // only 0b or 0B + throwUnexpectedToken(); } - return this.children.push(kid); - } - Node.indentLevel = 0; + if (index < length) { + ch = source.charCodeAt(index); + /* istanbul ignore else */ + if (isIdentifierStart(ch) || isDecimalDigit(ch)) { + throwUnexpectedToken(); + } + } - function tokenString(tt) { - var t = definitions.tokens[tt]; - return /^\W/.test(t) ? definitions.opTypeNames[t] : t.toUpperCase(); + return { + type: Token.NumericLiteral, + value: parseInt(number, 2), + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; } - Np.toString = function () { - var a = []; - for (var i in this) { - if (this.hasOwnProperty(i) && i !== 'type' && i !== 'target') - a.push({id: i, value: this[i]}); - } - a.sort(function (a,b) { return (a.id < b.id) ? -1 : 1; }); - const INDENTATION = " "; - var n = ++Node.indentLevel; - var s = "{\n" + INDENTATION.repeat(n) + "type: " + tokenString(this.type); - for (i = 0; i < a.length; i++) - s += ", " + a[i].id + ": " + a[i].value; - //s += ",\n" + INDENTATION.repeat(n) + a[i].id + ": " + a[i].value; - n = --Node.indentLevel; - s += "\n" + INDENTATION.repeat(n) + "}"; - return s; - } + function scanOctalLiteral(prefix, start) { + var number, octal; - Np.getSource = function () { - return this.tokenizer.source.slice(this.start, this.end); - }; + if (isOctalDigit(prefix)) { + octal = true; + number = '0' + source[index++]; + } else { + octal = false; + ++index; + number = ''; + } - /* - * Helper init objects for common nodes. - */ + while (index < length) { + if (!isOctalDigit(source[index])) { + break; + } + number += source[index++]; + } - const LOOP_INIT = { isLoop: true }; + if (!octal && number.length === 0) { + // only 0o or 0O + throwUnexpectedToken(); + } - function blockInit() { - return { type: BLOCK, varDecls: [] }; - } + if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) { + throwUnexpectedToken(); + } - function scriptInit() { - return { type: SCRIPT, - funDecls: [], - varDecls: [], - modDecls: [], - impDecls: [], - expDecls: [], - loadDeps: [], - hasEmptyReturn: false, - hasReturnWithValue: false, - isGenerator: false }; + return { + type: Token.NumericLiteral, + value: parseInt(number, 8), + octal: octal, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; } - definitions.defineGetter(Np, "filename", - function() { - return this.tokenizer.filename; - }); - - definitions.defineGetter(Np, "length", - function() { - throw new Error("Node.prototype.length is gone; " + - "use n.children.length instead"); - }); + function isImplicitOctalLiteral() { + var i, ch; - definitions.defineProperty(String.prototype, "repeat", - function(n) { - var s = "", t = this + s; - while (--n >= 0) - s += t; - return s; - }, false, false, true); + // Implicit octal, unless there is a non-octal digit. + // (Annex B.1.1 on Numeric Literals) + for (i = index + 1; i < length; ++i) { + ch = source[i]; + if (ch === '8' || ch === '9') { + return false; + } + if (!isOctalDigit(ch)) { + return true; + } + } - function MaybeLeftParen(t, x) { - if (x.parenFreeMode) - return t.match(LEFT_PAREN) ? LEFT_PAREN : END; - return t.mustMatch(LEFT_PAREN).type; + return true; } - function MaybeRightParen(t, p) { - if (p === LEFT_PAREN) - t.mustMatch(RIGHT_PAREN); - } - - /* - * Statements :: (tokenizer, compiler context, node) -> void - * - * Parses a sequence of Statements. - */ - function Statements(t, x, n) { - try { - while (!t.done && t.peek(true) !== RIGHT_CURLY) - n.push(Statement(t, x)); - } catch (e) { - if (t.done) - t.unexpectedEOF = true; - throw e; - } - } - - function Block(t, x) { - t.mustMatch(LEFT_CURLY); - var n = new Node(t, blockInit()); - Statements(t, x.update({ parentBlock: n }).pushTarget(n), n); - t.mustMatch(RIGHT_CURLY); - n.end = t.token.end; - return n; - } - - const DECLARED_FORM = 0, EXPRESSED_FORM = 1, STATEMENT_FORM = 2; - - /* - * Statement :: (tokenizer, compiler context) -> node - * - * Parses a Statement. - */ - function Statement(t, x) { - var i, label, n, n2, p, c, ss, tt = t.get(true), tt2, x2, x3; - - // Cases for statements ending in a right curly return early, avoiding the - // common semicolon insertion magic after this switch. - switch (tt) { - case FUNCTION: - // DECLARED_FORM extends funDecls of x, STATEMENT_FORM doesn't. - return FunctionDefinition(t, x, true, - (x.nesting !== NESTING_TOP) - ? STATEMENT_FORM - : DECLARED_FORM); - - case LEFT_CURLY: - n = new Node(t, blockInit()); - Statements(t, x.update({ parentBlock: n }).pushTarget(n).nest(NESTING_SHALLOW), n); - t.mustMatch(RIGHT_CURLY); - n.end = t.token.end; - return n; - - case IF: - n = new Node(t); - n.condition = HeadExpression(t, x); - x2 = x.pushTarget(n).nest(NESTING_DEEP); - n.thenPart = Statement(t, x2); - n.elsePart = t.match(ELSE) ? Statement(t, x2) : null; - return n; - - case SWITCH: - // This allows CASEs after a DEFAULT, which is in the standard. - n = new Node(t, { cases: [], defaultIndex: -1 }); - n.discriminant = HeadExpression(t, x); - x2 = x.pushTarget(n).nest(NESTING_DEEP); - t.mustMatch(LEFT_CURLY); - while ((tt = t.get()) !== RIGHT_CURLY) { - switch (tt) { - case DEFAULT: - if (n.defaultIndex >= 0) - throw t.newSyntaxError("More than one switch default"); - // FALL THROUGH - case CASE: - n2 = new Node(t); - if (tt === DEFAULT) - n.defaultIndex = n.cases.length; - else - n2.caseLabel = Expression(t, x2, COLON); - break; - - default: - throw t.newSyntaxError("Invalid switch case"); - } - t.mustMatch(COLON); - n2.statements = new Node(t, blockInit()); - while ((tt=t.peek(true)) !== CASE && tt !== DEFAULT && - tt !== RIGHT_CURLY) - n2.statements.push(Statement(t, x2)); - n.cases.push(n2); - } - n.end = t.token.end; - return n; - - case FOR: - n = new Node(t, LOOP_INIT); - if (t.match(IDENTIFIER)) { - if (t.token.value === "each") - n.isEach = true; - else - t.unget(); - } - if (!x.parenFreeMode) - t.mustMatch(LEFT_PAREN); - x2 = x.pushTarget(n).nest(NESTING_DEEP); - x3 = x.update({ inForLoopInit: true }); - if ((tt = t.peek()) !== SEMICOLON) { - if (tt === VAR || tt === CONST) { - t.get(); - n2 = Variables(t, x3); - } else if (tt === LET) { - t.get(); - if (t.peek() === LEFT_PAREN) { - n2 = LetBlock(t, x3, false); - } else { - // Let in for head, we need to add an implicit block - // around the rest of the for. - x3.parentBlock = n; - n.varDecls = []; - n2 = Variables(t, x3); - } - } else { - n2 = Expression(t, x3); + function scanNumericLiteral() { + var number, start, ch; + + ch = source[index]; + assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), + 'Numeric literal must start with a decimal digit or a decimal point'); + + start = index; + number = ''; + if (ch !== '.') { + number = source[index++]; + ch = source[index]; + + // Hex number starts with '0x'. + // Octal number starts with '0'. + // Octal number in ES6 starts with '0o'. + // Binary number in ES6 starts with '0b'. + if (number === '0') { + if (ch === 'x' || ch === 'X') { + ++index; + return scanHexLiteral(start); + } + if (ch === 'b' || ch === 'B') { + ++index; + return scanBinaryLiteral(start); + } + if (ch === 'o' || ch === 'O') { + return scanOctalLiteral(ch, start); } - } - if (n2 && t.match(IN)) { - n.type = FOR_IN; - n.object = Expression(t, x3); - if (n2.type === VAR || n2.type === LET) { - c = n2.children; - // Destructuring turns one decl into multiples, so either - // there must be only one destructuring or only one - // decl. - if (c.length !== 1 && n2.destructurings.length !== 1) { - throw new SyntaxError("Invalid for..in left-hand side", - t.filename, n2.lineno); - } - if (n2.destructurings.length > 0) { - n.iterator = n2.destructurings[0]; - } else { - n.iterator = c[0]; - } - n.varDecl = n2; - } else { - if (n2.type === ARRAY_INIT || n2.type === OBJECT_INIT) { - n2.destructuredNames = checkDestructuring(t, x3, n2); + if (isOctalDigit(ch)) { + if (isImplicitOctalLiteral()) { + return scanOctalLiteral(ch, start); } - n.iterator = n2; } - } else { - n.setup = n2; - t.mustMatch(SEMICOLON); - if (n.isEach) - throw t.newSyntaxError("Invalid for each..in loop"); - n.condition = (t.peek() === SEMICOLON) - ? null - : Expression(t, x3); - t.mustMatch(SEMICOLON); - tt2 = t.peek(); - n.update = (x.parenFreeMode - ? tt2 === LEFT_CURLY || definitions.isStatementStartCode[tt2] - : tt2 === RIGHT_PAREN) - ? null - : Expression(t, x3); - } - if (!x.parenFreeMode) - t.mustMatch(RIGHT_PAREN); - n.body = Statement(t, x2); - n.end = t.token.end; - return n; - - case WHILE: - n = new Node(t, { isLoop: true }); - n.condition = HeadExpression(t, x); - n.body = Statement(t, x.pushTarget(n).nest(NESTING_DEEP)); - n.end = t.token.end; - return n; - - case DO: - n = new Node(t, { isLoop: true }); - n.body = Statement(t, x.pushTarget(n).nest(NESTING_DEEP)); - t.mustMatch(WHILE); - n.condition = HeadExpression(t, x); - if (!x.ecmaStrictMode) { - // - - - - + + -