[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[GNUnet-SVN] [taler-wallet-webex] branch master updated: convert tests t
From: |
gnunet |
Subject: |
[GNUnet-SVN] [taler-wallet-webex] branch master updated: convert tests to ava tests |
Date: |
Sat, 27 May 2017 19:20:34 +0200 |
This is an automated email from the git hooks/post-receive script.
dold pushed a commit to branch master
in repository wallet-webex.
The following commit(s) were added to refs/heads/master by this push:
new 9a1b2c8c convert tests to ava tests
9a1b2c8c is described below
commit 9a1b2c8ccc5f079dae4966dfd011f4076a53dc20
Author: Florian Dold <address@hidden>
AuthorDate: Sat May 27 19:20:27 2017 +0200
convert tests to ava tests
---
node_modules/talertest/node/runtime.js | 43 -
node_modules/talertest/package.json | 19 -
node_modules/talertest/selenium/.gitignore | 2 -
.../talertest/selenium/escodegen.browser.js | 4947 ---------------
node_modules/talertest/selenium/esprima.js | 6605 --------------------
node_modules/talertest/selenium/instrumenter.js | 1097 ----
node_modules/talertest/selenium/runtime.js | 206 -
node_modules/talertest/selenium/system.js | 6 -
node_modules/talertest/selenium/testhost.html | 63 -
node_modules/talertest/talertest.d.ts | 19 -
node_modules/talertest/talertest.js | 111 -
node_modules/talertest/talertest.ts | 122 -
node_modules/talertest/tsconfig.json | 19 -
node_modules/talertest/yarn.lock | 7 -
package.json | 1 -
src/crypto/cryptoApi-test.ts | 14 +-
src/crypto/emscInterface-test.ts | 44 +-
src/helpers-test.ts | 16 +-
src/types-test.ts | 22 +-
src/wallet-test.ts | 22 +-
tooling/talertest/node/runtime.js | 43 -
tooling/talertest/package.json | 19 -
tooling/talertest/selenium/.gitignore | 2 -
tooling/talertest/selenium/escodegen.browser.js | 4947 ---------------
tooling/talertest/selenium/esprima.js | 6605 --------------------
tooling/talertest/selenium/instrumenter.js | 1097 ----
tooling/talertest/selenium/runtime.js | 206 -
tooling/talertest/selenium/system.js | 6 -
tooling/talertest/selenium/testhost.html | 63 -
tooling/talertest/talertest.d.ts | 19 -
tooling/talertest/talertest.js | 111 -
tooling/talertest/talertest.ts | 122 -
tooling/talertest/tsconfig.json | 19 -
tooling/talertest/yarn.lock | 7 -
34 files changed, 59 insertions(+), 26592 deletions(-)
diff --git a/node_modules/talertest/node/runtime.js
b/node_modules/talertest/node/runtime.js
deleted file mode 100644
index 8c899337..00000000
--- a/node_modules/talertest/node/runtime.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 Inria
-
- TALER is free software; you can redistribute it and/or modify it under the
- terms of the GNU General Public License as published by the Free Software
- Foundation; either version 3, or (at your option) any later version.
-
- TALER is distributed in the hope that it will be useful, but WITHOUT ANY
- WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
- A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License along with
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- *
- * @author Florian Dold
- */
-
-
-"use strict";
-
-let vm = require("vm");
-let fs = require("fs");
-let process = require("process");
-let path = require("path");
-
-let testFile = path.resolve(process.argv[2]);
-
-console.log("TAP version 13");
-console.log("running test", testFile);
-
-process.on('unhandledRejection', function(reason, p){
- console.log("Possibly Unhandled Rejection at: Promise ", p, " reason: ",
reason);
- process.exit(1);
-});
-
-let tt = require("../talertest");
-require(testFile);
-
-tt.run();
diff --git a/node_modules/talertest/package.json
b/node_modules/talertest/package.json
deleted file mode 100644
index ae7e58ee..00000000
--- a/node_modules/talertest/package.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "name": "talertest",
- "version": "1.0.0",
- "main": "talertest.js",
- "types": "talertest.d.ts",
- "author": "Florian Dold",
- "license": "GPL-2.0+",
- "scripts": {
- "build": "tsc"
- },
- "files": [
- "node/",
- "selenium/",
- "talertest.d.ts"
- ],
- "devDependencies": {
- "typescript": "^2.2.2"
- }
-}
diff --git a/node_modules/talertest/selenium/.gitignore
b/node_modules/talertest/selenium/.gitignore
deleted file mode 100644
index 8a8d8911..00000000
--- a/node_modules/talertest/selenium/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-coverage/
-coveage-*.json
diff --git a/node_modules/talertest/selenium/escodegen.browser.js
b/node_modules/talertest/selenium/escodegen.browser.js
deleted file mode 100644
index 5f8f5e5b..00000000
--- a/node_modules/talertest/selenium/escodegen.browser.js
+++ /dev/null
@@ -1,4947 +0,0 @@
-// Generated by CommonJS Everywhere 0.9.7
-(function (global) {
- function require(file, parentModule) {
- if ({}.hasOwnProperty.call(require.cache, file))
- return require.cache[file];
- var resolved = require.resolve(file);
- if (!resolved)
- throw new Error('Failed to resolve module ' + file);
- var module$ = {
- id: file,
- require: require,
- filename: file,
- exports: {},
- loaded: false,
- parent: parentModule,
- children: []
- };
- if (parentModule)
- parentModule.children.push(module$);
- var dirname = file.slice(0, file.lastIndexOf('/') + 1);
- require.cache[file] = module$.exports;
- resolved.call(module$.exports, module$, module$.exports, dirname, file);
- module$.loaded = true;
- return require.cache[file] = module$.exports;
- }
- require.modules = {};
- require.cache = {};
- require.resolve = function (file) {
- return {}.hasOwnProperty.call(require.modules, file) ?
require.modules[file] : void 0;
- };
- require.define = function (file, fn) {
- require.modules[file] = fn;
- };
- var process = function () {
- var cwd = '/';
- return {
- title: 'browser',
- version: 'v7.0.0',
- browser: true,
- env: {},
- argv: [],
- nextTick: global.setImmediate || function (fn) {
- setTimeout(fn, 0);
- },
- cwd: function () {
- return cwd;
- },
- chdir: function (dir) {
- cwd = dir;
- }
- };
- }();
- require.define('/tools/entry-point.js', function (module, exports,
__dirname, __filename) {
- (function () {
- 'use strict';
- global.escodegen = require('/escodegen.js', module);
- escodegen.browser = true;
- }());
- });
- require.define('/escodegen.js', function (module, exports, __dirname,
__filename) {
- (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('/node_modules/estraverse/estraverse.js', module);
- esutils = require('/node_modules/esutils/lib/utils.js', module);
- Syntax = estraverse.Syntax;
- function isExpression(node) {
- return CodeGenerator.Expression.hasOwnProperty(node.type);
- }
- 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
- };
- 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;
- 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;
- var S_TFFF = F_ALLOW_IN, S_TFFT = F_ALLOW_IN | F_SEMICOLON_OPT, S_FFFF =
0, S_TFTF = F_ALLOW_IN | F_DIRECTIVE_CTX, S_TTFF = F_ALLOW_IN | F_FUNC_BODY;
- function getDefaultOptions() {
- 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) === 48 && 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) === 48) {
- --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;
- }
- function escapeRegExpCharacter(ch, previousIsBackslash) {
- if ((ch & ~1) === 8232) {
- return (previousIsBackslash ? 'u' : '\\u') + (ch === 8232 ? '2028' :
'2029');
- } else if (ch === 10 || ch === 13) {
- 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) {
- 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 {
- result += escapeRegExpCharacter(ch, previousIsBackslash);
- previousIsBackslash = false;
- }
- }
- return '/' + result + '/' + flags;
- }
- return result;
- }
- function escapeAllowedCharacter(code, next) {
- var hex;
- if (code === 8) {
- return '\\b';
- }
- if (code === 12) {
- return '\\f';
- }
- if (code === 9) {
- return '\\t';
- }
- hex = code.toString(16).toUpperCase();
- if (json || code > 255) {
- return '\\u' + '0000'.slice(hex.length) + hex;
- } else if (code === 0 && !esutils.code.isDecimalDigit(next)) {
- return '\\0';
- } else if (code === 11) {
- return '\\x0B';
- } else {
- return '\\x' + '00'.slice(hex.length) + hex;
- }
- }
- function escapeDisallowedCharacter(code) {
- if (code === 92) {
- return '\\\\';
- }
- if (code === 10) {
- return '\\n';
- }
- if (code === 13) {
- return '\\r';
- }
- if (code === 8232) {
- return '\\u2028';
- }
- if (code === 8233) {
- 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 === 39) {
- quote = '"';
- break;
- } else if (code === 34) {
- quote = "'";
- break;
- } else if (code === 92) {
- ++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 === 39) {
- ++singleQuotes;
- } else if (code === 34) {
- ++doubleQuotes;
- } else if (code === 47 && json) {
- result += '\\';
- } else if (esutils.code.isLineTerminator(code) || code === 92) {
- result += escapeDisallowedCharacter(code);
- continue;
- } else if (!esutils.code.isIdentifierPartES5(code) && (json && code
< 32 || !json && !escapeless && (code < 32 || code > 126))) {
- 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 === 39 && single || code === 34 && !single) {
- result += '\\';
- }
- result += String.fromCharCode(code);
- }
- return result + quote;
- }
- 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;
- }
- function toSourceNodeWhenNeeded(generated, node) {
- if (!sourceMap) {
- 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 === 43 || leftCharCode === 45) && leftCharCode ===
rightCharCode || esutils.code.isIdentifierPartES5(leftCharCode) &&
esutils.code.isIdentifierPartES5(rightCharCode) || leftCharCode === 47 &&
rightCharCode === 105) {
- 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;
- 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') {
- previousBase = base;
- if (array[1][spaces] === '*') {
- specialBase += ' ';
- }
- base = specialBase;
- } else {
- if (spaces & 1) {
- --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 {
- 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) {
- if (i === 0) {
- 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 {
- result = generateVerbatimString(verbatim.content);
- prec = verbatim.precedence != null ? verbatim.precedence :
Precedence.Sequence;
- result = parenthesize(result, prec, precedence);
- }
- return toSourceNodeWhenNeeded(result, expr);
- }
- function CodeGenerator() {
- }
- 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 {
- 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) {
- 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]) {
- 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,
value) {
- var result = [];
- if (computed) {
- result.push('[');
- }
- if (value.type === 'AssignmentPattern') {
- result.push(this.AssignmentPattern(value, Precedence.Sequence,
E_TTT));
- } else {
- 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 ';';
- };
- CodeGenerator.Statement = {
- BlockStatement: function (stmt, flags) {
- var range, content, result = [
- '{',
- newline
- ], that = this;
- withIndent(function () {
- 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) {
- 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);
- }
- }
- 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) {
- if (!stmt.body[i + 1].leadingComments) {
- result.push(newline);
- }
- } else {
- result.push(newline);
- }
- }
- if (preserveBlankLines) {
- 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'];
- if (stmt.id) {
- result = join(result, this.generateExpression(stmt.id,
Precedence.Sequence, E_TTT));
- }
- 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) {
- 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 ';';
- },
- ExportDefaultDeclaration: function (stmt, flags) {
- var result = ['export'], bodyFlags;
- bodyFlags = flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF;
- 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;
- },
- ExportNamedDeclaration: function (stmt, flags) {
- var result = ['export'], bodyFlags, that = this;
- bodyFlags = flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF;
- if (stmt.declaration) {
- return join(result, this.generateStatement(stmt.declaration,
bodyFlags));
- }
- 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,
- this.generateExpression(stmt.source, Precedence.Sequence,
E_TTT),
- this.semicolon(flags)
- ]);
- } else {
- result.push(this.semicolon(flags));
- }
- }
- return result;
- },
- ExportAllDeclaration: function (stmt, flags) {
- return [
- 'export' + space,
- '*' + space,
- 'from' + space,
- this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
- this.semicolon(flags)
- ];
- },
- 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 === 123 || 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 === 40 || esutils.code.isWhiteSpace(code) || code ===
42 || 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 === 40 || esutils.code.isWhiteSpace(code) || code ===
42 || esutils.code.isLineTerminator(code);
- }
- result = [this.generateExpression(stmt.expression,
Precedence.Sequence, E_TTT)];
- fragment = toSourceNodeWhenNeeded(result).toString();
- if (fragment.charCodeAt(0) === 123 || 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) {
- var result, cursor, that = this;
- if (stmt.specifiers.length === 0) {
- return [
- 'import',
- space,
- this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
- this.semicolon(flags)
- ];
- }
- result = ['import'];
- cursor = 0;
- 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) {
- result = join(result, [
- space,
- this.generateExpression(stmt.specifiers[cursor],
Precedence.Sequence, E_TTT)
- ]);
- } else {
- result.push(space + '{');
- if (stmt.specifiers.length - cursor === 1) {
- result.push(space);
- result.push(this.generateExpression(stmt.specifiers[cursor],
Precedence.Sequence, E_TTT));
- result.push(space + '}' + space);
- } else {
- 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,
- 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) {
- 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) {
- 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);
- }
- }
- 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 {
- 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) {
- if (i === 0) {
- if (!stmt.body[0].leadingComments) {
- generateBlankLines(stmt.range[0], stmt.body[i].range[0],
result);
- }
- }
- 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) {
- 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(),
- stmt.id ? 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);
- 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) === 47 &&
esutils.code.isIdentifierPartES5(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) ===
'!--') {
- 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;
- 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;
- 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;
- 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();
- if (fragment.indexOf('.') < 0 && !/[eExX]/.test(fragment) &&
esutils.code.isDecimalDigit(fragment.charCodeAt(fragment.length - 1)) &&
!(fragment.length >= 2 && fragment.charCodeAt(0) === 48)) {
- result.push('.');
- }
- }
- result.push('.');
- result.push(generateIdentifier(expr.property));
- }
- return parenthesize(result, Precedence.Member, precedence);
- },
- MetaProperty: function (expr, precedence, flags) {
- var result;
- result = [];
- result.push(expr.meta);
- result.push('.');
- result.push(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) {
- result = join(result, fragment);
- } else {
- leftSource = toSourceNodeWhenNeeded(result).toString();
- leftCharCode = leftSource.charCodeAt(leftSource.length - 1);
- rightCharCode = fragment.toString().charCodeAt(0);
- if ((leftCharCode === 43 || leftCharCode === 45) && leftCharCode
=== rightCharCode || esutils.code.isIdentifierPartES5(leftCharCode) &&
esutils.code.isIdentifierPartES5(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.all ? '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;
- },
- ArrayPattern: function (expr, precedence, flags) {
- return this.ArrayExpression(expr, precedence, flags, true);
- },
- ArrayExpression: function (expr, precedence, flags, isPattern) {
- var result, multiline, that = this;
- if (!expr.elements.length) {
- return '[]';
- }
- multiline = isPattern ? false : 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;
- },
- RestElement: function (expr, precedence, flags) {
- return '...' + this.generatePattern(expr.argument);
- },
- 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, expr.value)),
- this.generateFunctionBody(expr.value)
- ];
- } else {
- fragment = [
- generateMethodPrefix(expr),
- this.generatePropertyKey(expr.key, expr.computed, expr.value),
- 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, expr.value),
- this.generateFunctionBody(expr.value)
- ];
- }
- if (expr.shorthand) {
- return this.generatePropertyKey(expr.key, expr.computed,
expr.value);
- }
- if (expr.method) {
- return [
- generateMethodPrefix(expr),
- this.generatePropertyKey(expr.key, expr.computed, expr.value),
- this.generateFunctionBody(expr.value)
- ];
- }
- return [
- this.generatePropertyKey(expr.key, expr.computed, expr.value),
- ':' + 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) {
- 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;
- },
- AssignmentPattern: function (expr, precedence, flags) {
- return this.generateAssignment(expr.left, expr.right, '=',
precedence, flags);
- },
- 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';
- },
- Super: function (expr, precedence, flags) {
- return 'super';
- },
- Identifier: function (expr, precedence, flags) {
- return generateIdentifier(expr);
- },
- ImportDefaultSpecifier: function (expr, precedence, flags) {
- return generateIdentifier(expr.id || expr.local);
- },
- ImportNamespaceSpecifier: function (expr, precedence, flags) {
- var result = ['*'];
- var id = expr.id || expr.local;
- if (id) {
- result.push(space + 'as' + noEmptySpace() +
generateIdentifier(id));
- }
- return result;
- },
- ImportSpecifier: function (expr, precedence, flags) {
- var imported = expr.imported;
- var result = [imported.name];
- var local = expr.local;
- if (local && local.name !== imported.name) {
- result.push(noEmptySpace() + 'as' + noEmptySpace() +
generateIdentifier(local));
- }
- return result;
- },
- ExportSpecifier: function (expr, precedence, flags) {
- var local = expr.local;
- var result = [local.name];
- var exported = expr.exported;
- if (exported && exported.name !== local.name) {
- result.push(noEmptySpace() + 'as' + noEmptySpace() +
generateIdentifier(exported));
- }
- 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) {
- }
- }
- 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';
- }
- if (expr.regex) {
- return '/' + expr.regex.pattern + '/' + expr.regex.flags;
- }
- return generateRegExp(expr.value);
- },
- GeneratorExpression: function (expr, precedence, flags) {
- return this.ComprehensionExpression(expr, precedence, flags);
- },
- ComprehensionExpression: function (expr, precedence, flags) {
- 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) {
- 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);
- 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) {
- 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) {
- SourceNode = require('/node_modules/source-map/lib/source-map.js',
module).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', module).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;
- }());
- });
- require.define('/package.json', function (module, exports, __dirname,
__filename) {
- module.exports = {
- 'name': 'escodegen',
- 'description': 'ECMAScript code generator',
- 'homepage': 'http://github.com/estools/escodegen',
- 'main': 'escodegen.js',
- 'bin': {
- 'esgenerate': './bin/esgenerate.js',
- 'escodegen': './bin/escodegen.js'
- },
- 'files': [
- 'LICENSE.BSD',
- 'LICENSE.source-map',
- 'README.md',
- 'bin',
- 'escodegen.js',
- 'package.json'
- ],
- 'version': '1.8.1',
- 'engines': { 'node': '>=0.12.0' },
- 'maintainers': [{
- 'name': 'Yusuke Suzuki',
- 'email': 'address@hidden',
- 'web': 'http://github.com/Constellation'
- }],
- 'repository': {
- 'type': 'git',
- 'url': 'http://github.com/estools/escodegen.git'
- },
- 'dependencies': {
- 'estraverse': '^1.9.1',
- 'esutils': '^2.0.2',
- 'esprima': '^2.7.1',
- 'optionator': '^0.8.1'
- },
- 'optionalDependencies': { 'source-map': '~0.2.0' },
- 'devDependencies': {
- 'acorn': '^2.7.0',
- 'bluebird': '^2.3.11',
- 'bower-registry-client': '^0.2.1',
- 'chai': '^1.10.0',
- 'commonjs-everywhere': '^0.9.7',
- 'gulp': '^3.8.10',
- 'gulp-eslint': '^0.2.0',
- 'gulp-mocha': '^2.0.0',
- 'semver': '^5.1.0'
- },
- 'license': 'BSD-2-Clause',
- 'scripts': {
- 'test': 'gulp travis',
- 'unit-test': 'gulp test',
- 'lint': 'gulp lint',
- 'release': 'node tools/release.js',
- 'build-min': './node_modules/.bin/cjsify -ma path:
tools/entry-point.js > escodegen.browser.min.js',
- 'build': './node_modules/.bin/cjsify -a path: tools/entry-point.js >
escodegen.browser.js'
- }
- };
- });
- require.define('/node_modules/source-map/lib/source-map.js', function
(module, exports, __dirname, __filename) {
- exports.SourceMapGenerator =
require('/node_modules/source-map/lib/source-map/source-map-generator.js',
module).SourceMapGenerator;
- exports.SourceMapConsumer =
require('/node_modules/source-map/lib/source-map/source-map-consumer.js',
module).SourceMapConsumer;
- exports.SourceNode =
require('/node_modules/source-map/lib/source-map/source-node.js',
module).SourceNode;
- });
- require.define('/node_modules/source-map/lib/source-map/source-node.js',
function (module, exports, __dirname, __filename) {
- if (typeof define !== 'function') {
- var define = require('/node_modules/amdefine/amdefine.js',
module)(module, require);
- }
- define(function (require, exports, module) {
- var SourceMapGenerator =
require('/node_modules/source-map/lib/source-map/source-map-generator.js',
module).SourceMapGenerator;
- var util = require('/node_modules/source-map/lib/source-map/util.js',
module);
- var REGEX_NEWLINE = /(\r?\n)/;
- var NEWLINE_CODE = 10;
- var isSourceNode = '$$$isSourceNode$$$';
- function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
- this.children = [];
- this.sourceContents = {};
- this.line = aLine == null ? null : aLine;
- this.column = aColumn == null ? null : aColumn;
- this.source = aSource == null ? null : aSource;
- this.name = aName == null ? null : aName;
- this[isSourceNode] = true;
- if (aChunks != null)
- this.add(aChunks);
- }
- SourceNode.fromStringWithSourceMap = function
SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer,
aRelativePath) {
- var node = new SourceNode;
- var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
- var shiftNextLine = function () {
- var lineContents = remainingLines.shift();
- var newLine = remainingLines.shift() || '';
- return lineContents + newLine;
- };
- var lastGeneratedLine = 1, lastGeneratedColumn = 0;
- var lastMapping = null;
- aSourceMapConsumer.eachMapping(function (mapping) {
- if (lastMapping !== null) {
- if (lastGeneratedLine < mapping.generatedLine) {
- var code = '';
- addMappingWithCode(lastMapping, shiftNextLine());
- lastGeneratedLine++;
- lastGeneratedColumn = 0;
- } else {
- var nextLine = remainingLines[0];
- var code = nextLine.substr(0, mapping.generatedColumn -
lastGeneratedColumn);
- remainingLines[0] = nextLine.substr(mapping.generatedColumn -
lastGeneratedColumn);
- lastGeneratedColumn = mapping.generatedColumn;
- addMappingWithCode(lastMapping, code);
- lastMapping = mapping;
- return;
- }
- }
- while (lastGeneratedLine < mapping.generatedLine) {
- node.add(shiftNextLine());
- lastGeneratedLine++;
- }
- if (lastGeneratedColumn < mapping.generatedColumn) {
- var nextLine = remainingLines[0];
- node.add(nextLine.substr(0, mapping.generatedColumn));
- remainingLines[0] = nextLine.substr(mapping.generatedColumn);
- lastGeneratedColumn = mapping.generatedColumn;
- }
- lastMapping = mapping;
- }, this);
- if (remainingLines.length > 0) {
- if (lastMapping) {
- addMappingWithCode(lastMapping, shiftNextLine());
- }
- node.add(remainingLines.join(''));
- }
- aSourceMapConsumer.sources.forEach(function (sourceFile) {
- var content = aSourceMapConsumer.sourceContentFor(sourceFile);
- if (content != null) {
- if (aRelativePath != null) {
- sourceFile = util.join(aRelativePath, sourceFile);
- }
- node.setSourceContent(sourceFile, content);
- }
- });
- return node;
- function addMappingWithCode(mapping, code) {
- if (mapping === null || mapping.source === undefined) {
- node.add(code);
- } else {
- var source = aRelativePath ? util.join(aRelativePath,
mapping.source) : mapping.source;
- node.add(new SourceNode(mapping.originalLine,
mapping.originalColumn, source, code, mapping.name));
- }
- }
- };
- SourceNode.prototype.add = function SourceNode_add(aChunk) {
- if (Array.isArray(aChunk)) {
- aChunk.forEach(function (chunk) {
- this.add(chunk);
- }, this);
- } else if (aChunk[isSourceNode] || typeof aChunk === 'string') {
- if (aChunk) {
- this.children.push(aChunk);
- }
- } else {
- throw new TypeError('Expected a SourceNode, string, or an array of
SourceNodes and strings. Got ' + aChunk);
- }
- return this;
- };
- SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
- if (Array.isArray(aChunk)) {
- for (var i = aChunk.length - 1; i >= 0; i--) {
- this.prepend(aChunk[i]);
- }
- } else if (aChunk[isSourceNode] || typeof aChunk === 'string') {
- this.children.unshift(aChunk);
- } else {
- throw new TypeError('Expected a SourceNode, string, or an array of
SourceNodes and strings. Got ' + aChunk);
- }
- return this;
- };
- SourceNode.prototype.walk = function SourceNode_walk(aFn) {
- var chunk;
- for (var i = 0, len = this.children.length; i < len; i++) {
- chunk = this.children[i];
- if (chunk[isSourceNode]) {
- chunk.walk(aFn);
- } else {
- if (chunk !== '') {
- aFn(chunk, {
- source: this.source,
- line: this.line,
- column: this.column,
- name: this.name
- });
- }
- }
- }
- };
- SourceNode.prototype.join = function SourceNode_join(aSep) {
- var newChildren;
- var i;
- var len = this.children.length;
- if (len > 0) {
- newChildren = [];
- for (i = 0; i < len - 1; i++) {
- newChildren.push(this.children[i]);
- newChildren.push(aSep);
- }
- newChildren.push(this.children[i]);
- this.children = newChildren;
- }
- return this;
- };
- SourceNode.prototype.replaceRight = function
SourceNode_replaceRight(aPattern, aReplacement) {
- var lastChild = this.children[this.children.length - 1];
- if (lastChild[isSourceNode]) {
- lastChild.replaceRight(aPattern, aReplacement);
- } else if (typeof lastChild === 'string') {
- this.children[this.children.length - 1] =
lastChild.replace(aPattern, aReplacement);
- } else {
- this.children.push(''.replace(aPattern, aReplacement));
- }
- return this;
- };
- SourceNode.prototype.setSourceContent = function
SourceNode_setSourceContent(aSourceFile, aSourceContent) {
- this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
- };
- SourceNode.prototype.walkSourceContents = function
SourceNode_walkSourceContents(aFn) {
- for (var i = 0, len = this.children.length; i < len; i++) {
- if (this.children[i][isSourceNode]) {
- this.children[i].walkSourceContents(aFn);
- }
- }
- var sources = Object.keys(this.sourceContents);
- for (var i = 0, len = sources.length; i < len; i++) {
- aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
- }
- };
- SourceNode.prototype.toString = function SourceNode_toString() {
- var str = '';
- this.walk(function (chunk) {
- str += chunk;
- });
- return str;
- };
- SourceNode.prototype.toStringWithSourceMap = function
SourceNode_toStringWithSourceMap(aArgs) {
- var generated = {
- code: '',
- line: 1,
- column: 0
- };
- var map = new SourceMapGenerator(aArgs);
- var sourceMappingActive = false;
- var lastOriginalSource = null;
- var lastOriginalLine = null;
- var lastOriginalColumn = null;
- var lastOriginalName = null;
- this.walk(function (chunk, original) {
- generated.code += chunk;
- if (original.source !== null && original.line !== null &&
original.column !== null) {
- if (lastOriginalSource !== original.source || lastOriginalLine !==
original.line || lastOriginalColumn !== original.column || lastOriginalName !==
original.name) {
- map.addMapping({
- source: original.source,
- original: {
- line: original.line,
- column: original.column
- },
- generated: {
- line: generated.line,
- column: generated.column
- },
- name: original.name
- });
- }
- lastOriginalSource = original.source;
- lastOriginalLine = original.line;
- lastOriginalColumn = original.column;
- lastOriginalName = original.name;
- sourceMappingActive = true;
- } else if (sourceMappingActive) {
- map.addMapping({
- generated: {
- line: generated.line,
- column: generated.column
- }
- });
- lastOriginalSource = null;
- sourceMappingActive = false;
- }
- for (var idx = 0, length = chunk.length; idx < length; idx++) {
- if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
- generated.line++;
- generated.column = 0;
- if (idx + 1 === length) {
- lastOriginalSource = null;
- sourceMappingActive = false;
- } else if (sourceMappingActive) {
- map.addMapping({
- source: original.source,
- original: {
- line: original.line,
- column: original.column
- },
- generated: {
- line: generated.line,
- column: generated.column
- },
- name: original.name
- });
- }
- } else {
- generated.column++;
- }
- }
- });
- this.walkSourceContents(function (sourceFile, sourceContent) {
- map.setSourceContent(sourceFile, sourceContent);
- });
- return {
- code: generated.code,
- map: map
- };
- };
- exports.SourceNode = SourceNode;
- });
- });
- require.define('/node_modules/source-map/lib/source-map/util.js', function
(module, exports, __dirname, __filename) {
- if (typeof define !== 'function') {
- var define = require('/node_modules/amdefine/amdefine.js',
module)(module, require);
- }
- define(function (require, exports, module) {
- function getArg(aArgs, aName, aDefaultValue) {
- if (aName in aArgs) {
- return aArgs[aName];
- } else if (arguments.length === 3) {
- return aDefaultValue;
- } else {
- throw new Error('"' + aName + '" is a required argument.');
- }
- }
- exports.getArg = getArg;
- var urlRegexp =
/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
- var dataUrlRegexp = /^data:.+\,.+$/;
- function urlParse(aUrl) {
- var match = aUrl.match(urlRegexp);
- if (!match) {
- return null;
- }
- return {
- scheme: match[1],
- auth: match[2],
- host: match[3],
- port: match[4],
- path: match[5]
- };
- }
- exports.urlParse = urlParse;
- function urlGenerate(aParsedUrl) {
- var url = '';
- if (aParsedUrl.scheme) {
- url += aParsedUrl.scheme + ':';
- }
- url += '//';
- if (aParsedUrl.auth) {
- url += aParsedUrl.auth + '@';
- }
- if (aParsedUrl.host) {
- url += aParsedUrl.host;
- }
- if (aParsedUrl.port) {
- url += ':' + aParsedUrl.port;
- }
- if (aParsedUrl.path) {
- url += aParsedUrl.path;
- }
- return url;
- }
- exports.urlGenerate = urlGenerate;
- function normalize(aPath) {
- var path = aPath;
- var url = urlParse(aPath);
- if (url) {
- if (!url.path) {
- return aPath;
- }
- path = url.path;
- }
- var isAbsolute = path.charAt(0) === '/';
- var parts = path.split(/\/+/);
- for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
- part = parts[i];
- if (part === '.') {
- parts.splice(i, 1);
- } else if (part === '..') {
- up++;
- } else if (up > 0) {
- if (part === '') {
- parts.splice(i + 1, up);
- up = 0;
- } else {
- parts.splice(i, 2);
- up--;
- }
- }
- }
- path = parts.join('/');
- if (path === '') {
- path = isAbsolute ? '/' : '.';
- }
- if (url) {
- url.path = path;
- return urlGenerate(url);
- }
- return path;
- }
- exports.normalize = normalize;
- function join(aRoot, aPath) {
- if (aRoot === '') {
- aRoot = '.';
- }
- if (aPath === '') {
- aPath = '.';
- }
- var aPathUrl = urlParse(aPath);
- var aRootUrl = urlParse(aRoot);
- if (aRootUrl) {
- aRoot = aRootUrl.path || '/';
- }
- if (aPathUrl && !aPathUrl.scheme) {
- if (aRootUrl) {
- aPathUrl.scheme = aRootUrl.scheme;
- }
- return urlGenerate(aPathUrl);
- }
- if (aPathUrl || aPath.match(dataUrlRegexp)) {
- return aPath;
- }
- if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
- aRootUrl.host = aPath;
- return urlGenerate(aRootUrl);
- }
- var joined = aPath.charAt(0) === '/' ? aPath :
normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
- if (aRootUrl) {
- aRootUrl.path = joined;
- return urlGenerate(aRootUrl);
- }
- return joined;
- }
- exports.join = join;
- function relative(aRoot, aPath) {
- if (aRoot === '') {
- aRoot = '.';
- }
- aRoot = aRoot.replace(/\/$/, '');
- var url = urlParse(aRoot);
- if (aPath.charAt(0) == '/' && url && url.path == '/') {
- return aPath.slice(1);
- }
- return aPath.indexOf(aRoot + '/') === 0 ? aPath.substr(aRoot.length +
1) : aPath;
- }
- exports.relative = relative;
- function toSetString(aStr) {
- return '$' + aStr;
- }
- exports.toSetString = toSetString;
- function fromSetString(aStr) {
- return aStr.substr(1);
- }
- exports.fromSetString = fromSetString;
- function strcmp(aStr1, aStr2) {
- var s1 = aStr1 || '';
- var s2 = aStr2 || '';
- return (s1 > s2) - (s1 < s2);
- }
- function compareByOriginalPositions(mappingA, mappingB,
onlyCompareOriginal) {
- var cmp;
- cmp = strcmp(mappingA.source, mappingB.source);
- if (cmp) {
- return cmp;
- }
- cmp = mappingA.originalLine - mappingB.originalLine;
- if (cmp) {
- return cmp;
- }
- cmp = mappingA.originalColumn - mappingB.originalColumn;
- if (cmp || onlyCompareOriginal) {
- return cmp;
- }
- cmp = strcmp(mappingA.name, mappingB.name);
- if (cmp) {
- return cmp;
- }
- cmp = mappingA.generatedLine - mappingB.generatedLine;
- if (cmp) {
- return cmp;
- }
- return mappingA.generatedColumn - mappingB.generatedColumn;
- }
- ;
- exports.compareByOriginalPositions = compareByOriginalPositions;
- function compareByGeneratedPositions(mappingA, mappingB,
onlyCompareGenerated) {
- var cmp;
- cmp = mappingA.generatedLine - mappingB.generatedLine;
- if (cmp) {
- return cmp;
- }
- cmp = mappingA.generatedColumn - mappingB.generatedColumn;
- if (cmp || onlyCompareGenerated) {
- return cmp;
- }
- cmp = strcmp(mappingA.source, mappingB.source);
- if (cmp) {
- return cmp;
- }
- cmp = mappingA.originalLine - mappingB.originalLine;
- if (cmp) {
- return cmp;
- }
- cmp = mappingA.originalColumn - mappingB.originalColumn;
- if (cmp) {
- return cmp;
- }
- return strcmp(mappingA.name, mappingB.name);
- }
- ;
- exports.compareByGeneratedPositions = compareByGeneratedPositions;
- });
- });
- require.define('/node_modules/amdefine/amdefine.js', function (module,
exports, __dirname, __filename) {
- 'use strict';
- function amdefine(module, requireFn) {
- 'use strict';
- var defineCache = {}, loaderCache = {}, alreadyCalled = false, path =
require('path', module), makeRequire, stringRequire;
- function trimDots(ary) {
- var i, part;
- for (i = 0; ary[i]; i += 1) {
- part = ary[i];
- if (part === '.') {
- ary.splice(i, 1);
- i -= 1;
- } else if (part === '..') {
- if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
- break;
- } else if (i > 0) {
- ary.splice(i - 1, 2);
- i -= 2;
- }
- }
- }
- }
- function normalize(name, baseName) {
- var baseParts;
- if (name && name.charAt(0) === '.') {
- if (baseName) {
- baseParts = baseName.split('/');
- baseParts = baseParts.slice(0, baseParts.length - 1);
- baseParts = baseParts.concat(name.split('/'));
- trimDots(baseParts);
- name = baseParts.join('/');
- }
- }
- return name;
- }
- function makeNormalize(relName) {
- return function (name) {
- return normalize(name, relName);
- };
- }
- function makeLoad(id) {
- function load(value) {
- loaderCache[id] = value;
- }
- load.fromText = function (id, text) {
- throw new Error('amdefine does not implement load.fromText');
- };
- return load;
- }
- makeRequire = function (systemRequire, exports, module, relId) {
- function amdRequire(deps, callback) {
- if (typeof deps === 'string') {
- return stringRequire(systemRequire, exports, module, deps, relId);
- } else {
- deps = deps.map(function (depName) {
- return stringRequire(systemRequire, exports, module, depName,
relId);
- });
- if (callback) {
- process.nextTick(function () {
- callback.apply(null, deps);
- });
- }
- }
- }
- amdRequire.toUrl = function (filePath) {
- if (filePath.indexOf('.') === 0) {
- return normalize(filePath, path.dirname(module.filename));
- } else {
- return filePath;
- }
- };
- return amdRequire;
- };
- requireFn = requireFn || function req() {
- return module.require.apply(module, arguments);
- };
- function runFactory(id, deps, factory) {
- var r, e, m, result;
- if (id) {
- e = loaderCache[id] = {};
- m = {
- id: id,
- uri: __filename,
- exports: e
- };
- r = makeRequire(requireFn, e, m, id);
- } else {
- if (alreadyCalled) {
- throw new Error('amdefine with no module ID cannot be called more
than once per file.');
- }
- alreadyCalled = true;
- e = module.exports;
- m = module;
- r = makeRequire(requireFn, e, m, module.id);
- }
- if (deps) {
- deps = deps.map(function (depName) {
- return r(depName);
- });
- }
- if (typeof factory === 'function') {
- result = factory.apply(m.exports, deps);
- } else {
- result = factory;
- }
- if (result !== undefined) {
- m.exports = result;
- if (id) {
- loaderCache[id] = m.exports;
- }
- }
- }
- stringRequire = function (systemRequire, exports, module, id, relId) {
- var index = id.indexOf('!'), originalId = id, prefix, plugin;
- if (index === -1) {
- id = normalize(id, relId);
- if (id === 'require') {
- return makeRequire(systemRequire, exports, module, relId);
- } else if (id === 'exports') {
- return exports;
- } else if (id === 'module') {
- return module;
- } else if (loaderCache.hasOwnProperty(id)) {
- return loaderCache[id];
- } else if (defineCache[id]) {
- runFactory.apply(null, defineCache[id]);
- return loaderCache[id];
- } else {
- if (systemRequire) {
- return systemRequire(originalId);
- } else {
- throw new Error('No module with ID: ' + id);
- }
- }
- } else {
- prefix = id.substring(0, index);
- id = id.substring(index + 1, id.length);
- plugin = stringRequire(systemRequire, exports, module, prefix,
relId);
- if (plugin.normalize) {
- id = plugin.normalize(id, makeNormalize(relId));
- } else {
- id = normalize(id, relId);
- }
- if (loaderCache[id]) {
- return loaderCache[id];
- } else {
- plugin.load(id, makeRequire(systemRequire, exports, module,
relId), makeLoad(id), {});
- return loaderCache[id];
- }
- }
- };
- function define(id, deps, factory) {
- if (Array.isArray(id)) {
- factory = deps;
- deps = id;
- id = undefined;
- } else if (typeof id !== 'string') {
- factory = id;
- id = deps = undefined;
- }
- if (deps && !Array.isArray(deps)) {
- factory = deps;
- deps = undefined;
- }
- if (!deps) {
- deps = [
- 'require',
- 'exports',
- 'module'
- ];
- }
- if (id) {
- defineCache[id] = [
- id,
- deps,
- factory
- ];
- } else {
- runFactory(id, deps, factory);
- }
- }
- define.require = function (id) {
- if (loaderCache[id]) {
- return loaderCache[id];
- }
- if (defineCache[id]) {
- runFactory.apply(null, defineCache[id]);
- return loaderCache[id];
- }
- };
- define.amd = {};
- return define;
- }
- module.exports = amdefine;
- });
-
require.define('/node_modules/source-map/lib/source-map/source-map-generator.js',
function (module, exports, __dirname, __filename) {
- if (typeof define !== 'function') {
- var define = require('/node_modules/amdefine/amdefine.js',
module)(module, require);
- }
- define(function (require, exports, module) {
- var base64VLQ =
require('/node_modules/source-map/lib/source-map/base64-vlq.js', module);
- var util = require('/node_modules/source-map/lib/source-map/util.js',
module);
- var ArraySet =
require('/node_modules/source-map/lib/source-map/array-set.js',
module).ArraySet;
- var MappingList =
require('/node_modules/source-map/lib/source-map/mapping-list.js',
module).MappingList;
- function SourceMapGenerator(aArgs) {
- if (!aArgs) {
- aArgs = {};
- }
- this._file = util.getArg(aArgs, 'file', null);
- this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
- this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
- this._sources = new ArraySet;
- this._names = new ArraySet;
- this._mappings = new MappingList;
- this._sourcesContents = null;
- }
- SourceMapGenerator.prototype._version = 3;
- SourceMapGenerator.fromSourceMap = function
SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
- var sourceRoot = aSourceMapConsumer.sourceRoot;
- var generator = new SourceMapGenerator({
- file: aSourceMapConsumer.file,
- sourceRoot: sourceRoot
- });
- aSourceMapConsumer.eachMapping(function (mapping) {
- var newMapping = {
- generated: {
- line: mapping.generatedLine,
- column: mapping.generatedColumn
- }
- };
- if (mapping.source != null) {
- newMapping.source = mapping.source;
- if (sourceRoot != null) {
- newMapping.source = util.relative(sourceRoot, newMapping.source);
- }
- newMapping.original = {
- line: mapping.originalLine,
- column: mapping.originalColumn
- };
- if (mapping.name != null) {
- newMapping.name = mapping.name;
- }
- }
- generator.addMapping(newMapping);
- });
- aSourceMapConsumer.sources.forEach(function (sourceFile) {
- var content = aSourceMapConsumer.sourceContentFor(sourceFile);
- if (content != null) {
- generator.setSourceContent(sourceFile, content);
- }
- });
- return generator;
- };
- SourceMapGenerator.prototype.addMapping = function
SourceMapGenerator_addMapping(aArgs) {
- var generated = util.getArg(aArgs, 'generated');
- var original = util.getArg(aArgs, 'original', null);
- var source = util.getArg(aArgs, 'source', null);
- var name = util.getArg(aArgs, 'name', null);
- if (!this._skipValidation) {
- this._validateMapping(generated, original, source, name);
- }
- if (source != null && !this._sources.has(source)) {
- this._sources.add(source);
- }
- if (name != null && !this._names.has(name)) {
- this._names.add(name);
- }
- this._mappings.add({
- generatedLine: generated.line,
- generatedColumn: generated.column,
- originalLine: original != null && original.line,
- originalColumn: original != null && original.column,
- source: source,
- name: name
- });
- };
- SourceMapGenerator.prototype.setSourceContent = function
SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
- var source = aSourceFile;
- if (this._sourceRoot != null) {
- source = util.relative(this._sourceRoot, source);
- }
- if (aSourceContent != null) {
- if (!this._sourcesContents) {
- this._sourcesContents = {};
- }
- this._sourcesContents[util.toSetString(source)] = aSourceContent;
- } else if (this._sourcesContents) {
- delete this._sourcesContents[util.toSetString(source)];
- if (Object.keys(this._sourcesContents).length === 0) {
- this._sourcesContents = null;
- }
- }
- };
- SourceMapGenerator.prototype.applySourceMap = function
SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile,
aSourceMapPath) {
- var sourceFile = aSourceFile;
- if (aSourceFile == null) {
- if (aSourceMapConsumer.file == null) {
- throw new Error('SourceMapGenerator.prototype.applySourceMap
requires either an explicit source file, ' + 'or the source map\'s "file"
property. Both were omitted.');
- }
- sourceFile = aSourceMapConsumer.file;
- }
- var sourceRoot = this._sourceRoot;
- if (sourceRoot != null) {
- sourceFile = util.relative(sourceRoot, sourceFile);
- }
- var newSources = new ArraySet;
- var newNames = new ArraySet;
- this._mappings.unsortedForEach(function (mapping) {
- if (mapping.source === sourceFile && mapping.originalLine != null) {
- var original = aSourceMapConsumer.originalPositionFor({
- line: mapping.originalLine,
- column: mapping.originalColumn
- });
- if (original.source != null) {
- mapping.source = original.source;
- if (aSourceMapPath != null) {
- mapping.source = util.join(aSourceMapPath, mapping.source);
- }
- if (sourceRoot != null) {
- mapping.source = util.relative(sourceRoot, mapping.source);
- }
- mapping.originalLine = original.line;
- mapping.originalColumn = original.column;
- if (original.name != null) {
- mapping.name = original.name;
- }
- }
- }
- var source = mapping.source;
- if (source != null && !newSources.has(source)) {
- newSources.add(source);
- }
- var name = mapping.name;
- if (name != null && !newNames.has(name)) {
- newNames.add(name);
- }
- }, this);
- this._sources = newSources;
- this._names = newNames;
- aSourceMapConsumer.sources.forEach(function (sourceFile) {
- var content = aSourceMapConsumer.sourceContentFor(sourceFile);
- if (content != null) {
- if (aSourceMapPath != null) {
- sourceFile = util.join(aSourceMapPath, sourceFile);
- }
- if (sourceRoot != null) {
- sourceFile = util.relative(sourceRoot, sourceFile);
- }
- this.setSourceContent(sourceFile, content);
- }
- }, this);
- };
- SourceMapGenerator.prototype._validateMapping = function
SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) {
- if (aGenerated && 'line' in aGenerated && 'column' in aGenerated &&
aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource &&
!aName) {
- return;
- } else if (aGenerated && 'line' in aGenerated && 'column' in
aGenerated && aOriginal && 'line' in aOriginal && 'column' in aOriginal &&
aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 &&
aOriginal.column >= 0 && aSource) {
- return;
- } else {
- throw new Error('Invalid mapping: ' + JSON.stringify({
- generated: aGenerated,
- source: aSource,
- original: aOriginal,
- name: aName
- }));
- }
- };
- SourceMapGenerator.prototype._serializeMappings = function
SourceMapGenerator_serializeMappings() {
- var previousGeneratedColumn = 0;
- var previousGeneratedLine = 1;
- var previousOriginalColumn = 0;
- var previousOriginalLine = 0;
- var previousName = 0;
- var previousSource = 0;
- var result = '';
- var mapping;
- var mappings = this._mappings.toArray();
- for (var i = 0, len = mappings.length; i < len; i++) {
- mapping = mappings[i];
- if (mapping.generatedLine !== previousGeneratedLine) {
- previousGeneratedColumn = 0;
- while (mapping.generatedLine !== previousGeneratedLine) {
- result += ';';
- previousGeneratedLine++;
- }
- } else {
- if (i > 0) {
- if (!util.compareByGeneratedPositions(mapping, mappings[i - 1]))
{
- continue;
- }
- result += ',';
- }
- }
- result += base64VLQ.encode(mapping.generatedColumn -
previousGeneratedColumn);
- previousGeneratedColumn = mapping.generatedColumn;
- if (mapping.source != null) {
- result += base64VLQ.encode(this._sources.indexOf(mapping.source) -
previousSource);
- previousSource = this._sources.indexOf(mapping.source);
- result += base64VLQ.encode(mapping.originalLine - 1 -
previousOriginalLine);
- previousOriginalLine = mapping.originalLine - 1;
- result += base64VLQ.encode(mapping.originalColumn -
previousOriginalColumn);
- previousOriginalColumn = mapping.originalColumn;
- if (mapping.name != null) {
- result += base64VLQ.encode(this._names.indexOf(mapping.name) -
previousName);
- previousName = this._names.indexOf(mapping.name);
- }
- }
- }
- return result;
- };
- SourceMapGenerator.prototype._generateSourcesContent = function
SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
- return aSources.map(function (source) {
- if (!this._sourcesContents) {
- return null;
- }
- if (aSourceRoot != null) {
- source = util.relative(aSourceRoot, source);
- }
- var key = util.toSetString(source);
- return Object.prototype.hasOwnProperty.call(this._sourcesContents,
key) ? this._sourcesContents[key] : null;
- }, this);
- };
- SourceMapGenerator.prototype.toJSON = function
SourceMapGenerator_toJSON() {
- var map = {
- version: this._version,
- sources: this._sources.toArray(),
- names: this._names.toArray(),
- mappings: this._serializeMappings()
- };
- if (this._file != null) {
- map.file = this._file;
- }
- if (this._sourceRoot != null) {
- map.sourceRoot = this._sourceRoot;
- }
- if (this._sourcesContents) {
- map.sourcesContent = this._generateSourcesContent(map.sources,
map.sourceRoot);
- }
- return map;
- };
- SourceMapGenerator.prototype.toString = function
SourceMapGenerator_toString() {
- return JSON.stringify(this);
- };
- exports.SourceMapGenerator = SourceMapGenerator;
- });
- });
- require.define('/node_modules/source-map/lib/source-map/mapping-list.js',
function (module, exports, __dirname, __filename) {
- if (typeof define !== 'function') {
- var define = require('/node_modules/amdefine/amdefine.js',
module)(module, require);
- }
- define(function (require, exports, module) {
- var util = require('/node_modules/source-map/lib/source-map/util.js',
module);
- function generatedPositionAfter(mappingA, mappingB) {
- var lineA = mappingA.generatedLine;
- var lineB = mappingB.generatedLine;
- var columnA = mappingA.generatedColumn;
- var columnB = mappingB.generatedColumn;
- return lineB > lineA || lineB == lineA && columnB >= columnA ||
util.compareByGeneratedPositions(mappingA, mappingB) <= 0;
- }
- function MappingList() {
- this._array = [];
- this._sorted = true;
- this._last = {
- generatedLine: -1,
- generatedColumn: 0
- };
- }
- MappingList.prototype.unsortedForEach = function
MappingList_forEach(aCallback, aThisArg) {
- this._array.forEach(aCallback, aThisArg);
- };
- MappingList.prototype.add = function MappingList_add(aMapping) {
- var mapping;
- if (generatedPositionAfter(this._last, aMapping)) {
- this._last = aMapping;
- this._array.push(aMapping);
- } else {
- this._sorted = false;
- this._array.push(aMapping);
- }
- };
- MappingList.prototype.toArray = function MappingList_toArray() {
- if (!this._sorted) {
- this._array.sort(util.compareByGeneratedPositions);
- this._sorted = true;
- }
- return this._array;
- };
- exports.MappingList = MappingList;
- });
- });
- require.define('/node_modules/source-map/lib/source-map/array-set.js',
function (module, exports, __dirname, __filename) {
- if (typeof define !== 'function') {
- var define = require('/node_modules/amdefine/amdefine.js',
module)(module, require);
- }
- define(function (require, exports, module) {
- var util = require('/node_modules/source-map/lib/source-map/util.js',
module);
- function ArraySet() {
- this._array = [];
- this._set = {};
- }
- ArraySet.fromArray = function ArraySet_fromArray(aArray,
aAllowDuplicates) {
- var set = new ArraySet;
- for (var i = 0, len = aArray.length; i < len; i++) {
- set.add(aArray[i], aAllowDuplicates);
- }
- return set;
- };
- ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
- var isDuplicate = this.has(aStr);
- var idx = this._array.length;
- if (!isDuplicate || aAllowDuplicates) {
- this._array.push(aStr);
- }
- if (!isDuplicate) {
- this._set[util.toSetString(aStr)] = idx;
- }
- };
- ArraySet.prototype.has = function ArraySet_has(aStr) {
- return Object.prototype.hasOwnProperty.call(this._set,
util.toSetString(aStr));
- };
- ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
- if (this.has(aStr)) {
- return this._set[util.toSetString(aStr)];
- }
- throw new Error('"' + aStr + '" is not in the set.');
- };
- ArraySet.prototype.at = function ArraySet_at(aIdx) {
- if (aIdx >= 0 && aIdx < this._array.length) {
- return this._array[aIdx];
- }
- throw new Error('No element indexed by ' + aIdx);
- };
- ArraySet.prototype.toArray = function ArraySet_toArray() {
- return this._array.slice();
- };
- exports.ArraySet = ArraySet;
- });
- });
- require.define('/node_modules/source-map/lib/source-map/base64-vlq.js',
function (module, exports, __dirname, __filename) {
- if (typeof define !== 'function') {
- var define = require('/node_modules/amdefine/amdefine.js',
module)(module, require);
- }
- define(function (require, exports, module) {
- var base64 =
require('/node_modules/source-map/lib/source-map/base64.js', module);
- var VLQ_BASE_SHIFT = 5;
- var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
- var VLQ_BASE_MASK = VLQ_BASE - 1;
- var VLQ_CONTINUATION_BIT = VLQ_BASE;
- function toVLQSigned(aValue) {
- return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0;
- }
- function fromVLQSigned(aValue) {
- var isNegative = (aValue & 1) === 1;
- var shifted = aValue >> 1;
- return isNegative ? -shifted : shifted;
- }
- exports.encode = function base64VLQ_encode(aValue) {
- var encoded = '';
- var digit;
- var vlq = toVLQSigned(aValue);
- do {
- digit = vlq & VLQ_BASE_MASK;
- vlq >>>= VLQ_BASE_SHIFT;
- if (vlq > 0) {
- digit |= VLQ_CONTINUATION_BIT;
- }
- encoded += base64.encode(digit);
- } while (vlq > 0);
- return encoded;
- };
- exports.decode = function base64VLQ_decode(aStr, aOutParam) {
- var i = 0;
- var strLen = aStr.length;
- var result = 0;
- var shift = 0;
- var continuation, digit;
- do {
- if (i >= strLen) {
- throw new Error('Expected more digits in base 64 VLQ value.');
- }
- digit = base64.decode(aStr.charAt(i++));
- continuation = !!(digit & VLQ_CONTINUATION_BIT);
- digit &= VLQ_BASE_MASK;
- result = result + (digit << shift);
- shift += VLQ_BASE_SHIFT;
- } while (continuation);
- aOutParam.value = fromVLQSigned(result);
- aOutParam.rest = aStr.slice(i);
- };
- });
- });
- require.define('/node_modules/source-map/lib/source-map/base64.js', function
(module, exports, __dirname, __filename) {
- if (typeof define !== 'function') {
- var define = require('/node_modules/amdefine/amdefine.js',
module)(module, require);
- }
- define(function (require, exports, module) {
- var charToIntMap = {};
- var intToCharMap = {};
-
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('').forEach(function
(ch, index) {
- charToIntMap[ch] = index;
- intToCharMap[index] = ch;
- });
- exports.encode = function base64_encode(aNumber) {
- if (aNumber in intToCharMap) {
- return intToCharMap[aNumber];
- }
- throw new TypeError('Must be between 0 and 63: ' + aNumber);
- };
- exports.decode = function base64_decode(aChar) {
- if (aChar in charToIntMap) {
- return charToIntMap[aChar];
- }
- throw new TypeError('Not a valid base 64 digit: ' + aChar);
- };
- });
- });
-
require.define('/node_modules/source-map/lib/source-map/source-map-consumer.js',
function (module, exports, __dirname, __filename) {
- if (typeof define !== 'function') {
- var define = require('/node_modules/amdefine/amdefine.js',
module)(module, require);
- }
- define(function (require, exports, module) {
- var util = require('/node_modules/source-map/lib/source-map/util.js',
module);
- function SourceMapConsumer(aSourceMap) {
- var sourceMap = aSourceMap;
- if (typeof aSourceMap === 'string') {
- sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
- }
- if (sourceMap.sections != null) {
- var indexedSourceMapConsumer =
require('/node_modules/source-map/lib/source-map/indexed-source-map-consumer.js',
module);
- return new
indexedSourceMapConsumer.IndexedSourceMapConsumer(sourceMap);
- } else {
- var basicSourceMapConsumer =
require('/node_modules/source-map/lib/source-map/basic-source-map-consumer.js',
module);
- return new basicSourceMapConsumer.BasicSourceMapConsumer(sourceMap);
- }
- }
- SourceMapConsumer.fromSourceMap = function (aSourceMap) {
- var basicSourceMapConsumer =
require('/node_modules/source-map/lib/source-map/basic-source-map-consumer.js',
module);
- return
basicSourceMapConsumer.BasicSourceMapConsumer.fromSourceMap(aSourceMap);
- };
- SourceMapConsumer.prototype._version = 3;
- SourceMapConsumer.prototype.__generatedMappings = null;
- Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings',
{
- get: function () {
- if (!this.__generatedMappings) {
- this.__generatedMappings = [];
- this.__originalMappings = [];
- this._parseMappings(this._mappings, this.sourceRoot);
- }
- return this.__generatedMappings;
- }
- });
- SourceMapConsumer.prototype.__originalMappings = null;
- Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
- get: function () {
- if (!this.__originalMappings) {
- this.__generatedMappings = [];
- this.__originalMappings = [];
- this._parseMappings(this._mappings, this.sourceRoot);
- }
- return this.__originalMappings;
- }
- });
- SourceMapConsumer.prototype._nextCharIsMappingSeparator = function
SourceMapConsumer_nextCharIsMappingSeparator(aStr) {
- var c = aStr.charAt(0);
- return c === ';' || c === ',';
- };
- SourceMapConsumer.prototype._parseMappings = function
SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
- throw new Error('Subclasses must implement _parseMappings');
- };
- SourceMapConsumer.GENERATED_ORDER = 1;
- SourceMapConsumer.ORIGINAL_ORDER = 2;
- SourceMapConsumer.prototype.eachMapping = function
SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
- var context = aContext || null;
- var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
- var mappings;
- switch (order) {
- case SourceMapConsumer.GENERATED_ORDER:
- mappings = this._generatedMappings;
- break;
- case SourceMapConsumer.ORIGINAL_ORDER:
- mappings = this._originalMappings;
- break;
- default:
- throw new Error('Unknown order of iteration.');
- }
- var sourceRoot = this.sourceRoot;
- mappings.map(function (mapping) {
- var source = mapping.source;
- if (source != null && sourceRoot != null) {
- source = util.join(sourceRoot, source);
- }
- return {
- source: source,
- generatedLine: mapping.generatedLine,
- generatedColumn: mapping.generatedColumn,
- originalLine: mapping.originalLine,
- originalColumn: mapping.originalColumn,
- name: mapping.name
- };
- }).forEach(aCallback, context);
- };
- SourceMapConsumer.prototype.allGeneratedPositionsFor = function
SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
- var needle = {
- source: util.getArg(aArgs, 'source'),
- originalLine: util.getArg(aArgs, 'line'),
- originalColumn: Infinity
- };
- if (this.sourceRoot != null) {
- needle.source = util.relative(this.sourceRoot, needle.source);
- }
- var mappings = [];
- var index = this._findMapping(needle, this._originalMappings,
'originalLine', 'originalColumn', util.compareByOriginalPositions);
- if (index >= 0) {
- var mapping = this._originalMappings[index];
- while (mapping && mapping.originalLine === needle.originalLine) {
- mappings.push({
- line: util.getArg(mapping, 'generatedLine', null),
- column: util.getArg(mapping, 'generatedColumn', null),
- lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
- });
- mapping = this._originalMappings[--index];
- }
- }
- return mappings.reverse();
- };
- exports.SourceMapConsumer = SourceMapConsumer;
- });
- });
-
require.define('/node_modules/source-map/lib/source-map/basic-source-map-consumer.js',
function (module, exports, __dirname, __filename) {
- if (typeof define !== 'function') {
- var define = require('/node_modules/amdefine/amdefine.js',
module)(module, require);
- }
- define(function (require, exports, module) {
- var util = require('/node_modules/source-map/lib/source-map/util.js',
module);
- var binarySearch =
require('/node_modules/source-map/lib/source-map/binary-search.js', module);
- var ArraySet =
require('/node_modules/source-map/lib/source-map/array-set.js',
module).ArraySet;
- var base64VLQ =
require('/node_modules/source-map/lib/source-map/base64-vlq.js', module);
- var SourceMapConsumer =
require('/node_modules/source-map/lib/source-map/source-map-consumer.js',
module).SourceMapConsumer;
- function BasicSourceMapConsumer(aSourceMap) {
- var sourceMap = aSourceMap;
- if (typeof aSourceMap === 'string') {
- sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
- }
- var version = util.getArg(sourceMap, 'version');
- var sources = util.getArg(sourceMap, 'sources');
- var names = util.getArg(sourceMap, 'names', []);
- var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
- var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
- var mappings = util.getArg(sourceMap, 'mappings');
- var file = util.getArg(sourceMap, 'file', null);
- if (version != this._version) {
- throw new Error('Unsupported version: ' + version);
- }
- sources = sources.map(util.normalize);
- this._names = ArraySet.fromArray(names, true);
- this._sources = ArraySet.fromArray(sources, true);
- this.sourceRoot = sourceRoot;
- this.sourcesContent = sourcesContent;
- this._mappings = mappings;
- this.file = file;
- }
- BasicSourceMapConsumer.prototype =
Object.create(SourceMapConsumer.prototype);
- BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
- BasicSourceMapConsumer.fromSourceMap = function
SourceMapConsumer_fromSourceMap(aSourceMap) {
- var smc = Object.create(BasicSourceMapConsumer.prototype);
- smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
- smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
- smc.sourceRoot = aSourceMap._sourceRoot;
- smc.sourcesContent =
aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot);
- smc.file = aSourceMap._file;
- smc.__generatedMappings = aSourceMap._mappings.toArray().slice();
- smc.__originalMappings =
aSourceMap._mappings.toArray().slice().sort(util.compareByOriginalPositions);
- return smc;
- };
- BasicSourceMapConsumer.prototype._version = 3;
- Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
- get: function () {
- return this._sources.toArray().map(function (s) {
- return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s;
- }, this);
- }
- });
- BasicSourceMapConsumer.prototype._parseMappings = function
SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
- var generatedLine = 1;
- var previousGeneratedColumn = 0;
- var previousOriginalLine = 0;
- var previousOriginalColumn = 0;
- var previousSource = 0;
- var previousName = 0;
- var str = aStr;
- var temp = {};
- var mapping;
- while (str.length > 0) {
- if (str.charAt(0) === ';') {
- generatedLine++;
- str = str.slice(1);
- previousGeneratedColumn = 0;
- } else if (str.charAt(0) === ',') {
- str = str.slice(1);
- } else {
- mapping = {};
- mapping.generatedLine = generatedLine;
- base64VLQ.decode(str, temp);
- mapping.generatedColumn = previousGeneratedColumn + temp.value;
- previousGeneratedColumn = mapping.generatedColumn;
- str = temp.rest;
- if (str.length > 0 && !this._nextCharIsMappingSeparator(str)) {
- base64VLQ.decode(str, temp);
- mapping.source = this._sources.at(previousSource + temp.value);
- previousSource += temp.value;
- str = temp.rest;
- if (str.length === 0 || this._nextCharIsMappingSeparator(str)) {
- throw new Error('Found a source, but no line and column');
- }
- base64VLQ.decode(str, temp);
- mapping.originalLine = previousOriginalLine + temp.value;
- previousOriginalLine = mapping.originalLine;
- mapping.originalLine += 1;
- str = temp.rest;
- if (str.length === 0 || this._nextCharIsMappingSeparator(str)) {
- throw new Error('Found a source and line, but no column');
- }
- base64VLQ.decode(str, temp);
- mapping.originalColumn = previousOriginalColumn + temp.value;
- previousOriginalColumn = mapping.originalColumn;
- str = temp.rest;
- if (str.length > 0 && !this._nextCharIsMappingSeparator(str)) {
- base64VLQ.decode(str, temp);
- mapping.name = this._names.at(previousName + temp.value);
- previousName += temp.value;
- str = temp.rest;
- }
- }
- this.__generatedMappings.push(mapping);
- if (typeof mapping.originalLine === 'number') {
- this.__originalMappings.push(mapping);
- }
- }
- }
- this.__generatedMappings.sort(util.compareByGeneratedPositions);
- this.__originalMappings.sort(util.compareByOriginalPositions);
- };
- BasicSourceMapConsumer.prototype._findMapping = function
SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName,
aComparator) {
- if (aNeedle[aLineName] <= 0) {
- throw new TypeError('Line must be greater than or equal to 1, got '
+ aNeedle[aLineName]);
- }
- if (aNeedle[aColumnName] < 0) {
- throw new TypeError('Column must be greater than or equal to 0, got
' + aNeedle[aColumnName]);
- }
- return binarySearch.search(aNeedle, aMappings, aComparator);
- };
- BasicSourceMapConsumer.prototype.computeColumnSpans = function
SourceMapConsumer_computeColumnSpans() {
- for (var index = 0; index < this._generatedMappings.length; ++index) {
- var mapping = this._generatedMappings[index];
- if (index + 1 < this._generatedMappings.length) {
- var nextMapping = this._generatedMappings[index + 1];
- if (mapping.generatedLine === nextMapping.generatedLine) {
- mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
- continue;
- }
- }
- mapping.lastGeneratedColumn = Infinity;
- }
- };
- BasicSourceMapConsumer.prototype.originalPositionFor = function
SourceMapConsumer_originalPositionFor(aArgs) {
- var needle = {
- generatedLine: util.getArg(aArgs, 'line'),
- generatedColumn: util.getArg(aArgs, 'column')
- };
- var index = this._findMapping(needle, this._generatedMappings,
'generatedLine', 'generatedColumn', util.compareByGeneratedPositions);
- if (index >= 0) {
- var mapping = this._generatedMappings[index];
- if (mapping.generatedLine === needle.generatedLine) {
- var source = util.getArg(mapping, 'source', null);
- if (source != null && this.sourceRoot != null) {
- source = util.join(this.sourceRoot, source);
- }
- return {
- source: source,
- line: util.getArg(mapping, 'originalLine', null),
- column: util.getArg(mapping, 'originalColumn', null),
- name: util.getArg(mapping, 'name', null)
- };
- }
- }
- return {
- source: null,
- line: null,
- column: null,
- name: null
- };
- };
- BasicSourceMapConsumer.prototype.sourceContentFor = function
SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
- if (!this.sourcesContent) {
- return null;
- }
- if (this.sourceRoot != null) {
- aSource = util.relative(this.sourceRoot, aSource);
- }
- if (this._sources.has(aSource)) {
- return this.sourcesContent[this._sources.indexOf(aSource)];
- }
- var url;
- if (this.sourceRoot != null && (url = util.urlParse(this.sourceRoot)))
{
- var fileUriAbsPath = aSource.replace(/^file:\/\//, '');
- if (url.scheme == 'file' && this._sources.has(fileUriAbsPath)) {
- return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)];
- }
- if ((!url.path || url.path == '/') && this._sources.has('/' +
aSource)) {
- return this.sourcesContent[this._sources.indexOf('/' + aSource)];
- }
- }
- if (nullOnMissing) {
- return null;
- } else {
- throw new Error('"' + aSource + '" is not in the SourceMap.');
- }
- };
- BasicSourceMapConsumer.prototype.generatedPositionFor = function
SourceMapConsumer_generatedPositionFor(aArgs) {
- var needle = {
- source: util.getArg(aArgs, 'source'),
- originalLine: util.getArg(aArgs, 'line'),
- originalColumn: util.getArg(aArgs, 'column')
- };
- if (this.sourceRoot != null) {
- needle.source = util.relative(this.sourceRoot, needle.source);
- }
- var index = this._findMapping(needle, this._originalMappings,
'originalLine', 'originalColumn', util.compareByOriginalPositions);
- if (index >= 0) {
- var mapping = this._originalMappings[index];
- return {
- line: util.getArg(mapping, 'generatedLine', null),
- column: util.getArg(mapping, 'generatedColumn', null),
- lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
- };
- }
- return {
- line: null,
- column: null,
- lastColumn: null
- };
- };
- exports.BasicSourceMapConsumer = BasicSourceMapConsumer;
- });
- });
- require.define('/node_modules/source-map/lib/source-map/binary-search.js',
function (module, exports, __dirname, __filename) {
- if (typeof define !== 'function') {
- var define = require('/node_modules/amdefine/amdefine.js',
module)(module, require);
- }
- define(function (require, exports, module) {
- function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {
- var mid = Math.floor((aHigh - aLow) / 2) + aLow;
- var cmp = aCompare(aNeedle, aHaystack[mid], true);
- if (cmp === 0) {
- return mid;
- } else if (cmp > 0) {
- if (aHigh - mid > 1) {
- return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);
- }
- return mid;
- } else {
- if (mid - aLow > 1) {
- return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);
- }
- return aLow < 0 ? -1 : aLow;
- }
- }
- exports.search = function search(aNeedle, aHaystack, aCompare) {
- if (aHaystack.length === 0) {
- return -1;
- }
- return recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
aCompare);
- };
- });
- });
-
require.define('/node_modules/source-map/lib/source-map/indexed-source-map-consumer.js',
function (module, exports, __dirname, __filename) {
- if (typeof define !== 'function') {
- var define = require('/node_modules/amdefine/amdefine.js',
module)(module, require);
- }
- define(function (require, exports, module) {
- var util = require('/node_modules/source-map/lib/source-map/util.js',
module);
- var binarySearch =
require('/node_modules/source-map/lib/source-map/binary-search.js', module);
- var SourceMapConsumer =
require('/node_modules/source-map/lib/source-map/source-map-consumer.js',
module).SourceMapConsumer;
- var BasicSourceMapConsumer =
require('/node_modules/source-map/lib/source-map/basic-source-map-consumer.js',
module).BasicSourceMapConsumer;
- function IndexedSourceMapConsumer(aSourceMap) {
- var sourceMap = aSourceMap;
- if (typeof aSourceMap === 'string') {
- sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
- }
- var version = util.getArg(sourceMap, 'version');
- var sections = util.getArg(sourceMap, 'sections');
- if (version != this._version) {
- throw new Error('Unsupported version: ' + version);
- }
- var lastOffset = {
- line: -1,
- column: 0
- };
- this._sections = sections.map(function (s) {
- if (s.url) {
- throw new Error('Support for url field in sections not
implemented.');
- }
- var offset = util.getArg(s, 'offset');
- var offsetLine = util.getArg(offset, 'line');
- var offsetColumn = util.getArg(offset, 'column');
- if (offsetLine < lastOffset.line || offsetLine === lastOffset.line
&& offsetColumn < lastOffset.column) {
- throw new Error('Section offsets must be ordered and
non-overlapping.');
- }
- lastOffset = offset;
- return {
- generatedOffset: {
- generatedLine: offsetLine + 1,
- generatedColumn: offsetColumn + 1
- },
- consumer: new SourceMapConsumer(util.getArg(s, 'map'))
- };
- });
- }
- IndexedSourceMapConsumer.prototype =
Object.create(SourceMapConsumer.prototype);
- IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
- IndexedSourceMapConsumer.prototype._version = 3;
- Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
- get: function () {
- var sources = [];
- for (var i = 0; i < this._sections.length; i++) {
- for (var j = 0; j < this._sections[i].consumer.sources.length;
j++) {
- sources.push(this._sections[i].consumer.sources[j]);
- }
- }
- ;
- return sources;
- }
- });
- IndexedSourceMapConsumer.prototype.originalPositionFor = function
IndexedSourceMapConsumer_originalPositionFor(aArgs) {
- var needle = {
- generatedLine: util.getArg(aArgs, 'line'),
- generatedColumn: util.getArg(aArgs, 'column')
- };
- var sectionIndex = binarySearch.search(needle, this._sections,
function (needle, section) {
- var cmp = needle.generatedLine -
section.generatedOffset.generatedLine;
- if (cmp) {
- return cmp;
- }
- return needle.generatedColumn -
section.generatedOffset.generatedColumn;
- });
- var section = this._sections[sectionIndex];
- if (!section) {
- return {
- source: null,
- line: null,
- column: null,
- name: null
- };
- }
- return section.consumer.originalPositionFor({
- line: needle.generatedLine - (section.generatedOffset.generatedLine
- 1),
- column: needle.generatedColumn -
(section.generatedOffset.generatedLine === needle.generatedLine ?
section.generatedOffset.generatedColumn - 1 : 0)
- });
- };
- IndexedSourceMapConsumer.prototype.sourceContentFor = function
IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
- for (var i = 0; i < this._sections.length; i++) {
- var section = this._sections[i];
- var content = section.consumer.sourceContentFor(aSource, true);
- if (content) {
- return content;
- }
- }
- if (nullOnMissing) {
- return null;
- } else {
- throw new Error('"' + aSource + '" is not in the SourceMap.');
- }
- };
- IndexedSourceMapConsumer.prototype.generatedPositionFor = function
IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
- for (var i = 0; i < this._sections.length; i++) {
- var section = this._sections[i];
- if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source'))
=== -1) {
- continue;
- }
- var generatedPosition = section.consumer.generatedPositionFor(aArgs);
- if (generatedPosition) {
- var ret = {
- line: generatedPosition.line +
(section.generatedOffset.generatedLine - 1),
- column: generatedPosition.column +
(section.generatedOffset.generatedLine === generatedPosition.line ?
section.generatedOffset.generatedColumn - 1 : 0)
- };
- return ret;
- }
- }
- return {
- line: null,
- column: null
- };
- };
- IndexedSourceMapConsumer.prototype._parseMappings = function
IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
- this.__generatedMappings = [];
- this.__originalMappings = [];
- for (var i = 0; i < this._sections.length; i++) {
- var section = this._sections[i];
- var sectionMappings = section.consumer._generatedMappings;
- for (var j = 0; j < sectionMappings.length; j++) {
- var mapping = sectionMappings[i];
- var source = mapping.source;
- var sourceRoot = section.consumer.sourceRoot;
- if (source != null && sourceRoot != null) {
- source = util.join(sourceRoot, source);
- }
- var adjustedMapping = {
- source: source,
- generatedLine: mapping.generatedLine +
(section.generatedOffset.generatedLine - 1),
- generatedColumn: mapping.column +
(section.generatedOffset.generatedLine === mapping.generatedLine) ?
section.generatedOffset.generatedColumn - 1 : 0,
- originalLine: mapping.originalLine,
- originalColumn: mapping.originalColumn,
- name: mapping.name
- };
- this.__generatedMappings.push(adjustedMapping);
- if (typeof adjustedMapping.originalLine === 'number') {
- this.__originalMappings.push(adjustedMapping);
- }
- }
- ;
- }
- ;
- this.__generatedMappings.sort(util.compareByGeneratedPositions);
- this.__originalMappings.sort(util.compareByOriginalPositions);
- };
- exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
- });
- });
- require.define('/node_modules/esutils/lib/utils.js', function (module,
exports, __dirname, __filename) {
- (function () {
- 'use strict';
- exports.ast = require('/node_modules/esutils/lib/ast.js', module);
- exports.code = require('/node_modules/esutils/lib/code.js', module);
- exports.keyword = require('/node_modules/esutils/lib/keyword.js',
module);
- }());
- });
- require.define('/node_modules/esutils/lib/keyword.js', function (module,
exports, __dirname, __filename) {
- (function () {
- 'use strict';
- var code = require('/node_modules/esutils/lib/code.js', module);
- function isStrictModeReservedWordES6(id) {
- switch (id) {
- case 'implements':
- case 'interface':
- case 'package':
- case 'private':
- case 'protected':
- case 'public':
- case 'static':
- case 'let':
- return true;
- default:
- return false;
- }
- }
- function isKeywordES5(id, strict) {
- if (!strict && id === 'yield') {
- return false;
- }
- return isKeywordES6(id, strict);
- }
- function isKeywordES6(id, strict) {
- if (strict && isStrictModeReservedWordES6(id)) {
- return true;
- }
- switch (id.length) {
- case 2:
- return id === 'if' || id === 'in' || id === 'do';
- case 3:
- return id === 'var' || id === 'for' || id === 'new' || id === 'try';
- 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;
- }
- }
- function isReservedWordES5(id, strict) {
- return id === 'null' || id === 'true' || id === 'false' ||
isKeywordES5(id, strict);
- }
- function isReservedWordES6(id, strict) {
- return id === 'null' || id === 'true' || id === 'false' ||
isKeywordES6(id, strict);
- }
- function isRestrictedWord(id) {
- return id === 'eval' || id === 'arguments';
- }
- function isIdentifierNameES5(id) {
- var i, iz, ch;
- if (id.length === 0) {
- return false;
- }
- ch = id.charCodeAt(0);
- if (!code.isIdentifierStartES5(ch)) {
- return false;
- }
- for (i = 1, iz = id.length; i < iz; ++i) {
- ch = id.charCodeAt(i);
- if (!code.isIdentifierPartES5(ch)) {
- return false;
- }
- }
- return true;
- }
- function decodeUtf16(lead, trail) {
- return (lead - 55296) * 1024 + (trail - 56320) + 65536;
- }
- function isIdentifierNameES6(id) {
- var i, iz, ch, lowCh, check;
- if (id.length === 0) {
- return false;
- }
- check = code.isIdentifierStartES6;
- for (i = 0, iz = id.length; i < iz; ++i) {
- ch = id.charCodeAt(i);
- if (55296 <= ch && ch <= 56319) {
- ++i;
- if (i >= iz) {
- return false;
- }
- lowCh = id.charCodeAt(i);
- if (!(56320 <= lowCh && lowCh <= 57343)) {
- return false;
- }
- ch = decodeUtf16(ch, lowCh);
- }
- if (!check(ch)) {
- return false;
- }
- check = code.isIdentifierPartES6;
- }
- return true;
- }
- function isIdentifierES5(id, strict) {
- return isIdentifierNameES5(id) && !isReservedWordES5(id, strict);
- }
- function isIdentifierES6(id, strict) {
- return isIdentifierNameES6(id) && !isReservedWordES6(id, strict);
- }
- module.exports = {
- isKeywordES5: isKeywordES5,
- isKeywordES6: isKeywordES6,
- isReservedWordES5: isReservedWordES5,
- isReservedWordES6: isReservedWordES6,
- isRestrictedWord: isRestrictedWord,
- isIdentifierNameES5: isIdentifierNameES5,
- isIdentifierNameES6: isIdentifierNameES6,
- isIdentifierES5: isIdentifierES5,
- isIdentifierES6: isIdentifierES6
- };
- }());
- });
- require.define('/node_modules/esutils/lib/code.js', function (module,
exports, __dirname, __filename) {
- (function () {
- 'use strict';
- var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START,
IDENTIFIER_PART, ch;
- ES5Regex = {
- NonAsciiIdentifierStart:
/[\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-\u085
[...]
- NonAsciiIdentifierPart:
/[\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-\u
[...]
- };
- ES6Regex = {
- NonAsciiIdentifierStart:
/[\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-\u085
[...]
- NonAsciiIdentifierPart:
/[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\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-\u08
[...]
- };
- function isDecimalDigit(ch) {
- return 48 <= ch && ch <= 57;
- }
- function isHexDigit(ch) {
- return 48 <= ch && ch <= 57 || 97 <= ch && ch <= 102 || 65 <= ch && ch
<= 70;
- }
- function isOctalDigit(ch) {
- return ch >= 48 && ch <= 55;
- }
- NON_ASCII_WHITESPACES = [
- 5760,
- 6158,
- 8192,
- 8193,
- 8194,
- 8195,
- 8196,
- 8197,
- 8198,
- 8199,
- 8200,
- 8201,
- 8202,
- 8239,
- 8287,
- 12288,
- 65279
- ];
- function isWhiteSpace(ch) {
- return ch === 32 || ch === 9 || ch === 11 || ch === 12 || ch === 160
|| ch >= 5760 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0;
- }
- function isLineTerminator(ch) {
- return ch === 10 || ch === 13 || ch === 8232 || ch === 8233;
- }
- function fromCodePoint(cp) {
- if (cp <= 65535) {
- return String.fromCharCode(cp);
- }
- var cu1 = String.fromCharCode(Math.floor((cp - 65536) / 1024) + 55296);
- var cu2 = String.fromCharCode((cp - 65536) % 1024 + 56320);
- return cu1 + cu2;
- }
- IDENTIFIER_START = new Array(128);
- for (ch = 0; ch < 128; ++ch) {
- IDENTIFIER_START[ch] = ch >= 97 && ch <= 122 || ch >= 65 && ch <= 90
|| ch === 36 || ch === 95;
- }
- IDENTIFIER_PART = new Array(128);
- for (ch = 0; ch < 128; ++ch) {
- IDENTIFIER_PART[ch] = ch >= 97 && ch <= 122 || ch >= 65 && ch <= 90 ||
ch >= 48 && ch <= 57 || ch === 36 || ch === 95;
- }
- function isIdentifierStartES5(ch) {
- return ch < 128 ? IDENTIFIER_START[ch] :
ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
- }
- function isIdentifierPartES5(ch) {
- return ch < 128 ? IDENTIFIER_PART[ch] :
ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
- }
- function isIdentifierStartES6(ch) {
- return ch < 128 ? IDENTIFIER_START[ch] :
ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
- }
- function isIdentifierPartES6(ch) {
- return ch < 128 ? IDENTIFIER_PART[ch] :
ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
- }
- module.exports = {
- isDecimalDigit: isDecimalDigit,
- isHexDigit: isHexDigit,
- isOctalDigit: isOctalDigit,
- isWhiteSpace: isWhiteSpace,
- isLineTerminator: isLineTerminator,
- isIdentifierStartES5: isIdentifierStartES5,
- isIdentifierPartES5: isIdentifierPartES5,
- isIdentifierStartES6: isIdentifierStartES6,
- isIdentifierPartES6: isIdentifierPartES6
- };
- }());
- });
- require.define('/node_modules/esutils/lib/ast.js', function (module,
exports, __dirname, __filename) {
- (function () {
- 'use strict';
- function isExpression(node) {
- if (node == null) {
- return false;
- }
- switch (node.type) {
- case 'ArrayExpression':
- case 'AssignmentExpression':
- case 'BinaryExpression':
- case 'CallExpression':
- case 'ConditionalExpression':
- case 'FunctionExpression':
- case 'Identifier':
- case 'Literal':
- case 'LogicalExpression':
- case 'MemberExpression':
- case 'NewExpression':
- case 'ObjectExpression':
- case 'SequenceExpression':
- case 'ThisExpression':
- case 'UnaryExpression':
- case 'UpdateExpression':
- return true;
- }
- return false;
- }
- function isIterationStatement(node) {
- if (node == null) {
- return false;
- }
- switch (node.type) {
- case 'DoWhileStatement':
- case 'ForInStatement':
- case 'ForStatement':
- case 'WhileStatement':
- return true;
- }
- return false;
- }
- function isStatement(node) {
- if (node == null) {
- return false;
- }
- switch (node.type) {
- case 'BlockStatement':
- case 'BreakStatement':
- case 'ContinueStatement':
- case 'DebuggerStatement':
- case 'DoWhileStatement':
- case 'EmptyStatement':
- case 'ExpressionStatement':
- case 'ForInStatement':
- case 'ForStatement':
- case 'IfStatement':
- case 'LabeledStatement':
- case 'ReturnStatement':
- case 'SwitchStatement':
- case 'ThrowStatement':
- case 'TryStatement':
- case 'VariableDeclaration':
- case 'WhileStatement':
- case 'WithStatement':
- return true;
- }
- return false;
- }
- function isSourceElement(node) {
- return isStatement(node) || node != null && node.type ===
'FunctionDeclaration';
- }
- function trailingStatement(node) {
- switch (node.type) {
- case 'IfStatement':
- if (node.alternate != null) {
- return node.alternate;
- }
- return node.consequent;
- case 'LabeledStatement':
- case 'ForStatement':
- case 'ForInStatement':
- case 'WhileStatement':
- case 'WithStatement':
- return node.body;
- }
- return null;
- }
- function isProblematicIfStatement(node) {
- var current;
- if (node.type !== 'IfStatement') {
- return false;
- }
- if (node.alternate == null) {
- return false;
- }
- current = node.consequent;
- do {
- if (current.type === 'IfStatement') {
- if (current.alternate == null) {
- return true;
- }
- }
- current = trailingStatement(current);
- } while (current);
- return false;
- }
- module.exports = {
- isExpression: isExpression,
- isStatement: isStatement,
- isIterationStatement: isIterationStatement,
- isSourceElement: isSourceElement,
- isProblematicIfStatement: isProblematicIfStatement,
- trailingStatement: trailingStatement
- };
- }());
- });
- require.define('/node_modules/estraverse/estraverse.js', function (module,
exports, __dirname, __filename) {
- (function (root, factory) {
- 'use strict';
- 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);
- 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) {
- var keys = objectKeys(from), key, i, len;
- for (i = 0, len = keys.length; i < len; i += 1) {
- key = keys[i];
- to[key] = from[key];
- }
- return to;
- }
- Syntax = {
- AssignmentExpression: 'AssignmentExpression',
- ArrayExpression: 'ArrayExpression',
- ArrayPattern: 'ArrayPattern',
- ArrowFunctionExpression: 'ArrowFunctionExpression',
- AwaitExpression: 'AwaitExpression',
- BlockStatement: 'BlockStatement',
- BinaryExpression: 'BinaryExpression',
- BreakStatement: 'BreakStatement',
- CallExpression: 'CallExpression',
- CatchClause: 'CatchClause',
- ClassBody: 'ClassBody',
- ClassDeclaration: 'ClassDeclaration',
- ClassExpression: 'ClassExpression',
- ComprehensionBlock: 'ComprehensionBlock',
- ComprehensionExpression: 'ComprehensionExpression',
- 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',
- 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'],
- 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'
- ],
- ComprehensionExpression: [
- 'blocks',
- 'filter',
- 'body'
- ],
- 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'
- ],
- 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']
- };
- 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() {
- }
- 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);
- }
- }
- if (!this.__current.path) {
- return null;
- }
- 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;
- };
- Controller.prototype.type = function () {
- var node = this.current();
- return node.type || this.__current.wrap;
- };
- Controller.prototype.parents = function parents() {
- var i, iz, result;
- result = [];
- for (i = 1, iz = this.__leavelist.length; i < iz; ++i) {
- result.push(this.__leavelist[i].node);
- }
- return result;
- };
- 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;
- };
- Controller.prototype.notify = function notify(flag) {
- this.__state = flag;
- };
- Controller.prototype.skip = function () {
- this.notify(SKIP);
- };
- Controller.prototype['break'] = function () {
- this.notify(BREAK);
- };
- 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 = {};
- worklist = this.__worklist;
- leavelist = this.__leavelist;
- 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()) {
- key = element.ref.key;
- parent = element.ref.parent;
- 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 = {};
- worklist = this.__worklist;
- leavelist = this.__leavelist;
- 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);
- if (target !== undefined && target !== BREAK && target !== SKIP &&
target !== REMOVE) {
- 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);
- if (target !== undefined && target !== BREAK && target !== SKIP &&
target !== REMOVE) {
- 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 = 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) {
- var comments = [], comment, len, i, cursor;
- if (!tree.range) {
- throw new Error('attachComments needs range information');
- }
- 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));
- }
- 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;
- }
- }
- 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;
- }
- }
- 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;
- }));
- });
- require('/tools/entry-point.js');
-}.call(this, this));
diff --git a/node_modules/talertest/selenium/esprima.js
b/node_modules/talertest/selenium/esprima.js
deleted file mode 100644
index d95f56eb..00000000
--- a/node_modules/talertest/selenium/esprima.js
+++ /dev/null
@@ -1,6605 +0,0 @@
-(function webpackUniversalModuleDefinition(root, factory) {
-/* istanbul ignore next */
- if(typeof exports === 'object' && typeof module === 'object')
- module.exports = factory();
- else if(typeof define === 'function' && define.amd)
- define([], factory);
-/* istanbul ignore next */
- else if(typeof exports === 'object')
- exports["esprima"] = factory();
- else
- root["esprima"] = factory();
-})(this, function() {
-return /******/ (function(modules) { // webpackBootstrap
-/******/ // The module cache
-/******/ var installedModules = {};
-
-/******/ // The require function
-/******/ function __webpack_require__(moduleId) {
-
-/******/ // Check if module is in cache
-/* istanbul ignore if */
-/******/ if(installedModules[moduleId])
-/******/ return installedModules[moduleId].exports;
-
-/******/ // Create a new module (and put it into the cache)
-/******/ var module = installedModules[moduleId] = {
-/******/ exports: {},
-/******/ id: moduleId,
-/******/ loaded: false
-/******/ };
-
-/******/ // Execute the module function
-/******/ modules[moduleId].call(module.exports, module,
module.exports, __webpack_require__);
-
-/******/ // Flag the module as loaded
-/******/ module.loaded = true;
-
-/******/ // Return the exports of the module
-/******/ return module.exports;
-/******/ }
-
-
-/******/ // expose the modules object (__webpack_modules__)
-/******/ __webpack_require__.m = modules;
-
-/******/ // expose the module cache
-/******/ __webpack_require__.c = installedModules;
-
-/******/ // __webpack_public_path__
-/******/ __webpack_require__.p = "";
-
-/******/ // Load entry module and return exports
-/******/ return __webpack_require__(0);
-/******/ })
-/************************************************************************/
-/******/ ([
-/* 0 */
-/***/ function(module, exports, __webpack_require__) {
-
- /*
- Copyright JS Foundation and other contributors, https://js.foundation/
-
- 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY
- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES
- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES;
- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND
- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
- "use strict";
- var comment_handler_1 = __webpack_require__(1);
- var parser_1 = __webpack_require__(3);
- var jsx_parser_1 = __webpack_require__(11);
- var tokenizer_1 = __webpack_require__(15);
- function parse(code, options, delegate) {
- var commentHandler = null;
- var proxyDelegate = function (node, metadata) {
- if (delegate) {
- delegate(node, metadata);
- }
- if (commentHandler) {
- commentHandler.visit(node, metadata);
- }
- };
- var parserDelegate = (typeof delegate === 'function') ?
proxyDelegate : null;
- var collectComment = false;
- if (options) {
- collectComment = (typeof options.comment === 'boolean' &&
options.comment);
- var attachComment = (typeof options.attachComment === 'boolean'
&& options.attachComment);
- if (collectComment || attachComment) {
- commentHandler = new comment_handler_1.CommentHandler();
- commentHandler.attach = attachComment;
- options.comment = true;
- parserDelegate = proxyDelegate;
- }
- }
- var isModule = false;
- if (options && typeof options.sourceType === 'string') {
- isModule = (options.sourceType === 'module');
- }
- var parser;
- if (options && typeof options.jsx === 'boolean' && options.jsx) {
- parser = new jsx_parser_1.JSXParser(code, options,
parserDelegate);
- }
- else {
- parser = new parser_1.Parser(code, options, parserDelegate);
- }
- var program = isModule ? parser.parseModule() :
parser.parseScript();
- var ast = (program);
- if (collectComment && commentHandler) {
- ast.comments = commentHandler.comments;
- }
- if (parser.config.tokens) {
- ast.tokens = parser.tokens;
- }
- if (parser.config.tolerant) {
- ast.errors = parser.errorHandler.errors;
- }
- return ast;
- }
- exports.parse = parse;
- function parseModule(code, options, delegate) {
- var parsingOptions = options || {};
- parsingOptions.sourceType = 'module';
- return parse(code, parsingOptions, delegate);
- }
- exports.parseModule = parseModule;
- function parseScript(code, options, delegate) {
- var parsingOptions = options || {};
- parsingOptions.sourceType = 'script';
- return parse(code, parsingOptions, delegate);
- }
- exports.parseScript = parseScript;
- function tokenize(code, options, delegate) {
- var tokenizer = new tokenizer_1.Tokenizer(code, options);
- var tokens;
- tokens = [];
- try {
- while (true) {
- var token = tokenizer.getNextToken();
- if (!token) {
- break;
- }
- if (delegate) {
- token = delegate(token);
- }
- tokens.push(token);
- }
- }
- catch (e) {
- tokenizer.errorHandler.tolerate(e);
- }
- if (tokenizer.errorHandler.tolerant) {
- tokens.errors = tokenizer.errors();
- }
- return tokens;
- }
- exports.tokenize = tokenize;
- var syntax_1 = __webpack_require__(2);
- exports.Syntax = syntax_1.Syntax;
- // Sync with *.json manifests.
- exports.version = '4.0.0-dev';
-
-
-/***/ },
-/* 1 */
-/***/ function(module, exports, __webpack_require__) {
-
- "use strict";
- var syntax_1 = __webpack_require__(2);
- var CommentHandler = (function () {
- function CommentHandler() {
- this.attach = false;
- this.comments = [];
- this.stack = [];
- this.leading = [];
- this.trailing = [];
- }
- CommentHandler.prototype.insertInnerComments = function (node,
metadata) {
- // innnerComments for properties empty block
- // `function a() {/** comments **\/}`
- if (node.type === syntax_1.Syntax.BlockStatement &&
node.body.length === 0) {
- var innerComments = [];
- for (var i = this.leading.length - 1; i >= 0; --i) {
- var entry = this.leading[i];
- if (metadata.end.offset >= entry.start) {
- innerComments.unshift(entry.comment);
- this.leading.splice(i, 1);
- this.trailing.splice(i, 1);
- }
- }
- if (innerComments.length) {
- node.innerComments = innerComments;
- }
- }
- };
- CommentHandler.prototype.findTrailingComments = function (metadata)
{
- var trailingComments = [];
- if (this.trailing.length > 0) {
- for (var i = this.trailing.length - 1; i >= 0; --i) {
- var entry_1 = this.trailing[i];
- if (entry_1.start >= metadata.end.offset) {
- trailingComments.unshift(entry_1.comment);
- }
- }
- this.trailing.length = 0;
- return trailingComments;
- }
- var entry = this.stack[this.stack.length - 1];
- if (entry && entry.node.trailingComments) {
- var firstComment = entry.node.trailingComments[0];
- if (firstComment && firstComment.range[0] >=
metadata.end.offset) {
- trailingComments = entry.node.trailingComments;
- delete entry.node.trailingComments;
- }
- }
- return trailingComments;
- };
- CommentHandler.prototype.findLeadingComments = function (metadata) {
- var leadingComments = [];
- var target;
- while (this.stack.length > 0) {
- var entry = this.stack[this.stack.length - 1];
- if (entry && entry.start >= metadata.start.offset) {
- target = entry.node;
- this.stack.pop();
- }
- else {
- break;
- }
- }
- if (target) {
- var count = target.leadingComments ?
target.leadingComments.length : 0;
- for (var i = count - 1; i >= 0; --i) {
- var comment = target.leadingComments[i];
- if (comment.range[1] <= metadata.start.offset) {
- leadingComments.unshift(comment);
- target.leadingComments.splice(i, 1);
- }
- }
- if (target.leadingComments && target.leadingComments.length
=== 0) {
- delete target.leadingComments;
- }
- return leadingComments;
- }
- for (var i = this.leading.length - 1; i >= 0; --i) {
- var entry = this.leading[i];
- if (entry.start <= metadata.start.offset) {
- leadingComments.unshift(entry.comment);
- this.leading.splice(i, 1);
- }
- }
- return leadingComments;
- };
- CommentHandler.prototype.visitNode = function (node, metadata) {
- if (node.type === syntax_1.Syntax.Program && node.body.length >
0) {
- return;
- }
- this.insertInnerComments(node, metadata);
- var trailingComments = this.findTrailingComments(metadata);
- var leadingComments = this.findLeadingComments(metadata);
- if (leadingComments.length > 0) {
- node.leadingComments = leadingComments;
- }
- if (trailingComments.length > 0) {
- node.trailingComments = trailingComments;
- }
- this.stack.push({
- node: node,
- start: metadata.start.offset
- });
- };
- CommentHandler.prototype.visitComment = function (node, metadata) {
- var type = (node.type[0] === 'L') ? 'Line' : 'Block';
- var comment = {
- type: type,
- value: node.value
- };
- if (node.range) {
- comment.range = node.range;
- }
- if (node.loc) {
- comment.loc = node.loc;
- }
- this.comments.push(comment);
- if (this.attach) {
- var entry = {
- comment: {
- type: type,
- value: node.value,
- range: [metadata.start.offset, metadata.end.offset]
- },
- start: metadata.start.offset
- };
- if (node.loc) {
- entry.comment.loc = node.loc;
- }
- node.type = type;
- this.leading.push(entry);
- this.trailing.push(entry);
- }
- };
- CommentHandler.prototype.visit = function (node, metadata) {
- if (node.type === 'LineComment') {
- this.visitComment(node, metadata);
- }
- else if (node.type === 'BlockComment') {
- this.visitComment(node, metadata);
- }
- else if (this.attach) {
- this.visitNode(node, metadata);
- }
- };
- return CommentHandler;
- }());
- exports.CommentHandler = CommentHandler;
-
-
-/***/ },
-/* 2 */
-/***/ function(module, exports) {
-
- "use strict";
- exports.Syntax = {
- AssignmentExpression: 'AssignmentExpression',
- AssignmentPattern: 'AssignmentPattern',
- ArrayExpression: 'ArrayExpression',
- ArrayPattern: 'ArrayPattern',
- ArrowFunctionExpression: 'ArrowFunctionExpression',
- AwaitExpression: 'AwaitExpression',
- BlockStatement: 'BlockStatement',
- BinaryExpression: 'BinaryExpression',
- BreakStatement: 'BreakStatement',
- CallExpression: 'CallExpression',
- CatchClause: 'CatchClause',
- ClassBody: 'ClassBody',
- ClassDeclaration: 'ClassDeclaration',
- ClassExpression: 'ClassExpression',
- ConditionalExpression: 'ConditionalExpression',
- ContinueStatement: 'ContinueStatement',
- DoWhileStatement: 'DoWhileStatement',
- DebuggerStatement: 'DebuggerStatement',
- EmptyStatement: 'EmptyStatement',
- ExportAllDeclaration: 'ExportAllDeclaration',
- ExportDefaultDeclaration: 'ExportDefaultDeclaration',
- ExportNamedDeclaration: 'ExportNamedDeclaration',
- ExportSpecifier: 'ExportSpecifier',
- ExpressionStatement: 'ExpressionStatement',
- ForStatement: 'ForStatement',
- ForOfStatement: 'ForOfStatement',
- ForInStatement: 'ForInStatement',
- FunctionDeclaration: 'FunctionDeclaration',
- FunctionExpression: 'FunctionExpression',
- Identifier: 'Identifier',
- IfStatement: 'IfStatement',
- ImportDeclaration: 'ImportDeclaration',
- ImportDefaultSpecifier: 'ImportDefaultSpecifier',
- ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
- ImportSpecifier: 'ImportSpecifier',
- Literal: 'Literal',
- LabeledStatement: 'LabeledStatement',
- LogicalExpression: 'LogicalExpression',
- MemberExpression: 'MemberExpression',
- MetaProperty: 'MetaProperty',
- MethodDefinition: 'MethodDefinition',
- NewExpression: 'NewExpression',
- ObjectExpression: 'ObjectExpression',
- ObjectPattern: 'ObjectPattern',
- Program: 'Program',
- Property: 'Property',
- RestElement: 'RestElement',
- ReturnStatement: 'ReturnStatement',
- SequenceExpression: 'SequenceExpression',
- SpreadElement: 'SpreadElement',
- Super: 'Super',
- SwitchCase: 'SwitchCase',
- SwitchStatement: 'SwitchStatement',
- 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'
- };
-
-
-/***/ },
-/* 3 */
-/***/ function(module, exports, __webpack_require__) {
-
- "use strict";
- var assert_1 = __webpack_require__(4);
- var messages_1 = __webpack_require__(5);
- var error_handler_1 = __webpack_require__(6);
- var token_1 = __webpack_require__(7);
- var scanner_1 = __webpack_require__(8);
- var syntax_1 = __webpack_require__(2);
- var Node = __webpack_require__(10);
- var ArrowParameterPlaceHolder = 'ArrowParameterPlaceHolder';
- var Parser = (function () {
- function Parser(code, options, delegate) {
- if (options === void 0) { options = {}; }
- this.config = {
- range: (typeof options.range === 'boolean') &&
options.range,
- loc: (typeof options.loc === 'boolean') && options.loc,
- source: null,
- tokens: (typeof options.tokens === 'boolean') &&
options.tokens,
- comment: (typeof options.comment === 'boolean') &&
options.comment,
- tolerant: (typeof options.tolerant === 'boolean') &&
options.tolerant
- };
- if (this.config.loc && options.source && options.source !==
null) {
- this.config.source = String(options.source);
- }
- this.delegate = delegate;
- this.errorHandler = new error_handler_1.ErrorHandler();
- this.errorHandler.tolerant = this.config.tolerant;
- this.scanner = new scanner_1.Scanner(code, this.errorHandler);
- this.scanner.trackComment = this.config.comment;
- this.operatorPrecedence = {
- ')': 0,
- ';': 0,
- ',': 0,
- '=': 0,
- ']': 0,
- '||': 1,
- '&&': 2,
- '|': 3,
- '^': 4,
- '&': 5,
- '==': 6,
- '!=': 6,
- '===': 6,
- '!==': 6,
- '<': 7,
- '>': 7,
- '<=': 7,
- '>=': 7,
- '<<': 8,
- '>>': 8,
- '>>>': 8,
- '+': 9,
- '-': 9,
- '*': 11,
- '/': 11,
- '%': 11
- };
- this.lookahead = null;
- this.hasLineTerminator = false;
- this.context = {
- isModule: false,
- await: false,
- allowIn: true,
- allowYield: true,
- firstCoverInitializedNameError: null,
- isAssignmentTarget: false,
- isBindingElement: false,
- inFunctionBody: false,
- inIteration: false,
- inSwitch: false,
- labelSet: {},
- strict: false
- };
- this.tokens = [];
- this.startMarker = {
- index: 0,
- lineNumber: this.scanner.lineNumber,
- lineStart: 0
- };
- this.lastMarker = {
- index: 0,
- lineNumber: this.scanner.lineNumber,
- lineStart: 0
- };
- this.nextToken();
- this.lastMarker = {
- index: this.scanner.index,
- lineNumber: this.scanner.lineNumber,
- lineStart: this.scanner.lineStart
- };
- }
- Parser.prototype.throwError = function (messageFormat) {
- var values = [];
- for (var _i = 1; _i < arguments.length; _i++) {
- values[_i - 1] = arguments[_i];
- }
- var args = Array.prototype.slice.call(arguments, 1);
- var msg = messageFormat.replace(/%(\d)/g, function (whole, idx)
{
- assert_1.assert(idx < args.length, 'Message reference must
be in range');
- return args[idx];
- });
- var index = this.lastMarker.index;
- var line = this.lastMarker.lineNumber;
- var column = this.lastMarker.index - this.lastMarker.lineStart
+ 1;
- throw this.errorHandler.createError(index, line, column, msg);
- };
- Parser.prototype.tolerateError = function (messageFormat) {
- var values = [];
- for (var _i = 1; _i < arguments.length; _i++) {
- values[_i - 1] = arguments[_i];
- }
- var args = Array.prototype.slice.call(arguments, 1);
- var msg = messageFormat.replace(/%(\d)/g, function (whole, idx)
{
- assert_1.assert(idx < args.length, 'Message reference must
be in range');
- return args[idx];
- });
- var index = this.lastMarker.index;
- var line = this.scanner.lineNumber;
- var column = this.lastMarker.index - this.lastMarker.lineStart
+ 1;
- this.errorHandler.tolerateError(index, line, column, msg);
- };
- // Throw an exception because of the token.
- Parser.prototype.unexpectedTokenError = function (token, message) {
- var msg = message || messages_1.Messages.UnexpectedToken;
- var value;
- if (token) {
- if (!message) {
- msg = (token.type === token_1.Token.EOF) ?
messages_1.Messages.UnexpectedEOS :
- (token.type === token_1.Token.Identifier) ?
messages_1.Messages.UnexpectedIdentifier :
- (token.type === token_1.Token.NumericLiteral) ?
messages_1.Messages.UnexpectedNumber :
- (token.type ===
token_1.Token.StringLiteral) ? messages_1.Messages.UnexpectedString :
- (token.type === token_1.Token.Template)
? messages_1.Messages.UnexpectedTemplate :
- messages_1.Messages.UnexpectedToken;
- if (token.type === token_1.Token.Keyword) {
- if (this.scanner.isFutureReservedWord(token.value))
{
- msg = messages_1.Messages.UnexpectedReserved;
- }
- else if (this.context.strict &&
this.scanner.isStrictModeReservedWord(token.value)) {
- msg = messages_1.Messages.StrictReservedWord;
- }
- }
- }
- value = (token.type === token_1.Token.Template) ?
token.value.raw : token.value;
- }
- else {
- value = 'ILLEGAL';
- }
- msg = msg.replace('%0', value);
- if (token && typeof token.lineNumber === 'number') {
- var index = token.start;
- var line = token.lineNumber;
- var column = token.start - this.lastMarker.lineStart + 1;
- return this.errorHandler.createError(index, line, column,
msg);
- }
- else {
- var index = this.lastMarker.index;
- var line = this.lastMarker.lineNumber;
- var column = index - this.lastMarker.lineStart + 1;
- return this.errorHandler.createError(index, line, column,
msg);
- }
- };
- Parser.prototype.throwUnexpectedToken = function (token, message) {
- throw this.unexpectedTokenError(token, message);
- };
- Parser.prototype.tolerateUnexpectedToken = function (token,
message) {
- this.errorHandler.tolerate(this.unexpectedTokenError(token,
message));
- };
- Parser.prototype.collectComments = function () {
- if (!this.config.comment) {
- this.scanner.scanComments();
- }
- else {
- var comments = this.scanner.scanComments();
- if (comments.length > 0 && this.delegate) {
- for (var i = 0; i < comments.length; ++i) {
- var e = comments[i];
- var node = void 0;
- node = {
- type: e.multiLine ? 'BlockComment' :
'LineComment',
- value: this.scanner.source.slice(e.slice[0],
e.slice[1])
- };
- if (this.config.range) {
- node.range = e.range;
- }
- if (this.config.loc) {
- node.loc = e.loc;
- }
- var metadata = {
- start: {
- line: e.loc.start.line,
- column: e.loc.start.column,
- offset: e.range[0]
- },
- end: {
- line: e.loc.end.line,
- column: e.loc.end.column,
- offset: e.range[1]
- }
- };
- this.delegate(node, metadata);
- }
- }
- }
- };
- // From internal representation to an external structure
- Parser.prototype.getTokenRaw = function (token) {
- return this.scanner.source.slice(token.start, token.end);
- };
- Parser.prototype.convertToken = function (token) {
- var t;
- t = {
- type: token_1.TokenName[token.type],
- value: this.getTokenRaw(token)
- };
- if (this.config.range) {
- t.range = [token.start, token.end];
- }
- if (this.config.loc) {
- t.loc = {
- start: {
- line: this.startMarker.lineNumber,
- column: this.startMarker.index -
this.startMarker.lineStart
- },
- end: {
- line: this.scanner.lineNumber,
- column: this.scanner.index - this.scanner.lineStart
- }
- };
- }
- if (token.regex) {
- t.regex = token.regex;
- }
- return t;
- };
- Parser.prototype.nextToken = function () {
- var token = this.lookahead;
- this.lastMarker.index = this.scanner.index;
- this.lastMarker.lineNumber = this.scanner.lineNumber;
- this.lastMarker.lineStart = this.scanner.lineStart;
- this.collectComments();
- this.startMarker.index = this.scanner.index;
- this.startMarker.lineNumber = this.scanner.lineNumber;
- this.startMarker.lineStart = this.scanner.lineStart;
- var next;
- next = this.scanner.lex();
- this.hasLineTerminator = (token && next) ? (token.lineNumber
!== next.lineNumber) : false;
- if (next && this.context.strict && next.type ===
token_1.Token.Identifier) {
- if (this.scanner.isStrictModeReservedWord(next.value)) {
- next.type = token_1.Token.Keyword;
- }
- }
- this.lookahead = next;
- if (this.config.tokens && next.type !== token_1.Token.EOF) {
- this.tokens.push(this.convertToken(next));
- }
- return token;
- };
- Parser.prototype.nextRegexToken = function () {
- this.collectComments();
- var token = this.scanner.scanRegExp();
- if (this.config.tokens) {
- // Pop the previous token, '/' or '/='
- // This is added from the lookahead token.
- this.tokens.pop();
- this.tokens.push(this.convertToken(token));
- }
- // Prime the next lookahead.
- this.lookahead = token;
- this.nextToken();
- return token;
- };
- Parser.prototype.createNode = function () {
- return {
- index: this.startMarker.index,
- line: this.startMarker.lineNumber,
- column: this.startMarker.index - this.startMarker.lineStart
- };
- };
- Parser.prototype.startNode = function (token) {
- return {
- index: token.start,
- line: token.lineNumber,
- column: token.start - token.lineStart
- };
- };
- Parser.prototype.finalize = function (meta, node) {
- if (this.config.range) {
- node.range = [meta.index, this.lastMarker.index];
- }
- if (this.config.loc) {
- node.loc = {
- start: {
- line: meta.line,
- column: meta.column
- },
- end: {
- line: this.lastMarker.lineNumber,
- column: this.lastMarker.index -
this.lastMarker.lineStart
- }
- };
- if (this.config.source) {
- node.loc.source = this.config.source;
- }
- }
- if (this.delegate) {
- var metadata = {
- start: {
- line: meta.line,
- column: meta.column,
- offset: meta.index
- },
- end: {
- line: this.lastMarker.lineNumber,
- column: this.lastMarker.index -
this.lastMarker.lineStart,
- offset: this.lastMarker.index
- }
- };
- this.delegate(node, metadata);
- }
- return node;
- };
- // Expect the next token to match the specified punctuator.
- // If not, an exception will be thrown.
- Parser.prototype.expect = function (value) {
- var token = this.nextToken();
- if (token.type !== token_1.Token.Punctuator || token.value !==
value) {
- this.throwUnexpectedToken(token);
- }
- };
- // Quietly expect a comma when in tolerant mode, otherwise
delegates to expect().
- Parser.prototype.expectCommaSeparator = function () {
- if (this.config.tolerant) {
- var token = this.lookahead;
- if (token.type === token_1.Token.Punctuator && token.value
=== ',') {
- this.nextToken();
- }
- else if (token.type === token_1.Token.Punctuator &&
token.value === ';') {
- this.nextToken();
- this.tolerateUnexpectedToken(token);
- }
- else {
- this.tolerateUnexpectedToken(token,
messages_1.Messages.UnexpectedToken);
- }
- }
- else {
- this.expect(',');
- }
- };
- // Expect the next token to match the specified keyword.
- // If not, an exception will be thrown.
- Parser.prototype.expectKeyword = function (keyword) {
- var token = this.nextToken();
- if (token.type !== token_1.Token.Keyword || token.value !==
keyword) {
- this.throwUnexpectedToken(token);
- }
- };
- // Return true if the next token matches the specified punctuator.
- Parser.prototype.match = function (value) {
- return this.lookahead.type === token_1.Token.Punctuator &&
this.lookahead.value === value;
- };
- // Return true if the next token matches the specified keyword
- Parser.prototype.matchKeyword = function (keyword) {
- return this.lookahead.type === token_1.Token.Keyword &&
this.lookahead.value === keyword;
- };
- // Return true if the next token matches the specified contextual
keyword
- // (where an identifier is sometimes a keyword depending on the
context)
- Parser.prototype.matchContextualKeyword = function (keyword) {
- return this.lookahead.type === token_1.Token.Identifier &&
this.lookahead.value === keyword;
- };
- // Return true if the next token is an assignment operator
- Parser.prototype.matchAssign = function () {
- if (this.lookahead.type !== token_1.Token.Punctuator) {
- return false;
- }
- var op = this.lookahead.value;
- return op === '=' ||
- op === '*=' ||
- op === '**=' ||
- op === '/=' ||
- op === '%=' ||
- op === '+=' ||
- op === '-=' ||
- op === '<<=' ||
- op === '>>=' ||
- op === '>>>=' ||
- op === '&=' ||
- op === '^=' ||
- op === '|=';
- };
- // Cover grammar support.
- //
- // When an assignment expression position starts with an left
parenthesis, the determination of the type
- // of the syntax is to be deferred arbitrarily long until the end
of the parentheses pair (plus a lookahead)
- // or the first comma. This situation also defers the determination
of all the expressions nested in the pair.
- //
- // There are three productions that can be parsed in a parentheses
pair that needs to be determined
- // after the outermost pair is closed. They are:
- //
- // 1. AssignmentExpression
- // 2. BindingElements
- // 3. AssignmentTargets
- //
- // In order to avoid exponential backtracking, we use two flags to
denote if the production can be
- // binding element or assignment target.
- //
- // The three productions have the relationship:
- //
- // BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression
- //
- // with a single exception that CoverInitializedName when used
directly in an Expression, generates
- // an early error. Therefore, we need the third state,
firstCoverInitializedNameError, to track the
- // first usage of CoverInitializedName and report it when we
reached the end of the parentheses pair.
- //
- // isolateCoverGrammar function runs the given parser function with
a new cover grammar context, and it does not
- // effect the current flags. This means the production the parser
parses is only used as an expression. Therefore
- // the CoverInitializedName check is conducted.
- //
- // inheritCoverGrammar function runs the given parse function with
a new cover grammar context, and it propagates
- // the flags outside of the parser. This means the production the
parser parses is used as a part of a potential
- // pattern. The CoverInitializedName check is deferred.
- Parser.prototype.isolateCoverGrammar = function (parseFunction) {
- var previousIsBindingElement = this.context.isBindingElement;
- var previousIsAssignmentTarget =
this.context.isAssignmentTarget;
- var previousFirstCoverInitializedNameError =
this.context.firstCoverInitializedNameError;
- this.context.isBindingElement = true;
- this.context.isAssignmentTarget = true;
- this.context.firstCoverInitializedNameError = null;
- var result = parseFunction.call(this);
- if (this.context.firstCoverInitializedNameError !== null) {
-
this.throwUnexpectedToken(this.context.firstCoverInitializedNameError);
- }
- this.context.isBindingElement = previousIsBindingElement;
- this.context.isAssignmentTarget = previousIsAssignmentTarget;
- this.context.firstCoverInitializedNameError =
previousFirstCoverInitializedNameError;
- return result;
- };
- Parser.prototype.inheritCoverGrammar = function (parseFunction) {
- var previousIsBindingElement = this.context.isBindingElement;
- var previousIsAssignmentTarget =
this.context.isAssignmentTarget;
- var previousFirstCoverInitializedNameError =
this.context.firstCoverInitializedNameError;
- this.context.isBindingElement = true;
- this.context.isAssignmentTarget = true;
- this.context.firstCoverInitializedNameError = null;
- var result = parseFunction.call(this);
- this.context.isBindingElement = this.context.isBindingElement
&& previousIsBindingElement;
- this.context.isAssignmentTarget =
this.context.isAssignmentTarget && previousIsAssignmentTarget;
- this.context.firstCoverInitializedNameError =
previousFirstCoverInitializedNameError ||
this.context.firstCoverInitializedNameError;
- return result;
- };
- Parser.prototype.consumeSemicolon = function () {
- if (this.match(';')) {
- this.nextToken();
- }
- else if (!this.hasLineTerminator) {
- if (this.lookahead.type !== token_1.Token.EOF &&
!this.match('}')) {
- this.throwUnexpectedToken(this.lookahead);
- }
- this.lastMarker.index = this.startMarker.index;
- this.lastMarker.lineNumber = this.startMarker.lineNumber;
- this.lastMarker.lineStart = this.startMarker.lineStart;
- }
- };
- // ECMA-262 12.2 Primary Expressions
- Parser.prototype.parsePrimaryExpression = function () {
- var node = this.createNode();
- var expr;
- var value, token, raw;
- switch (this.lookahead.type) {
- case token_1.Token.Identifier:
- if ((this.context.isModule || this.context.await) &&
this.lookahead.value === 'await') {
- this.tolerateUnexpectedToken(this.lookahead);
- }
- expr = this.matchAsyncFunction() ?
this.parseFunctionExpression() : this.finalize(node, new
Node.Identifier(this.nextToken().value));
- break;
- case token_1.Token.NumericLiteral:
- case token_1.Token.StringLiteral:
- if (this.context.strict && this.lookahead.octal) {
- this.tolerateUnexpectedToken(this.lookahead,
messages_1.Messages.StrictOctalLiteral);
- }
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- token = this.nextToken();
- raw = this.getTokenRaw(token);
- expr = this.finalize(node, new
Node.Literal(token.value, raw));
- break;
- case token_1.Token.BooleanLiteral:
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- token = this.nextToken();
- token.value = (token.value === 'true');
- raw = this.getTokenRaw(token);
- expr = this.finalize(node, new
Node.Literal(token.value, raw));
- break;
- case token_1.Token.NullLiteral:
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- token = this.nextToken();
- token.value = null;
- raw = this.getTokenRaw(token);
- expr = this.finalize(node, new
Node.Literal(token.value, raw));
- break;
- case token_1.Token.Template:
- expr = this.parseTemplateLiteral();
- break;
- case token_1.Token.Punctuator:
- value = this.lookahead.value;
- switch (value) {
- case '(':
- this.context.isBindingElement = false;
- expr =
this.inheritCoverGrammar(this.parseGroupExpression);
- break;
- case '[':
- expr =
this.inheritCoverGrammar(this.parseArrayInitializer);
- break;
- case '{':
- expr =
this.inheritCoverGrammar(this.parseObjectInitializer);
- break;
- case '/':
- case '/=':
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- this.scanner.index = this.startMarker.index;
- token = this.nextRegexToken();
- raw = this.getTokenRaw(token);
- expr = this.finalize(node, new
Node.RegexLiteral(token.value, raw, token.regex));
- break;
- default:
- expr =
this.throwUnexpectedToken(this.nextToken());
- }
- break;
- case token_1.Token.Keyword:
- if (!this.context.strict && this.context.allowYield &&
this.matchKeyword('yield')) {
- expr = this.parseIdentifierName();
- }
- else if (!this.context.strict &&
this.matchKeyword('let')) {
- expr = this.finalize(node, new
Node.Identifier(this.nextToken().value));
- }
- else {
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- if (this.matchKeyword('function')) {
- expr = this.parseFunctionExpression();
- }
- else if (this.matchKeyword('this')) {
- this.nextToken();
- expr = this.finalize(node, new
Node.ThisExpression());
- }
- else if (this.matchKeyword('class')) {
- expr = this.parseClassExpression();
- }
- else {
- expr =
this.throwUnexpectedToken(this.nextToken());
- }
- }
- break;
- default:
- expr = this.throwUnexpectedToken(this.nextToken());
- }
- return expr;
- };
- // ECMA-262 12.2.5 Array Initializer
- Parser.prototype.parseSpreadElement = function () {
- var node = this.createNode();
- this.expect('...');
- var arg =
this.inheritCoverGrammar(this.parseAssignmentExpression);
- return this.finalize(node, new Node.SpreadElement(arg));
- };
- Parser.prototype.parseArrayInitializer = function () {
- var node = this.createNode();
- var elements = [];
- this.expect('[');
- while (!this.match(']')) {
- if (this.match(',')) {
- this.nextToken();
- elements.push(null);
- }
- else if (this.match('...')) {
- var element = this.parseSpreadElement();
- if (!this.match(']')) {
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- this.expect(',');
- }
- elements.push(element);
- }
- else {
-
elements.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
- if (!this.match(']')) {
- this.expect(',');
- }
- }
- }
- this.expect(']');
- return this.finalize(node, new Node.ArrayExpression(elements));
- };
- // ECMA-262 12.2.6 Object Initializer
- Parser.prototype.parsePropertyMethod = function (params) {
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- var previousStrict = this.context.strict;
- var body =
this.isolateCoverGrammar(this.parseFunctionSourceElements);
- if (this.context.strict && params.firstRestricted) {
- this.tolerateUnexpectedToken(params.firstRestricted,
params.message);
- }
- if (this.context.strict && params.stricted) {
- this.tolerateUnexpectedToken(params.stricted,
params.message);
- }
- this.context.strict = previousStrict;
- return body;
- };
- Parser.prototype.parsePropertyMethodFunction = function () {
- var isGenerator = false;
- var node = this.createNode();
- var previousAllowYield = this.context.allowYield;
- this.context.allowYield = false;
- var params = this.parseFormalParameters();
- var method = this.parsePropertyMethod(params);
- this.context.allowYield = previousAllowYield;
- return this.finalize(node, new Node.FunctionExpression(null,
params.params, method, isGenerator));
- };
- Parser.prototype.parsePropertyMethodAsyncFunction = function () {
- var node = this.createNode();
- var previousAllowYield = this.context.allowYield;
- var previousAwait = this.context.await;
- this.context.allowYield = false;
- this.context.await = true;
- var params = this.parseFormalParameters();
- var method = this.parsePropertyMethod(params);
- this.context.allowYield = previousAllowYield;
- this.context.await = previousAwait;
- return this.finalize(node, new
Node.AsyncFunctionExpression(null, params.params, method));
- };
- Parser.prototype.parseObjectPropertyKey = function () {
- var node = this.createNode();
- var token = this.nextToken();
- var key;
- switch (token.type) {
- case token_1.Token.StringLiteral:
- case token_1.Token.NumericLiteral:
- if (this.context.strict && token.octal) {
- this.tolerateUnexpectedToken(token,
messages_1.Messages.StrictOctalLiteral);
- }
- var raw = this.getTokenRaw(token);
- key = this.finalize(node, new Node.Literal(token.value,
raw));
- break;
- case token_1.Token.Identifier:
- case token_1.Token.BooleanLiteral:
- case token_1.Token.NullLiteral:
- case token_1.Token.Keyword:
- key = this.finalize(node, new
Node.Identifier(token.value));
- break;
- case token_1.Token.Punctuator:
- if (token.value === '[') {
- key =
this.isolateCoverGrammar(this.parseAssignmentExpression);
- this.expect(']');
- }
- else {
- key = this.throwUnexpectedToken(token);
- }
- break;
- default:
- key = this.throwUnexpectedToken(token);
- }
- return key;
- };
- Parser.prototype.isPropertyKey = function (key, value) {
- return (key.type === syntax_1.Syntax.Identifier && key.name ===
value) ||
- (key.type === syntax_1.Syntax.Literal && key.value ===
value);
- };
- Parser.prototype.parseObjectProperty = function (hasProto) {
- var node = this.createNode();
- var token = this.lookahead;
- var kind;
- var key = null;
- var value = null;
- var computed = false;
- var method = false;
- var shorthand = false;
- var isAsync = false;
- if (token.type === token_1.Token.Identifier) {
- var id = token.value;
- this.nextToken();
- if (id === 'async') {
- isAsync = !this.hasLineTerminator &&
(this.lookahead.type === token_1.Token.Identifier);
- if (isAsync) {
- token = this.lookahead;
- id = token.value;
- this.nextToken();
- }
- }
- key = this.finalize(node, new Node.Identifier(id));
- }
- else if (this.match('*')) {
- this.nextToken();
- }
- else {
- computed = this.match('[');
- key = this.parseObjectPropertyKey();
- }
- var lookaheadPropertyKey =
this.qualifiedPropertyName(this.lookahead);
- if (token.type === token_1.Token.Identifier && !isAsync &&
token.value === 'get' && lookaheadPropertyKey) {
- kind = 'get';
- computed = this.match('[');
- key = this.parseObjectPropertyKey();
- this.context.allowYield = false;
- value = this.parseGetterMethod();
- }
- else if (token.type === token_1.Token.Identifier && !isAsync &&
token.value === 'set' && lookaheadPropertyKey) {
- kind = 'set';
- computed = this.match('[');
- key = this.parseObjectPropertyKey();
- value = this.parseSetterMethod();
- }
- else if (token.type === token_1.Token.Punctuator && token.value
=== '*' && lookaheadPropertyKey) {
- kind = 'init';
- computed = this.match('[');
- key = this.parseObjectPropertyKey();
- value = this.parseGeneratorMethod();
- method = true;
- }
- else {
- if (!key) {
- this.throwUnexpectedToken(this.lookahead);
- }
- kind = 'init';
- if (this.match(':')) {
- if (!computed && this.isPropertyKey(key, '__proto__')) {
- if (hasProto.value) {
-
this.tolerateError(messages_1.Messages.DuplicateProtoProperty);
- }
- hasProto.value = true;
- }
- this.nextToken();
- value =
this.inheritCoverGrammar(this.parseAssignmentExpression);
- }
- else if (this.match('(')) {
- value = isAsync ?
this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction();
- method = true;
- }
- else if (token.type === token_1.Token.Identifier) {
- var id = this.finalize(node, new
Node.Identifier(token.value));
- if (this.match('=')) {
- this.context.firstCoverInitializedNameError =
this.lookahead;
- this.nextToken();
- shorthand = true;
- var init =
this.isolateCoverGrammar(this.parseAssignmentExpression);
- value = this.finalize(node, new
Node.AssignmentPattern(id, init));
- }
- else {
- shorthand = true;
- value = id;
- }
- }
- else {
- this.throwUnexpectedToken(this.nextToken());
- }
- }
- return this.finalize(node, new Node.Property(kind, (key),
computed, value, method, shorthand));
- };
- Parser.prototype.parseObjectInitializer = function () {
- var node = this.createNode();
- this.expect('{');
- var properties = [];
- var hasProto = { value: false };
- while (!this.match('}')) {
- properties.push(this.parseObjectProperty(hasProto));
- if (!this.match('}')) {
- this.expectCommaSeparator();
- }
- }
- this.expect('}');
- return this.finalize(node, new
Node.ObjectExpression(properties));
- };
- // ECMA-262 12.2.9 Template Literals
- Parser.prototype.parseTemplateHead = function () {
- assert_1.assert(this.lookahead.head, 'Template literal must
start with a template head');
- var node = this.createNode();
- var token = this.nextToken();
- var value = {
- raw: token.value.raw,
- cooked: token.value.cooked
- };
- return this.finalize(node, new Node.TemplateElement(value,
token.tail));
- };
- Parser.prototype.parseTemplateElement = function () {
- if (this.lookahead.type !== token_1.Token.Template) {
- this.throwUnexpectedToken();
- }
- var node = this.createNode();
- var token = this.nextToken();
- var value = {
- raw: token.value.raw,
- cooked: token.value.cooked
- };
- return this.finalize(node, new Node.TemplateElement(value,
token.tail));
- };
- Parser.prototype.parseTemplateLiteral = function () {
- var node = this.createNode();
- var expressions = [];
- var quasis = [];
- var quasi = this.parseTemplateHead();
- quasis.push(quasi);
- while (!quasi.tail) {
- expressions.push(this.parseExpression());
- quasi = this.parseTemplateElement();
- quasis.push(quasi);
- }
- return this.finalize(node, new Node.TemplateLiteral(quasis,
expressions));
- };
- // ECMA-262 12.2.10 The Grouping Operator
- Parser.prototype.reinterpretExpressionAsPattern = function (expr) {
- switch (expr.type) {
- case syntax_1.Syntax.Identifier:
- case syntax_1.Syntax.MemberExpression:
- case syntax_1.Syntax.RestElement:
- case syntax_1.Syntax.AssignmentPattern:
- break;
- case syntax_1.Syntax.SpreadElement:
- expr.type = syntax_1.Syntax.RestElement;
- this.reinterpretExpressionAsPattern(expr.argument);
- break;
- case syntax_1.Syntax.ArrayExpression:
- expr.type = syntax_1.Syntax.ArrayPattern;
- for (var i = 0; i < expr.elements.length; i++) {
- if (expr.elements[i] !== null) {
-
this.reinterpretExpressionAsPattern(expr.elements[i]);
- }
- }
- break;
- case syntax_1.Syntax.ObjectExpression:
- expr.type = syntax_1.Syntax.ObjectPattern;
- for (var i = 0; i < expr.properties.length; i++) {
-
this.reinterpretExpressionAsPattern(expr.properties[i].value);
- }
- break;
- case syntax_1.Syntax.AssignmentExpression:
- expr.type = syntax_1.Syntax.AssignmentPattern;
- delete expr.operator;
- this.reinterpretExpressionAsPattern(expr.left);
- break;
- default:
- // Allow other node type for tolerant parsing.
- break;
- }
- };
- Parser.prototype.parseGroupExpression = function () {
- var expr;
- this.expect('(');
- if (this.match(')')) {
- this.nextToken();
- if (!this.match('=>')) {
- this.expect('=>');
- }
- expr = {
- type: ArrowParameterPlaceHolder,
- params: [],
- async: false
- };
- }
- else {
- var startToken = this.lookahead;
- var params = [];
- if (this.match('...')) {
- expr = this.parseRestElement(params);
- this.expect(')');
- if (!this.match('=>')) {
- this.expect('=>');
- }
- expr = {
- type: ArrowParameterPlaceHolder,
- params: [expr],
- async: false
- };
- }
- else {
- var arrow = false;
- this.context.isBindingElement = true;
- expr =
this.inheritCoverGrammar(this.parseAssignmentExpression);
- if (this.match(',')) {
- var expressions = [];
- this.context.isAssignmentTarget = false;
- expressions.push(expr);
- while (this.startMarker.index <
this.scanner.length) {
- if (!this.match(',')) {
- break;
- }
- this.nextToken();
- if (this.match(')')) {
- this.nextToken();
- for (var i = 0; i < expressions.length;
i++) {
-
this.reinterpretExpressionAsPattern(expressions[i]);
- }
- arrow = true;
- expr = {
- type: ArrowParameterPlaceHolder,
- params: expressions,
- async: false
- };
- }
- else if (this.match('...')) {
- if (!this.context.isBindingElement) {
-
this.throwUnexpectedToken(this.lookahead);
- }
-
expressions.push(this.parseRestElement(params));
- this.expect(')');
- if (!this.match('=>')) {
- this.expect('=>');
- }
- this.context.isBindingElement = false;
- for (var i = 0; i < expressions.length;
i++) {
-
this.reinterpretExpressionAsPattern(expressions[i]);
- }
- arrow = true;
- expr = {
- type: ArrowParameterPlaceHolder,
- params: expressions,
- async: false
- };
- }
- else {
-
expressions.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
- }
- if (arrow) {
- break;
- }
- }
- if (!arrow) {
- expr =
this.finalize(this.startNode(startToken), new
Node.SequenceExpression(expressions));
- }
- }
- if (!arrow) {
- this.expect(')');
- if (this.match('=>')) {
- if (expr.type === syntax_1.Syntax.Identifier &&
expr.name === 'yield') {
- arrow = true;
- expr = {
- type: ArrowParameterPlaceHolder,
- params: [expr],
- async: false
- };
- }
- if (!arrow) {
- if (!this.context.isBindingElement) {
-
this.throwUnexpectedToken(this.lookahead);
- }
- if (expr.type ===
syntax_1.Syntax.SequenceExpression) {
- for (var i = 0; i <
expr.expressions.length; i++) {
-
this.reinterpretExpressionAsPattern(expr.expressions[i]);
- }
- }
- else {
-
this.reinterpretExpressionAsPattern(expr);
- }
- var params_1 = (expr.type ===
syntax_1.Syntax.SequenceExpression ? expr.expressions : [expr]);
- expr = {
- type: ArrowParameterPlaceHolder,
- params: params_1,
- async: false
- };
- }
- }
- this.context.isBindingElement = false;
- }
- }
- }
- return expr;
- };
- // ECMA-262 12.3 Left-Hand-Side Expressions
- Parser.prototype.parseArguments = function () {
- this.expect('(');
- var args = [];
- if (!this.match(')')) {
- while (true) {
- var expr = this.match('...') ?
this.parseSpreadElement() :
-
this.isolateCoverGrammar(this.parseAssignmentExpression);
- args.push(expr);
- if (this.match(')')) {
- break;
- }
- this.expectCommaSeparator();
- if (this.match(')')) {
- break;
- }
- }
- }
- this.expect(')');
- return args;
- };
- Parser.prototype.isIdentifierName = function (token) {
- return token.type === token_1.Token.Identifier ||
- token.type === token_1.Token.Keyword ||
- token.type === token_1.Token.BooleanLiteral ||
- token.type === token_1.Token.NullLiteral;
- };
- Parser.prototype.parseIdentifierName = function () {
- var node = this.createNode();
- var token = this.nextToken();
- if (!this.isIdentifierName(token)) {
- this.throwUnexpectedToken(token);
- }
- return this.finalize(node, new Node.Identifier(token.value));
- };
- Parser.prototype.parseNewExpression = function () {
- var node = this.createNode();
- var id = this.parseIdentifierName();
- assert_1.assert(id.name === 'new', 'New expression must start
with `new`');
- var expr;
- if (this.match('.')) {
- this.nextToken();
- if (this.lookahead.type === token_1.Token.Identifier &&
this.context.inFunctionBody && this.lookahead.value === 'target') {
- var property = this.parseIdentifierName();
- expr = new Node.MetaProperty(id, property);
- }
- else {
- this.throwUnexpectedToken(this.lookahead);
- }
- }
- else {
- var callee =
this.isolateCoverGrammar(this.parseLeftHandSideExpression);
- var args = this.match('(') ? this.parseArguments() : [];
- expr = new Node.NewExpression(callee, args);
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- }
- return this.finalize(node, expr);
- };
- Parser.prototype.parseAsyncArgument = function () {
- var arg = this.parseAssignmentExpression();
- this.context.firstCoverInitializedNameError = null;
- return arg;
- };
- Parser.prototype.parseAsyncArguments = function () {
- this.expect('(');
- var args = [];
- if (!this.match(')')) {
- while (true) {
- var expr = this.match('...') ?
this.parseSpreadElement() :
- this.isolateCoverGrammar(this.parseAsyncArgument);
- args.push(expr);
- if (this.match(')')) {
- break;
- }
- this.expectCommaSeparator();
- if (this.match(')')) {
- break;
- }
- }
- }
- this.expect(')');
- return args;
- };
- Parser.prototype.parseLeftHandSideExpressionAllowCall = function ()
{
- var startToken = this.lookahead;
- var maybeAsync = this.matchContextualKeyword('async');
- var previousAllowIn = this.context.allowIn;
- this.context.allowIn = true;
- var expr;
- if (this.matchKeyword('super') && this.context.inFunctionBody) {
- expr = this.createNode();
- this.nextToken();
- expr = this.finalize(expr, new Node.Super());
- if (!this.match('(') && !this.match('.') &&
!this.match('[')) {
- this.throwUnexpectedToken(this.lookahead);
- }
- }
- else {
- expr = this.inheritCoverGrammar(this.matchKeyword('new') ?
this.parseNewExpression : this.parsePrimaryExpression);
- }
- while (true) {
- if (this.match('.')) {
- this.context.isBindingElement = false;
- this.context.isAssignmentTarget = true;
- this.expect('.');
- var property = this.parseIdentifierName();
- expr = this.finalize(this.startNode(startToken), new
Node.StaticMemberExpression(expr, property));
- }
- else if (this.match('(')) {
- var asyncArrow = maybeAsync && (startToken.lineNumber
=== this.lookahead.lineNumber);
- this.context.isBindingElement = false;
- this.context.isAssignmentTarget = false;
- var args = asyncArrow ? this.parseAsyncArguments() :
this.parseArguments();
- expr = this.finalize(this.startNode(startToken), new
Node.CallExpression(expr, args));
- if (asyncArrow && this.match('=>')) {
- expr = {
- type: ArrowParameterPlaceHolder,
- params: args,
- async: true
- };
- }
- }
- else if (this.match('[')) {
- this.context.isBindingElement = false;
- this.context.isAssignmentTarget = true;
- this.expect('[');
- var property =
this.isolateCoverGrammar(this.parseExpression);
- this.expect(']');
- expr = this.finalize(this.startNode(startToken), new
Node.ComputedMemberExpression(expr, property));
- }
- else if (this.lookahead.type === token_1.Token.Template &&
this.lookahead.head) {
- var quasi = this.parseTemplateLiteral();
- expr = this.finalize(this.startNode(startToken), new
Node.TaggedTemplateExpression(expr, quasi));
- }
- else {
- break;
- }
- }
- this.context.allowIn = previousAllowIn;
- return expr;
- };
- Parser.prototype.parseSuper = function () {
- var node = this.createNode();
- this.expectKeyword('super');
- if (!this.match('[') && !this.match('.')) {
- this.throwUnexpectedToken(this.lookahead);
- }
- return this.finalize(node, new Node.Super());
- };
- Parser.prototype.parseLeftHandSideExpression = function () {
- assert_1.assert(this.context.allowIn, 'callee of new expression
always allow in keyword.');
- var node = this.startNode(this.lookahead);
- var expr = (this.matchKeyword('super') &&
this.context.inFunctionBody) ? this.parseSuper() :
- this.inheritCoverGrammar(this.matchKeyword('new') ?
this.parseNewExpression : this.parsePrimaryExpression);
- while (true) {
- if (this.match('[')) {
- this.context.isBindingElement = false;
- this.context.isAssignmentTarget = true;
- this.expect('[');
- var property =
this.isolateCoverGrammar(this.parseExpression);
- this.expect(']');
- expr = this.finalize(node, new
Node.ComputedMemberExpression(expr, property));
- }
- else if (this.match('.')) {
- this.context.isBindingElement = false;
- this.context.isAssignmentTarget = true;
- this.expect('.');
- var property = this.parseIdentifierName();
- expr = this.finalize(node, new
Node.StaticMemberExpression(expr, property));
- }
- else if (this.lookahead.type === token_1.Token.Template &&
this.lookahead.head) {
- var quasi = this.parseTemplateLiteral();
- expr = this.finalize(node, new
Node.TaggedTemplateExpression(expr, quasi));
- }
- else {
- break;
- }
- }
- return expr;
- };
- // ECMA-262 12.4 Update Expressions
- Parser.prototype.parseUpdateExpression = function () {
- var expr;
- var startToken = this.lookahead;
- if (this.match('++') || this.match('--')) {
- var node = this.startNode(startToken);
- var token = this.nextToken();
- expr = this.inheritCoverGrammar(this.parseUnaryExpression);
- if (this.context.strict && expr.type ===
syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) {
- this.tolerateError(messages_1.Messages.StrictLHSPrefix);
- }
- if (!this.context.isAssignmentTarget) {
-
this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
- }
- var prefix = true;
- expr = this.finalize(node, new
Node.UpdateExpression(token.value, expr, prefix));
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- }
- else {
- expr =
this.inheritCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
- if (!this.hasLineTerminator && this.lookahead.type ===
token_1.Token.Punctuator) {
- if (this.match('++') || this.match('--')) {
- if (this.context.strict && expr.type ===
syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) {
-
this.tolerateError(messages_1.Messages.StrictLHSPostfix);
- }
- if (!this.context.isAssignmentTarget) {
-
this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
- }
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- var operator = this.nextToken().value;
- var prefix = false;
- expr = this.finalize(this.startNode(startToken),
new Node.UpdateExpression(operator, expr, prefix));
- }
- }
- }
- return expr;
- };
- // ECMA-262 12.5 Unary Operators
- Parser.prototype.parseAwaitExpression = function () {
- var node = this.createNode();
- this.nextToken();
- var argument = this.parseUnaryExpression();
- return this.finalize(node, new Node.AwaitExpression(argument));
- };
- Parser.prototype.parseUnaryExpression = function () {
- var expr;
- if (this.match('+') || this.match('-') || this.match('~') ||
this.match('!') ||
- this.matchKeyword('delete') || this.matchKeyword('void') ||
this.matchKeyword('typeof')) {
- var node = this.startNode(this.lookahead);
- var token = this.nextToken();
- expr = this.inheritCoverGrammar(this.parseUnaryExpression);
- expr = this.finalize(node, new
Node.UnaryExpression(token.value, expr));
- if (this.context.strict && expr.operator === 'delete' &&
expr.argument.type === syntax_1.Syntax.Identifier) {
- this.tolerateError(messages_1.Messages.StrictDelete);
- }
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- }
- else if (this.context.await &&
this.matchContextualKeyword('await')) {
- expr = this.parseAwaitExpression();
- }
- else {
- expr = this.parseUpdateExpression();
- }
- return expr;
- };
- Parser.prototype.parseExponentiationExpression = function () {
- var startToken = this.lookahead;
- var expr = this.inheritCoverGrammar(this.parseUnaryExpression);
- if (expr.type !== syntax_1.Syntax.UnaryExpression &&
this.match('**')) {
- this.nextToken();
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- var left = expr;
- var right =
this.isolateCoverGrammar(this.parseExponentiationExpression);
- expr = this.finalize(this.startNode(startToken), new
Node.BinaryExpression('**', left, right));
- }
- return expr;
- };
- // ECMA-262 12.6 Exponentiation Operators
- // ECMA-262 12.7 Multiplicative Operators
- // ECMA-262 12.8 Additive Operators
- // ECMA-262 12.9 Bitwise Shift Operators
- // ECMA-262 12.10 Relational Operators
- // ECMA-262 12.11 Equality Operators
- // ECMA-262 12.12 Binary Bitwise Operators
- // ECMA-262 12.13 Binary Logical Operators
- Parser.prototype.binaryPrecedence = function (token) {
- var op = token.value;
- var precedence;
- if (token.type === token_1.Token.Punctuator) {
- precedence = this.operatorPrecedence[op] || 0;
- }
- else if (token.type === token_1.Token.Keyword) {
- precedence = (op === 'instanceof' || (this.context.allowIn
&& op === 'in')) ? 7 : 0;
- }
- else {
- precedence = 0;
- }
- return precedence;
- };
- Parser.prototype.parseBinaryExpression = function () {
- var startToken = this.lookahead;
- var expr =
this.inheritCoverGrammar(this.parseExponentiationExpression);
- var token = this.lookahead;
- var prec = this.binaryPrecedence(token);
- if (prec > 0) {
- this.nextToken();
- token.prec = prec;
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- var markers = [startToken, this.lookahead];
- var left = expr;
- var right =
this.isolateCoverGrammar(this.parseExponentiationExpression);
- var stack = [left, token, right];
- while (true) {
- prec = this.binaryPrecedence(this.lookahead);
- if (prec <= 0) {
- break;
- }
- // Reduce: make a binary expression from the three
topmost entries.
- while ((stack.length > 2) && (prec <=
stack[stack.length - 2].prec)) {
- right = stack.pop();
- var operator = stack.pop().value;
- left = stack.pop();
- markers.pop();
- var node = this.startNode(markers[markers.length -
1]);
- stack.push(this.finalize(node, new
Node.BinaryExpression(operator, left, right)));
- }
- // Shift.
- token = this.nextToken();
- token.prec = prec;
- stack.push(token);
- markers.push(this.lookahead);
-
stack.push(this.isolateCoverGrammar(this.parseExponentiationExpression));
- }
- // Final reduce to clean-up the stack.
- var i = stack.length - 1;
- expr = stack[i];
- markers.pop();
- while (i > 1) {
- var node = this.startNode(markers.pop());
- expr = this.finalize(node, new
Node.BinaryExpression(stack[i - 1].value, stack[i - 2], expr));
- i -= 2;
- }
- }
- return expr;
- };
- // ECMA-262 12.14 Conditional Operator
- Parser.prototype.parseConditionalExpression = function () {
- var startToken = this.lookahead;
- var expr = this.inheritCoverGrammar(this.parseBinaryExpression);
- if (this.match('?')) {
- this.nextToken();
- var previousAllowIn = this.context.allowIn;
- this.context.allowIn = true;
- var consequent =
this.isolateCoverGrammar(this.parseAssignmentExpression);
- this.context.allowIn = previousAllowIn;
- this.expect(':');
- var alternate =
this.isolateCoverGrammar(this.parseAssignmentExpression);
- expr = this.finalize(this.startNode(startToken), new
Node.ConditionalExpression(expr, consequent, alternate));
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- }
- return expr;
- };
- // ECMA-262 12.15 Assignment Operators
- Parser.prototype.checkPatternParam = function (options, param) {
- switch (param.type) {
- case syntax_1.Syntax.Identifier:
- this.validateParam(options, param, param.name);
- break;
- case syntax_1.Syntax.RestElement:
- this.checkPatternParam(options, param.argument);
- break;
- case syntax_1.Syntax.AssignmentPattern:
- this.checkPatternParam(options, param.left);
- break;
- case syntax_1.Syntax.ArrayPattern:
- for (var i = 0; i < param.elements.length; i++) {
- if (param.elements[i] !== null) {
- this.checkPatternParam(options,
param.elements[i]);
- }
- }
- break;
- case syntax_1.Syntax.ObjectPattern:
- for (var i = 0; i < param.properties.length; i++) {
- this.checkPatternParam(options,
param.properties[i].value);
- }
- break;
- default:
- break;
- }
- };
- Parser.prototype.reinterpretAsCoverFormalsList = function (expr) {
- var params = [expr];
- var options;
- var asyncArrow = false;
- switch (expr.type) {
- case syntax_1.Syntax.Identifier:
- break;
- case ArrowParameterPlaceHolder:
- params = expr.params;
- asyncArrow = expr.async;
- break;
- default:
- return null;
- }
- options = {
- paramSet: {}
- };
- for (var i = 0; i < params.length; ++i) {
- var param = params[i];
- if (param.type === syntax_1.Syntax.AssignmentPattern) {
- if (param.right.type ===
syntax_1.Syntax.YieldExpression) {
- if (param.right.argument) {
- this.throwUnexpectedToken(this.lookahead);
- }
- param.right.type = syntax_1.Syntax.Identifier;
- param.right.name = 'yield';
- delete param.right.argument;
- delete param.right.delegate;
- }
- }
- else if (asyncArrow && param.type ===
syntax_1.Syntax.Identifier && param.name === 'await') {
- this.throwUnexpectedToken(this.lookahead);
- }
- this.checkPatternParam(options, param);
- params[i] = param;
- }
- if (this.context.strict || !this.context.allowYield) {
- for (var i = 0; i < params.length; ++i) {
- var param = params[i];
- if (param.type === syntax_1.Syntax.YieldExpression) {
- this.throwUnexpectedToken(this.lookahead);
- }
- }
- }
- if (options.message === messages_1.Messages.StrictParamDupe) {
- var token = this.context.strict ? options.stricted :
options.firstRestricted;
- this.throwUnexpectedToken(token, options.message);
- }
- return {
- params: params,
- stricted: options.stricted,
- firstRestricted: options.firstRestricted,
- message: options.message
- };
- };
- Parser.prototype.parseAssignmentExpression = function () {
- var expr;
- if (!this.context.allowYield && this.matchKeyword('yield')) {
- expr = this.parseYieldExpression();
- }
- else {
- var startToken = this.lookahead;
- var token = startToken;
- expr = this.parseConditionalExpression();
- if (token.type === token_1.Token.Identifier &&
(token.lineNumber === this.lookahead.lineNumber) && token.value === 'async' &&
(this.lookahead.type === token_1.Token.Identifier)) {
- var arg = this.parsePrimaryExpression();
- expr = {
- type: ArrowParameterPlaceHolder,
- params: [arg],
- async: true
- };
- }
- if (expr.type === ArrowParameterPlaceHolder ||
this.match('=>')) {
- // ECMA-262 14.2 Arrow Function Definitions
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- var isAsync = expr.async;
- var list = this.reinterpretAsCoverFormalsList(expr);
- if (list) {
- if (this.hasLineTerminator) {
- this.tolerateUnexpectedToken(this.lookahead);
- }
- this.context.firstCoverInitializedNameError = null;
- var previousStrict = this.context.strict;
- var previousAllowYield = this.context.allowYield;
- var previousAwait = this.context.await;
- this.context.allowYield = true;
- this.context.await = isAsync;
- var node = this.startNode(startToken);
- this.expect('=>');
- var body = this.match('{') ?
this.parseFunctionSourceElements() :
-
this.isolateCoverGrammar(this.parseAssignmentExpression);
- var expression = body.type !==
syntax_1.Syntax.BlockStatement;
- if (this.context.strict && list.firstRestricted) {
- this.throwUnexpectedToken(list.firstRestricted,
list.message);
- }
- if (this.context.strict && list.stricted) {
- this.tolerateUnexpectedToken(list.stricted,
list.message);
- }
- expr = isAsync ? this.finalize(node, new
Node.AsyncArrowFunctionExpression(list.params, body, expression)) :
- this.finalize(node, new
Node.ArrowFunctionExpression(list.params, body, expression));
- this.context.strict = previousStrict;
- this.context.allowYield = previousAllowYield;
- this.context.await = previousAwait;
- }
- }
- else {
- if (this.matchAssign()) {
- if (!this.context.isAssignmentTarget) {
-
this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
- }
- if (this.context.strict && expr.type ===
syntax_1.Syntax.Identifier) {
- var id = (expr);
- if (this.scanner.isRestrictedWord(id.name)) {
- this.tolerateUnexpectedToken(token,
messages_1.Messages.StrictLHSAssignment);
- }
- if
(this.scanner.isStrictModeReservedWord(id.name)) {
- this.tolerateUnexpectedToken(token,
messages_1.Messages.StrictReservedWord);
- }
- }
- if (!this.match('=')) {
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- }
- else {
- this.reinterpretExpressionAsPattern(expr);
- }
- token = this.nextToken();
- var right =
this.isolateCoverGrammar(this.parseAssignmentExpression);
- expr = this.finalize(this.startNode(startToken),
new Node.AssignmentExpression(token.value, expr, right));
- this.context.firstCoverInitializedNameError = null;
- }
- }
- }
- return expr;
- };
- // ECMA-262 12.16 Comma Operator
- Parser.prototype.parseExpression = function () {
- var startToken = this.lookahead;
- var expr =
this.isolateCoverGrammar(this.parseAssignmentExpression);
- if (this.match(',')) {
- var expressions = [];
- expressions.push(expr);
- while (this.startMarker.index < this.scanner.length) {
- if (!this.match(',')) {
- break;
- }
- this.nextToken();
-
expressions.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
- }
- expr = this.finalize(this.startNode(startToken), new
Node.SequenceExpression(expressions));
- }
- return expr;
- };
- // ECMA-262 13.2 Block
- Parser.prototype.parseStatementListItem = function () {
- var statement;
- this.context.isAssignmentTarget = true;
- this.context.isBindingElement = true;
- if (this.lookahead.type === token_1.Token.Keyword) {
- switch (this.lookahead.value) {
- case 'export':
- if (!this.context.isModule) {
- this.tolerateUnexpectedToken(this.lookahead,
messages_1.Messages.IllegalExportDeclaration);
- }
- statement = this.parseExportDeclaration();
- break;
- case 'import':
- if (!this.context.isModule) {
- this.tolerateUnexpectedToken(this.lookahead,
messages_1.Messages.IllegalImportDeclaration);
- }
- statement = this.parseImportDeclaration();
- break;
- case 'const':
- statement = this.parseLexicalDeclaration({ inFor:
false });
- break;
- case 'function':
- statement = this.parseFunctionDeclaration();
- break;
- case 'class':
- statement = this.parseClassDeclaration();
- break;
- case 'let':
- statement = this.isLexicalDeclaration() ?
this.parseLexicalDeclaration({ inFor: false }) : this.parseStatement();
- break;
- default:
- statement = this.parseStatement();
- break;
- }
- }
- else {
- statement = this.parseStatement();
- }
- return statement;
- };
- Parser.prototype.parseBlock = function () {
- var node = this.createNode();
- this.expect('{');
- var block = [];
- while (true) {
- if (this.match('}')) {
- break;
- }
- block.push(this.parseStatementListItem());
- }
- this.expect('}');
- return this.finalize(node, new Node.BlockStatement(block));
- };
- // ECMA-262 13.3.1 Let and Const Declarations
- Parser.prototype.parseLexicalBinding = function (kind, options) {
- var node = this.createNode();
- var params = [];
- var id = this.parsePattern(params, kind);
- // ECMA-262 12.2.1
- if (this.context.strict && id.type ===
syntax_1.Syntax.Identifier) {
- if (this.scanner.isRestrictedWord((id).name)) {
- this.tolerateError(messages_1.Messages.StrictVarName);
- }
- }
- var init = null;
- if (kind === 'const') {
- if (!this.matchKeyword('in') &&
!this.matchContextualKeyword('of')) {
- if (this.match('=')) {
- this.nextToken();
- init =
this.isolateCoverGrammar(this.parseAssignmentExpression);
- }
- else {
-
this.throwError(messages_1.Messages.DeclarationMissingInitializer, 'const');
- }
- }
- }
- else if ((!options.inFor && id.type !==
syntax_1.Syntax.Identifier) || this.match('=')) {
- this.expect('=');
- init =
this.isolateCoverGrammar(this.parseAssignmentExpression);
- }
- return this.finalize(node, new Node.VariableDeclarator(id,
init));
- };
- Parser.prototype.parseBindingList = function (kind, options) {
- var list = [this.parseLexicalBinding(kind, options)];
- while (this.match(',')) {
- this.nextToken();
- list.push(this.parseLexicalBinding(kind, options));
- }
- return list;
- };
- Parser.prototype.isLexicalDeclaration = function () {
- var previousIndex = this.scanner.index;
- var previousLineNumber = this.scanner.lineNumber;
- var previousLineStart = this.scanner.lineStart;
- this.collectComments();
- var next = this.scanner.lex();
- this.scanner.index = previousIndex;
- this.scanner.lineNumber = previousLineNumber;
- this.scanner.lineStart = previousLineStart;
- return (next.type === token_1.Token.Identifier) ||
- (next.type === token_1.Token.Punctuator && next.value ===
'[') ||
- (next.type === token_1.Token.Punctuator && next.value ===
'{') ||
- (next.type === token_1.Token.Keyword && next.value ===
'let') ||
- (next.type === token_1.Token.Keyword && next.value ===
'yield');
- };
- Parser.prototype.parseLexicalDeclaration = function (options) {
- var node = this.createNode();
- var kind = this.nextToken().value;
- assert_1.assert(kind === 'let' || kind === 'const', 'Lexical
declaration must be either let or const');
- var declarations = this.parseBindingList(kind, options);
- this.consumeSemicolon();
- return this.finalize(node, new
Node.VariableDeclaration(declarations, kind));
- };
- // ECMA-262 13.3.3 Destructuring Binding Patterns
- Parser.prototype.parseBindingRestElement = function (params, kind) {
- var node = this.createNode();
- this.expect('...');
- params.push(this.lookahead);
- var arg = this.parseVariableIdentifier(kind);
- return this.finalize(node, new Node.RestElement(arg));
- };
- Parser.prototype.parseArrayPattern = function (params, kind) {
- var node = this.createNode();
- this.expect('[');
- var elements = [];
- while (!this.match(']')) {
- if (this.match(',')) {
- this.nextToken();
- elements.push(null);
- }
- else {
- if (this.match('...')) {
- elements.push(this.parseBindingRestElement(params,
kind));
- break;
- }
- else {
- elements.push(this.parsePatternWithDefault(params,
kind));
- }
- if (!this.match(']')) {
- this.expect(',');
- }
- }
- }
- this.expect(']');
- return this.finalize(node, new Node.ArrayPattern(elements));
- };
- Parser.prototype.parsePropertyPattern = function (params, kind) {
- var node = this.createNode();
- var computed = false;
- var shorthand = false;
- var method = false;
- var key;
- var value;
- if (this.lookahead.type === token_1.Token.Identifier) {
- var keyToken = this.lookahead;
- key = this.parseVariableIdentifier();
- var init = this.finalize(node, new
Node.Identifier(keyToken.value));
- if (this.match('=')) {
- params.push(keyToken);
- shorthand = true;
- this.nextToken();
- var expr = this.parseAssignmentExpression();
- value = this.finalize(this.startNode(keyToken), new
Node.AssignmentPattern(init, expr));
- }
- else if (!this.match(':')) {
- params.push(keyToken);
- shorthand = true;
- value = init;
- }
- else {
- this.expect(':');
- value = this.parsePatternWithDefault(params, kind);
- }
- }
- else {
- computed = this.match('[');
- key = this.parseObjectPropertyKey();
- this.expect(':');
- value = this.parsePatternWithDefault(params, kind);
- }
- return this.finalize(node, new Node.Property('init', key,
computed, value, method, shorthand));
- };
- Parser.prototype.parseObjectPattern = function (params, kind) {
- var node = this.createNode();
- var properties = [];
- this.expect('{');
- while (!this.match('}')) {
- properties.push(this.parsePropertyPattern(params, kind));
- if (!this.match('}')) {
- this.expect(',');
- }
- }
- this.expect('}');
- return this.finalize(node, new Node.ObjectPattern(properties));
- };
- Parser.prototype.parsePattern = function (params, kind) {
- var pattern;
- if (this.match('[')) {
- pattern = this.parseArrayPattern(params, kind);
- }
- else if (this.match('{')) {
- pattern = this.parseObjectPattern(params, kind);
- }
- else {
- if (this.matchKeyword('let') && (kind === 'const' || kind
=== 'let')) {
- this.tolerateUnexpectedToken(this.lookahead,
messages_1.Messages.LetInLexicalBinding);
- }
- params.push(this.lookahead);
- pattern = this.parseVariableIdentifier(kind);
- }
- return pattern;
- };
- Parser.prototype.parsePatternWithDefault = function (params, kind) {
- var startToken = this.lookahead;
- var pattern = this.parsePattern(params, kind);
- if (this.match('=')) {
- this.nextToken();
- var previousAllowYield = this.context.allowYield;
- this.context.allowYield = true;
- var right =
this.isolateCoverGrammar(this.parseAssignmentExpression);
- this.context.allowYield = previousAllowYield;
- pattern = this.finalize(this.startNode(startToken), new
Node.AssignmentPattern(pattern, right));
- }
- return pattern;
- };
- // ECMA-262 13.3.2 Variable Statement
- Parser.prototype.parseVariableIdentifier = function (kind) {
- var node = this.createNode();
- var token = this.nextToken();
- if (token.type === token_1.Token.Keyword && token.value ===
'yield') {
- if (this.context.strict) {
- this.tolerateUnexpectedToken(token,
messages_1.Messages.StrictReservedWord);
- }
- if (!this.context.allowYield) {
- this.throwUnexpectedToken(token);
- }
- }
- else if (token.type !== token_1.Token.Identifier) {
- if (this.context.strict && token.type ===
token_1.Token.Keyword && this.scanner.isStrictModeReservedWord(token.value)) {
- this.tolerateUnexpectedToken(token,
messages_1.Messages.StrictReservedWord);
- }
- else {
- if (this.context.strict || token.value !== 'let' ||
kind !== 'var') {
- this.throwUnexpectedToken(token);
- }
- }
- }
- else if ((this.context.isModule || this.context.await) &&
token.type === token_1.Token.Identifier && token.value === 'await') {
- this.tolerateUnexpectedToken(token);
- }
- return this.finalize(node, new Node.Identifier(token.value));
- };
- Parser.prototype.parseVariableDeclaration = function (options) {
- var node = this.createNode();
- var params = [];
- var id = this.parsePattern(params, 'var');
- // ECMA-262 12.2.1
- if (this.context.strict && id.type ===
syntax_1.Syntax.Identifier) {
- if (this.scanner.isRestrictedWord((id).name)) {
- this.tolerateError(messages_1.Messages.StrictVarName);
- }
- }
- var init = null;
- if (this.match('=')) {
- this.nextToken();
- init =
this.isolateCoverGrammar(this.parseAssignmentExpression);
- }
- else if (id.type !== syntax_1.Syntax.Identifier &&
!options.inFor) {
- this.expect('=');
- }
- return this.finalize(node, new Node.VariableDeclarator(id,
init));
- };
- Parser.prototype.parseVariableDeclarationList = function (options) {
- var opt = { inFor: options.inFor };
- var list = [];
- list.push(this.parseVariableDeclaration(opt));
- while (this.match(',')) {
- this.nextToken();
- list.push(this.parseVariableDeclaration(opt));
- }
- return list;
- };
- Parser.prototype.parseVariableStatement = function () {
- var node = this.createNode();
- this.expectKeyword('var');
- var declarations = this.parseVariableDeclarationList({ inFor:
false });
- this.consumeSemicolon();
- return this.finalize(node, new
Node.VariableDeclaration(declarations, 'var'));
- };
- // ECMA-262 13.4 Empty Statement
- Parser.prototype.parseEmptyStatement = function () {
- var node = this.createNode();
- this.expect(';');
- return this.finalize(node, new Node.EmptyStatement());
- };
- // ECMA-262 13.5 Expression Statement
- Parser.prototype.parseExpressionStatement = function () {
- var node = this.createNode();
- var expr = this.parseExpression();
- this.consumeSemicolon();
- return this.finalize(node, new Node.ExpressionStatement(expr));
- };
- // ECMA-262 13.6 If statement
- Parser.prototype.parseIfStatement = function () {
- var node = this.createNode();
- var consequent;
- var alternate = null;
- this.expectKeyword('if');
- this.expect('(');
- var test = this.parseExpression();
- if (!this.match(')') && this.config.tolerant) {
- this.tolerateUnexpectedToken(this.nextToken());
- consequent = this.finalize(this.createNode(), new
Node.EmptyStatement());
- }
- else {
- this.expect(')');
- consequent = this.parseStatement();
- if (this.matchKeyword('else')) {
- this.nextToken();
- alternate = this.parseStatement();
- }
- }
- return this.finalize(node, new Node.IfStatement(test,
consequent, alternate));
- };
- // ECMA-262 13.7.2 The do-while Statement
- Parser.prototype.parseDoWhileStatement = function () {
- var node = this.createNode();
- this.expectKeyword('do');
- var previousInIteration = this.context.inIteration;
- this.context.inIteration = true;
- var body = this.parseStatement();
- this.context.inIteration = previousInIteration;
- this.expectKeyword('while');
- this.expect('(');
- var test = this.parseExpression();
- this.expect(')');
- if (this.match(';')) {
- this.nextToken();
- }
- return this.finalize(node, new Node.DoWhileStatement(body,
test));
- };
- // ECMA-262 13.7.3 The while Statement
- Parser.prototype.parseWhileStatement = function () {
- var node = this.createNode();
- var body;
- this.expectKeyword('while');
- this.expect('(');
- var test = this.parseExpression();
- if (!this.match(')') && this.config.tolerant) {
- this.tolerateUnexpectedToken(this.nextToken());
- body = this.finalize(this.createNode(), new
Node.EmptyStatement());
- }
- else {
- this.expect(')');
- var previousInIteration = this.context.inIteration;
- this.context.inIteration = true;
- body = this.parseStatement();
- this.context.inIteration = previousInIteration;
- }
- return this.finalize(node, new Node.WhileStatement(test, body));
- };
- // ECMA-262 13.7.4 The for Statement
- // ECMA-262 13.7.5 The for-in and for-of Statements
- Parser.prototype.parseForStatement = function () {
- var init = null;
- var test = null;
- var update = null;
- var forIn = true;
- var left, right;
- var node = this.createNode();
- this.expectKeyword('for');
- this.expect('(');
- if (this.match(';')) {
- this.nextToken();
- }
- else {
- if (this.matchKeyword('var')) {
- init = this.createNode();
- this.nextToken();
- var previousAllowIn = this.context.allowIn;
- this.context.allowIn = false;
- var declarations = this.parseVariableDeclarationList({
inFor: true });
- this.context.allowIn = previousAllowIn;
- if (declarations.length === 1 &&
this.matchKeyword('in')) {
- var decl = declarations[0];
- if (decl.init && (decl.id.type ===
syntax_1.Syntax.ArrayPattern || decl.id.type === syntax_1.Syntax.ObjectPattern
|| this.context.strict)) {
-
this.tolerateError(messages_1.Messages.ForInOfLoopInitializer, 'for-in');
- }
- init = this.finalize(init, new
Node.VariableDeclaration(declarations, 'var'));
- this.nextToken();
- left = init;
- right = this.parseExpression();
- init = null;
- }
- else if (declarations.length === 1 &&
declarations[0].init === null && this.matchContextualKeyword('of')) {
- init = this.finalize(init, new
Node.VariableDeclaration(declarations, 'var'));
- this.nextToken();
- left = init;
- right = this.parseAssignmentExpression();
- init = null;
- forIn = false;
- }
- else {
- init = this.finalize(init, new
Node.VariableDeclaration(declarations, 'var'));
- this.expect(';');
- }
- }
- else if (this.matchKeyword('const') ||
this.matchKeyword('let')) {
- init = this.createNode();
- var kind = this.nextToken().value;
- if (!this.context.strict && this.lookahead.value ===
'in') {
- init = this.finalize(init, new
Node.Identifier(kind));
- this.nextToken();
- left = init;
- right = this.parseExpression();
- init = null;
- }
- else {
- var previousAllowIn = this.context.allowIn;
- this.context.allowIn = false;
- var declarations = this.parseBindingList(kind, {
inFor: true });
- this.context.allowIn = previousAllowIn;
- if (declarations.length === 1 &&
declarations[0].init === null && this.matchKeyword('in')) {
- init = this.finalize(init, new
Node.VariableDeclaration(declarations, kind));
- this.nextToken();
- left = init;
- right = this.parseExpression();
- init = null;
- }
- else if (declarations.length === 1 &&
declarations[0].init === null && this.matchContextualKeyword('of')) {
- init = this.finalize(init, new
Node.VariableDeclaration(declarations, kind));
- this.nextToken();
- left = init;
- right = this.parseAssignmentExpression();
- init = null;
- forIn = false;
- }
- else {
- this.consumeSemicolon();
- init = this.finalize(init, new
Node.VariableDeclaration(declarations, kind));
- }
- }
- }
- else {
- var initStartToken = this.lookahead;
- var previousAllowIn = this.context.allowIn;
- this.context.allowIn = false;
- init =
this.inheritCoverGrammar(this.parseAssignmentExpression);
- this.context.allowIn = previousAllowIn;
- if (this.matchKeyword('in')) {
- if (!this.context.isAssignmentTarget || init.type
=== syntax_1.Syntax.AssignmentExpression) {
-
this.tolerateError(messages_1.Messages.InvalidLHSInForIn);
- }
- this.nextToken();
- this.reinterpretExpressionAsPattern(init);
- left = init;
- right = this.parseExpression();
- init = null;
- }
- else if (this.matchContextualKeyword('of')) {
- if (!this.context.isAssignmentTarget || init.type
=== syntax_1.Syntax.AssignmentExpression) {
-
this.tolerateError(messages_1.Messages.InvalidLHSInForLoop);
- }
- this.nextToken();
- this.reinterpretExpressionAsPattern(init);
- left = init;
- right = this.parseAssignmentExpression();
- init = null;
- forIn = false;
- }
- else {
- if (this.match(',')) {
- var initSeq = [init];
- while (this.match(',')) {
- this.nextToken();
-
initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
- }
- init =
this.finalize(this.startNode(initStartToken), new
Node.SequenceExpression(initSeq));
- }
- this.expect(';');
- }
- }
- }
- if (typeof left === 'undefined') {
- if (!this.match(';')) {
- test = this.parseExpression();
- }
- this.expect(';');
- if (!this.match(')')) {
- update = this.parseExpression();
- }
- }
- var body;
- if (!this.match(')') && this.config.tolerant) {
- this.tolerateUnexpectedToken(this.nextToken());
- body = this.finalize(this.createNode(), new
Node.EmptyStatement());
- }
- else {
- this.expect(')');
- var previousInIteration = this.context.inIteration;
- this.context.inIteration = true;
- body = this.isolateCoverGrammar(this.parseStatement);
- this.context.inIteration = previousInIteration;
- }
- return (typeof left === 'undefined') ?
- this.finalize(node, new Node.ForStatement(init, test,
update, body)) :
- forIn ? this.finalize(node, new Node.ForInStatement(left,
right, body)) :
- this.finalize(node, new Node.ForOfStatement(left,
right, body));
- };
- // ECMA-262 13.8 The continue statement
- Parser.prototype.parseContinueStatement = function () {
- var node = this.createNode();
- this.expectKeyword('continue');
- var label = null;
- if (this.lookahead.type === token_1.Token.Identifier &&
!this.hasLineTerminator) {
- var id = this.parseVariableIdentifier();
- label = id;
- var key = '$' + id.name;
- if
(!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
- this.throwError(messages_1.Messages.UnknownLabel,
id.name);
- }
- }
- this.consumeSemicolon();
- if (label === null && !this.context.inIteration) {
- this.throwError(messages_1.Messages.IllegalContinue);
- }
- return this.finalize(node, new Node.ContinueStatement(label));
- };
- // ECMA-262 13.9 The break statement
- Parser.prototype.parseBreakStatement = function () {
- var node = this.createNode();
- this.expectKeyword('break');
- var label = null;
- if (this.lookahead.type === token_1.Token.Identifier &&
!this.hasLineTerminator) {
- var id = this.parseVariableIdentifier();
- var key = '$' + id.name;
- if
(!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
- this.throwError(messages_1.Messages.UnknownLabel,
id.name);
- }
- label = id;
- }
- this.consumeSemicolon();
- if (label === null && !this.context.inIteration &&
!this.context.inSwitch) {
- this.throwError(messages_1.Messages.IllegalBreak);
- }
- return this.finalize(node, new Node.BreakStatement(label));
- };
- // ECMA-262 13.10 The return statement
- Parser.prototype.parseReturnStatement = function () {
- if (!this.context.inFunctionBody) {
- this.tolerateError(messages_1.Messages.IllegalReturn);
- }
- var node = this.createNode();
- this.expectKeyword('return');
- var hasArgument = !this.match(';') && !this.match('}') &&
- !this.hasLineTerminator && this.lookahead.type !==
token_1.Token.EOF;
- var argument = hasArgument ? this.parseExpression() : null;
- this.consumeSemicolon();
- return this.finalize(node, new Node.ReturnStatement(argument));
- };
- // ECMA-262 13.11 The with statement
- Parser.prototype.parseWithStatement = function () {
- if (this.context.strict) {
- this.tolerateError(messages_1.Messages.StrictModeWith);
- }
- var node = this.createNode();
- this.expectKeyword('with');
- this.expect('(');
- var object = this.parseExpression();
- this.expect(')');
- var body = this.parseStatement();
- return this.finalize(node, new Node.WithStatement(object,
body));
- };
- // ECMA-262 13.12 The switch statement
- Parser.prototype.parseSwitchCase = function () {
- var node = this.createNode();
- var test;
- if (this.matchKeyword('default')) {
- this.nextToken();
- test = null;
- }
- else {
- this.expectKeyword('case');
- test = this.parseExpression();
- }
- this.expect(':');
- var consequent = [];
- while (true) {
- if (this.match('}') || this.matchKeyword('default') ||
this.matchKeyword('case')) {
- break;
- }
- consequent.push(this.parseStatementListItem());
- }
- return this.finalize(node, new Node.SwitchCase(test,
consequent));
- };
- Parser.prototype.parseSwitchStatement = function () {
- var node = this.createNode();
- this.expectKeyword('switch');
- this.expect('(');
- var discriminant = this.parseExpression();
- this.expect(')');
- var previousInSwitch = this.context.inSwitch;
- this.context.inSwitch = true;
- var cases = [];
- var defaultFound = false;
- this.expect('{');
- while (true) {
- if (this.match('}')) {
- break;
- }
- var clause = this.parseSwitchCase();
- if (clause.test === null) {
- if (defaultFound) {
-
this.throwError(messages_1.Messages.MultipleDefaultsInSwitch);
- }
- defaultFound = true;
- }
- cases.push(clause);
- }
- this.expect('}');
- this.context.inSwitch = previousInSwitch;
- return this.finalize(node, new
Node.SwitchStatement(discriminant, cases));
- };
- // ECMA-262 13.13 Labelled Statements
- Parser.prototype.parseLabelledStatement = function () {
- var node = this.createNode();
- var expr = this.parseExpression();
- var statement;
- if ((expr.type === syntax_1.Syntax.Identifier) &&
this.match(':')) {
- this.nextToken();
- var id = (expr);
- var key = '$' + id.name;
- if
(Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
- this.throwError(messages_1.Messages.Redeclaration,
'Label', id.name);
- }
- this.context.labelSet[key] = true;
- var labeledBody = this.parseStatement();
- delete this.context.labelSet[key];
- statement = new Node.LabeledStatement(id, labeledBody);
- }
- else {
- this.consumeSemicolon();
- statement = new Node.ExpressionStatement(expr);
- }
- return this.finalize(node, statement);
- };
- // ECMA-262 13.14 The throw statement
- Parser.prototype.parseThrowStatement = function () {
- var node = this.createNode();
- this.expectKeyword('throw');
- if (this.hasLineTerminator) {
- this.throwError(messages_1.Messages.NewlineAfterThrow);
- }
- var argument = this.parseExpression();
- this.consumeSemicolon();
- return this.finalize(node, new Node.ThrowStatement(argument));
- };
- // ECMA-262 13.15 The try statement
- Parser.prototype.parseCatchClause = function () {
- var node = this.createNode();
- this.expectKeyword('catch');
- this.expect('(');
- if (this.match(')')) {
- this.throwUnexpectedToken(this.lookahead);
- }
- var params = [];
- var param = this.parsePattern(params);
- var paramMap = {};
- for (var i = 0; i < params.length; i++) {
- var key = '$' + params[i].value;
- if (Object.prototype.hasOwnProperty.call(paramMap, key)) {
-
this.tolerateError(messages_1.Messages.DuplicateBinding, params[i].value);
- }
- paramMap[key] = true;
- }
- if (this.context.strict && param.type ===
syntax_1.Syntax.Identifier) {
- if (this.scanner.isRestrictedWord((param).name)) {
-
this.tolerateError(messages_1.Messages.StrictCatchVariable);
- }
- }
- this.expect(')');
- var body = this.parseBlock();
- return this.finalize(node, new Node.CatchClause(param, body));
- };
- Parser.prototype.parseFinallyClause = function () {
- this.expectKeyword('finally');
- return this.parseBlock();
- };
- Parser.prototype.parseTryStatement = function () {
- var node = this.createNode();
- this.expectKeyword('try');
- var block = this.parseBlock();
- var handler = this.matchKeyword('catch') ?
this.parseCatchClause() : null;
- var finalizer = this.matchKeyword('finally') ?
this.parseFinallyClause() : null;
- if (!handler && !finalizer) {
- this.throwError(messages_1.Messages.NoCatchOrFinally);
- }
- return this.finalize(node, new Node.TryStatement(block,
handler, finalizer));
- };
- // ECMA-262 13.16 The debugger statement
- Parser.prototype.parseDebuggerStatement = function () {
- var node = this.createNode();
- this.expectKeyword('debugger');
- this.consumeSemicolon();
- return this.finalize(node, new Node.DebuggerStatement());
- };
- // ECMA-262 13 Statements
- Parser.prototype.parseStatement = function () {
- var statement;
- switch (this.lookahead.type) {
- case token_1.Token.BooleanLiteral:
- case token_1.Token.NullLiteral:
- case token_1.Token.NumericLiteral:
- case token_1.Token.StringLiteral:
- case token_1.Token.Template:
- case token_1.Token.RegularExpression:
- statement = this.parseExpressionStatement();
- break;
- case token_1.Token.Punctuator:
- var value = this.lookahead.value;
- if (value === '{') {
- statement = this.parseBlock();
- }
- else if (value === '(') {
- statement = this.parseExpressionStatement();
- }
- else if (value === ';') {
- statement = this.parseEmptyStatement();
- }
- else {
- statement = this.parseExpressionStatement();
- }
- break;
- case token_1.Token.Identifier:
- statement = this.matchAsyncFunction() ?
this.parseFunctionDeclaration() : this.parseLabelledStatement();
- break;
- case token_1.Token.Keyword:
- switch (this.lookahead.value) {
- case 'break':
- statement = this.parseBreakStatement();
- break;
- case 'continue':
- statement = this.parseContinueStatement();
- break;
- case 'debugger':
- statement = this.parseDebuggerStatement();
- break;
- case 'do':
- statement = this.parseDoWhileStatement();
- break;
- case 'for':
- statement = this.parseForStatement();
- break;
- case 'function':
- statement = this.parseFunctionDeclaration();
- break;
- case 'if':
- statement = this.parseIfStatement();
- break;
- case 'return':
- statement = this.parseReturnStatement();
- break;
- case 'switch':
- statement = this.parseSwitchStatement();
- break;
- case 'throw':
- statement = this.parseThrowStatement();
- break;
- case 'try':
- statement = this.parseTryStatement();
- break;
- case 'var':
- statement = this.parseVariableStatement();
- break;
- case 'while':
- statement = this.parseWhileStatement();
- break;
- case 'with':
- statement = this.parseWithStatement();
- break;
- default:
- statement = this.parseExpressionStatement();
- break;
- }
- break;
- default:
- statement = this.throwUnexpectedToken(this.lookahead);
- }
- return statement;
- };
- // ECMA-262 14.1 Function Definition
- Parser.prototype.parseFunctionSourceElements = function () {
- var node = this.createNode();
- this.expect('{');
- var body = this.parseDirectivePrologues();
- var previousLabelSet = this.context.labelSet;
- var previousInIteration = this.context.inIteration;
- var previousInSwitch = this.context.inSwitch;
- var previousInFunctionBody = this.context.inFunctionBody;
- this.context.labelSet = {};
- this.context.inIteration = false;
- this.context.inSwitch = false;
- this.context.inFunctionBody = true;
- while (this.startMarker.index < this.scanner.length) {
- if (this.match('}')) {
- break;
- }
- body.push(this.parseStatementListItem());
- }
- this.expect('}');
- this.context.labelSet = previousLabelSet;
- this.context.inIteration = previousInIteration;
- this.context.inSwitch = previousInSwitch;
- this.context.inFunctionBody = previousInFunctionBody;
- return this.finalize(node, new Node.BlockStatement(body));
- };
- Parser.prototype.validateParam = function (options, param, name) {
- var key = '$' + name;
- if (this.context.strict) {
- if (this.scanner.isRestrictedWord(name)) {
- options.stricted = param;
- options.message = messages_1.Messages.StrictParamName;
- }
- if (Object.prototype.hasOwnProperty.call(options.paramSet,
key)) {
- options.stricted = param;
- options.message = messages_1.Messages.StrictParamDupe;
- }
- }
- else if (!options.firstRestricted) {
- if (this.scanner.isRestrictedWord(name)) {
- options.firstRestricted = param;
- options.message = messages_1.Messages.StrictParamName;
- }
- else if (this.scanner.isStrictModeReservedWord(name)) {
- options.firstRestricted = param;
- options.message =
messages_1.Messages.StrictReservedWord;
- }
- else if
(Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
- options.stricted = param;
- options.message = messages_1.Messages.StrictParamDupe;
- }
- }
- /* istanbul ignore next */
- if (typeof Object.defineProperty === 'function') {
- Object.defineProperty(options.paramSet, key, { value: true,
enumerable: true, writable: true, configurable: true });
- }
- else {
- options.paramSet[key] = true;
- }
- };
- Parser.prototype.parseRestElement = function (params) {
- var node = this.createNode();
- this.nextToken();
- if (this.match('{')) {
-
this.throwError(messages_1.Messages.ObjectPatternAsRestParameter);
- }
- params.push(this.lookahead);
- var param = this.parseVariableIdentifier();
- if (this.match('=')) {
- this.throwError(messages_1.Messages.DefaultRestParameter);
- }
- if (!this.match(')')) {
-
this.throwError(messages_1.Messages.ParameterAfterRestParameter);
- }
- return this.finalize(node, new Node.RestElement(param));
- };
- Parser.prototype.parseFormalParameter = function (options) {
- var param;
- var params = [];
- var token = this.lookahead;
- if (token.value === '...') {
- param = this.parseRestElement(params);
- this.validateParam(options, param.argument,
param.argument.name);
- options.params.push(param);
- return;
- }
- param = this.parsePatternWithDefault(params);
- for (var i = 0; i < params.length; i++) {
- this.validateParam(options, params[i], params[i].value);
- }
- options.params.push(param);
- };
- Parser.prototype.parseFormalParameters = function (firstRestricted)
{
- var options;
- options = {
- params: [],
- firstRestricted: firstRestricted
- };
- this.expect('(');
- if (!this.match(')')) {
- options.paramSet = {};
- while (this.startMarker.index < this.scanner.length) {
- this.parseFormalParameter(options);
- if (this.match(')')) {
- break;
- }
- this.expect(',');
- if (this.match(')')) {
- break;
- }
- }
- }
- this.expect(')');
- return {
- params: options.params,
- stricted: options.stricted,
- firstRestricted: options.firstRestricted,
- message: options.message
- };
- };
- Parser.prototype.matchAsyncFunction = function () {
- var match = this.matchContextualKeyword('async');
- if (match) {
- var previousIndex = this.scanner.index;
- var previousLineNumber = this.scanner.lineNumber;
- var previousLineStart = this.scanner.lineStart;
- this.collectComments();
- var next = this.scanner.lex();
- this.scanner.index = previousIndex;
- this.scanner.lineNumber = previousLineNumber;
- this.scanner.lineStart = previousLineStart;
- match = (previousLineNumber === next.lineNumber) &&
((next.type === token_1.Token.Keyword) || (next.value === 'function'));
- }
- return match;
- };
- Parser.prototype.parseFunctionDeclaration = function
(identifierIsOptional) {
- var node = this.createNode();
- var isAsync = this.matchContextualKeyword('async');
- if (isAsync) {
- this.nextToken();
- }
- this.expectKeyword('function');
- var isGenerator = isAsync ? false : this.match('*');
- if (isGenerator) {
- this.nextToken();
- }
- var message;
- var id = null;
- var firstRestricted = null;
- if (!identifierIsOptional || !this.match('(')) {
- var token = this.lookahead;
- id = this.parseVariableIdentifier();
- if (this.context.strict) {
- if (this.scanner.isRestrictedWord(token.value)) {
- this.tolerateUnexpectedToken(token,
messages_1.Messages.StrictFunctionName);
- }
- }
- else {
- if (this.scanner.isRestrictedWord(token.value)) {
- firstRestricted = token;
- message = messages_1.Messages.StrictFunctionName;
- }
- else if
(this.scanner.isStrictModeReservedWord(token.value)) {
- firstRestricted = token;
- message = messages_1.Messages.StrictReservedWord;
- }
- }
- }
- var previousAllowAwait = this.context.await;
- var previousAllowYield = this.context.allowYield;
- this.context.await = isAsync;
- this.context.allowYield = !isGenerator;
- var formalParameters =
this.parseFormalParameters(firstRestricted);
- var params = formalParameters.params;
- var stricted = formalParameters.stricted;
- firstRestricted = formalParameters.firstRestricted;
- if (formalParameters.message) {
- message = formalParameters.message;
- }
- var previousStrict = this.context.strict;
- var body = this.parseFunctionSourceElements();
- if (this.context.strict && firstRestricted) {
- this.throwUnexpectedToken(firstRestricted, message);
- }
- if (this.context.strict && stricted) {
- this.tolerateUnexpectedToken(stricted, message);
- }
- this.context.strict = previousStrict;
- this.context.await = previousAllowAwait;
- this.context.allowYield = previousAllowYield;
- return isAsync ? this.finalize(node, new
Node.AsyncFunctionDeclaration(id, params, body)) :
- this.finalize(node, new Node.FunctionDeclaration(id,
params, body, isGenerator));
- };
- Parser.prototype.parseFunctionExpression = function () {
- var node = this.createNode();
- var isAsync = this.matchContextualKeyword('async');
- if (isAsync) {
- this.nextToken();
- }
- this.expectKeyword('function');
- var isGenerator = isAsync ? false : this.match('*');
- if (isGenerator) {
- this.nextToken();
- }
- var message;
- var id = null;
- var firstRestricted;
- var previousAllowAwait = this.context.await;
- var previousAllowYield = this.context.allowYield;
- this.context.await = isAsync;
- this.context.allowYield = !isGenerator;
- if (!this.match('(')) {
- var token = this.lookahead;
- id = (!this.context.strict && !isGenerator &&
this.matchKeyword('yield')) ? this.parseIdentifierName() :
this.parseVariableIdentifier();
- if (this.context.strict) {
- if (this.scanner.isRestrictedWord(token.value)) {
- this.tolerateUnexpectedToken(token,
messages_1.Messages.StrictFunctionName);
- }
- }
- else {
- if (this.scanner.isRestrictedWord(token.value)) {
- firstRestricted = token;
- message = messages_1.Messages.StrictFunctionName;
- }
- else if
(this.scanner.isStrictModeReservedWord(token.value)) {
- firstRestricted = token;
- message = messages_1.Messages.StrictReservedWord;
- }
- }
- }
- var formalParameters =
this.parseFormalParameters(firstRestricted);
- var params = formalParameters.params;
- var stricted = formalParameters.stricted;
- firstRestricted = formalParameters.firstRestricted;
- if (formalParameters.message) {
- message = formalParameters.message;
- }
- var previousStrict = this.context.strict;
- var body = this.parseFunctionSourceElements();
- if (this.context.strict && firstRestricted) {
- this.throwUnexpectedToken(firstRestricted, message);
- }
- if (this.context.strict && stricted) {
- this.tolerateUnexpectedToken(stricted, message);
- }
- this.context.strict = previousStrict;
- this.context.await = previousAllowAwait;
- this.context.allowYield = previousAllowYield;
- return isAsync ? this.finalize(node, new
Node.AsyncFunctionExpression(id, params, body)) :
- this.finalize(node, new Node.FunctionExpression(id, params,
body, isGenerator));
- };
- // ECMA-262 14.1.1 Directive Prologues
- Parser.prototype.parseDirective = function () {
- var token = this.lookahead;
- var node = this.createNode();
- var expr = this.parseExpression();
- var directive = (expr.type === syntax_1.Syntax.Literal) ?
this.getTokenRaw(token).slice(1, -1) : null;
- this.consumeSemicolon();
- return this.finalize(node, directive ? new Node.Directive(expr,
directive) : new Node.ExpressionStatement(expr));
- };
- Parser.prototype.parseDirectivePrologues = function () {
- var firstRestricted = null;
- var body = [];
- while (true) {
- var token = this.lookahead;
- if (token.type !== token_1.Token.StringLiteral) {
- break;
- }
- var statement = this.parseDirective();
- body.push(statement);
- var directive = statement.directive;
- if (typeof directive !== 'string') {
- break;
- }
- if (directive === 'use strict') {
- this.context.strict = true;
- if (firstRestricted) {
- this.tolerateUnexpectedToken(firstRestricted,
messages_1.Messages.StrictOctalLiteral);
- }
- }
- else {
- if (!firstRestricted && token.octal) {
- firstRestricted = token;
- }
- }
- }
- return body;
- };
- // ECMA-262 14.3 Method Definitions
- Parser.prototype.qualifiedPropertyName = function (token) {
- switch (token.type) {
- case token_1.Token.Identifier:
- case token_1.Token.StringLiteral:
- case token_1.Token.BooleanLiteral:
- case token_1.Token.NullLiteral:
- case token_1.Token.NumericLiteral:
- case token_1.Token.Keyword:
- return true;
- case token_1.Token.Punctuator:
- return token.value === '[';
- }
- return false;
- };
- Parser.prototype.parseGetterMethod = function () {
- var node = this.createNode();
- this.expect('(');
- this.expect(')');
- var isGenerator = false;
- var params = {
- params: [],
- stricted: null,
- firstRestricted: null,
- message: null
- };
- var previousAllowYield = this.context.allowYield;
- this.context.allowYield = false;
- var method = this.parsePropertyMethod(params);
- this.context.allowYield = previousAllowYield;
- return this.finalize(node, new Node.FunctionExpression(null,
params.params, method, isGenerator));
- };
- Parser.prototype.parseSetterMethod = function () {
- var node = this.createNode();
- var options = {
- params: [],
- firstRestricted: null,
- paramSet: {}
- };
- var isGenerator = false;
- var previousAllowYield = this.context.allowYield;
- this.context.allowYield = false;
- this.expect('(');
- if (this.match(')')) {
- this.tolerateUnexpectedToken(this.lookahead);
- }
- else {
- this.parseFormalParameter(options);
- }
- this.expect(')');
- var method = this.parsePropertyMethod(options);
- this.context.allowYield = previousAllowYield;
- return this.finalize(node, new Node.FunctionExpression(null,
options.params, method, isGenerator));
- };
- Parser.prototype.parseGeneratorMethod = function () {
- var node = this.createNode();
- var isGenerator = true;
- var previousAllowYield = this.context.allowYield;
- this.context.allowYield = true;
- var params = this.parseFormalParameters();
- this.context.allowYield = false;
- var method = this.parsePropertyMethod(params);
- this.context.allowYield = previousAllowYield;
- return this.finalize(node, new Node.FunctionExpression(null,
params.params, method, isGenerator));
- };
- // ECMA-262 14.4 Generator Function Definitions
- Parser.prototype.parseYieldExpression = function () {
- var node = this.createNode();
- this.expectKeyword('yield');
- var argument = null;
- var delegate = false;
- if (!this.hasLineTerminator) {
- var previousAllowYield = this.context.allowYield;
- this.context.allowYield = false;
- delegate = this.match('*');
- if (delegate) {
- this.nextToken();
- argument = this.parseAssignmentExpression();
- }
- else {
- if (!this.match(';') && !this.match('}') &&
!this.match(')') && this.lookahead.type !== token_1.Token.EOF) {
- argument = this.parseAssignmentExpression();
- }
- }
- this.context.allowYield = previousAllowYield;
- }
- return this.finalize(node, new Node.YieldExpression(argument,
delegate));
- };
- // ECMA-262 14.5 Class Definitions
- Parser.prototype.parseClassElement = function (hasConstructor) {
- var token = this.lookahead;
- var node = this.createNode();
- var kind = '';
- var key = null;
- var value = null;
- var computed = false;
- var method = false;
- var isStatic = false;
- var isAsync = false;
- if (this.match('*')) {
- this.nextToken();
- }
- else {
- computed = this.match('[');
- key = this.parseObjectPropertyKey();
- var id = key;
- if (id.name === 'static' &&
(this.qualifiedPropertyName(this.lookahead) || this.match('*'))) {
- token = this.lookahead;
- isStatic = true;
- computed = this.match('[');
- if (this.match('*')) {
- this.nextToken();
- }
- else {
- key = this.parseObjectPropertyKey();
- }
- }
- isAsync = (token.type === token_1.Token.Identifier) &&
!this.hasLineTerminator && (this.lookahead.type === token_1.Token.Identifier)
&& (token.value === 'async');
- if (isAsync) {
- token = this.lookahead;
- key = this.parseObjectPropertyKey();
- if (token.type === token_1.Token.Identifier && ['get',
'set', 'constructor'].indexOf(token.value) >= 0) {
- this.tolerateUnexpectedToken(token);
- }
- }
- }
- var lookaheadPropertyKey =
this.qualifiedPropertyName(this.lookahead);
- if (token.type === token_1.Token.Identifier) {
- if (token.value === 'get' && lookaheadPropertyKey) {
- kind = 'get';
- computed = this.match('[');
- key = this.parseObjectPropertyKey();
- this.context.allowYield = false;
- value = this.parseGetterMethod();
- }
- else if (token.value === 'set' && lookaheadPropertyKey) {
- kind = 'set';
- computed = this.match('[');
- key = this.parseObjectPropertyKey();
- value = this.parseSetterMethod();
- }
- }
- else if (token.type === token_1.Token.Punctuator && token.value
=== '*' && lookaheadPropertyKey) {
- kind = 'init';
- computed = this.match('[');
- key = this.parseObjectPropertyKey();
- value = this.parseGeneratorMethod();
- method = true;
- }
- if (!kind && key && this.match('(')) {
- kind = 'init';
- value = isAsync ? this.parsePropertyMethodAsyncFunction() :
this.parsePropertyMethodFunction();
- method = true;
- }
- if (!kind) {
- this.throwUnexpectedToken(this.lookahead);
- }
- if (kind === 'init') {
- kind = 'method';
- }
- if (!computed) {
- if (isStatic && this.isPropertyKey(key, 'prototype')) {
- this.throwUnexpectedToken(token,
messages_1.Messages.StaticPrototype);
- }
- if (!isStatic && this.isPropertyKey(key, 'constructor')) {
- if (kind !== 'method' || !method || (value &&
value.generator)) {
- this.throwUnexpectedToken(token,
messages_1.Messages.ConstructorSpecialMethod);
- }
- if (hasConstructor.value) {
- this.throwUnexpectedToken(token,
messages_1.Messages.DuplicateConstructor);
- }
- else {
- hasConstructor.value = true;
- }
- kind = 'constructor';
- }
- }
- return this.finalize(node, new Node.MethodDefinition(key,
computed, value, kind, isStatic));
- };
- Parser.prototype.parseClassElementList = function () {
- var body = [];
- var hasConstructor = { value: false };
- this.expect('{');
- while (!this.match('}')) {
- if (this.match(';')) {
- this.nextToken();
- }
- else {
- body.push(this.parseClassElement(hasConstructor));
- }
- }
- this.expect('}');
- return body;
- };
- Parser.prototype.parseClassBody = function () {
- var node = this.createNode();
- var elementList = this.parseClassElementList();
- return this.finalize(node, new Node.ClassBody(elementList));
- };
- Parser.prototype.parseClassDeclaration = function
(identifierIsOptional) {
- var node = this.createNode();
- var previousStrict = this.context.strict;
- this.context.strict = true;
- this.expectKeyword('class');
- var id = (identifierIsOptional && (this.lookahead.type !==
token_1.Token.Identifier)) ? null : this.parseVariableIdentifier();
- var superClass = null;
- if (this.matchKeyword('extends')) {
- this.nextToken();
- superClass =
this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
- }
- var classBody = this.parseClassBody();
- this.context.strict = previousStrict;
- return this.finalize(node, new Node.ClassDeclaration(id,
superClass, classBody));
- };
- Parser.prototype.parseClassExpression = function () {
- var node = this.createNode();
- var previousStrict = this.context.strict;
- this.context.strict = true;
- this.expectKeyword('class');
- var id = (this.lookahead.type === token_1.Token.Identifier) ?
this.parseVariableIdentifier() : null;
- var superClass = null;
- if (this.matchKeyword('extends')) {
- this.nextToken();
- superClass =
this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
- }
- var classBody = this.parseClassBody();
- this.context.strict = previousStrict;
- return this.finalize(node, new Node.ClassExpression(id,
superClass, classBody));
- };
- // ECMA-262 15.1 Scripts
- // ECMA-262 15.2 Modules
- Parser.prototype.parseModule = function () {
- this.context.strict = true;
- this.context.isModule = true;
- var node = this.createNode();
- var body = this.parseDirectivePrologues();
- while (this.startMarker.index < this.scanner.length) {
- body.push(this.parseStatementListItem());
- }
- return this.finalize(node, new Node.Module(body));
- };
- Parser.prototype.parseScript = function () {
- var node = this.createNode();
- var body = this.parseDirectivePrologues();
- while (this.startMarker.index < this.scanner.length) {
- body.push(this.parseStatementListItem());
- }
- return this.finalize(node, new Node.Script(body));
- };
- // ECMA-262 15.2.2 Imports
- Parser.prototype.parseModuleSpecifier = function () {
- var node = this.createNode();
- if (this.lookahead.type !== token_1.Token.StringLiteral) {
- this.throwError(messages_1.Messages.InvalidModuleSpecifier);
- }
- var token = this.nextToken();
- var raw = this.getTokenRaw(token);
- return this.finalize(node, new Node.Literal(token.value, raw));
- };
- // import {<foo as bar>} ...;
- Parser.prototype.parseImportSpecifier = function () {
- var node = this.createNode();
- var imported;
- var local;
- if (this.lookahead.type === token_1.Token.Identifier) {
- imported = this.parseVariableIdentifier();
- local = imported;
- if (this.matchContextualKeyword('as')) {
- this.nextToken();
- local = this.parseVariableIdentifier();
- }
- }
- else {
- imported = this.parseIdentifierName();
- local = imported;
- if (this.matchContextualKeyword('as')) {
- this.nextToken();
- local = this.parseVariableIdentifier();
- }
- else {
- this.throwUnexpectedToken(this.nextToken());
- }
- }
- return this.finalize(node, new Node.ImportSpecifier(local,
imported));
- };
- // {foo, bar as bas}
- Parser.prototype.parseNamedImports = function () {
- this.expect('{');
- var specifiers = [];
- while (!this.match('}')) {
- specifiers.push(this.parseImportSpecifier());
- if (!this.match('}')) {
- this.expect(',');
- }
- }
- this.expect('}');
- return specifiers;
- };
- // import <foo> ...;
- Parser.prototype.parseImportDefaultSpecifier = function () {
- var node = this.createNode();
- var local = this.parseIdentifierName();
- return this.finalize(node, new
Node.ImportDefaultSpecifier(local));
- };
- // import <* as foo> ...;
- Parser.prototype.parseImportNamespaceSpecifier = function () {
- var node = this.createNode();
- this.expect('*');
- if (!this.matchContextualKeyword('as')) {
-
this.throwError(messages_1.Messages.NoAsAfterImportNamespace);
- }
- this.nextToken();
- var local = this.parseIdentifierName();
- return this.finalize(node, new
Node.ImportNamespaceSpecifier(local));
- };
- Parser.prototype.parseImportDeclaration = function () {
- if (this.context.inFunctionBody) {
-
this.throwError(messages_1.Messages.IllegalImportDeclaration);
- }
- var node = this.createNode();
- this.expectKeyword('import');
- var src;
- var specifiers = [];
- if (this.lookahead.type === token_1.Token.StringLiteral) {
- // import 'foo';
- src = this.parseModuleSpecifier();
- }
- else {
- if (this.match('{')) {
- // import {bar}
- specifiers =
specifiers.concat(this.parseNamedImports());
- }
- else if (this.match('*')) {
- // import * as foo
- specifiers.push(this.parseImportNamespaceSpecifier());
- }
- else if (this.isIdentifierName(this.lookahead) &&
!this.matchKeyword('default')) {
- // import foo
- specifiers.push(this.parseImportDefaultSpecifier());
- if (this.match(',')) {
- this.nextToken();
- if (this.match('*')) {
- // import foo, * as foo
-
specifiers.push(this.parseImportNamespaceSpecifier());
- }
- else if (this.match('{')) {
- // import foo, {bar}
- specifiers =
specifiers.concat(this.parseNamedImports());
- }
- else {
- this.throwUnexpectedToken(this.lookahead);
- }
- }
- }
- else {
- this.throwUnexpectedToken(this.nextToken());
- }
- if (!this.matchContextualKeyword('from')) {
- var message = this.lookahead.value ?
messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
- this.throwError(message, this.lookahead.value);
- }
- this.nextToken();
- src = this.parseModuleSpecifier();
- }
- this.consumeSemicolon();
- return this.finalize(node, new
Node.ImportDeclaration(specifiers, src));
- };
- // ECMA-262 15.2.3 Exports
- Parser.prototype.parseExportSpecifier = function () {
- var node = this.createNode();
- var local = this.parseIdentifierName();
- var exported = local;
- if (this.matchContextualKeyword('as')) {
- this.nextToken();
- exported = this.parseIdentifierName();
- }
- return this.finalize(node, new Node.ExportSpecifier(local,
exported));
- };
- Parser.prototype.parseExportDeclaration = function () {
- if (this.context.inFunctionBody) {
-
this.throwError(messages_1.Messages.IllegalExportDeclaration);
- }
- var node = this.createNode();
- this.expectKeyword('export');
- var exportDeclaration;
- if (this.matchKeyword('default')) {
- // export default ...
- this.nextToken();
- if (this.matchKeyword('function')) {
- // export default function foo () {}
- // export default function () {}
- var declaration = this.parseFunctionDeclaration(true);
- exportDeclaration = this.finalize(node, new
Node.ExportDefaultDeclaration(declaration));
- }
- else if (this.matchKeyword('class')) {
- // export default class foo {}
- var declaration = this.parseClassDeclaration(true);
- exportDeclaration = this.finalize(node, new
Node.ExportDefaultDeclaration(declaration));
- }
- else {
- if (this.matchContextualKeyword('from')) {
-
this.throwError(messages_1.Messages.UnexpectedToken, this.lookahead.value);
- }
- // export default {};
- // export default [];
- // export default (1 + 2);
- var declaration = this.match('{') ?
this.parseObjectInitializer() :
- this.match('[') ? this.parseArrayInitializer() :
this.parseAssignmentExpression();
- this.consumeSemicolon();
- exportDeclaration = this.finalize(node, new
Node.ExportDefaultDeclaration(declaration));
- }
- }
- else if (this.match('*')) {
- // export * from 'foo';
- this.nextToken();
- if (!this.matchContextualKeyword('from')) {
- var message = this.lookahead.value ?
messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
- this.throwError(message, this.lookahead.value);
- }
- this.nextToken();
- var src = this.parseModuleSpecifier();
- this.consumeSemicolon();
- exportDeclaration = this.finalize(node, new
Node.ExportAllDeclaration(src));
- }
- else if (this.lookahead.type === token_1.Token.Keyword) {
- // export var f = 1;
- var declaration = void 0;
- switch (this.lookahead.value) {
- case 'let':
- case 'const':
- declaration = this.parseLexicalDeclaration({ inFor:
false });
- break;
- case 'var':
- case 'class':
- case 'function':
- declaration = this.parseStatementListItem();
- break;
- default:
- this.throwUnexpectedToken(this.lookahead);
- }
- exportDeclaration = this.finalize(node, new
Node.ExportNamedDeclaration(declaration, [], null));
- }
- else if (this.matchAsyncFunction()) {
- var declaration = this.parseFunctionDeclaration();
- exportDeclaration = this.finalize(node, new
Node.ExportNamedDeclaration(declaration, [], null));
- }
- else {
- var specifiers = [];
- var source = null;
- var isExportFromIdentifier = false;
- this.expect('{');
- while (!this.match('}')) {
- isExportFromIdentifier = isExportFromIdentifier ||
this.matchKeyword('default');
- specifiers.push(this.parseExportSpecifier());
- if (!this.match('}')) {
- this.expect(',');
- }
- }
- this.expect('}');
- if (this.matchContextualKeyword('from')) {
- // export {default} from 'foo';
- // export {foo} from 'foo';
- this.nextToken();
- source = this.parseModuleSpecifier();
- this.consumeSemicolon();
- }
- else if (isExportFromIdentifier) {
- // export {default}; // missing fromClause
- var message = this.lookahead.value ?
messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
- this.throwError(message, this.lookahead.value);
- }
- else {
- // export {foo};
- this.consumeSemicolon();
- }
- exportDeclaration = this.finalize(node, new
Node.ExportNamedDeclaration(null, specifiers, source));
- }
- return exportDeclaration;
- };
- return Parser;
- }());
- exports.Parser = Parser;
-
-
-/***/ },
-/* 4 */
-/***/ function(module, exports) {
-
- // 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.
- "use strict";
- function assert(condition, message) {
- /* istanbul ignore if */
- if (!condition) {
- throw new Error('ASSERT: ' + message);
- }
- }
- exports.assert = assert;
-
-
-/***/ },
-/* 5 */
-/***/ function(module, exports) {
-
- "use strict";
- // Error messages should be identical to V8.
- exports.Messages = {
- UnexpectedToken: 'Unexpected token %0',
- UnexpectedTokenIllegal: 'Unexpected token ILLEGAL',
- UnexpectedNumber: 'Unexpected number',
- UnexpectedString: 'Unexpected string',
- UnexpectedIdentifier: 'Unexpected identifier',
- UnexpectedReserved: 'Unexpected reserved word',
- UnexpectedTemplate: 'Unexpected quasi %0',
- 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',
- InvalidLHSInForLoop: 'Invalid left-hand side in for-loop',
- 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.',
- 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',
- TemplateOctalLiteral: 'Octal literals are not allowed in template
strings.',
- ParameterAfterRestParameter: 'Rest parameter must be last formal
parameter',
- DefaultRestParameter: 'Unexpected token =',
- ObjectPatternAsRestParameter: 'Unexpected token {',
- DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed
in object literals',
- ConstructorSpecialMethod: 'Class constructor may not be an
accessor',
- DuplicateConstructor: 'A class may only have one constructor',
- StaticPrototype: 'Classes may not have static property named
prototype',
- MissingFromClause: 'Unexpected token',
- NoAsAfterImportNamespace: 'Unexpected token',
- InvalidModuleSpecifier: 'Unexpected token',
- IllegalImportDeclaration: 'Unexpected token',
- IllegalExportDeclaration: 'Unexpected token',
- DuplicateBinding: 'Duplicate binding %0',
- DeclarationMissingInitializer: 'Missing initializer in %0
declaration',
- LetInLexicalBinding: 'let is disallowed as a lexically bound name',
- ForInOfLoopInitializer: '%0 loop variable declaration may not have
an initializer'
- };
-
-
-/***/ },
-/* 6 */
-/***/ function(module, exports) {
-
- "use strict";
- var ErrorHandler = (function () {
- function ErrorHandler() {
- this.errors = [];
- this.tolerant = false;
- }
- ;
- ErrorHandler.prototype.recordError = function (error) {
- this.errors.push(error);
- };
- ;
- ErrorHandler.prototype.tolerate = function (error) {
- if (this.tolerant) {
- this.recordError(error);
- }
- else {
- throw error;
- }
- };
- ;
- ErrorHandler.prototype.constructError = function (msg, column) {
- var error = new Error(msg);
- try {
- throw error;
- }
- catch (base) {
- /* istanbul ignore else */
- if (Object.create && Object.defineProperty) {
- error = Object.create(base);
- Object.defineProperty(error, 'column', { value: column
});
- }
- }
- finally {
- return error;
- }
- /* istanbul ignore next */
- return error;
- };
- ;
- ErrorHandler.prototype.createError = function (index, line, col,
description) {
- var msg = 'Line ' + line + ': ' + description;
- var error = this.constructError(msg, col);
- error.index = index;
- error.lineNumber = line;
- error.description = description;
- return error;
- };
- ;
- ErrorHandler.prototype.throwError = function (index, line, col,
description) {
- throw this.createError(index, line, col, description);
- };
- ;
- ErrorHandler.prototype.tolerateError = function (index, line, col,
description) {
- var error = this.createError(index, line, col, description);
- if (this.tolerant) {
- this.recordError(error);
- }
- else {
- throw error;
- }
- };
- ;
- return ErrorHandler;
- }());
- exports.ErrorHandler = ErrorHandler;
-
-
-/***/ },
-/* 7 */
-/***/ function(module, exports) {
-
- "use strict";
- (function (Token) {
- Token[Token["BooleanLiteral"] = 1] = "BooleanLiteral";
- Token[Token["EOF"] = 2] = "EOF";
- Token[Token["Identifier"] = 3] = "Identifier";
- Token[Token["Keyword"] = 4] = "Keyword";
- Token[Token["NullLiteral"] = 5] = "NullLiteral";
- Token[Token["NumericLiteral"] = 6] = "NumericLiteral";
- Token[Token["Punctuator"] = 7] = "Punctuator";
- Token[Token["StringLiteral"] = 8] = "StringLiteral";
- Token[Token["RegularExpression"] = 9] = "RegularExpression";
- Token[Token["Template"] = 10] = "Template";
- })(exports.Token || (exports.Token = {}));
- var Token = exports.Token;
- ;
- exports.TokenName = {};
- exports.TokenName[Token.BooleanLiteral] = 'Boolean';
- exports.TokenName[Token.EOF] = '<end>';
- exports.TokenName[Token.Identifier] = 'Identifier';
- exports.TokenName[Token.Keyword] = 'Keyword';
- exports.TokenName[Token.NullLiteral] = 'Null';
- exports.TokenName[Token.NumericLiteral] = 'Numeric';
- exports.TokenName[Token.Punctuator] = 'Punctuator';
- exports.TokenName[Token.StringLiteral] = 'String';
- exports.TokenName[Token.RegularExpression] = 'RegularExpression';
- exports.TokenName[Token.Template] = 'Template';
-
-
-/***/ },
-/* 8 */
-/***/ function(module, exports, __webpack_require__) {
-
- "use strict";
- var assert_1 = __webpack_require__(4);
- var messages_1 = __webpack_require__(5);
- var character_1 = __webpack_require__(9);
- var token_1 = __webpack_require__(7);
- function hexValue(ch) {
- return '0123456789abcdef'.indexOf(ch.toLowerCase());
- }
- function octalValue(ch) {
- return '01234567'.indexOf(ch);
- }
- var Scanner = (function () {
- function Scanner(code, handler) {
- this.source = code;
- this.errorHandler = handler;
- this.trackComment = false;
- this.length = code.length;
- this.index = 0;
- this.lineNumber = (code.length > 0) ? 1 : 0;
- this.lineStart = 0;
- this.curlyStack = [];
- }
- ;
- Scanner.prototype.eof = function () {
- return this.index >= this.length;
- };
- ;
- Scanner.prototype.throwUnexpectedToken = function (message) {
- if (message === void 0) { message =
messages_1.Messages.UnexpectedTokenIllegal; }
- this.errorHandler.throwError(this.index, this.lineNumber,
this.index - this.lineStart + 1, message);
- };
- ;
- Scanner.prototype.tolerateUnexpectedToken = function () {
- this.errorHandler.tolerateError(this.index, this.lineNumber,
this.index - this.lineStart + 1, messages_1.Messages.UnexpectedTokenIllegal);
- };
- ;
- // ECMA-262 11.4 Comments
- Scanner.prototype.skipSingleLineComment = function (offset) {
- var comments = [];
- var start, loc;
- if (this.trackComment) {
- comments = [];
- start = this.index - offset;
- loc = {
- start: {
- line: this.lineNumber,
- column: this.index - this.lineStart - offset
- },
- end: {}
- };
- }
- while (!this.eof()) {
- var ch = this.source.charCodeAt(this.index);
- ++this.index;
- if (character_1.Character.isLineTerminator(ch)) {
- if (this.trackComment) {
- loc.end = {
- line: this.lineNumber,
- column: this.index - this.lineStart - 1
- };
- var entry = {
- multiLine: false,
- slice: [start + offset, this.index - 1],
- range: [start, this.index - 1],
- loc: loc
- };
- comments.push(entry);
- }
- if (ch === 13 && this.source.charCodeAt(this.index) ===
10) {
- ++this.index;
- }
- ++this.lineNumber;
- this.lineStart = this.index;
- return comments;
- }
- }
- if (this.trackComment) {
- loc.end = {
- line: this.lineNumber,
- column: this.index - this.lineStart
- };
- var entry = {
- multiLine: false,
- slice: [start + offset, this.index],
- range: [start, this.index],
- loc: loc
- };
- comments.push(entry);
- }
- return comments;
- };
- ;
- Scanner.prototype.skipMultiLineComment = function () {
- var comments = [];
- var start, loc;
- if (this.trackComment) {
- comments = [];
- start = this.index - 2;
- loc = {
- start: {
- line: this.lineNumber,
- column: this.index - this.lineStart - 2
- },
- end: {}
- };
- }
- while (!this.eof()) {
- var ch = this.source.charCodeAt(this.index);
- if (character_1.Character.isLineTerminator(ch)) {
- if (ch === 0x0D && this.source.charCodeAt(this.index +
1) === 0x0A) {
- ++this.index;
- }
- ++this.lineNumber;
- ++this.index;
- this.lineStart = this.index;
- }
- else if (ch === 0x2A) {
- // Block comment ends with '*/'.
- if (this.source.charCodeAt(this.index + 1) === 0x2F) {
- this.index += 2;
- if (this.trackComment) {
- loc.end = {
- line: this.lineNumber,
- column: this.index - this.lineStart
- };
- var entry = {
- multiLine: true,
- slice: [start + 2, this.index - 2],
- range: [start, this.index],
- loc: loc
- };
- comments.push(entry);
- }
- return comments;
- }
- ++this.index;
- }
- else {
- ++this.index;
- }
- }
- // Ran off the end of the file - the whole thing is a comment
- if (this.trackComment) {
- loc.end = {
- line: this.lineNumber,
- column: this.index - this.lineStart
- };
- var entry = {
- multiLine: true,
- slice: [start + 2, this.index],
- range: [start, this.index],
- loc: loc
- };
- comments.push(entry);
- }
- this.tolerateUnexpectedToken();
- return comments;
- };
- ;
- Scanner.prototype.scanComments = function () {
- var comments;
- if (this.trackComment) {
- comments = [];
- }
- var start = (this.index === 0);
- while (!this.eof()) {
- var ch = this.source.charCodeAt(this.index);
- if (character_1.Character.isWhiteSpace(ch)) {
- ++this.index;
- }
- else if (character_1.Character.isLineTerminator(ch)) {
- ++this.index;
- if (ch === 0x0D && this.source.charCodeAt(this.index)
=== 0x0A) {
- ++this.index;
- }
- ++this.lineNumber;
- this.lineStart = this.index;
- start = true;
- }
- else if (ch === 0x2F) {
- ch = this.source.charCodeAt(this.index + 1);
- if (ch === 0x2F) {
- this.index += 2;
- var comment = this.skipSingleLineComment(2);
- if (this.trackComment) {
- comments = comments.concat(comment);
- }
- start = true;
- }
- else if (ch === 0x2A) {
- this.index += 2;
- var comment = this.skipMultiLineComment();
- if (this.trackComment) {
- comments = comments.concat(comment);
- }
- }
- else {
- break;
- }
- }
- else if (start && ch === 0x2D) {
- // U+003E is '>'
- if ((this.source.charCodeAt(this.index + 1) === 0x2D)
&& (this.source.charCodeAt(this.index + 2) === 0x3E)) {
- // '-->' is a single-line comment
- this.index += 3;
- var comment = this.skipSingleLineComment(3);
- if (this.trackComment) {
- comments = comments.concat(comment);
- }
- }
- else {
- break;
- }
- }
- else if (ch === 0x3C) {
- if (this.source.slice(this.index + 1, this.index + 4)
=== '!--') {
- this.index += 4; // `<!--`
- var comment = this.skipSingleLineComment(4);
- if (this.trackComment) {
- comments = comments.concat(comment);
- }
- }
- else {
- break;
- }
- }
- else {
- break;
- }
- }
- return comments;
- };
- ;
- // ECMA-262 11.6.2.2 Future Reserved Words
- Scanner.prototype.isFutureReservedWord = function (id) {
- switch (id) {
- case 'enum':
- case 'export':
- case 'import':
- case 'super':
- return true;
- default:
- return false;
- }
- };
- ;
- Scanner.prototype.isStrictModeReservedWord = function (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;
- }
- };
- ;
- Scanner.prototype.isRestrictedWord = function (id) {
- return id === 'eval' || id === 'arguments';
- };
- ;
- // ECMA-262 11.6.2.1 Keywords
- Scanner.prototype.isKeyword = function (id) {
- 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;
- }
- };
- ;
- Scanner.prototype.codePointAt = function (i) {
- var cp = this.source.charCodeAt(i);
- if (cp >= 0xD800 && cp <= 0xDBFF) {
- var second = this.source.charCodeAt(i + 1);
- if (second >= 0xDC00 && second <= 0xDFFF) {
- var first = cp;
- cp = (first - 0xD800) * 0x400 + second - 0xDC00 +
0x10000;
- }
- }
- return cp;
- };
- ;
- Scanner.prototype.scanHexEscape = function (prefix) {
- var len = (prefix === 'u') ? 4 : 2;
- var code = 0;
- for (var i = 0; i < len; ++i) {
- if (!this.eof() &&
character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
- code = code * 16 + hexValue(this.source[this.index++]);
- }
- else {
- return '';
- }
- }
- return String.fromCharCode(code);
- };
- ;
- Scanner.prototype.scanUnicodeCodePointEscape = function () {
- var ch = this.source[this.index];
- var code = 0;
- // At least, one hex digit is required.
- if (ch === '}') {
- this.throwUnexpectedToken();
- }
- while (!this.eof()) {
- ch = this.source[this.index++];
- if (!character_1.Character.isHexDigit(ch.charCodeAt(0))) {
- break;
- }
- code = code * 16 + hexValue(ch);
- }
- if (code > 0x10FFFF || ch !== '}') {
- this.throwUnexpectedToken();
- }
- return character_1.Character.fromCodePoint(code);
- };
- ;
- Scanner.prototype.getIdentifier = function () {
- var start = this.index++;
- while (!this.eof()) {
- var ch = this.source.charCodeAt(this.index);
- if (ch === 0x5C) {
- // Blackslash (U+005C) marks Unicode escape sequence.
- this.index = start;
- return this.getComplexIdentifier();
- }
- else if (ch >= 0xD800 && ch < 0xDFFF) {
- // Need to handle surrogate pairs.
- this.index = start;
- return this.getComplexIdentifier();
- }
- if (character_1.Character.isIdentifierPart(ch)) {
- ++this.index;
- }
- else {
- break;
- }
- }
- return this.source.slice(start, this.index);
- };
- ;
- Scanner.prototype.getComplexIdentifier = function () {
- var cp = this.codePointAt(this.index);
- var id = character_1.Character.fromCodePoint(cp);
- this.index += id.length;
- // '\u' (U+005C, U+0075) denotes an escaped character.
- var ch;
- if (cp === 0x5C) {
- if (this.source.charCodeAt(this.index) !== 0x75) {
- this.throwUnexpectedToken();
- }
- ++this.index;
- if (this.source[this.index] === '{') {
- ++this.index;
- ch = this.scanUnicodeCodePointEscape();
- }
- else {
- ch = this.scanHexEscape('u');
- cp = ch.charCodeAt(0);
- if (!ch || ch === '\\' ||
!character_1.Character.isIdentifierStart(cp)) {
- this.throwUnexpectedToken();
- }
- }
- id = ch;
- }
- while (!this.eof()) {
- cp = this.codePointAt(this.index);
- if (!character_1.Character.isIdentifierPart(cp)) {
- break;
- }
- ch = character_1.Character.fromCodePoint(cp);
- id += ch;
- this.index += ch.length;
- // '\u' (U+005C, U+0075) denotes an escaped character.
- if (cp === 0x5C) {
- id = id.substr(0, id.length - 1);
- if (this.source.charCodeAt(this.index) !== 0x75) {
- this.throwUnexpectedToken();
- }
- ++this.index;
- if (this.source[this.index] === '{') {
- ++this.index;
- ch = this.scanUnicodeCodePointEscape();
- }
- else {
- ch = this.scanHexEscape('u');
- cp = ch.charCodeAt(0);
- if (!ch || ch === '\\' ||
!character_1.Character.isIdentifierPart(cp)) {
- this.throwUnexpectedToken();
- }
- }
- id += ch;
- }
- }
- return id;
- };
- ;
- Scanner.prototype.octalToDecimal = function (ch) {
- // \0 is not octal escape sequence
- var octal = (ch !== '0');
- var code = octalValue(ch);
- if (!this.eof() &&
character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
- octal = true;
- code = code * 8 + octalValue(this.source[this.index++]);
- // 3 digits are only allowed when string starts
- // with 0, 1, 2, 3
- if ('0123'.indexOf(ch) >= 0 && !this.eof() &&
character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
- code = code * 8 + octalValue(this.source[this.index++]);
- }
- }
- return {
- code: code,
- octal: octal
- };
- };
- ;
- // ECMA-262 11.6 Names and Keywords
- Scanner.prototype.scanIdentifier = function () {
- var type;
- var start = this.index;
- // Backslash (U+005C) starts an escaped character.
- var id = (this.source.charCodeAt(start) === 0x5C) ?
this.getComplexIdentifier() : this.getIdentifier();
- // There is no keyword or literal with only one character.
- // Thus, it must be an identifier.
- if (id.length === 1) {
- type = token_1.Token.Identifier;
- }
- else if (this.isKeyword(id)) {
- type = token_1.Token.Keyword;
- }
- else if (id === 'null') {
- type = token_1.Token.NullLiteral;
- }
- else if (id === 'true' || id === 'false') {
- type = token_1.Token.BooleanLiteral;
- }
- else {
- type = token_1.Token.Identifier;
- }
- return {
- type: type,
- value: id,
- lineNumber: this.lineNumber,
- lineStart: this.lineStart,
- start: start,
- end: this.index
- };
- };
- ;
- // ECMA-262 11.7 Punctuators
- Scanner.prototype.scanPunctuator = function () {
- var token = {
- type: token_1.Token.Punctuator,
- value: '',
- lineNumber: this.lineNumber,
- lineStart: this.lineStart,
- start: this.index,
- end: this.index
- };
- // Check for most common single-character punctuators.
- var str = this.source[this.index];
- switch (str) {
- case '(':
- case '{':
- if (str === '{') {
- this.curlyStack.push('{');
- }
- ++this.index;
- break;
- case '.':
- ++this.index;
- if (this.source[this.index] === '.' &&
this.source[this.index + 1] === '.') {
- // Spread operator: ...
- this.index += 2;
- str = '...';
- }
- break;
- case '}':
- ++this.index;
- this.curlyStack.pop();
- break;
- case ')':
- case ';':
- case ',':
- case '[':
- case ']':
- case ':':
- case '?':
- case '~':
- ++this.index;
- break;
- default:
- // 4-character punctuator.
- str = this.source.substr(this.index, 4);
- if (str === '>>>=') {
- this.index += 4;
- }
- else {
- // 3-character punctuators.
- str = str.substr(0, 3);
- if (str === '===' || str === '!==' || str === '>>>'
||
- str === '<<=' || str === '>>=' || str ===
'**=') {
- this.index += 3;
- }
- else {
- // 2-character punctuators.
- str = str.substr(0, 2);
- if (str === '&&' || str === '||' || str ===
'==' || str === '!=' ||
- str === '+=' || str === '-=' || str ===
'*=' || str === '/=' ||
- str === '++' || str === '--' || str ===
'<<' || str === '>>' ||
- str === '&=' || str === '|=' || str ===
'^=' || str === '%=' ||
- str === '<=' || str === '>=' || str ===
'=>' || str === '**') {
- this.index += 2;
- }
- else {
- // 1-character punctuators.
- str = this.source[this.index];
- if ('<>=!+-*%&|^/'.indexOf(str) >= 0) {
- ++this.index;
- }
- }
- }
- }
- }
- if (this.index === token.start) {
- this.throwUnexpectedToken();
- }
- token.end = this.index;
- token.value = str;
- return token;
- };
- ;
- // ECMA-262 11.8.3 Numeric Literals
- Scanner.prototype.scanHexLiteral = function (start) {
- var number = '';
- while (!this.eof()) {
- if
(!character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
- break;
- }
- number += this.source[this.index++];
- }
- if (number.length === 0) {
- this.throwUnexpectedToken();
- }
- if
(character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
- this.throwUnexpectedToken();
- }
- return {
- type: token_1.Token.NumericLiteral,
- value: parseInt('0x' + number, 16),
- lineNumber: this.lineNumber,
- lineStart: this.lineStart,
- start: start,
- end: this.index
- };
- };
- ;
- Scanner.prototype.scanBinaryLiteral = function (start) {
- var number = '';
- var ch;
- while (!this.eof()) {
- ch = this.source[this.index];
- if (ch !== '0' && ch !== '1') {
- break;
- }
- number += this.source[this.index++];
- }
- if (number.length === 0) {
- // only 0b or 0B
- this.throwUnexpectedToken();
- }
- if (!this.eof()) {
- ch = this.source.charCodeAt(this.index);
- /* istanbul ignore else */
- if (character_1.Character.isIdentifierStart(ch) ||
character_1.Character.isDecimalDigit(ch)) {
- this.throwUnexpectedToken();
- }
- }
- return {
- type: token_1.Token.NumericLiteral,
- value: parseInt(number, 2),
- lineNumber: this.lineNumber,
- lineStart: this.lineStart,
- start: start,
- end: this.index
- };
- };
- ;
- Scanner.prototype.scanOctalLiteral = function (prefix, start) {
- var number = '';
- var octal = false;
- if (character_1.Character.isOctalDigit(prefix.charCodeAt(0))) {
- octal = true;
- number = '0' + this.source[this.index++];
- }
- else {
- ++this.index;
- }
- while (!this.eof()) {
- if
(!character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
- break;
- }
- number += this.source[this.index++];
- }
- if (!octal && number.length === 0) {
- // only 0o or 0O
- this.throwUnexpectedToken();
- }
- if
(character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index)) ||
character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
- this.throwUnexpectedToken();
- }
- return {
- type: token_1.Token.NumericLiteral,
- value: parseInt(number, 8),
- octal: octal,
- lineNumber: this.lineNumber,
- lineStart: this.lineStart,
- start: start,
- end: this.index
- };
- };
- ;
- Scanner.prototype.isImplicitOctalLiteral = function () {
- // Implicit octal, unless there is a non-octal digit.
- // (Annex B.1.1 on Numeric Literals)
- for (var i = this.index + 1; i < this.length; ++i) {
- var ch = this.source[i];
- if (ch === '8' || ch === '9') {
- return false;
- }
- if (!character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
- return true;
- }
- }
- return true;
- };
- ;
- Scanner.prototype.scanNumericLiteral = function () {
- var start = this.index;
- var ch = this.source[start];
-
assert_1.assert(character_1.Character.isDecimalDigit(ch.charCodeAt(0)) || (ch
=== '.'), 'Numeric literal must start with a decimal digit or a decimal point');
- var number = '';
- if (ch !== '.') {
- number = this.source[this.index++];
- ch = this.source[this.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') {
- ++this.index;
- return this.scanHexLiteral(start);
- }
- if (ch === 'b' || ch === 'B') {
- ++this.index;
- return this.scanBinaryLiteral(start);
- }
- if (ch === 'o' || ch === 'O') {
- return this.scanOctalLiteral(ch, start);
- }
- if (ch &&
character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
- if (this.isImplicitOctalLiteral()) {
- return this.scanOctalLiteral(ch, start);
- }
- }
- }
- while
(character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
- number += this.source[this.index++];
- }
- ch = this.source[this.index];
- }
- if (ch === '.') {
- number += this.source[this.index++];
- while
(character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
- number += this.source[this.index++];
- }
- ch = this.source[this.index];
- }
- if (ch === 'e' || ch === 'E') {
- number += this.source[this.index++];
- ch = this.source[this.index];
- if (ch === '+' || ch === '-') {
- number += this.source[this.index++];
- }
- if
(character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
- while
(character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
- number += this.source[this.index++];
- }
- }
- else {
- this.throwUnexpectedToken();
- }
- }
- if
(character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
- this.throwUnexpectedToken();
- }
- return {
- type: token_1.Token.NumericLiteral,
- value: parseFloat(number),
- lineNumber: this.lineNumber,
- lineStart: this.lineStart,
- start: start,
- end: this.index
- };
- };
- ;
- // ECMA-262 11.8.4 String Literals
- Scanner.prototype.scanStringLiteral = function () {
- var start = this.index;
- var quote = this.source[start];
- assert_1.assert((quote === '\'' || quote === '"'), 'String
literal must starts with a quote');
- ++this.index;
- var octal = false;
- var str = '';
- while (!this.eof()) {
- var ch = this.source[this.index++];
- if (ch === quote) {
- quote = '';
- break;
- }
- else if (ch === '\\') {
- ch = this.source[this.index++];
- if (!ch ||
!character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
- switch (ch) {
- case 'u':
- case 'x':
- if (this.source[this.index] === '{') {
- ++this.index;
- str +=
this.scanUnicodeCodePointEscape();
- }
- else {
- var unescaped = this.scanHexEscape(ch);
- if (!unescaped) {
- this.throwUnexpectedToken();
- }
- str += unescaped;
- }
- break;
- case 'n':
- str += '\n';
- break;
- case 'r':
- str += '\r';
- break;
- case 't':
- str += '\t';
- break;
- case 'b':
- str += '\b';
- break;
- case 'f':
- str += '\f';
- break;
- case 'v':
- str += '\x0B';
- break;
- case '8':
- case '9':
- str += ch;
- this.tolerateUnexpectedToken();
- break;
- default:
- if (ch &&
character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
- var octToDec = this.octalToDecimal(ch);
- octal = octToDec.octal || octal;
- str +=
String.fromCharCode(octToDec.code);
- }
- else {
- str += ch;
- }
- break;
- }
- }
- else {
- ++this.lineNumber;
- if (ch === '\r' && this.source[this.index] ===
'\n') {
- ++this.index;
- }
- this.lineStart = this.index;
- }
- }
- else if
(character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
- break;
- }
- else {
- str += ch;
- }
- }
- if (quote !== '') {
- this.index = start;
- this.throwUnexpectedToken();
- }
- return {
- type: token_1.Token.StringLiteral,
- value: str,
- octal: octal,
- lineNumber: this.lineNumber,
- lineStart: this.lineStart,
- start: start,
- end: this.index
- };
- };
- ;
- // ECMA-262 11.8.6 Template Literal Lexical Components
- Scanner.prototype.scanTemplate = function () {
- var cooked = '';
- var terminated = false;
- var start = this.index;
- var head = (this.source[start] === '`');
- var tail = false;
- var rawOffset = 2;
- ++this.index;
- while (!this.eof()) {
- var ch = this.source[this.index++];
- if (ch === '`') {
- rawOffset = 1;
- tail = true;
- terminated = true;
- break;
- }
- else if (ch === '$') {
- if (this.source[this.index] === '{') {
- this.curlyStack.push('${');
- ++this.index;
- terminated = true;
- break;
- }
- cooked += ch;
- }
- else if (ch === '\\') {
- ch = this.source[this.index++];
- if
(!character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
- switch (ch) {
- case 'n':
- cooked += '\n';
- break;
- case 'r':
- cooked += '\r';
- break;
- case 't':
- cooked += '\t';
- break;
- case 'u':
- case 'x':
- if (this.source[this.index] === '{') {
- ++this.index;
- cooked +=
this.scanUnicodeCodePointEscape();
- }
- else {
- var restore = this.index;
- var unescaped = this.scanHexEscape(ch);
- if (unescaped) {
- cooked += unescaped;
- }
- else {
- this.index = restore;
- cooked += ch;
- }
- }
- break;
- case 'b':
- cooked += '\b';
- break;
- case 'f':
- cooked += '\f';
- break;
- case 'v':
- cooked += '\v';
- break;
- default:
- if (ch === '0') {
- if
(character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
- // Illegal: \01 \02 and so on
-
this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
- }
- cooked += '\0';
- }
- else if
(character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
- // Illegal: \1 \2
-
this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
- }
- else {
- cooked += ch;
- }
- break;
- }
- }
- else {
- ++this.lineNumber;
- if (ch === '\r' && this.source[this.index] ===
'\n') {
- ++this.index;
- }
- this.lineStart = this.index;
- }
- }
- else if
(character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
- ++this.lineNumber;
- if (ch === '\r' && this.source[this.index] === '\n') {
- ++this.index;
- }
- this.lineStart = this.index;
- cooked += '\n';
- }
- else {
- cooked += ch;
- }
- }
- if (!terminated) {
- this.throwUnexpectedToken();
- }
- if (!head) {
- this.curlyStack.pop();
- }
- return {
- type: token_1.Token.Template,
- value: {
- cooked: cooked,
- raw: this.source.slice(start + 1, this.index -
rawOffset)
- },
- head: head,
- tail: tail,
- lineNumber: this.lineNumber,
- lineStart: this.lineStart,
- start: start,
- end: this.index
- };
- };
- ;
- // ECMA-262 11.8.5 Regular Expression Literals
- Scanner.prototype.testRegExp = function (pattern, flags) {
- // The BMP character to use as a replacement for astral symbols
when
- // translating an ES6 "u"-flagged pattern to an ES5-compatible
- // approximation.
- // Note: replacing with '\uFFFF' enables false positives in
unlikely
- // scenarios. For example, `[\u{1044f}-\u{10440}]` is an invalid
- // pattern that would not be detected by this substitution.
- var astralSubstitute = '\uFFFF';
- var tmp = pattern;
- var self = this;
- if (flags.indexOf('u') >= 0) {
- tmp = tmp
- .replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g,
function ($0, $1, $2) {
- var codePoint = parseInt($1 || $2, 16);
- if (codePoint > 0x10FFFF) {
-
self.throwUnexpectedToken(messages_1.Messages.InvalidRegExp);
- }
- if (codePoint <= 0xFFFF) {
- return String.fromCharCode(codePoint);
- }
- return astralSubstitute;
- })
- .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
astralSubstitute);
- }
- // First, detect invalid regular expressions.
- try {
- RegExp(tmp);
- }
- catch (e) {
-
this.throwUnexpectedToken(messages_1.Messages.InvalidRegExp);
- }
- // Return a regular expression object for this pattern-flag
pair, or
- // `null` in case the current environment doesn't support the
flags it
- // uses.
- try {
- return new RegExp(pattern, flags);
- }
- catch (exception) {
- /* istanbul ignore next */
- return null;
- }
- };
- ;
- Scanner.prototype.scanRegExpBody = function () {
- var ch = this.source[this.index];
- assert_1.assert(ch === '/', 'Regular expression literal must
start with a slash');
- var str = this.source[this.index++];
- var classMarker = false;
- var terminated = false;
- while (!this.eof()) {
- ch = this.source[this.index++];
- str += ch;
- if (ch === '\\') {
- ch = this.source[this.index++];
- // ECMA-262 7.8.5
- if
(character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
-
this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
- }
- str += ch;
- }
- else if
(character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
-
this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
- }
- else if (classMarker) {
- if (ch === ']') {
- classMarker = false;
- }
- }
- else {
- if (ch === '/') {
- terminated = true;
- break;
- }
- else if (ch === '[') {
- classMarker = true;
- }
- }
- }
- if (!terminated) {
-
this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
- }
- // Exclude leading and trailing slash.
- var body = str.substr(1, str.length - 2);
- return {
- value: body,
- literal: str
- };
- };
- ;
- Scanner.prototype.scanRegExpFlags = function () {
- var str = '';
- var flags = '';
- while (!this.eof()) {
- var ch = this.source[this.index];
- if
(!character_1.Character.isIdentifierPart(ch.charCodeAt(0))) {
- break;
- }
- ++this.index;
- if (ch === '\\' && !this.eof()) {
- ch = this.source[this.index];
- if (ch === 'u') {
- ++this.index;
- var restore = this.index;
- ch = this.scanHexEscape('u');
- if (ch) {
- flags += ch;
- for (str += '\\u'; restore < this.index;
++restore) {
- str += this.source[restore];
- }
- }
- else {
- this.index = restore;
- flags += 'u';
- str += '\\u';
- }
- this.tolerateUnexpectedToken();
- }
- else {
- str += '\\';
- this.tolerateUnexpectedToken();
- }
- }
- else {
- flags += ch;
- str += ch;
- }
- }
- return {
- value: flags,
- literal: str
- };
- };
- ;
- Scanner.prototype.scanRegExp = function () {
- var start = this.index;
- var body = this.scanRegExpBody();
- var flags = this.scanRegExpFlags();
- var value = this.testRegExp(body.value, flags.value);
- return {
- type: token_1.Token.RegularExpression,
- value: value,
- literal: body.literal + flags.literal,
- regex: {
- pattern: body.value,
- flags: flags.value
- },
- lineNumber: this.lineNumber,
- lineStart: this.lineStart,
- start: start,
- end: this.index
- };
- };
- ;
- Scanner.prototype.lex = function () {
- if (this.eof()) {
- return {
- type: token_1.Token.EOF,
- lineNumber: this.lineNumber,
- lineStart: this.lineStart,
- start: this.index,
- end: this.index
- };
- }
- var cp = this.source.charCodeAt(this.index);
- if (character_1.Character.isIdentifierStart(cp)) {
- return this.scanIdentifier();
- }
- // Very common: ( and ) and ;
- if (cp === 0x28 || cp === 0x29 || cp === 0x3B) {
- return this.scanPunctuator();
- }
- // String literal starts with single quote (U+0027) or double
quote (U+0022).
- if (cp === 0x27 || cp === 0x22) {
- return this.scanStringLiteral();
- }
- // Dot (.) U+002E can also start a floating-point number, hence
the need
- // to check the next character.
- if (cp === 0x2E) {
- if
(character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index + 1))) {
- return this.scanNumericLiteral();
- }
- return this.scanPunctuator();
- }
- if (character_1.Character.isDecimalDigit(cp)) {
- return this.scanNumericLiteral();
- }
- // Template literals start with ` (U+0060) for template head
- // or } (U+007D) for template middle or template tail.
- if (cp === 0x60 || (cp === 0x7D &&
this.curlyStack[this.curlyStack.length - 1] === '${')) {
- return this.scanTemplate();
- }
- // Possible identifier start in a surrogate pair.
- if (cp >= 0xD800 && cp < 0xDFFF) {
- if
(character_1.Character.isIdentifierStart(this.codePointAt(this.index))) {
- return this.scanIdentifier();
- }
- }
- return this.scanPunctuator();
- };
- ;
- return Scanner;
- }());
- exports.Scanner = Scanner;
-
-
-/***/ },
-/* 9 */
-/***/ function(module, exports) {
-
- "use strict";
- // See also tools/generate-unicode-regex.js.
- var Regex = {
- // Unicode v8.0.0 NonAsciiIdentifierStart:
- NonAsciiIdentifierStart:
/[\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\u
[...]
- // Unicode v8.0.0 NonAsciiIdentifierPart:
- NonAsciiIdentifierPart:
/[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\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\
[...]
- };
- exports.Character = {
- fromCodePoint: function (cp) {
- return (cp < 0x10000) ? String.fromCharCode(cp) :
- String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) +
- String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023));
- },
- // ECMA-262 11.2 White Space
- isWhiteSpace: function (cp) {
- return (cp === 0x20) || (cp === 0x09) || (cp === 0x0B) || (cp
=== 0x0C) || (cp === 0xA0) ||
- (cp >= 0x1680 && [0x1680, 0x2000, 0x2001, 0x2002, 0x2003,
0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000,
0xFEFF].indexOf(cp) >= 0);
- },
- // ECMA-262 11.3 Line Terminators
- isLineTerminator: function (cp) {
- return (cp === 0x0A) || (cp === 0x0D) || (cp === 0x2028) || (cp
=== 0x2029);
- },
- // ECMA-262 11.6 Identifier Names and Identifiers
- isIdentifierStart: function (cp) {
- return (cp === 0x24) || (cp === 0x5F) ||
- (cp >= 0x41 && cp <= 0x5A) ||
- (cp >= 0x61 && cp <= 0x7A) ||
- (cp === 0x5C) ||
- ((cp >= 0x80) &&
Regex.NonAsciiIdentifierStart.test(exports.Character.fromCodePoint(cp)));
- },
- isIdentifierPart: function (cp) {
- return (cp === 0x24) || (cp === 0x5F) ||
- (cp >= 0x41 && cp <= 0x5A) ||
- (cp >= 0x61 && cp <= 0x7A) ||
- (cp >= 0x30 && cp <= 0x39) ||
- (cp === 0x5C) ||
- ((cp >= 0x80) &&
Regex.NonAsciiIdentifierPart.test(exports.Character.fromCodePoint(cp)));
- },
- // ECMA-262 11.8.3 Numeric Literals
- isDecimalDigit: function (cp) {
- return (cp >= 0x30 && cp <= 0x39); // 0..9
- },
- isHexDigit: function (cp) {
- return (cp >= 0x30 && cp <= 0x39) ||
- (cp >= 0x41 && cp <= 0x46) ||
- (cp >= 0x61 && cp <= 0x66); // a..f
- },
- isOctalDigit: function (cp) {
- return (cp >= 0x30 && cp <= 0x37); // 0..7
- }
- };
-
-
-/***/ },
-/* 10 */
-/***/ function(module, exports, __webpack_require__) {
-
- "use strict";
- var syntax_1 = __webpack_require__(2);
- var ArrayExpression = (function () {
- function ArrayExpression(elements) {
- this.type = syntax_1.Syntax.ArrayExpression;
- this.elements = elements;
- }
- return ArrayExpression;
- }());
- exports.ArrayExpression = ArrayExpression;
- var ArrayPattern = (function () {
- function ArrayPattern(elements) {
- this.type = syntax_1.Syntax.ArrayPattern;
- this.elements = elements;
- }
- return ArrayPattern;
- }());
- exports.ArrayPattern = ArrayPattern;
- var ArrowFunctionExpression = (function () {
- function ArrowFunctionExpression(params, body, expression) {
- this.type = syntax_1.Syntax.ArrowFunctionExpression;
- this.id = null;
- this.params = params;
- this.body = body;
- this.generator = false;
- this.expression = expression;
- this.async = false;
- }
- return ArrowFunctionExpression;
- }());
- exports.ArrowFunctionExpression = ArrowFunctionExpression;
- var AssignmentExpression = (function () {
- function AssignmentExpression(operator, left, right) {
- this.type = syntax_1.Syntax.AssignmentExpression;
- this.operator = operator;
- this.left = left;
- this.right = right;
- }
- return AssignmentExpression;
- }());
- exports.AssignmentExpression = AssignmentExpression;
- var AssignmentPattern = (function () {
- function AssignmentPattern(left, right) {
- this.type = syntax_1.Syntax.AssignmentPattern;
- this.left = left;
- this.right = right;
- }
- return AssignmentPattern;
- }());
- exports.AssignmentPattern = AssignmentPattern;
- var AsyncArrowFunctionExpression = (function () {
- function AsyncArrowFunctionExpression(params, body, expression) {
- this.type = syntax_1.Syntax.ArrowFunctionExpression;
- this.id = null;
- this.params = params;
- this.body = body;
- this.generator = false;
- this.expression = expression;
- this.async = true;
- }
- return AsyncArrowFunctionExpression;
- }());
- exports.AsyncArrowFunctionExpression = AsyncArrowFunctionExpression;
- var AsyncFunctionDeclaration = (function () {
- function AsyncFunctionDeclaration(id, params, body) {
- this.type = syntax_1.Syntax.FunctionDeclaration;
- this.id = id;
- this.params = params;
- this.body = body;
- this.generator = false;
- this.expression = false;
- this.async = true;
- }
- return AsyncFunctionDeclaration;
- }());
- exports.AsyncFunctionDeclaration = AsyncFunctionDeclaration;
- var AsyncFunctionExpression = (function () {
- function AsyncFunctionExpression(id, params, body) {
- this.type = syntax_1.Syntax.FunctionExpression;
- this.id = id;
- this.params = params;
- this.body = body;
- this.generator = false;
- this.expression = false;
- this.async = true;
- }
- return AsyncFunctionExpression;
- }());
- exports.AsyncFunctionExpression = AsyncFunctionExpression;
- var AwaitExpression = (function () {
- function AwaitExpression(argument) {
- this.type = syntax_1.Syntax.AwaitExpression;
- this.argument = argument;
- }
- return AwaitExpression;
- }());
- exports.AwaitExpression = AwaitExpression;
- var BinaryExpression = (function () {
- function BinaryExpression(operator, left, right) {
- var logical = (operator === '||' || operator === '&&');
- this.type = logical ? syntax_1.Syntax.LogicalExpression :
syntax_1.Syntax.BinaryExpression;
- this.operator = operator;
- this.left = left;
- this.right = right;
- }
- return BinaryExpression;
- }());
- exports.BinaryExpression = BinaryExpression;
- var BlockStatement = (function () {
- function BlockStatement(body) {
- this.type = syntax_1.Syntax.BlockStatement;
- this.body = body;
- }
- return BlockStatement;
- }());
- exports.BlockStatement = BlockStatement;
- var BreakStatement = (function () {
- function BreakStatement(label) {
- this.type = syntax_1.Syntax.BreakStatement;
- this.label = label;
- }
- return BreakStatement;
- }());
- exports.BreakStatement = BreakStatement;
- var CallExpression = (function () {
- function CallExpression(callee, args) {
- this.type = syntax_1.Syntax.CallExpression;
- this.callee = callee;
- this.arguments = args;
- }
- return CallExpression;
- }());
- exports.CallExpression = CallExpression;
- var CatchClause = (function () {
- function CatchClause(param, body) {
- this.type = syntax_1.Syntax.CatchClause;
- this.param = param;
- this.body = body;
- }
- return CatchClause;
- }());
- exports.CatchClause = CatchClause;
- var ClassBody = (function () {
- function ClassBody(body) {
- this.type = syntax_1.Syntax.ClassBody;
- this.body = body;
- }
- return ClassBody;
- }());
- exports.ClassBody = ClassBody;
- var ClassDeclaration = (function () {
- function ClassDeclaration(id, superClass, body) {
- this.type = syntax_1.Syntax.ClassDeclaration;
- this.id = id;
- this.superClass = superClass;
- this.body = body;
- }
- return ClassDeclaration;
- }());
- exports.ClassDeclaration = ClassDeclaration;
- var ClassExpression = (function () {
- function ClassExpression(id, superClass, body) {
- this.type = syntax_1.Syntax.ClassExpression;
- this.id = id;
- this.superClass = superClass;
- this.body = body;
- }
- return ClassExpression;
- }());
- exports.ClassExpression = ClassExpression;
- var ComputedMemberExpression = (function () {
- function ComputedMemberExpression(object, property) {
- this.type = syntax_1.Syntax.MemberExpression;
- this.computed = true;
- this.object = object;
- this.property = property;
- }
- return ComputedMemberExpression;
- }());
- exports.ComputedMemberExpression = ComputedMemberExpression;
- var ConditionalExpression = (function () {
- function ConditionalExpression(test, consequent, alternate) {
- this.type = syntax_1.Syntax.ConditionalExpression;
- this.test = test;
- this.consequent = consequent;
- this.alternate = alternate;
- }
- return ConditionalExpression;
- }());
- exports.ConditionalExpression = ConditionalExpression;
- var ContinueStatement = (function () {
- function ContinueStatement(label) {
- this.type = syntax_1.Syntax.ContinueStatement;
- this.label = label;
- }
- return ContinueStatement;
- }());
- exports.ContinueStatement = ContinueStatement;
- var DebuggerStatement = (function () {
- function DebuggerStatement() {
- this.type = syntax_1.Syntax.DebuggerStatement;
- }
- return DebuggerStatement;
- }());
- exports.DebuggerStatement = DebuggerStatement;
- var Directive = (function () {
- function Directive(expression, directive) {
- this.type = syntax_1.Syntax.ExpressionStatement;
- this.expression = expression;
- this.directive = directive;
- }
- return Directive;
- }());
- exports.Directive = Directive;
- var DoWhileStatement = (function () {
- function DoWhileStatement(body, test) {
- this.type = syntax_1.Syntax.DoWhileStatement;
- this.body = body;
- this.test = test;
- }
- return DoWhileStatement;
- }());
- exports.DoWhileStatement = DoWhileStatement;
- var EmptyStatement = (function () {
- function EmptyStatement() {
- this.type = syntax_1.Syntax.EmptyStatement;
- }
- return EmptyStatement;
- }());
- exports.EmptyStatement = EmptyStatement;
- var ExportAllDeclaration = (function () {
- function ExportAllDeclaration(source) {
- this.type = syntax_1.Syntax.ExportAllDeclaration;
- this.source = source;
- }
- return ExportAllDeclaration;
- }());
- exports.ExportAllDeclaration = ExportAllDeclaration;
- var ExportDefaultDeclaration = (function () {
- function ExportDefaultDeclaration(declaration) {
- this.type = syntax_1.Syntax.ExportDefaultDeclaration;
- this.declaration = declaration;
- }
- return ExportDefaultDeclaration;
- }());
- exports.ExportDefaultDeclaration = ExportDefaultDeclaration;
- var ExportNamedDeclaration = (function () {
- function ExportNamedDeclaration(declaration, specifiers, source) {
- this.type = syntax_1.Syntax.ExportNamedDeclaration;
- this.declaration = declaration;
- this.specifiers = specifiers;
- this.source = source;
- }
- return ExportNamedDeclaration;
- }());
- exports.ExportNamedDeclaration = ExportNamedDeclaration;
- var ExportSpecifier = (function () {
- function ExportSpecifier(local, exported) {
- this.type = syntax_1.Syntax.ExportSpecifier;
- this.exported = exported;
- this.local = local;
- }
- return ExportSpecifier;
- }());
- exports.ExportSpecifier = ExportSpecifier;
- var ExpressionStatement = (function () {
- function ExpressionStatement(expression) {
- this.type = syntax_1.Syntax.ExpressionStatement;
- this.expression = expression;
- }
- return ExpressionStatement;
- }());
- exports.ExpressionStatement = ExpressionStatement;
- var ForInStatement = (function () {
- function ForInStatement(left, right, body) {
- this.type = syntax_1.Syntax.ForInStatement;
- this.left = left;
- this.right = right;
- this.body = body;
- this.each = false;
- }
- return ForInStatement;
- }());
- exports.ForInStatement = ForInStatement;
- var ForOfStatement = (function () {
- function ForOfStatement(left, right, body) {
- this.type = syntax_1.Syntax.ForOfStatement;
- this.left = left;
- this.right = right;
- this.body = body;
- }
- return ForOfStatement;
- }());
- exports.ForOfStatement = ForOfStatement;
- var ForStatement = (function () {
- function ForStatement(init, test, update, body) {
- this.type = syntax_1.Syntax.ForStatement;
- this.init = init;
- this.test = test;
- this.update = update;
- this.body = body;
- }
- return ForStatement;
- }());
- exports.ForStatement = ForStatement;
- var FunctionDeclaration = (function () {
- function FunctionDeclaration(id, params, body, generator) {
- this.type = syntax_1.Syntax.FunctionDeclaration;
- this.id = id;
- this.params = params;
- this.body = body;
- this.generator = generator;
- this.expression = false;
- this.async = false;
- }
- return FunctionDeclaration;
- }());
- exports.FunctionDeclaration = FunctionDeclaration;
- var FunctionExpression = (function () {
- function FunctionExpression(id, params, body, generator) {
- this.type = syntax_1.Syntax.FunctionExpression;
- this.id = id;
- this.params = params;
- this.body = body;
- this.generator = generator;
- this.expression = false;
- this.async = false;
- }
- return FunctionExpression;
- }());
- exports.FunctionExpression = FunctionExpression;
- var Identifier = (function () {
- function Identifier(name) {
- this.type = syntax_1.Syntax.Identifier;
- this.name = name;
- }
- return Identifier;
- }());
- exports.Identifier = Identifier;
- var IfStatement = (function () {
- function IfStatement(test, consequent, alternate) {
- this.type = syntax_1.Syntax.IfStatement;
- this.test = test;
- this.consequent = consequent;
- this.alternate = alternate;
- }
- return IfStatement;
- }());
- exports.IfStatement = IfStatement;
- var ImportDeclaration = (function () {
- function ImportDeclaration(specifiers, source) {
- this.type = syntax_1.Syntax.ImportDeclaration;
- this.specifiers = specifiers;
- this.source = source;
- }
- return ImportDeclaration;
- }());
- exports.ImportDeclaration = ImportDeclaration;
- var ImportDefaultSpecifier = (function () {
- function ImportDefaultSpecifier(local) {
- this.type = syntax_1.Syntax.ImportDefaultSpecifier;
- this.local = local;
- }
- return ImportDefaultSpecifier;
- }());
- exports.ImportDefaultSpecifier = ImportDefaultSpecifier;
- var ImportNamespaceSpecifier = (function () {
- function ImportNamespaceSpecifier(local) {
- this.type = syntax_1.Syntax.ImportNamespaceSpecifier;
- this.local = local;
- }
- return ImportNamespaceSpecifier;
- }());
- exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier;
- var ImportSpecifier = (function () {
- function ImportSpecifier(local, imported) {
- this.type = syntax_1.Syntax.ImportSpecifier;
- this.local = local;
- this.imported = imported;
- }
- return ImportSpecifier;
- }());
- exports.ImportSpecifier = ImportSpecifier;
- var LabeledStatement = (function () {
- function LabeledStatement(label, body) {
- this.type = syntax_1.Syntax.LabeledStatement;
- this.label = label;
- this.body = body;
- }
- return LabeledStatement;
- }());
- exports.LabeledStatement = LabeledStatement;
- var Literal = (function () {
- function Literal(value, raw) {
- this.type = syntax_1.Syntax.Literal;
- this.value = value;
- this.raw = raw;
- }
- return Literal;
- }());
- exports.Literal = Literal;
- var MetaProperty = (function () {
- function MetaProperty(meta, property) {
- this.type = syntax_1.Syntax.MetaProperty;
- this.meta = meta;
- this.property = property;
- }
- return MetaProperty;
- }());
- exports.MetaProperty = MetaProperty;
- var MethodDefinition = (function () {
- function MethodDefinition(key, computed, value, kind, isStatic) {
- this.type = syntax_1.Syntax.MethodDefinition;
- this.key = key;
- this.computed = computed;
- this.value = value;
- this.kind = kind;
- this.static = isStatic;
- }
- return MethodDefinition;
- }());
- exports.MethodDefinition = MethodDefinition;
- var Module = (function () {
- function Module(body) {
- this.type = syntax_1.Syntax.Program;
- this.body = body;
- this.sourceType = 'module';
- }
- return Module;
- }());
- exports.Module = Module;
- var NewExpression = (function () {
- function NewExpression(callee, args) {
- this.type = syntax_1.Syntax.NewExpression;
- this.callee = callee;
- this.arguments = args;
- }
- return NewExpression;
- }());
- exports.NewExpression = NewExpression;
- var ObjectExpression = (function () {
- function ObjectExpression(properties) {
- this.type = syntax_1.Syntax.ObjectExpression;
- this.properties = properties;
- }
- return ObjectExpression;
- }());
- exports.ObjectExpression = ObjectExpression;
- var ObjectPattern = (function () {
- function ObjectPattern(properties) {
- this.type = syntax_1.Syntax.ObjectPattern;
- this.properties = properties;
- }
- return ObjectPattern;
- }());
- exports.ObjectPattern = ObjectPattern;
- var Property = (function () {
- function Property(kind, key, computed, value, method, shorthand) {
- this.type = syntax_1.Syntax.Property;
- this.key = key;
- this.computed = computed;
- this.value = value;
- this.kind = kind;
- this.method = method;
- this.shorthand = shorthand;
- }
- return Property;
- }());
- exports.Property = Property;
- var RegexLiteral = (function () {
- function RegexLiteral(value, raw, regex) {
- this.type = syntax_1.Syntax.Literal;
- this.value = value;
- this.raw = raw;
- this.regex = regex;
- }
- return RegexLiteral;
- }());
- exports.RegexLiteral = RegexLiteral;
- var RestElement = (function () {
- function RestElement(argument) {
- this.type = syntax_1.Syntax.RestElement;
- this.argument = argument;
- }
- return RestElement;
- }());
- exports.RestElement = RestElement;
- var ReturnStatement = (function () {
- function ReturnStatement(argument) {
- this.type = syntax_1.Syntax.ReturnStatement;
- this.argument = argument;
- }
- return ReturnStatement;
- }());
- exports.ReturnStatement = ReturnStatement;
- var Script = (function () {
- function Script(body) {
- this.type = syntax_1.Syntax.Program;
- this.body = body;
- this.sourceType = 'script';
- }
- return Script;
- }());
- exports.Script = Script;
- var SequenceExpression = (function () {
- function SequenceExpression(expressions) {
- this.type = syntax_1.Syntax.SequenceExpression;
- this.expressions = expressions;
- }
- return SequenceExpression;
- }());
- exports.SequenceExpression = SequenceExpression;
- var SpreadElement = (function () {
- function SpreadElement(argument) {
- this.type = syntax_1.Syntax.SpreadElement;
- this.argument = argument;
- }
- return SpreadElement;
- }());
- exports.SpreadElement = SpreadElement;
- var StaticMemberExpression = (function () {
- function StaticMemberExpression(object, property) {
- this.type = syntax_1.Syntax.MemberExpression;
- this.computed = false;
- this.object = object;
- this.property = property;
- }
- return StaticMemberExpression;
- }());
- exports.StaticMemberExpression = StaticMemberExpression;
- var Super = (function () {
- function Super() {
- this.type = syntax_1.Syntax.Super;
- }
- return Super;
- }());
- exports.Super = Super;
- var SwitchCase = (function () {
- function SwitchCase(test, consequent) {
- this.type = syntax_1.Syntax.SwitchCase;
- this.test = test;
- this.consequent = consequent;
- }
- return SwitchCase;
- }());
- exports.SwitchCase = SwitchCase;
- var SwitchStatement = (function () {
- function SwitchStatement(discriminant, cases) {
- this.type = syntax_1.Syntax.SwitchStatement;
- this.discriminant = discriminant;
- this.cases = cases;
- }
- return SwitchStatement;
- }());
- exports.SwitchStatement = SwitchStatement;
- var TaggedTemplateExpression = (function () {
- function TaggedTemplateExpression(tag, quasi) {
- this.type = syntax_1.Syntax.TaggedTemplateExpression;
- this.tag = tag;
- this.quasi = quasi;
- }
- return TaggedTemplateExpression;
- }());
- exports.TaggedTemplateExpression = TaggedTemplateExpression;
- var TemplateElement = (function () {
- function TemplateElement(value, tail) {
- this.type = syntax_1.Syntax.TemplateElement;
- this.value = value;
- this.tail = tail;
- }
- return TemplateElement;
- }());
- exports.TemplateElement = TemplateElement;
- var TemplateLiteral = (function () {
- function TemplateLiteral(quasis, expressions) {
- this.type = syntax_1.Syntax.TemplateLiteral;
- this.quasis = quasis;
- this.expressions = expressions;
- }
- return TemplateLiteral;
- }());
- exports.TemplateLiteral = TemplateLiteral;
- var ThisExpression = (function () {
- function ThisExpression() {
- this.type = syntax_1.Syntax.ThisExpression;
- }
- return ThisExpression;
- }());
- exports.ThisExpression = ThisExpression;
- var ThrowStatement = (function () {
- function ThrowStatement(argument) {
- this.type = syntax_1.Syntax.ThrowStatement;
- this.argument = argument;
- }
- return ThrowStatement;
- }());
- exports.ThrowStatement = ThrowStatement;
- var TryStatement = (function () {
- function TryStatement(block, handler, finalizer) {
- this.type = syntax_1.Syntax.TryStatement;
- this.block = block;
- this.handler = handler;
- this.finalizer = finalizer;
- }
- return TryStatement;
- }());
- exports.TryStatement = TryStatement;
- var UnaryExpression = (function () {
- function UnaryExpression(operator, argument) {
- this.type = syntax_1.Syntax.UnaryExpression;
- this.operator = operator;
- this.argument = argument;
- this.prefix = true;
- }
- return UnaryExpression;
- }());
- exports.UnaryExpression = UnaryExpression;
- var UpdateExpression = (function () {
- function UpdateExpression(operator, argument, prefix) {
- this.type = syntax_1.Syntax.UpdateExpression;
- this.operator = operator;
- this.argument = argument;
- this.prefix = prefix;
- }
- return UpdateExpression;
- }());
- exports.UpdateExpression = UpdateExpression;
- var VariableDeclaration = (function () {
- function VariableDeclaration(declarations, kind) {
- this.type = syntax_1.Syntax.VariableDeclaration;
- this.declarations = declarations;
- this.kind = kind;
- }
- return VariableDeclaration;
- }());
- exports.VariableDeclaration = VariableDeclaration;
- var VariableDeclarator = (function () {
- function VariableDeclarator(id, init) {
- this.type = syntax_1.Syntax.VariableDeclarator;
- this.id = id;
- this.init = init;
- }
- return VariableDeclarator;
- }());
- exports.VariableDeclarator = VariableDeclarator;
- var WhileStatement = (function () {
- function WhileStatement(test, body) {
- this.type = syntax_1.Syntax.WhileStatement;
- this.test = test;
- this.body = body;
- }
- return WhileStatement;
- }());
- exports.WhileStatement = WhileStatement;
- var WithStatement = (function () {
- function WithStatement(object, body) {
- this.type = syntax_1.Syntax.WithStatement;
- this.object = object;
- this.body = body;
- }
- return WithStatement;
- }());
- exports.WithStatement = WithStatement;
- var YieldExpression = (function () {
- function YieldExpression(argument, delegate) {
- this.type = syntax_1.Syntax.YieldExpression;
- this.argument = argument;
- this.delegate = delegate;
- }
- return YieldExpression;
- }());
- exports.YieldExpression = YieldExpression;
-
-
-/***/ },
-/* 11 */
-/***/ function(module, exports, __webpack_require__) {
-
- "use strict";
-/* istanbul ignore next */
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype =
b.prototype, new __());
- };
- var character_1 = __webpack_require__(9);
- var token_1 = __webpack_require__(7);
- var parser_1 = __webpack_require__(3);
- var xhtml_entities_1 = __webpack_require__(12);
- var jsx_syntax_1 = __webpack_require__(13);
- var Node = __webpack_require__(10);
- var JSXNode = __webpack_require__(14);
- var JSXToken;
- (function (JSXToken) {
- JSXToken[JSXToken["Identifier"] = 100] = "Identifier";
- JSXToken[JSXToken["Text"] = 101] = "Text";
- })(JSXToken || (JSXToken = {}));
- token_1.TokenName[JSXToken.Identifier] = 'JSXIdentifier';
- token_1.TokenName[JSXToken.Text] = 'JSXText';
- // Fully qualified element name, e.g. <svg:path> returns "svg:path"
- function getQualifiedElementName(elementName) {
- var qualifiedName;
- switch (elementName.type) {
- case jsx_syntax_1.JSXSyntax.JSXIdentifier:
- var id = (elementName);
- qualifiedName = id.name;
- break;
- case jsx_syntax_1.JSXSyntax.JSXNamespacedName:
- var ns = (elementName);
- qualifiedName = getQualifiedElementName(ns.namespace) + ':'
+
- getQualifiedElementName(ns.name);
- break;
- case jsx_syntax_1.JSXSyntax.JSXMemberExpression:
- var expr = (elementName);
- qualifiedName = getQualifiedElementName(expr.object) + '.' +
- getQualifiedElementName(expr.property);
- break;
- }
- return qualifiedName;
- }
- var JSXParser = (function (_super) {
- __extends(JSXParser, _super);
- function JSXParser(code, options, delegate) {
- _super.call(this, code, options, delegate);
- }
- JSXParser.prototype.parsePrimaryExpression = function () {
- return this.match('<') ? this.parseJSXRoot() :
_super.prototype.parsePrimaryExpression.call(this);
- };
- JSXParser.prototype.startJSX = function () {
- // Unwind the scanner before the lookahead token.
- this.scanner.index = this.startMarker.index;
- this.scanner.lineNumber = this.startMarker.lineNumber;
- this.scanner.lineStart = this.startMarker.lineStart;
- };
- JSXParser.prototype.finishJSX = function () {
- // Prime the next lookahead.
- this.nextToken();
- };
- JSXParser.prototype.reenterJSX = function () {
- this.startJSX();
- this.expectJSX('}');
- // Pop the closing '}' added from the lookahead.
- if (this.config.tokens) {
- this.tokens.pop();
- }
- };
- JSXParser.prototype.createJSXNode = function () {
- this.collectComments();
- return {
- index: this.scanner.index,
- line: this.scanner.lineNumber,
- column: this.scanner.index - this.scanner.lineStart
- };
- };
- JSXParser.prototype.createJSXChildNode = function () {
- return {
- index: this.scanner.index,
- line: this.scanner.lineNumber,
- column: this.scanner.index - this.scanner.lineStart
- };
- };
- JSXParser.prototype.scanXHTMLEntity = function () {
- var result = '&';
- var str = '';
- while (!this.scanner.eof()) {
- var ch = this.scanner.source[this.scanner.index++];
- if (ch === ';') {
- if (str[0] === '#') {
- str = str.substr(1);
- var hex = (str[0] === 'x');
- var cp = hex ? parseInt('0' + str, 16) :
parseInt(str, 10);
- result = String.fromCharCode(cp);
- }
- else if (xhtml_entities_1.XHTMLEntities[str]) {
- result = xhtml_entities_1.XHTMLEntities[str];
- }
- else {
- result += ch;
- }
- break;
- }
- str += ch;
- result += ch;
- }
- return result;
- };
- // Scan the next JSX token. This replaces Scanner#lex when in JSX
mode.
- JSXParser.prototype.lexJSX = function () {
- var cp = this.scanner.source.charCodeAt(this.scanner.index);
- // < > / : = { }
- if (cp === 60 || cp === 62 || cp === 47 || cp === 58 || cp ===
61 || cp === 123 || cp === 125) {
- var value = this.scanner.source[this.scanner.index++];
- return {
- type: token_1.Token.Punctuator,
- value: value,
- lineNumber: this.scanner.lineNumber,
- lineStart: this.scanner.lineStart,
- start: this.scanner.index - 1,
- end: this.scanner.index
- };
- }
- // " '
- if (cp === 34 || cp === 39) {
- var start = this.scanner.index;
- var quote = this.scanner.source[this.scanner.index++];
- var str = '';
- while (!this.scanner.eof()) {
- var ch = this.scanner.source[this.scanner.index++];
- if (ch === quote) {
- break;
- }
- else if (ch === '&') {
- str += this.scanXHTMLEntity();
- }
- else {
- str += ch;
- }
- }
- return {
- type: token_1.Token.StringLiteral,
- value: str,
- lineNumber: this.scanner.lineNumber,
- lineStart: this.scanner.lineStart,
- start: start,
- end: this.scanner.index
- };
- }
- // ... or .
- if (cp === 46) {
- var n1 = this.scanner.source.charCodeAt(this.scanner.index
+ 1);
- var n2 = this.scanner.source.charCodeAt(this.scanner.index
+ 2);
- var value = (n1 === 46 && n2 === 46) ? '...' : '.';
- var start = this.scanner.index;
- this.scanner.index += value.length;
- return {
- type: token_1.Token.Punctuator,
- value: value,
- lineNumber: this.scanner.lineNumber,
- lineStart: this.scanner.lineStart,
- start: start,
- end: this.scanner.index
- };
- }
- // Identifer can not contain backslash (char code 92).
- if (character_1.Character.isIdentifierStart(cp) && (cp !== 92))
{
- var start = this.scanner.index;
- ++this.scanner.index;
- while (!this.scanner.eof()) {
- var ch =
this.scanner.source.charCodeAt(this.scanner.index);
- if (character_1.Character.isIdentifierPart(ch) && (ch
!== 92)) {
- ++this.scanner.index;
- }
- else if (ch === 45) {
- // Hyphen (char code 45) can be part of an
identifier.
- ++this.scanner.index;
- }
- else {
- break;
- }
- }
- var id = this.scanner.source.slice(start,
this.scanner.index);
- return {
- type: JSXToken.Identifier,
- value: id,
- lineNumber: this.scanner.lineNumber,
- lineStart: this.scanner.lineStart,
- start: start,
- end: this.scanner.index
- };
- }
- this.scanner.throwUnexpectedToken();
- };
- JSXParser.prototype.nextJSXToken = function () {
- this.collectComments();
- this.startMarker.index = this.scanner.index;
- this.startMarker.lineNumber = this.scanner.lineNumber;
- this.startMarker.lineStart = this.scanner.lineStart;
- var token = this.lexJSX();
- this.lastMarker.index = this.scanner.index;
- this.lastMarker.lineNumber = this.scanner.lineNumber;
- this.lastMarker.lineStart = this.scanner.lineStart;
- if (this.config.tokens) {
- this.tokens.push(this.convertToken(token));
- }
- return token;
- };
- JSXParser.prototype.nextJSXText = function () {
- this.startMarker.index = this.scanner.index;
- this.startMarker.lineNumber = this.scanner.lineNumber;
- this.startMarker.lineStart = this.scanner.lineStart;
- var start = this.scanner.index;
- var text = '';
- while (!this.scanner.eof()) {
- var ch = this.scanner.source[this.scanner.index];
- if (ch === '{' || ch === '<') {
- break;
- }
- ++this.scanner.index;
- text += ch;
- if
(character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
- ++this.scanner.lineNumber;
- if (ch === '\r' &&
this.scanner.source[this.scanner.index] === '\n') {
- ++this.scanner.index;
- }
- this.scanner.lineStart = this.scanner.index;
- }
- }
- this.lastMarker.index = this.scanner.index;
- this.lastMarker.lineNumber = this.scanner.lineNumber;
- this.lastMarker.lineStart = this.scanner.lineStart;
- var token = {
- type: JSXToken.Text,
- value: text,
- lineNumber: this.scanner.lineNumber,
- lineStart: this.scanner.lineStart,
- start: start,
- end: this.scanner.index
- };
- if ((text.length > 0) && this.config.tokens) {
- this.tokens.push(this.convertToken(token));
- }
- return token;
- };
- JSXParser.prototype.peekJSXToken = function () {
- var previousIndex = this.scanner.index;
- var previousLineNumber = this.scanner.lineNumber;
- var previousLineStart = this.scanner.lineStart;
- this.scanner.scanComments();
- var next = this.lexJSX();
- this.scanner.index = previousIndex;
- this.scanner.lineNumber = previousLineNumber;
- this.scanner.lineStart = previousLineStart;
- return next;
- };
- // Expect the next JSX token to match the specified punctuator.
- // If not, an exception will be thrown.
- JSXParser.prototype.expectJSX = function (value) {
- var token = this.nextJSXToken();
- if (token.type !== token_1.Token.Punctuator || token.value !==
value) {
- this.throwUnexpectedToken(token);
- }
- };
- // Return true if the next JSX token matches the specified
punctuator.
- JSXParser.prototype.matchJSX = function (value) {
- var next = this.peekJSXToken();
- return next.type === token_1.Token.Punctuator && next.value ===
value;
- };
- JSXParser.prototype.parseJSXIdentifier = function () {
- var node = this.createJSXNode();
- var token = this.nextJSXToken();
- if (token.type !== JSXToken.Identifier) {
- this.throwUnexpectedToken(token);
- }
- return this.finalize(node, new
JSXNode.JSXIdentifier(token.value));
- };
- JSXParser.prototype.parseJSXElementName = function () {
- var node = this.createJSXNode();
- var elementName = this.parseJSXIdentifier();
- if (this.matchJSX(':')) {
- var namespace = elementName;
- this.expectJSX(':');
- var name_1 = this.parseJSXIdentifier();
- elementName = this.finalize(node, new
JSXNode.JSXNamespacedName(namespace, name_1));
- }
- else if (this.matchJSX('.')) {
- while (this.matchJSX('.')) {
- var object = elementName;
- this.expectJSX('.');
- var property = this.parseJSXIdentifier();
- elementName = this.finalize(node, new
JSXNode.JSXMemberExpression(object, property));
- }
- }
- return elementName;
- };
- JSXParser.prototype.parseJSXAttributeName = function () {
- var node = this.createJSXNode();
- var attributeName;
- var identifier = this.parseJSXIdentifier();
- if (this.matchJSX(':')) {
- var namespace = identifier;
- this.expectJSX(':');
- var name_2 = this.parseJSXIdentifier();
- attributeName = this.finalize(node, new
JSXNode.JSXNamespacedName(namespace, name_2));
- }
- else {
- attributeName = identifier;
- }
- return attributeName;
- };
- JSXParser.prototype.parseJSXStringLiteralAttribute = function () {
- var node = this.createJSXNode();
- var token = this.nextJSXToken();
- if (token.type !== token_1.Token.StringLiteral) {
- this.throwUnexpectedToken(token);
- }
- var raw = this.getTokenRaw(token);
- return this.finalize(node, new Node.Literal(token.value, raw));
- };
- JSXParser.prototype.parseJSXExpressionAttribute = function () {
- var node = this.createJSXNode();
- this.expectJSX('{');
- this.finishJSX();
- if (this.match('}')) {
- this.tolerateError('JSX attributes must only be assigned a
non-empty expression');
- }
- var expression = this.parseAssignmentExpression();
- this.reenterJSX();
- return this.finalize(node, new
JSXNode.JSXExpressionContainer(expression));
- };
- JSXParser.prototype.parseJSXAttributeValue = function () {
- return this.matchJSX('{') ? this.parseJSXExpressionAttribute() :
- this.matchJSX('<') ? this.parseJSXElement() :
this.parseJSXStringLiteralAttribute();
- };
- JSXParser.prototype.parseJSXNameValueAttribute = function () {
- var node = this.createJSXNode();
- var name = this.parseJSXAttributeName();
- var value = null;
- if (this.matchJSX('=')) {
- this.expectJSX('=');
- value = this.parseJSXAttributeValue();
- }
- return this.finalize(node, new JSXNode.JSXAttribute(name,
value));
- };
- JSXParser.prototype.parseJSXSpreadAttribute = function () {
- var node = this.createJSXNode();
- this.expectJSX('{');
- this.expectJSX('...');
- this.finishJSX();
- var argument = this.parseAssignmentExpression();
- this.reenterJSX();
- return this.finalize(node, new
JSXNode.JSXSpreadAttribute(argument));
- };
- JSXParser.prototype.parseJSXAttributes = function () {
- var attributes = [];
- while (!this.matchJSX('/') && !this.matchJSX('>')) {
- var attribute = this.matchJSX('{') ?
this.parseJSXSpreadAttribute() :
- this.parseJSXNameValueAttribute();
- attributes.push(attribute);
- }
- return attributes;
- };
- JSXParser.prototype.parseJSXOpeningElement = function () {
- var node = this.createJSXNode();
- this.expectJSX('<');
- var name = this.parseJSXElementName();
- var attributes = this.parseJSXAttributes();
- var selfClosing = this.matchJSX('/');
- if (selfClosing) {
- this.expectJSX('/');
- }
- this.expectJSX('>');
- return this.finalize(node, new JSXNode.JSXOpeningElement(name,
selfClosing, attributes));
- };
- JSXParser.prototype.parseJSXBoundaryElement = function () {
- var node = this.createJSXNode();
- this.expectJSX('<');
- if (this.matchJSX('/')) {
- this.expectJSX('/');
- var name_3 = this.parseJSXElementName();
- this.expectJSX('>');
- return this.finalize(node, new
JSXNode.JSXClosingElement(name_3));
- }
- var name = this.parseJSXElementName();
- var attributes = this.parseJSXAttributes();
- var selfClosing = this.matchJSX('/');
- if (selfClosing) {
- this.expectJSX('/');
- }
- this.expectJSX('>');
- return this.finalize(node, new JSXNode.JSXOpeningElement(name,
selfClosing, attributes));
- };
- JSXParser.prototype.parseJSXEmptyExpression = function () {
- var node = this.createJSXChildNode();
- this.collectComments();
- this.lastMarker.index = this.scanner.index;
- this.lastMarker.lineNumber = this.scanner.lineNumber;
- this.lastMarker.lineStart = this.scanner.lineStart;
- return this.finalize(node, new JSXNode.JSXEmptyExpression());
- };
- JSXParser.prototype.parseJSXExpressionContainer = function () {
- var node = this.createJSXNode();
- this.expectJSX('{');
- var expression;
- if (this.matchJSX('}')) {
- expression = this.parseJSXEmptyExpression();
- this.expectJSX('}');
- }
- else {
- this.finishJSX();
- expression = this.parseAssignmentExpression();
- this.reenterJSX();
- }
- return this.finalize(node, new
JSXNode.JSXExpressionContainer(expression));
- };
- JSXParser.prototype.parseJSXChildren = function () {
- var children = [];
- while (!this.scanner.eof()) {
- var node = this.createJSXChildNode();
- var token = this.nextJSXText();
- if (token.start < token.end) {
- var raw = this.getTokenRaw(token);
- var child = this.finalize(node, new
JSXNode.JSXText(token.value, raw));
- children.push(child);
- }
- if (this.scanner.source[this.scanner.index] === '{') {
- var container = this.parseJSXExpressionContainer();
- children.push(container);
- }
- else {
- break;
- }
- }
- return children;
- };
- JSXParser.prototype.parseComplexJSXElement = function (el) {
- var stack = [];
- while (!this.scanner.eof()) {
- el.children = el.children.concat(this.parseJSXChildren());
- var node = this.createJSXChildNode();
- var element = this.parseJSXBoundaryElement();
- if (element.type ===
jsx_syntax_1.JSXSyntax.JSXOpeningElement) {
- var opening = (element);
- if (opening.selfClosing) {
- var child = this.finalize(node, new
JSXNode.JSXElement(opening, [], null));
- el.children.push(child);
- }
- else {
- stack.push(el);
- el = { node: node, opening: opening, closing: null,
children: [] };
- }
- }
- if (element.type ===
jsx_syntax_1.JSXSyntax.JSXClosingElement) {
- el.closing = (element);
- var open_1 = getQualifiedElementName(el.opening.name);
- var close_1 = getQualifiedElementName(el.closing.name);
- if (open_1 !== close_1) {
- this.tolerateError('Expected corresponding JSX
closing tag for %0', open_1);
- }
- if (stack.length > 0) {
- var child = this.finalize(el.node, new
JSXNode.JSXElement(el.opening, el.children, el.closing));
- el = stack[stack.length - 1];
- el.children.push(child);
- stack.pop();
- }
- else {
- break;
- }
- }
- }
- return el;
- };
- JSXParser.prototype.parseJSXElement = function () {
- var node = this.createJSXNode();
- var opening = this.parseJSXOpeningElement();
- var children = [];
- var closing = null;
- if (!opening.selfClosing) {
- var el = this.parseComplexJSXElement({ node: node, opening:
opening, closing: closing, children: children });
- children = el.children;
- closing = el.closing;
- }
- return this.finalize(node, new JSXNode.JSXElement(opening,
children, closing));
- };
- JSXParser.prototype.parseJSXRoot = function () {
- // Pop the opening '<' added from the lookahead.
- if (this.config.tokens) {
- this.tokens.pop();
- }
- this.startJSX();
- var element = this.parseJSXElement();
- this.finishJSX();
- return element;
- };
- return JSXParser;
- }(parser_1.Parser));
- exports.JSXParser = JSXParser;
-
-
-/***/ },
-/* 12 */
-/***/ function(module, exports) {
-
- // Generated by generate-xhtml-entities.js. DO NOT MODIFY!
- "use strict";
- exports.XHTMLEntities = {
- quot: '\u0022',
- amp: '\u0026',
- apos: '\u0027',
- gt: '\u003E',
- nbsp: '\u00A0',
- iexcl: '\u00A1',
- cent: '\u00A2',
- pound: '\u00A3',
- curren: '\u00A4',
- yen: '\u00A5',
- brvbar: '\u00A6',
- sect: '\u00A7',
- uml: '\u00A8',
- copy: '\u00A9',
- ordf: '\u00AA',
- laquo: '\u00AB',
- not: '\u00AC',
- shy: '\u00AD',
- reg: '\u00AE',
- macr: '\u00AF',
- deg: '\u00B0',
- plusmn: '\u00B1',
- sup2: '\u00B2',
- sup3: '\u00B3',
- acute: '\u00B4',
- micro: '\u00B5',
- para: '\u00B6',
- middot: '\u00B7',
- cedil: '\u00B8',
- sup1: '\u00B9',
- ordm: '\u00BA',
- raquo: '\u00BB',
- frac14: '\u00BC',
- frac12: '\u00BD',
- frac34: '\u00BE',
- iquest: '\u00BF',
- Agrave: '\u00C0',
- Aacute: '\u00C1',
- Acirc: '\u00C2',
- Atilde: '\u00C3',
- Auml: '\u00C4',
- Aring: '\u00C5',
- AElig: '\u00C6',
- Ccedil: '\u00C7',
- Egrave: '\u00C8',
- Eacute: '\u00C9',
- Ecirc: '\u00CA',
- Euml: '\u00CB',
- Igrave: '\u00CC',
- Iacute: '\u00CD',
- Icirc: '\u00CE',
- Iuml: '\u00CF',
- ETH: '\u00D0',
- Ntilde: '\u00D1',
- Ograve: '\u00D2',
- Oacute: '\u00D3',
- Ocirc: '\u00D4',
- Otilde: '\u00D5',
- Ouml: '\u00D6',
- times: '\u00D7',
- Oslash: '\u00D8',
- Ugrave: '\u00D9',
- Uacute: '\u00DA',
- Ucirc: '\u00DB',
- Uuml: '\u00DC',
- Yacute: '\u00DD',
- THORN: '\u00DE',
- szlig: '\u00DF',
- agrave: '\u00E0',
- aacute: '\u00E1',
- acirc: '\u00E2',
- atilde: '\u00E3',
- auml: '\u00E4',
- aring: '\u00E5',
- aelig: '\u00E6',
- ccedil: '\u00E7',
- egrave: '\u00E8',
- eacute: '\u00E9',
- ecirc: '\u00EA',
- euml: '\u00EB',
- igrave: '\u00EC',
- iacute: '\u00ED',
- icirc: '\u00EE',
- iuml: '\u00EF',
- eth: '\u00F0',
- ntilde: '\u00F1',
- ograve: '\u00F2',
- oacute: '\u00F3',
- ocirc: '\u00F4',
- otilde: '\u00F5',
- ouml: '\u00F6',
- divide: '\u00F7',
- oslash: '\u00F8',
- ugrave: '\u00F9',
- uacute: '\u00FA',
- ucirc: '\u00FB',
- uuml: '\u00FC',
- yacute: '\u00FD',
- thorn: '\u00FE',
- yuml: '\u00FF',
- OElig: '\u0152',
- oelig: '\u0153',
- Scaron: '\u0160',
- scaron: '\u0161',
- Yuml: '\u0178',
- fnof: '\u0192',
- circ: '\u02C6',
- tilde: '\u02DC',
- Alpha: '\u0391',
- Beta: '\u0392',
- Gamma: '\u0393',
- Delta: '\u0394',
- Epsilon: '\u0395',
- Zeta: '\u0396',
- Eta: '\u0397',
- Theta: '\u0398',
- Iota: '\u0399',
- Kappa: '\u039A',
- Lambda: '\u039B',
- Mu: '\u039C',
- Nu: '\u039D',
- Xi: '\u039E',
- Omicron: '\u039F',
- Pi: '\u03A0',
- Rho: '\u03A1',
- Sigma: '\u03A3',
- Tau: '\u03A4',
- Upsilon: '\u03A5',
- Phi: '\u03A6',
- Chi: '\u03A7',
- Psi: '\u03A8',
- Omega: '\u03A9',
- alpha: '\u03B1',
- beta: '\u03B2',
- gamma: '\u03B3',
- delta: '\u03B4',
- epsilon: '\u03B5',
- zeta: '\u03B6',
- eta: '\u03B7',
- theta: '\u03B8',
- iota: '\u03B9',
- kappa: '\u03BA',
- lambda: '\u03BB',
- mu: '\u03BC',
- nu: '\u03BD',
- xi: '\u03BE',
- omicron: '\u03BF',
- pi: '\u03C0',
- rho: '\u03C1',
- sigmaf: '\u03C2',
- sigma: '\u03C3',
- tau: '\u03C4',
- upsilon: '\u03C5',
- phi: '\u03C6',
- chi: '\u03C7',
- psi: '\u03C8',
- omega: '\u03C9',
- thetasym: '\u03D1',
- upsih: '\u03D2',
- piv: '\u03D6',
- ensp: '\u2002',
- emsp: '\u2003',
- thinsp: '\u2009',
- zwnj: '\u200C',
- zwj: '\u200D',
- lrm: '\u200E',
- rlm: '\u200F',
- ndash: '\u2013',
- mdash: '\u2014',
- lsquo: '\u2018',
- rsquo: '\u2019',
- sbquo: '\u201A',
- ldquo: '\u201C',
- rdquo: '\u201D',
- bdquo: '\u201E',
- dagger: '\u2020',
- Dagger: '\u2021',
- bull: '\u2022',
- hellip: '\u2026',
- permil: '\u2030',
- prime: '\u2032',
- Prime: '\u2033',
- lsaquo: '\u2039',
- rsaquo: '\u203A',
- oline: '\u203E',
- frasl: '\u2044',
- euro: '\u20AC',
- image: '\u2111',
- weierp: '\u2118',
- real: '\u211C',
- trade: '\u2122',
- alefsym: '\u2135',
- larr: '\u2190',
- uarr: '\u2191',
- rarr: '\u2192',
- darr: '\u2193',
- harr: '\u2194',
- crarr: '\u21B5',
- lArr: '\u21D0',
- uArr: '\u21D1',
- rArr: '\u21D2',
- dArr: '\u21D3',
- hArr: '\u21D4',
- forall: '\u2200',
- part: '\u2202',
- exist: '\u2203',
- empty: '\u2205',
- nabla: '\u2207',
- isin: '\u2208',
- notin: '\u2209',
- ni: '\u220B',
- prod: '\u220F',
- sum: '\u2211',
- minus: '\u2212',
- lowast: '\u2217',
- radic: '\u221A',
- prop: '\u221D',
- infin: '\u221E',
- ang: '\u2220',
- and: '\u2227',
- or: '\u2228',
- cap: '\u2229',
- cup: '\u222A',
- int: '\u222B',
- there4: '\u2234',
- sim: '\u223C',
- cong: '\u2245',
- asymp: '\u2248',
- ne: '\u2260',
- equiv: '\u2261',
- le: '\u2264',
- ge: '\u2265',
- sub: '\u2282',
- sup: '\u2283',
- nsub: '\u2284',
- sube: '\u2286',
- supe: '\u2287',
- oplus: '\u2295',
- otimes: '\u2297',
- perp: '\u22A5',
- sdot: '\u22C5',
- lceil: '\u2308',
- rceil: '\u2309',
- lfloor: '\u230A',
- rfloor: '\u230B',
- loz: '\u25CA',
- spades: '\u2660',
- clubs: '\u2663',
- hearts: '\u2665',
- diams: '\u2666',
- lang: '\u27E8',
- rang: '\u27E9'
- };
-
-
-/***/ },
-/* 13 */
-/***/ function(module, exports) {
-
- "use strict";
- exports.JSXSyntax = {
- JSXAttribute: 'JSXAttribute',
- JSXClosingElement: 'JSXClosingElement',
- JSXElement: 'JSXElement',
- JSXEmptyExpression: 'JSXEmptyExpression',
- JSXExpressionContainer: 'JSXExpressionContainer',
- JSXIdentifier: 'JSXIdentifier',
- JSXMemberExpression: 'JSXMemberExpression',
- JSXNamespacedName: 'JSXNamespacedName',
- JSXOpeningElement: 'JSXOpeningElement',
- JSXSpreadAttribute: 'JSXSpreadAttribute',
- JSXText: 'JSXText'
- };
-
-
-/***/ },
-/* 14 */
-/***/ function(module, exports, __webpack_require__) {
-
- "use strict";
- var jsx_syntax_1 = __webpack_require__(13);
- var JSXClosingElement = (function () {
- function JSXClosingElement(name) {
- this.type = jsx_syntax_1.JSXSyntax.JSXClosingElement;
- this.name = name;
- }
- return JSXClosingElement;
- }());
- exports.JSXClosingElement = JSXClosingElement;
- var JSXElement = (function () {
- function JSXElement(openingElement, children, closingElement) {
- this.type = jsx_syntax_1.JSXSyntax.JSXElement;
- this.openingElement = openingElement;
- this.children = children;
- this.closingElement = closingElement;
- }
- return JSXElement;
- }());
- exports.JSXElement = JSXElement;
- var JSXEmptyExpression = (function () {
- function JSXEmptyExpression() {
- this.type = jsx_syntax_1.JSXSyntax.JSXEmptyExpression;
- }
- return JSXEmptyExpression;
- }());
- exports.JSXEmptyExpression = JSXEmptyExpression;
- var JSXExpressionContainer = (function () {
- function JSXExpressionContainer(expression) {
- this.type = jsx_syntax_1.JSXSyntax.JSXExpressionContainer;
- this.expression = expression;
- }
- return JSXExpressionContainer;
- }());
- exports.JSXExpressionContainer = JSXExpressionContainer;
- var JSXIdentifier = (function () {
- function JSXIdentifier(name) {
- this.type = jsx_syntax_1.JSXSyntax.JSXIdentifier;
- this.name = name;
- }
- return JSXIdentifier;
- }());
- exports.JSXIdentifier = JSXIdentifier;
- var JSXMemberExpression = (function () {
- function JSXMemberExpression(object, property) {
- this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression;
- this.object = object;
- this.property = property;
- }
- return JSXMemberExpression;
- }());
- exports.JSXMemberExpression = JSXMemberExpression;
- var JSXAttribute = (function () {
- function JSXAttribute(name, value) {
- this.type = jsx_syntax_1.JSXSyntax.JSXAttribute;
- this.name = name;
- this.value = value;
- }
- return JSXAttribute;
- }());
- exports.JSXAttribute = JSXAttribute;
- var JSXNamespacedName = (function () {
- function JSXNamespacedName(namespace, name) {
- this.type = jsx_syntax_1.JSXSyntax.JSXNamespacedName;
- this.namespace = namespace;
- this.name = name;
- }
- return JSXNamespacedName;
- }());
- exports.JSXNamespacedName = JSXNamespacedName;
- var JSXOpeningElement = (function () {
- function JSXOpeningElement(name, selfClosing, attributes) {
- this.type = jsx_syntax_1.JSXSyntax.JSXOpeningElement;
- this.name = name;
- this.selfClosing = selfClosing;
- this.attributes = attributes;
- }
- return JSXOpeningElement;
- }());
- exports.JSXOpeningElement = JSXOpeningElement;
- var JSXSpreadAttribute = (function () {
- function JSXSpreadAttribute(argument) {
- this.type = jsx_syntax_1.JSXSyntax.JSXSpreadAttribute;
- this.argument = argument;
- }
- return JSXSpreadAttribute;
- }());
- exports.JSXSpreadAttribute = JSXSpreadAttribute;
- var JSXText = (function () {
- function JSXText(value, raw) {
- this.type = jsx_syntax_1.JSXSyntax.JSXText;
- this.value = value;
- this.raw = raw;
- }
- return JSXText;
- }());
- exports.JSXText = JSXText;
-
-
-/***/ },
-/* 15 */
-/***/ function(module, exports, __webpack_require__) {
-
- "use strict";
- var scanner_1 = __webpack_require__(8);
- var error_handler_1 = __webpack_require__(6);
- var token_1 = __webpack_require__(7);
- var Reader = (function () {
- function Reader() {
- this.values = [];
- this.curly = this.paren = -1;
- }
- ;
- // A function following one of those tokens is an expression.
- Reader.prototype.beforeFunctionExpression = function (t) {
- return ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
- 'return', 'case', 'delete', 'throw', 'void',
- // assignment operators
- '=', '+=', '-=', '*=', '**=', '/=', '%=', '<<=', '>>=',
'>>>=',
- '&=', '|=', '^=', ',',
- // binary/unary operators
- '+', '-', '*', '**', '/', '%', '++', '--', '<<', '>>',
'>>>', '&',
- '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
- '<=', '<', '>', '!=', '!=='].indexOf(t) >= 0;
- };
- ;
- // Determine if forward slash (/) is an operator or part of a
regular expression
- // https://github.com/mozilla/sweet.js/wiki/design
- Reader.prototype.isRegexStart = function () {
- var previous = this.values[this.values.length - 1];
- var regex = (previous !== null);
- switch (previous) {
- case 'this':
- case ']':
- regex = false;
- break;
- case ')':
- var check = this.values[this.paren - 1];
- regex = (check === 'if' || check === 'while' || check
=== 'for' || check === 'with');
- break;
- case '}':
- // Dividing a function by anything makes little sense,
- // but we have to check for that.
- regex = false;
- if (this.values[this.curly - 3] === 'function') {
- // Anonymous function, e.g. function(){} /42
- var check_1 = this.values[this.curly - 4];
- regex = check_1 ?
!this.beforeFunctionExpression(check_1) : false;
- }
- else if (this.values[this.curly - 4] === 'function') {
- // Named function, e.g. function f(){} /42/
- var check_2 = this.values[this.curly - 5];
- regex = check_2 ?
!this.beforeFunctionExpression(check_2) : true;
- }
- }
- return regex;
- };
- ;
- Reader.prototype.push = function (token) {
- if (token.type === token_1.Token.Punctuator || token.type ===
token_1.Token.Keyword) {
- if (token.value === '{') {
- this.curly = this.values.length;
- }
- else if (token.value === '(') {
- this.paren = this.values.length;
- }
- this.values.push(token.value);
- }
- else {
- this.values.push(null);
- }
- };
- ;
- return Reader;
- }());
- var Tokenizer = (function () {
- function Tokenizer(code, config) {
- this.errorHandler = new error_handler_1.ErrorHandler();
- this.errorHandler.tolerant = config ? (typeof config.tolerant
=== 'boolean' && config.tolerant) : false;
- this.scanner = new scanner_1.Scanner(code, this.errorHandler);
- this.scanner.trackComment = config ? (typeof config.comment ===
'boolean' && config.comment) : false;
- this.trackRange = config ? (typeof config.range === 'boolean'
&& config.range) : false;
- this.trackLoc = config ? (typeof config.loc === 'boolean' &&
config.loc) : false;
- this.buffer = [];
- this.reader = new Reader();
- }
- ;
- Tokenizer.prototype.errors = function () {
- return this.errorHandler.errors;
- };
- ;
- Tokenizer.prototype.getNextToken = function () {
- if (this.buffer.length === 0) {
- var comments = this.scanner.scanComments();
- if (this.scanner.trackComment) {
- for (var i = 0; i < comments.length; ++i) {
- var e = comments[i];
- var comment = void 0;
- var value = this.scanner.source.slice(e.slice[0],
e.slice[1]);
- comment = {
- type: e.multiLine ? 'BlockComment' :
'LineComment',
- value: value
- };
- if (this.trackRange) {
- comment.range = e.range;
- }
- if (this.trackLoc) {
- comment.loc = e.loc;
- }
- this.buffer.push(comment);
- }
- }
- if (!this.scanner.eof()) {
- var loc = void 0;
- if (this.trackLoc) {
- loc = {
- start: {
- line: this.scanner.lineNumber,
- column: this.scanner.index -
this.scanner.lineStart
- },
- end: {}
- };
- }
- var token = void 0;
- if (this.scanner.source[this.scanner.index] === '/') {
- token = this.reader.isRegexStart() ?
this.scanner.scanRegExp() : this.scanner.scanPunctuator();
- }
- else {
- token = this.scanner.lex();
- }
- this.reader.push(token);
- var entry = void 0;
- entry = {
- type: token_1.TokenName[token.type],
- value: this.scanner.source.slice(token.start,
token.end)
- };
- if (this.trackRange) {
- entry.range = [token.start, token.end];
- }
- if (this.trackLoc) {
- loc.end = {
- line: this.scanner.lineNumber,
- column: this.scanner.index -
this.scanner.lineStart
- };
- entry.loc = loc;
- }
- if (token.regex) {
- entry.regex = token.regex;
- }
- this.buffer.push(entry);
- }
- }
- return this.buffer.shift();
- };
- ;
- return Tokenizer;
- }());
- exports.Tokenizer = Tokenizer;
-
-
-/***/ }
-/******/ ])
-});
-;
\ No newline at end of file
diff --git a/node_modules/talertest/selenium/instrumenter.js
b/node_modules/talertest/selenium/instrumenter.js
deleted file mode 100644
index 61c02cf0..00000000
--- a/node_modules/talertest/selenium/instrumenter.js
+++ /dev/null
@@ -1,1097 +0,0 @@
-/*
- Copyright (c) 2012, Yahoo! Inc. All rights reserved.
- Copyrights licensed under the New BSD License. See the accompanying LICENSE
file for terms.
- */
-
-/*global esprima, escodegen, window */
-(function (isNode) {
- "use strict";
- var SYNTAX,
- nodeType,
- ESP = isNode ? require('esprima') : esprima,
- ESPGEN = isNode ? require('escodegen') : escodegen, //TODO - package
as dependency
- crypto = isNode ? require('crypto') : null,
- LEADER_WRAP = '(function () { ',
- TRAILER_WRAP = '\n}());',
- COMMENT_RE = /^\s*istanbul\s+ignore\s+(if|else|next)(?=\W|$)/,
- astgen,
- preconditions,
- cond,
- isArray = Array.isArray;
-
- /* istanbul ignore if: untestable */
- if (!isArray) {
- isArray = function (thing) { return thing &&
Object.prototype.toString.call(thing) === '[object Array]'; };
- }
-
- if (!isNode) {
- preconditions = {
- 'Could not find esprima': ESP,
- 'Could not find escodegen': ESPGEN,
- 'JSON object not in scope': JSON,
- 'Array does not implement push': [].push,
- 'Array does not implement unshift': [].unshift
- };
- /* istanbul ignore next: untestable */
- for (cond in preconditions) {
- if (preconditions.hasOwnProperty(cond)) {
- if (!preconditions[cond]) { throw new Error(cond); }
- }
- }
- }
-
- function generateTrackerVar(filename, omitSuffix) {
- var hash, suffix;
- if (crypto !== null) {
- hash = crypto.createHash('md5');
- hash.update(filename);
- suffix = hash.digest('base64');
- //trim trailing equal signs, turn identifier unsafe chars to safe
ones + => _ and / => $
- suffix = suffix.replace(new RegExp('=', 'g'), '')
- .replace(new RegExp('\\+', 'g'), '_')
- .replace(new RegExp('/', 'g'), '$');
- } else {
- window.__cov_seq = window.__cov_seq || 0;
- window.__cov_seq += 1;
- suffix = window.__cov_seq;
- }
- return '__cov_' + (omitSuffix ? '' : suffix);
- }
-
- function pushAll(ary, thing) {
- if (!isArray(thing)) {
- thing = [ thing ];
- }
- Array.prototype.push.apply(ary, thing);
- }
-
- SYNTAX = {
- // keep in sync with estraverse's VisitorKeys
- AssignmentExpression: ['left', 'right'],
- AssignmentPattern: ['left', 'right'],
- ArrayExpression: ['elements'],
- ArrayPattern: ['elements'],
- ArrowFunctionExpression: ['params', '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', 'superClass', 'body'],
- ClassExpression: ['id', 'superClass', 'body'],
- 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: [],
- ExportAllDeclaration: ['source'],
- ExportDefaultDeclaration: ['declaration'],
- ExportNamedDeclaration: ['declaration', 'specifiers', 'source'],
- ExportSpecifier: ['exported', 'local'],
- ExpressionStatement: ['expression'],
- ForStatement: ['init', 'test', 'update', 'body'],
- ForInStatement: ['left', 'right', 'body'],
- ForOfStatement: ['left', 'right', 'body'],
- FunctionDeclaration: ['id', 'params', 'body'],
- FunctionExpression: ['id', 'params', 'body'],
- GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's
deferred to ES7.
- Identifier: [],
- IfStatement: ['test', 'consequent', 'alternate'],
- ImportDeclaration: ['specifiers', 'source'],
- ImportDefaultSpecifier: ['local'],
- ImportNamespaceSpecifier: ['local'],
- ImportSpecifier: ['imported', 'local'],
- Literal: [],
- LabeledStatement: ['label', 'body'],
- LogicalExpression: ['left', 'right'],
- MetaProperty: ['meta', 'property'],
- MemberExpression: ['object', 'property'],
- MethodDefinition: ['key', 'value'],
- ModuleSpecifier: [],
- NewExpression: ['callee', 'arguments'],
- ObjectExpression: ['properties'],
- ObjectPattern: ['properties'],
- Program: ['body'],
- Property: ['key', 'value'],
- RestElement: [ 'argument' ],
- ReturnStatement: ['argument'],
- SequenceExpression: ['expressions'],
- SpreadElement: ['argument'],
- Super: [],
- SwitchStatement: ['discriminant', 'cases'],
- SwitchCase: ['test', 'consequent'],
- TaggedTemplateExpression: ['tag', 'quasi'],
- TemplateElement: [],
- TemplateLiteral: ['quasis', 'expressions'],
- ThisExpression: [],
- ThrowStatement: ['argument'],
- TryStatement: ['block', 'handler', 'finalizer'],
- UnaryExpression: ['argument'],
- UpdateExpression: ['argument'],
- VariableDeclaration: ['declarations'],
- VariableDeclarator: ['id', 'init'],
- WhileStatement: ['test', 'body'],
- WithStatement: ['object', 'body'],
- YieldExpression: ['argument']
- };
-
- for (nodeType in SYNTAX) {
- /* istanbul ignore else: has own property */
- if (SYNTAX.hasOwnProperty(nodeType)) {
- SYNTAX[nodeType] = { name: nodeType, children: SYNTAX[nodeType] };
- }
- }
-
- astgen = {
- variable: function (name) { return { type: SYNTAX.Identifier.name,
name: name }; },
- stringLiteral: function (str) { return { type: SYNTAX.Literal.name,
value: String(str) }; },
- numericLiteral: function (num) { return { type: SYNTAX.Literal.name,
value: Number(num) }; },
- statement: function (contents) { return { type:
SYNTAX.ExpressionStatement.name, expression: contents }; },
- dot: function (obj, field) { return { type:
SYNTAX.MemberExpression.name, computed: false, object: obj, property: field };
},
- subscript: function (obj, sub) { return { type:
SYNTAX.MemberExpression.name, computed: true, object: obj, property: sub }; },
- postIncrement: function (obj) { return { type:
SYNTAX.UpdateExpression.name, operator: '++', prefix: false, argument: obj }; },
- sequence: function (one, two) { return { type:
SYNTAX.SequenceExpression.name, expressions: [one, two] }; },
- returnStatement: function (expr) { return { type:
SYNTAX.ReturnStatement.name, argument: expr }; }
- };
-
- function Walker(walkMap, preprocessor, scope, debug) {
- this.walkMap = walkMap;
- this.preprocessor = preprocessor;
- this.scope = scope;
- this.debug = debug;
- if (this.debug) {
- this.level = 0;
- this.seq = true;
- }
- }
-
- function defaultWalker(node, walker) {
-
- var type = node.type,
- preprocessor,
- postprocessor,
- children = SYNTAX[type],
- // don't run generated nodes thru custom walks otherwise we will
attempt to instrument the instrumentation code :)
- applyCustomWalker = !!node.loc || node.type ===
SYNTAX.Program.name,
- walkerFn = applyCustomWalker ? walker.walkMap[type] : null,
- i,
- j,
- walkFnIndex,
- childType,
- childNode,
- ret,
- childArray,
- childElement,
- pathElement,
- assignNode,
- isLast;
-
- if (!SYNTAX[type]) {
- console.error(node);
- console.error('Unsupported node type:' + type);
- return;
- }
- children = SYNTAX[type].children;
- /* istanbul ignore if: guard */
- if (node.walking) { throw new Error('Infinite regress: Custom walkers
may NOT call walker.apply(node)'); }
- node.walking = true;
-
- ret = walker.apply(node, walker.preprocessor);
-
- preprocessor = ret.preprocessor;
- if (preprocessor) {
- delete ret.preprocessor;
- ret = walker.apply(node, preprocessor);
- }
-
- if (isArray(walkerFn)) {
- for (walkFnIndex = 0; walkFnIndex < walkerFn.length; walkFnIndex
+= 1) {
- isLast = walkFnIndex === walkerFn.length - 1;
- ret = walker.apply(ret, walkerFn[walkFnIndex]);
- /*istanbul ignore next: paranoid check */
- if (ret.type !== type && !isLast) {
- throw new Error('Only the last walker is allowed to change
the node type: [type was: ' + type + ' ]');
- }
- }
- } else {
- if (walkerFn) {
- ret = walker.apply(node, walkerFn);
- }
- }
-
- if (node.skipSelf) {
- return;
- }
-
- for (i = 0; i < children.length; i += 1) {
- childType = children[i];
- childNode = node[childType];
- if (childNode && !childNode.skipWalk) {
- pathElement = { node: node, property: childType };
- if (isArray(childNode)) {
- childArray = [];
- for (j = 0; j < childNode.length; j += 1) {
- childElement = childNode[j];
- pathElement.index = j;
- if (childElement) {
- assignNode = walker.apply(childElement, null,
pathElement);
- if (isArray(assignNode.prepend)) {
- pushAll(childArray, assignNode.prepend);
- delete assignNode.prepend;
- }
- } else {
- assignNode = undefined;
- }
- pushAll(childArray, assignNode);
- }
- node[childType] = childArray;
- } else {
- assignNode = walker.apply(childNode, null, pathElement);
- /*istanbul ignore if: paranoid check */
- if (isArray(assignNode.prepend)) {
- throw new Error('Internal error: attempt to prepend
statements in disallowed (non-array) context');
- /* if this should be allowed, this is how to solve it
- tmpNode = { type: 'BlockStatement', body: [] };
- pushAll(tmpNode.body, assignNode.prepend);
- pushAll(tmpNode.body, assignNode);
- node[childType] = tmpNode;
- delete assignNode.prepend;
- */
- } else {
- node[childType] = assignNode;
- }
- }
- }
- }
-
- postprocessor = ret.postprocessor;
- if (postprocessor) {
- delete ret.postprocessor;
- ret = walker.apply(ret, postprocessor);
- }
-
- delete node.walking;
-
- return ret;
- }
-
- Walker.prototype = {
- startWalk: function (node) {
- this.path = [];
- this.apply(node);
- },
-
- apply: function (node, walkFn, pathElement) {
- var ret, i, seq, prefix;
-
- walkFn = walkFn || defaultWalker;
- if (this.debug) {
- this.seq += 1;
- this.level += 1;
- seq = this.seq;
- prefix = '';
- for (i = 0; i < this.level; i += 1) { prefix += ' '; }
- console.log(prefix + 'Enter (' + seq + '):' + node.type);
- }
- if (pathElement) { this.path.push(pathElement); }
- ret = walkFn.call(this.scope, node, this);
- if (pathElement) { this.path.pop(); }
- if (this.debug) {
- this.level -= 1;
- console.log(prefix + 'Return (' + seq + '):' + node.type);
- }
- return ret || node;
- },
-
- startLineForNode: function (node) {
- return node && node.loc && node.loc.start ? node.loc.start.line :
/* istanbul ignore next: guard */ null;
- },
-
- ancestor: function (n) {
- return this.path.length > n - 1 ? this.path[this.path.length - n]
: /* istanbul ignore next: guard */ null;
- },
-
- parent: function () {
- return this.ancestor(1);
- },
-
- isLabeled: function () {
- var el = this.parent();
- return el && el.node.type === SYNTAX.LabeledStatement.name;
- }
- };
-
- /**
- * mechanism to instrument code for coverage. It uses the `esprima` and
- * `escodegen` libraries for JS parsing and code generation respectively.
- *
- * Works on `node` as well as the browser.
- *
- * Usage on nodejs
- * ---------------
- *
- * var instrumenter = new require('istanbul').Instrumenter(),
- * changed = instrumenter.instrumentSync('function
meaningOfLife() { return 42; }', 'filename.js');
- *
- * Usage in a browser
- * ------------------
- *
- * Load `esprima.js`, `escodegen.js` and `instrumenter.js` (this file)
using `script` tags or other means.
- *
- * Create an instrumenter object as:
- *
- * var instrumenter = new Instrumenter(),
- * changed = instrumenter.instrumentSync('function
meaningOfLife() { return 42; }', 'filename.js');
- *
- * Aside from demonstration purposes, it is unclear why you would want to
instrument code in a browser.
- *
- * @class Instrumenter
- * @constructor
- * @param {Object} options Optional. Configuration options.
- * @param {String} [options.coverageVariable] the global variable name to
use for
- * tracking coverage. Defaults to `__coverage__`
- * @param {Boolean} [options.embedSource] whether to embed the source code
of every
- * file as an array in the file coverage object for that file.
Defaults to `false`
- * @param {Boolean} [options.preserveComments] whether comments should be
preserved in the output. Defaults to `false`
- * @param {Boolean} [options.noCompact] emit readable code when set.
Defaults to `false`
- * @param {Boolean} [options.esModules] whether the code to instrument
contains uses es
- * imports or exports.
- * @param {Boolean} [options.noAutoWrap] do not automatically wrap the
source in
- * an anonymous function before covering it. By default, code is
wrapped in
- * an anonymous function before it is parsed. This is done because
- * some nodejs libraries have `return` statements outside of
- * a function which is technically invalid Javascript and causes the
parser to fail.
- * This construct, however, works correctly in node since module
loading
- * is done in the context of an anonymous function.
- *
- * Note that the semantics of the code *returned* by the instrumenter does
not change in any way.
- * The function wrapper is "unwrapped" before the instrumented code is
generated.
- * @param {Object} [options.codeGenerationOptions] an object that is
directly passed to the `escodegen`
- * library as configuration for code generation. The `noCompact`
setting is not honored when this
- * option is specified
- * @param {Boolean} [options.debug] assist in debugging. Currently, the
only effect of
- * setting this option is a pretty-print of the coverage variable.
Defaults to `false`
- * @param {Boolean} [options.walkDebug] assist in debugging of the AST
walker used by this class.
- *
- */
- function Instrumenter(options) {
- this.opts = options || {
- debug: false,
- walkDebug: false,
- coverageVariable: '__coverage__',
- codeGenerationOptions: undefined,
- noAutoWrap: false,
- noCompact: false,
- embedSource: false,
- preserveComments: false,
- esModules: false
- };
-
- if (this.opts.esModules && !this.opts.noAutoWrap) {
- this.opts.noAutoWrap = true;
- if (this.opts.debug) {
- console.log('Setting noAutoWrap to true as required by
esModules');
- }
- }
-
- this.walker = new Walker({
- ArrowFunctionExpression: [ this.arrowBlockConverter ],
- ExpressionStatement: this.coverStatement,
- ExportNamedDeclaration: this.coverExport,
- BreakStatement: this.coverStatement,
- ContinueStatement: this.coverStatement,
- DebuggerStatement: this.coverStatement,
- ReturnStatement: this.coverStatement,
- ThrowStatement: this.coverStatement,
- TryStatement: [ this.paranoidHandlerCheck, this.coverStatement],
- VariableDeclaration: this.coverStatement,
- IfStatement: [ this.ifBlockConverter, this.coverStatement,
this.ifBranchInjector ],
- ForStatement: [ this.skipInit, this.loopBlockConverter,
this.coverStatement ],
- ForInStatement: [ this.skipLeft, this.loopBlockConverter,
this.coverStatement ],
- ForOfStatement: [ this.skipLeft, this.loopBlockConverter,
this.coverStatement ],
- WhileStatement: [ this.loopBlockConverter, this.coverStatement ],
- DoWhileStatement: [ this.loopBlockConverter, this.coverStatement ],
- SwitchStatement: [ this.coverStatement, this.switchBranchInjector
],
- SwitchCase: [ this.switchCaseInjector ],
- WithStatement: [ this.withBlockConverter, this.coverStatement ],
- FunctionDeclaration: [ this.coverFunction, this.coverStatement ],
- FunctionExpression: this.coverFunction,
- LabeledStatement: this.coverStatement,
- ConditionalExpression: this.conditionalBranchInjector,
- LogicalExpression: this.logicalExpressionBranchInjector,
- ObjectExpression: this.maybeAddType,
- MetaProperty: this.coverMetaProperty,
- }, this.extractCurrentHint, this, this.opts.walkDebug);
-
- //unit testing purposes only
- if (this.opts.backdoor && this.opts.backdoor.omitTrackerSuffix) {
- this.omitTrackerSuffix = true;
- }
- }
-
- Instrumenter.prototype = {
- /**
- * synchronous instrumentation method. Throws when illegal code is
passed to it
- * @method instrumentSync
- * @param {String} code the code to be instrumented as a String
- * @param {String} filename Optional. The name of the file from which
- * the code was read. A temporary filename is generated when not
specified.
- * Not specifying a filename is only useful for unit tests and
demonstrations
- * of this library.
- */
- instrumentSync: function (code, filename) {
- var program;
-
- //protect from users accidentally passing in a Buffer object
instead
- if (typeof code !== 'string') { throw new Error('Code must be
string'); }
- if (code.charAt(0) === '#') { //shebang, 'comment' it out, won't
affect syntax tree locations for things we care about
- code = '//' + code;
- }
- if (!this.opts.noAutoWrap) {
- code = LEADER_WRAP + code + TRAILER_WRAP;
- }
- try {
- program = ESP.parse(code, {
- loc: true,
- range: true,
- tokens: this.opts.preserveComments,
- comment: true,
- sourceType: this.opts.esModules ? 'module' : 'script'
- });
- } catch (e) {
- console.log('Failed to parse file: ' + filename);
- throw e;
- }
- if (this.opts.preserveComments) {
- program = ESPGEN.attachComments(program, program.comments,
program.tokens);
- }
- if (!this.opts.noAutoWrap) {
- program = {
- type: SYNTAX.Program.name,
- body: program.body[0].expression.callee.body.body,
- comments: program.comments
- };
- }
- return this.instrumentASTSync(program, filename, code);
- },
- filterHints: function (comments) {
- var ret = [],
- i,
- comment,
- groups;
- if (!(comments && isArray(comments))) {
- return ret;
- }
- for (i = 0; i < comments.length; i += 1) {
- comment = comments[i];
- /* istanbul ignore else: paranoid check */
- if (comment && comment.value && comment.range &&
isArray(comment.range)) {
- groups = String(comment.value).match(COMMENT_RE);
- if (groups) {
- ret.push({ type: groups[1], start: comment.range[0],
end: comment.range[1] });
- }
- }
- }
- return ret;
- },
- extractCurrentHint: function (node) {
- if (!node.range) { return; }
- var i = this.currentState.lastHintPosition + 1,
- hints = this.currentState.hints,
- nodeStart = node.range[0],
- hint;
- this.currentState.currentHint = null;
- while (i < hints.length) {
- hint = hints[i];
- if (hint.end < nodeStart) {
- this.currentState.currentHint = hint;
- this.currentState.lastHintPosition = i;
- i += 1;
- } else {
- break;
- }
- }
- },
- /**
- * synchronous instrumentation method that instruments an AST instead.
- * @method instrumentASTSync
- * @param {String} program the AST to be instrumented
- * @param {String} filename Optional. The name of the file from which
- * the code was read. A temporary filename is generated when not
specified.
- * Not specifying a filename is only useful for unit tests and
demonstrations
- * of this library.
- * @param {String} originalCode the original code corresponding to
the AST,
- * used for embedding the source into the coverage object
- */
- instrumentASTSync: function (program, filename, originalCode) {
- var usingStrict = false,
- codegenOptions,
- generated,
- preamble,
- lineCount,
- i;
- filename = filename || String(new Date().getTime()) + '.js';
- this.sourceMap = null;
- this.coverState = {
- path: filename,
- s: {},
- b: {},
- f: {},
- fnMap: {},
- statementMap: {},
- branchMap: {}
- };
- this.currentState = {
- trackerVar: generateTrackerVar(filename,
this.omitTrackerSuffix),
- func: 0,
- branch: 0,
- variable: 0,
- statement: 0,
- hints: this.filterHints(program.comments),
- currentHint: null,
- lastHintPosition: -1,
- ignoring: 0
- };
- if (program.body && program.body.length > 0 &&
this.isUseStrictExpression(program.body[0])) {
- //nuke it
- program.body.shift();
- //and add it back at code generation time
- usingStrict = true;
- }
- this.walker.startWalk(program);
- codegenOptions = this.opts.codeGenerationOptions || { format: {
compact: !this.opts.noCompact }};
- codegenOptions.comment = this.opts.preserveComments;
- //console.log(JSON.stringify(program, undefined, 2));
-
- generated = ESPGEN.generate(program, codegenOptions);
- preamble = this.getPreamble(originalCode || '', usingStrict);
-
- if (generated.map && generated.code) {
- lineCount = preamble.split(/\r\n|\r|\n/).length;
- // offset all the generated line numbers by the number of
lines in the preamble
- for (i = 0; i < generated.map._mappings._array.length; i += 1)
{
- generated.map._mappings._array[i].generatedLine +=
lineCount;
- }
- this.sourceMap = generated.map;
- generated = generated.code;
- }
-
- return preamble + '\n' + generated + '\n';
- },
- /**
- * Callback based instrumentation. Note that this still executes
synchronously in the same process tick
- * and calls back immediately. It only provides the options for
callback style error handling as
- * opposed to a `try-catch` style and nothing more. Implemented as a
wrapper over `instrumentSync`
- *
- * @method instrument
- * @param {String} code the code to be instrumented as a String
- * @param {String} filename Optional. The name of the file from which
- * the code was read. A temporary filename is generated when not
specified.
- * Not specifying a filename is only useful for unit tests and
demonstrations
- * of this library.
- * @param {Function(err, instrumentedCode)} callback - the callback
function
- */
- instrument: function (code, filename, callback) {
-
- if (!callback && typeof filename === 'function') {
- callback = filename;
- filename = null;
- }
- try {
- callback(null, this.instrumentSync(code, filename));
- } catch (ex) {
- callback(ex);
- }
- },
- /**
- * returns the file coverage object for the code that was instrumented
- * just before calling this method. Note that this represents a
- * "zero-coverage" object which is not even representative of the code
- * being loaded in node or a browser (which would increase the
statement
- * counts for mainline code).
- * @method lastFileCoverage
- * @return {Object} a "zero-coverage" file coverage object for the
code last instrumented
- * by this instrumenter
- */
- lastFileCoverage: function () {
- return this.coverState;
- },
- /**
- * returns the source map object for the code that was instrumented
- * just before calling this method.
- * @method lastSourceMap
- * @return {Object} a source map object for the code last instrumented
- * by this instrumenter
- */
- lastSourceMap: function () {
- return this.sourceMap;
- },
- fixColumnPositions: function (coverState) {
- var offset = LEADER_WRAP.length,
- fixer = function (loc) {
- if (loc.start.line === 1) {
- loc.start.column -= offset;
- }
- if (loc.end.line === 1) {
- loc.end.column -= offset;
- }
- },
- k,
- obj,
- i,
- locations;
-
- obj = coverState.statementMap;
- for (k in obj) {
- /* istanbul ignore else: has own property */
- if (obj.hasOwnProperty(k)) { fixer(obj[k]); }
- }
- obj = coverState.fnMap;
- for (k in obj) {
- /* istanbul ignore else: has own property */
- if (obj.hasOwnProperty(k)) { fixer(obj[k].loc); }
- }
- obj = coverState.branchMap;
- for (k in obj) {
- /* istanbul ignore else: has own property */
- if (obj.hasOwnProperty(k)) {
- locations = obj[k].locations;
- for (i = 0; i < locations.length; i += 1) {
- fixer(locations[i]);
- }
- }
- }
- },
-
- getPreamble: function (sourceCode, emitUseStrict) {
- var varName = this.opts.coverageVariable || '__coverage__',
- file = this.coverState.path.replace(/\\/g, '\\\\'),
- tracker = this.currentState.trackerVar,
- coverState,
- strictLine = emitUseStrict ? '"use strict";' : '',
- // return replacements using the function to ensure that the
replacement is
- // treated like a dumb string and not as a string with RE
replacement patterns
- replacer = function (s) {
- return function () { return s; };
- },
- code;
- if (!this.opts.noAutoWrap) {
- this.fixColumnPositions(this.coverState);
- }
- if (this.opts.embedSource) {
- this.coverState.code = sourceCode.split(/(?:\r?\n)|\r/);
- }
- coverState = this.opts.debug ? JSON.stringify(this.coverState,
undefined, 4) : JSON.stringify(this.coverState);
- code = [
- "%STRICT%",
- "var %VAR% = (Function('return this'))();",
- "if (!%VAR%.%GLOBAL%) { %VAR%.%GLOBAL% = {}; }",
- "%VAR% = %VAR%.%GLOBAL%;",
- "if (!(%VAR%['%FILE%'])) {",
- " %VAR%['%FILE%'] = %OBJECT%;",
- "}",
- "%VAR% = %VAR%['%FILE%'];"
- ].join("\n")
- .replace(/%STRICT%/g, replacer(strictLine))
- .replace(/%VAR%/g, replacer(tracker))
- .replace(/%GLOBAL%/g, replacer(varName))
- .replace(/%FILE%/g, replacer(file))
- .replace(/%OBJECT%/g, replacer(coverState));
- return code;
- },
-
- startIgnore: function () {
- this.currentState.ignoring += 1;
- },
-
- endIgnore: function () {
- this.currentState.ignoring -= 1;
- },
-
- convertToBlock: function (node) {
- if (!node) {
- return { type: 'BlockStatement', body: [] };
- } else if (node.type === 'BlockStatement') {
- return node;
- } else {
- return { type: 'BlockStatement', body: [ node ] };
- }
- },
-
- arrowBlockConverter: function (node) {
- var retStatement;
- if (node.expression) { // turn expression nodes into a block with
a return statement
- retStatement = astgen.returnStatement(node.body);
- // ensure the generated return statement is covered
- retStatement.loc = node.body.loc;
- node.body = this.convertToBlock(retStatement);
- node.expression = false;
- }
- },
-
- paranoidHandlerCheck: function (node) {
- // if someone is using an older esprima on the browser
- // convert handlers array to single handler attribute
- // containing its first element
- /* istanbul ignore next */
- if (!node.handler && node.handlers) {
- node.handler = node.handlers[0];
- }
- },
-
- ifBlockConverter: function (node) {
- node.consequent = this.convertToBlock(node.consequent);
- node.alternate = this.convertToBlock(node.alternate);
- },
-
- loopBlockConverter: function (node) {
- node.body = this.convertToBlock(node.body);
- },
-
- withBlockConverter: function (node) {
- node.body = this.convertToBlock(node.body);
- },
-
- statementName: function (location, initValue) {
- var sName,
- ignoring = !!this.currentState.ignoring;
-
- location.skip = ignoring || undefined;
- initValue = initValue || 0;
- this.currentState.statement += 1;
- sName = this.currentState.statement;
- this.coverState.statementMap[sName] = location;
- this.coverState.s[sName] = initValue;
- return sName;
- },
-
- skipInit: function (node /*, walker */) {
- if (node.init) {
- node.init.skipWalk = true;
- }
- },
-
- skipLeft: function (node /*, walker */) {
- node.left.skipWalk = true;
- },
-
- isUseStrictExpression: function (node) {
- return node && node.type === SYNTAX.ExpressionStatement.name &&
- node.expression && node.expression.type ===
SYNTAX.Literal.name &&
- node.expression.value === 'use strict';
- },
-
- maybeSkipNode: function (node, type) {
- var alreadyIgnoring = !!this.currentState.ignoring,
- hint = this.currentState.currentHint,
- ignoreThis = !alreadyIgnoring && hint && hint.type === type;
-
- if (ignoreThis) {
- this.startIgnore();
- node.postprocessor = this.endIgnore;
- return true;
- }
- return false;
- },
-
- coverMetaProperty: function(node /* , walker */) {
- node.skipSelf = true;
- },
-
- coverStatement: function (node, walker) {
- var sName,
- incrStatementCount,
- parent,
- grandParent;
-
- this.maybeSkipNode(node, 'next');
-
- if (this.isUseStrictExpression(node)) {
- grandParent = walker.ancestor(2);
- /* istanbul ignore else: difficult to test */
- if (grandParent) {
- if ((grandParent.node.type ===
SYNTAX.FunctionExpression.name ||
- grandParent.node.type ===
SYNTAX.FunctionDeclaration.name) &&
- walker.parent().node.body[0] === node) {
- return;
- }
- }
- }
-
- if (node.type === SYNTAX.FunctionDeclaration.name) {
- // Called for the side-effect of setting the function's
statement count to 1.
- this.statementName(node.loc, 1);
- } else {
- // We let `coverExport` handle ExportNamedDeclarations.
- parent = walker.parent();
- if (parent && parent.node.type ===
SYNTAX.ExportNamedDeclaration.name) {
- return;
- }
-
- sName = this.statementName(node.loc);
-
- incrStatementCount = astgen.statement(
- astgen.postIncrement(
- astgen.subscript(
-
astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('s')),
- astgen.stringLiteral(sName)
- )
- )
- );
-
- this.splice(incrStatementCount, node, walker);
- }
- },
-
- coverExport: function (node, walker) {
- var sName, incrStatementCount;
-
- if ( !node.declaration || !node.declaration.declarations ) {
return; }
-
- this.maybeSkipNode(node, 'next');
-
- sName = this.statementName(node.declaration.loc);
- incrStatementCount = astgen.statement(
- astgen.postIncrement(
- astgen.subscript(
-
astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('s')),
- astgen.stringLiteral(sName)
- )
- )
- );
-
- this.splice(incrStatementCount, node, walker);
- },
-
- splice: function (statements, node, walker) {
- var targetNode = walker.isLabeled() ? walker.parent().node : node;
- targetNode.prepend = targetNode.prepend || [];
- pushAll(targetNode.prepend, statements);
- },
-
- functionName: function (node, line, location) {
- this.currentState.func += 1;
- var id = this.currentState.func,
- ignoring = !!this.currentState.ignoring,
- name = node.id ? node.id.name : '(anonymous_' + id + ')',
- clone = function (attr) {
- var obj = location[attr] || /* istanbul ignore next */ {};
- return { line: obj.line, column: obj.column };
- };
- this.coverState.fnMap[id] = {
- name: name, line: line,
- loc: {
- start: clone('start'),
- end: clone('end')
- },
- skip: ignoring || undefined
- };
- this.coverState.f[id] = 0;
- return id;
- },
-
- coverFunction: function (node, walker) {
- var id,
- body = node.body,
- blockBody = body.body,
- popped;
-
- this.maybeSkipNode(node, 'next');
-
- id = this.functionName(node, walker.startLineForNode(node), {
- start: node.loc.start,
- end: { line: node.body.loc.start.line, column:
node.body.loc.start.column }
- });
-
- if (blockBody.length > 0 &&
this.isUseStrictExpression(blockBody[0])) {
- popped = blockBody.shift();
- }
- blockBody.unshift(
- astgen.statement(
- astgen.postIncrement(
- astgen.subscript(
-
astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('f')),
- astgen.stringLiteral(id)
- )
- )
- )
- );
- if (popped) {
- blockBody.unshift(popped);
- }
- },
-
- branchName: function (type, startLine, pathLocations) {
- var bName,
- paths = [],
- locations = [],
- i,
- ignoring = !!this.currentState.ignoring;
- this.currentState.branch += 1;
- bName = this.currentState.branch;
- for (i = 0; i < pathLocations.length; i += 1) {
- pathLocations[i].skip = pathLocations[i].skip || ignoring ||
undefined;
- locations.push(pathLocations[i]);
- paths.push(0);
- }
- this.coverState.b[bName] = paths;
- this.coverState.branchMap[bName] = { line: startLine, type: type,
locations: locations };
- return bName;
- },
-
- branchIncrementExprAst: function (varName, branchIndex, down) {
- var ret = astgen.postIncrement(
- astgen.subscript(
- astgen.subscript(
-
astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('b')),
- astgen.stringLiteral(varName)
- ),
- astgen.numericLiteral(branchIndex)
- ),
- down
- );
- return ret;
- },
-
- locationsForNodes: function (nodes) {
- var ret = [],
- i;
- for (i = 0; i < nodes.length; i += 1) {
- ret.push(nodes[i].loc);
- }
- return ret;
- },
-
- ifBranchInjector: function (node, walker) {
- var alreadyIgnoring = !!this.currentState.ignoring,
- hint = this.currentState.currentHint,
- ignoreThen = !alreadyIgnoring && hint && hint.type === 'if',
- ignoreElse = !alreadyIgnoring && hint && hint.type === 'else',
- line = node.loc.start.line,
- col = node.loc.start.column,
- makeLoc = function () { return { line: line, column: col }; },
- bName = this.branchName('if', walker.startLineForNode(node), [
- { start: makeLoc(), end: makeLoc(), skip: ignoreThen ||
undefined },
- { start: makeLoc(), end: makeLoc(), skip: ignoreElse ||
undefined }
- ]),
- thenBody = node.consequent.body,
- elseBody = node.alternate.body,
- child;
-
thenBody.unshift(astgen.statement(this.branchIncrementExprAst(bName, 0)));
-
elseBody.unshift(astgen.statement(this.branchIncrementExprAst(bName, 1)));
- if (ignoreThen) { child = node.consequent; child.preprocessor =
this.startIgnore; child.postprocessor = this.endIgnore; }
- if (ignoreElse) { child = node.alternate; child.preprocessor =
this.startIgnore; child.postprocessor = this.endIgnore; }
- },
-
- branchLocationFor: function (name, index) {
- return this.coverState.branchMap[name].locations[index];
- },
-
- switchBranchInjector: function (node, walker) {
- var cases = node.cases,
- bName,
- i;
-
- if (!(cases && cases.length > 0)) {
- return;
- }
- bName = this.branchName('switch', walker.startLineForNode(node),
this.locationsForNodes(cases));
- for (i = 0; i < cases.length; i += 1) {
- cases[i].branchLocation = this.branchLocationFor(bName, i);
-
cases[i].consequent.unshift(astgen.statement(this.branchIncrementExprAst(bName,
i)));
- }
- },
-
- switchCaseInjector: function (node) {
- var location = node.branchLocation;
- delete node.branchLocation;
- if (this.maybeSkipNode(node, 'next')) {
- location.skip = true;
- }
- },
-
- conditionalBranchInjector: function (node, walker) {
- var bName = this.branchName('cond-expr',
walker.startLineForNode(node), this.locationsForNodes([ node.consequent,
node.alternate ])),
- ast1 = this.branchIncrementExprAst(bName, 0),
- ast2 = this.branchIncrementExprAst(bName, 1);
-
- node.consequent.preprocessor =
this.maybeAddSkip(this.branchLocationFor(bName, 0));
- node.alternate.preprocessor =
this.maybeAddSkip(this.branchLocationFor(bName, 1));
- node.consequent = astgen.sequence(ast1, node.consequent);
- node.alternate = astgen.sequence(ast2, node.alternate);
- },
-
- maybeAddSkip: function (branchLocation) {
- return function (node) {
- var alreadyIgnoring = !!this.currentState.ignoring,
- hint = this.currentState.currentHint,
- ignoreThis = !alreadyIgnoring && hint && hint.type ===
'next';
- if (ignoreThis) {
- this.startIgnore();
- node.postprocessor = this.endIgnore;
- }
- if (ignoreThis || alreadyIgnoring) {
- branchLocation.skip = true;
- }
- };
- },
-
- logicalExpressionBranchInjector: function (node, walker) {
- var parent = walker.parent(),
- leaves = [],
- bName,
- tuple,
- i;
-
- this.maybeSkipNode(node, 'next');
-
- if (parent && parent.node.type === SYNTAX.LogicalExpression.name) {
- //already covered
- return;
- }
-
- this.findLeaves(node, leaves);
- bName = this.branchName('binary-expr',
- walker.startLineForNode(node),
- this.locationsForNodes(leaves.map(function (item) { return
item.node; }))
- );
- for (i = 0; i < leaves.length; i += 1) {
- tuple = leaves[i];
- tuple.parent[tuple.property] =
astgen.sequence(this.branchIncrementExprAst(bName, i), tuple.node);
- tuple.node.preprocessor =
this.maybeAddSkip(this.branchLocationFor(bName, i));
- }
- },
-
- findLeaves: function (node, accumulator, parent, property) {
- if (node.type === SYNTAX.LogicalExpression.name) {
- this.findLeaves(node.left, accumulator, node, 'left');
- this.findLeaves(node.right, accumulator, node, 'right');
- } else {
- accumulator.push({ node: node, parent: parent, property:
property });
- }
- },
- maybeAddType: function (node /*, walker */) {
- var props = node.properties,
- i,
- child;
- for (i = 0; i < props.length; i += 1) {
- child = props[i];
- if (!child.type) {
- child.type = SYNTAX.Property.name;
- }
- }
- },
- };
-
- if (isNode) {
- module.exports = Instrumenter;
- } else {
- window.Instrumenter = Instrumenter;
- }
-
-}(typeof module !== 'undefined' && typeof module.exports !== 'undefined' &&
typeof exports !== 'undefined'));
diff --git a/node_modules/talertest/selenium/runtime.js
b/node_modules/talertest/selenium/runtime.js
deleted file mode 100644
index e0067117..00000000
--- a/node_modules/talertest/selenium/runtime.js
+++ /dev/null
@@ -1,206 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 Inria
-
- TALER is free software; you can redistribute it and/or modify it under the
- terms of the GNU General Public License as published by the Free Software
- Foundation; either version 3, or (at your option) any later version.
-
- TALER is distributed in the hope that it will be useful, but WITHOUT ANY
- WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
- A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License along with
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- *
- * @author Florian Dold
- */
-
-"use strict";
-
-var webdriver = require('selenium-webdriver');
-var chrome = require('selenium-webdriver/chrome');
-var path = require("path");
-var process = require("process");
-var fs = require("fs");
-var globSync = require("glob").sync;
-
-var connect = require('connect');
-var serveStatic = require('serve-static');
-
-// Port of the web server used to serve the test files
-var httpPort = 8080;
-
-var p = `http://localhost:${httpPort}/testlib/selenium/testhost.html`;
-
-var argv = require('minimist')(process.argv.slice(2), {"boolean":
["keep-open", "coverage"]});
-
-function printUsage() {
- console.log(`Usage: [--keep-open] TESTSCRIPT`);
-}
-
-function randId(n) {
- let s = "";
- var choices =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
-
- for (let i = 0; i < n; i++) {
- s += choices.charAt(Math.floor(Math.random() * choices.length));
- }
-
- return s;
-}
-
-if (argv._.length != 1) {
- console.log("exactly one test script must be given");
- printUsage();
- process.exit(1);
-}
-
-var testScriptName = path.resolve(argv._[0]);
-var testName = path.basename(testScriptName, ".js");
-var projectRoot = path.resolve(__dirname, "../../") + "/";
-if (!testScriptName.startsWith(projectRoot)) {
- console.log("test file must be inside wallet project root");
- process.exit(1);
-}
-
-var testScript = testScriptName.substring(projectRoot.length);
-
-try {
- var stats = fs.lstatSync(path.resolve(projectRoot, "./" + testScript));
- if (!stats.isFile()) {
- throw Error("test must be a file");
- }
-} catch (e) {
- console.log("can't execute test");
- console.log(e);
- process.exit(e);
-}
-
-
-var script = `
- function onStatus(s) {
- document.body.appendChild(document.createTextNode(s));
- document.body.appendChild(document.createElement("br"));
- }
- function f() {
- if ("undefined" == typeof System) {
- console.log("can't access module loader");
- return
- }
- System.import("testlib/talertest")
- .then(tt => {
- SystemJS.import("http://localhost:${httpPort}/${testScript}")
- .then(() => {
- return tt.run(onStatus);
- })
- .then(() => {
- window.__test_over = true;
- })
- .catch((e) => {
- window.__test_over = true;
- });
- })
- .catch((e) => {
- console.error("can't locate talertest");
- console.error(e);
- });
- }
- if (document.readyState == "complete") {
- f();
- } else {
- document.addEventListener("DOMContentLoaded", f);
- }
-`;
-
-function untilTestOver() {
- return driver.executeScript("return window.__test_over");
-}
-
-console.log("TAP version 13");
-
-let srv = connect().use(serveStatic(__dirname + "/../../"));
-let l = srv.listen(8080);
-
-var driver = new webdriver.Builder()
- .setLoggingPrefs({browser: 'ALL'})
- .forBrowser('chrome')
- .build();
-
-driver.get(p);
-if (argv["coverage"]) {
- driver.executeScript("window.requestCoverage = true;");
-}
-driver.executeScript(script);
-driver.wait(untilTestOver);
-
-
-/**
- * Instrument and get a coverage stub for all
- * files we don't have coverage for, so they show
- * up in the report.
- */
-function augmentCoverage(cov) {
- for (let file of globSync(projectRoot + "/src/**/*.js")) {
- let suffix = file.substring(0, projectRoot.lenth);
- if (/.*\/vendor\/.*/.test(suffix)) {
- continue;
- }
- if (/.*\/taler-emscripten-lib.js/.test(suffix)) {
- continue;
- }
- if (file in cov) {
- continue;
- }
- let instrumenter = new (require("istanbul").Instrumenter)();
- let source = fs.readFileSync(file, "utf-8");
- let instrumentedSrc = instrumenter.instrumentSync(source, file);
- let covStubRE = /\{.*"path".*"fnMap".*"statementMap".*"branchMap".*\}/g;
- let covStubMatch = covStubRE.exec(instrumentedSrc);
-
- if (covStubMatch !== null) {
- let covStub = JSON.parse(covStubMatch[0]);
- cov[file] = covStub;
- }
- }
-}
-
-
-driver.manage().logs().get("browser").then((logs) => {
- for (let l of logs) {
- if (l.message.startsWith("{")) {
- // format not understood, sometimes messages are logged
- // with more structure, just pass it on
- console.log(l.message);
- continue;
- }
- let s1 = l.message.indexOf(" ") + 1;
- let s2 = l.message.indexOf(" ", s1) + 1;
- // Skip file url and LINE:COL
- console.log(l.message.substring(s2));
- }
-
- let coverage = driver.executeScript("return
JSON.stringify(window.__coverage__);");
- coverage.then((covStr) => {
- let cov = JSON.parse(covStr);
- if (cov) {
- let covTranslated = {};
- for (let f in cov) {
- let p = path.resolve(projectRoot, f);
- let c = covTranslated[p] = cov[f];
- c.path = p;
- }
- augmentCoverage(covTranslated);
- fs.writeFileSync(`coverage-${testName}-${randId(5)}.json`,
JSON.stringify(covTranslated));
- }
- if (!argv["keep-open"]) {
- driver.quit();
- l.close();
- }
- })
-
-});
-
diff --git a/node_modules/talertest/selenium/system.js
b/node_modules/talertest/selenium/system.js
deleted file mode 100644
index 1b7c1f82..00000000
--- a/node_modules/talertest/selenium/system.js
+++ /dev/null
@@ -1,6 +0,0 @@
-/*
- * SystemJS v0.19.41
- */
-!function(){function e(){!function(e){function t(e,r){if("string"!=typeof
e)throw new TypeError("URL must be a string");var
n=String(e).replace(/^\s+|\s+$/g,"").match(/^([^:\/?#]+:)?(?:\/\/(?:([^:@\/?#]*)(?::([^:@\/?#]*))?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);if(!n)throw
new RangeError("Invalid URL format");var
a=n[1]||"",o=n[2]||"",i=n[3]||"",s=n[4]||"",l=n[5]||"",u=n[6]||"",d=n[7]||"",c=n[8]||"",f=n[9]||"";if(void
0!==r){var m=r instanceof t?r:new t(r),p=!a&&!s&& [...]
-if(!v)return h+(p?".js":"");var b=h.substr(v.length+1);return
r(s,s.packages[v]||{},v,b,i)}}),i("normalize",function(t){return
function(r,n,a){var o=this;return
a=a===!0,Promise.resolve().then(function(){if(n)var
t=e(o,n)||o.defaultJSExtensions&&".js"==n.substr(n.length-3,3)&&e(o,n.substr(0,n.length-3));var
i=t&&o.packages[t];if(i&&"./"!=r.substr(0,2)){var
s=i.map,l=s&&S(s,r);if(l)return d(o,i,t,l,r,a)}return
Promise.resolve()}).then(function(i){if(i)return i;var s=o.defaultJSExtensions&
[...]
-//# sourceMappingURL=system.js.map
diff --git a/node_modules/talertest/selenium/testhost.html
b/node_modules/talertest/selenium/testhost.html
deleted file mode 100644
index 01641547..00000000
--- a/node_modules/talertest/selenium/testhost.html
+++ /dev/null
@@ -1,63 +0,0 @@
-<!doctype html>
-<html>
- <head>
- <title>Browser Test Host</title>
-
- <script src="/testlib/selenium/esprima.js"></script>
- <script src="/testlib/selenium/escodegen.browser.js"></script>
- <script src="/testlib/selenium/instrumenter.js"></script>
-
- <script src="/src/vendor/URI.js"></script>
-
- <!-- for instrumentation to work, we have to use the non-csp version -->
- <script src="/testlib/selenium/system.js"></script>
-
- </head>
- <body>
- <script>
- document.body.appendChild(document.createTextNode(`starting test`));
- document.body.appendChild(document.createElement("br"));
-
- var requestCoverage = false;
-
- let parser = document.createElement('a');
-
- let oldTranslate = System.translate.bind(System);
- System.translate = (load) => {
- let srcP = oldTranslate(load);
- if (!requestCoverage) {
- return srcP;
- }
-
- parser.href = load.name;
- let modName = parser.pathname.substring(1);
-
- if (/.*\/?taler-emscripten-lib.js/.test(load.name)) {
- // don't instrument emscripten
- document.body.appendChild(document.createTextNode(`not instrumenting
${modName}`));
- document.body.appendChild(document.createElement("br"));
- return srcP;
- }
-
- let inst = new Instrumenter();
- document.body.appendChild(document.createTextNode(`instrumenting
${modName}`));
- document.body.appendChild(document.createElement("br"));
-
- return Promise.resolve(srcP).then((src) => {
- return inst.instrumentSync(src, modName);
- });
- }
-
- System.config({
- baseURL: "/",
- defaultJSExtensions: true,
- meta: {
- "src/emscripten/taler-emscripten-lib": {
- format: "global",
- exports: "Module",
- },
- },
- });
- </script>
- </body>
-</html>
diff --git a/node_modules/talertest/talertest.d.ts
b/node_modules/talertest/talertest.d.ts
deleted file mode 100644
index 599b8b60..00000000
--- a/node_modules/talertest/talertest.d.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-/**
- *
- * @author Florian Dold
- */
-export declare type TestFn = (t: TestLib) => void | Promise<void>;
-export interface TestLib {
- pass(msg?: string): void;
- fail(msg?: string): void;
- assert(v: any, msg?: string): void;
- assertEqualsStrict(v1: any, v2: any, msg?: string): void;
-}
-/**
- * Register a test case.
- */
-export declare function test(name: string, testFn: TestFn): void;
-/**
- * Run all registered test case, producing a TAP stream.
- */
-export declare function run(statusCallback?: (m: string) => void):
Promise<void>;
diff --git a/node_modules/talertest/talertest.js
b/node_modules/talertest/talertest.js
deleted file mode 100644
index 9f7d63a0..00000000
--- a/node_modules/talertest/talertest.js
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 Inria
-
- TALER is free software; you can redistribute it and/or modify it under the
- terms of the GNU General Public License as published by the Free Software
- Foundation; either version 3, or (at your option) any later version.
-
- TALER is distributed in the hope that it will be useful, but WITHOUT ANY
- WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
- A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License along with
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-"use strict";
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P,
generator) {
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch
(e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); }
catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : new
P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-let tests = [];
-let testRunner;
-/**
- * Register a test case.
- */
-function test(name, testFn) {
- tests.push({ name, testFn });
-}
-exports.test = test;
-/**
- * Run all registered test case, producing a TAP stream.
- */
-function run(statusCallback) {
- return __awaiter(this, void 0, void 0, function* () {
- console.log(`1..${tests.length}`);
- for (let i in tests) {
- let t = tests[i];
- let passed = false;
- let lastMsg = undefined;
- let p = new Promise((resolve, reject) => {
- let pass = (msg) => {
- if (passed) {
- let e = Error("test passed twice");
- reject(e);
- throw e;
- }
- passed = true;
- lastMsg = msg;
- resolve();
- };
- let fail = (msg) => {
- lastMsg = msg;
- let e = Error("test failed");
- reject(e);
- throw e;
- };
- let assert = (v, msg) => {
- if (!v) {
- lastMsg = msg;
- reject(Error("test failed"));
- return;
- }
- };
- let assertEqualsStrict = (v1, v2, msg) => {
- if (v1 !== v2) {
- console.log(`# expected: ${v1}`);
- console.log(`# actual: ${v2}`);
- lastMsg = msg;
- let e = Error("test failed");
- reject(e);
- throw e;
- }
- };
- // Test might return a promise. If so, wait for it.
- let r = t.testFn({ pass, fail, assert, assertEqualsStrict });
- if (r) {
- r.then(() => pass(), (e) => fail(e.toString()));
- }
- });
- console.log(`# ${t.name}`);
- statusCallback && statusCallback(`starting test ${t.name}`);
- if (!lastMsg) {
- lastMsg = "-";
- }
- try {
- yield p;
- if (!passed) {
- throw Error("test did not call 'pass'");
- }
- console.log(`ok ${Number(i) + 1} ${lastMsg || "-"}`);
- statusCallback && statusCallback(`finished test ${t.name}`);
- }
- catch (e) {
- try {
- console.error(e.stack);
- }
- catch (e2) {
- console.error(e);
- }
- console.log(`not ok ${Number(i) + 1} ${lastMsg || "-"}`);
- statusCallback && statusCallback(`failed test ${t.name}`);
- }
- }
- });
-}
-exports.run = run;
diff --git a/node_modules/talertest/talertest.ts
b/node_modules/talertest/talertest.ts
deleted file mode 100644
index 5e561981..00000000
--- a/node_modules/talertest/talertest.ts
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 Inria
-
- TALER is free software; you can redistribute it and/or modify it under the
- terms of the GNU General Public License as published by the Free Software
- Foundation; either version 3, or (at your option) any later version.
-
- TALER is distributed in the hope that it will be useful, but WITHOUT ANY
- WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
- A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License along with
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- *
- * @author Florian Dold
- */
-
-export type TestFn = (t: TestLib) => void | Promise<void>;
-
-interface Test {
- name: string;
- testFn: TestFn;
-}
-
-export interface TestLib {
- pass(msg?: string): void;
- fail(msg?: string): void;
- assert(v: any, msg?: string): void;
- assertEqualsStrict(v1: any, v2: any, msg?: string): void;
-}
-
-let tests: Test[] = [];
-let testRunner: any;
-
-
-/**
- * Register a test case.
- */
-export function test(name: string, testFn: TestFn) {
- tests.push({name, testFn});
-}
-
-
-/**
- * Run all registered test case, producing a TAP stream.
- */
-export async function run(statusCallback?: (m: string) => void) {
- console.log(`1..${tests.length}`);
- for (let i in tests) {
- let t = tests[i];
- let passed = false;
- let lastMsg: string|undefined = undefined;
- let p = new Promise((resolve, reject) => {
- let pass = (msg?: string) => {
- if (passed) {
- let e = Error("test passed twice");
- reject(e);
- throw e;
- }
- passed = true;
- lastMsg = msg;
- resolve();
- };
- let fail = (msg?: string) => {
- lastMsg = msg;
- let e = Error("test failed");
- reject(e);
- throw e;
- };
- let assert = (v: any, msg?: string) => {
- if (!v) {
- lastMsg = msg;
- reject(Error("test failed"));
- return;
- }
- };
- let assertEqualsStrict = (v1: any, v2: any, msg?: string) => {
- if (v1 !== v2) {
- console.log(`# expected: ${v1}`);
- console.log(`# actual: ${v2}`);
- lastMsg = msg;
- let e = Error("test failed");
- reject(e);
- throw e;
- }
- };
- // Test might return a promise. If so, wait for it.
- let r = t.testFn({pass,fail, assert, assertEqualsStrict});
- if (r) {
- r.then(() => pass(), (e) => fail(e.toString()));
- }
- });
-
- console.log(`# ${t.name}`);
- statusCallback && statusCallback(`starting test ${t.name}`);
-
- if (!lastMsg) {
- lastMsg = "-";
- }
-
- try {
- await p;
- if (!passed) {
- throw Error("test did not call 'pass'");
- }
- console.log(`ok ${Number(i) + 1} ${lastMsg || "-"}`);
- statusCallback && statusCallback(`finished test ${t.name}`);
- } catch (e) {
- try {
- console.error(e.stack);
- } catch (e2) {
- console.error(e);
- }
- console.log(`not ok ${Number(i) + 1} ${lastMsg || "-"}`);
- statusCallback && statusCallback(`failed test ${t.name}`);
- }
- }
-}
diff --git a/node_modules/talertest/tsconfig.json
b/node_modules/talertest/tsconfig.json
deleted file mode 100644
index 1f668701..00000000
--- a/node_modules/talertest/tsconfig.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "compilerOptions": {
- "target": "es6",
- "module": "commonjs",
- "lib": [
- "ES6",
- "DOM"
- ],
- "noImplicitReturns": true,
- "noFallthroughCasesInSwitch": true,
- "strictNullChecks": true,
- "noImplicitAny": true,
- "declaration": true,
- "alwaysStrict": true
- },
- "files": [
- "talertest.ts"
- ]
-}
diff --git a/node_modules/talertest/yarn.lock b/node_modules/talertest/yarn.lock
deleted file mode 100644
index 0be90c94..00000000
--- a/node_modules/talertest/yarn.lock
+++ /dev/null
@@ -1,7 +0,0 @@
-# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
-# yarn lockfile v1
-
-
address@hidden:
- version "2.2.2"
- resolved
"https://registry.yarnpkg.com/typescript/-/typescript-2.2.2.tgz#606022508479b55ffa368b58fee963a03dfd7b0c"
diff --git a/package.json b/package.json
index 102a937d..cd6033da 100644
--- a/package.json
+++ b/package.json
@@ -39,7 +39,6 @@
"pogen": "file:tooling/pogen/",
"react": "^15.5.4",
"react-dom": "^15.5.4",
- "talertest": "file:tooling/talertest/",
"through2": "^2.0.1",
"tiny-worker": "^2.1.1",
"ts-loader": "^2.0.3",
diff --git a/src/crypto/cryptoApi-test.ts b/src/crypto/cryptoApi-test.ts
index 89b74d77..cc5d1156 100644
--- a/src/crypto/cryptoApi-test.ts
+++ b/src/crypto/cryptoApi-test.ts
@@ -1,6 +1,6 @@
import {CryptoApi} from "./cryptoApi";
import {ReserveRecord, DenominationRecord, DenominationStatus} from "../types";
-import {test, TestLib} from "talertest";
+import {test} from "ava";
let masterPub1: string =
"CQQZ9DY3MZ1ARMN5K1VKDETS04Y2QCKMMCFHZSWJWWVN82BTTH00";
@@ -45,15 +45,15 @@ let denomValid1: DenominationRecord = {
let denomInvalid1 = JSON.parse(JSON.stringify(denomValid1));
denomInvalid1.value.value += 1;
-test("string hashing", async (t: TestLib) => {
+test("string hashing", async t => {
let crypto = new CryptoApi();
let s = await crypto.hashString("hello taler");
let sh =
"8RDMADB3YNF3QZBS3V467YZVJAMC2QAQX0TZGVZ6Q5PFRRAJFT70HHN0QF661QR9QWKYMMC7YEMPD679D2RADXCYK8Y669A2A5MKQFR";
- t.assert(s == sh);
+ t.true(s == sh);
t.pass();
});
-test("precoin creation", async (t: TestLib) => {
+test("precoin creation", async t => {
let crypto = new CryptoApi();
let {priv, pub} = await crypto.createEddsaKeypair();
let r: ReserveRecord = {
@@ -73,12 +73,12 @@ test("precoin creation", async (t: TestLib) => {
t.pass();
});
-test("denom validation", async (t: TestLib) => {
+test("denom validation", async t => {
let crypto = new CryptoApi();
let v: boolean;
v = await crypto.isValidDenom(denomValid1, masterPub1);
- t.assert(v);
+ t.true(v);
v = await crypto.isValidDenom(denomInvalid1, masterPub1);
- t.assert(!v);
+ t.true(!v);
t.pass();
});
diff --git a/src/crypto/emscInterface-test.ts b/src/crypto/emscInterface-test.ts
index 4f57bf80..dc98308f 100644
--- a/src/crypto/emscInterface-test.ts
+++ b/src/crypto/emscInterface-test.ts
@@ -1,55 +1,55 @@
-import {test, TestLib} from "talertest";
+import {test} from "ava";
import * as native from "./emscInterface";
-test("string hashing", (t: TestLib) => {
+test("string hashing", t => {
let x = native.ByteArray.fromStringWithNull("hello taler");
let h =
"8RDMADB3YNF3QZBS3V467YZVJAMC2QAQX0TZGVZ6Q5PFRRAJFT70HHN0QF661QR9QWKYMMC7YEMPD679D2RADXCYK8Y669A2A5MKQFR"
let hc = x.hash().toCrock();
console.log(`# hc ${hc}`);
- t.assert(h === hc, "must equal");
+ t.true(h === hc, "must equal");
t.pass();
});
-test("signing", (t: TestLib) => {
+test("signing", t => {
let x = native.ByteArray.fromStringWithNull("hello taler");
let priv = native.EddsaPrivateKey.create();
let pub = priv.getPublicKey();
let purpose = new native.EccSignaturePurpose(native.SignaturePurpose.TEST,
x);
let sig = native.eddsaSign(purpose, priv);
- t.assert(native.eddsaVerify(native.SignaturePurpose.TEST, purpose, sig,
pub));
+ t.true(native.eddsaVerify(native.SignaturePurpose.TEST, purpose, sig, pub));
t.pass();
});
-test("signing-fixed-data", (t: TestLib) => {
+test("signing-fixed-data", t => {
let x = native.ByteArray.fromStringWithNull("hello taler");
let purpose = new native.EccSignaturePurpose(native.SignaturePurpose.TEST,
x);
const privStr = "G9R8KRRCAFKPD0KW7PW48CC2T03VQ8K2AN9J6J6K2YW27J5MHN90";
const pubStr = "YHCZB442FQFJ0ET20MWA8YJ53M61EZGJ6QKV1KTJZMRNXDY45WT0";
const sigStr =
"7V6XY4QGC1406GPMT305MZQ1HDCR7R0S5BP02GTGDQFPSXB6YD2YDN5ZS7NJQCNP61Y39MRHXNXQ1Z15JY4CJY4CPDA6CKQ3313WG38";
let priv = native.EddsaPrivateKey.fromCrock(privStr);
- t.assert(privStr == priv.toCrock())
+ t.true(privStr == priv.toCrock())
let pub = priv.getPublicKey();
- t.assert(pubStr == pub.toCrock());
+ t.true(pubStr == pub.toCrock());
let sig = native.EddsaSignature.fromCrock(sigStr);
- t.assert(sigStr == sig.toCrock())
+ t.true(sigStr == sig.toCrock())
let sig2 = native.eddsaSign(purpose, priv);
- t.assert(sig.toCrock() == sig2.toCrock());
- t.assert(native.eddsaVerify(native.SignaturePurpose.TEST, purpose, sig,
pub));
+ t.true(sig.toCrock() == sig2.toCrock());
+ t.true(native.eddsaVerify(native.SignaturePurpose.TEST, purpose, sig, pub));
t.pass();
});
const denomPubStr1 =
"51R7ARKCD5HJTTV5F4G0M818E9SP280A40G2GVH04CR30G9R64VK6HHS6MW42DSN8MVKJGHK6WR3CGT18MWMCDSM75138E1K8S0MADSQ68W34DHH6MW4CHA270W4CG9J6GW48DHG8MVK4E9S7523GEA56H0K4E1Q891KCCSG752KGC1M88VMCDSQ6D23CHHG8H33AGHG6MSK8GT26CRKAC1M64V3JCJ56CVKCC228MWMCHA26MS30H1J8MVKEDHJ70TMADHK892KJC1H60TKJDHM710KGGT584T38H9K851KCDHG60W30HJ28CT4CC1G8CR3JGJ28H236DJ28H330H9S890M2D9S8S14AGA369344GA36S248CHS70RKEDSS6MWKGDJ26D136GT465348CSS8S232CHM6GS34C9N8CS3GD9H60W36H1R8MSK2GSQ8MSM6C9R70SKCHHN6MW3AC
[...]
-test("rsa-encode", (t: TestLib) => {
+test("rsa-encode", t => {
const pubHashStr =
"JM63YM5X7X547164QJ3MGJZ4WDD47GEQR5DW5SH35G4JFZXEJBHE5JBNZM5K8XN5C4BRW25BE6GSVAYBF790G2BZZ13VW91D41S4DS0"
let denomPub = native.RsaPublicKey.fromCrock(denomPubStr1);
let pubHash = denomPub.encode().hash();
- t.assert(pubHashStr == pubHash.toCrock());
+ t.true(pubHashStr == pubHash.toCrock());
t.pass();
});
-test("withdraw-request", (t: TestLib) => {
+test("withdraw-request", t => {
const reservePrivStr =
"G9R8KRRCAFKPD0KW7PW48CC2T03VQ8K2AN9J6J6K2YW27J5MHN90";
const reservePriv = native.EddsaPrivateKey.fromCrock(reservePrivStr);
const reservePub = reservePriv.getPublicKey();
@@ -72,30 +72,30 @@ test("withdraw-request", (t: TestLib) => {
var sigStr =
"AD3T8W44NV193J19RAN3NAJHPP6RVB0R3NWV7ZK5G8Q946YDK0B6F8YJBNRRBXSPVTKY31S7BVZPJFFTJJRMY61DH51X4JSXK677428";
var sig = native.eddsaSign(withdrawRequest.toPurpose(), reservePriv);
- t.assert(native.eddsaVerify(native.SignaturePurpose.RESERVE_WITHDRAW,
withdrawRequest.toPurpose(), sig, reservePub));
- t.assert(sig.toCrock() == sigStr);
+ t.true(native.eddsaVerify(native.SignaturePurpose.RESERVE_WITHDRAW,
withdrawRequest.toPurpose(), sig, reservePub));
+ t.true(sig.toCrock() == sigStr);
t.pass();
});
-test("withdraw-request", (t: TestLib) => {
+test("withdraw-request", t => {
const a1 = new native.Amount({currency: "KUDOS", value: 1, fraction:
50000000});
const a2 = new native.Amount({currency: "KUDOS", value: 1, fraction:
50000000});
a1.add(a2);
let x = a1.toJson();
- t.assert(x.currency == "KUDOS");
- t.assert(x.fraction == 0);
- t.assert(x.value == 3);
+ t.true(x.currency == "KUDOS");
+ t.true(x.fraction == 0);
+ t.true(x.value == 3);
t.pass();
});
-test("ecdsa", (t: TestLib) => {
+test("ecdsa", t => {
const priv = native.EcdsaPrivateKey.create();
const pub1 = priv.getPublicKey();
t.pass();
});
-test("ecdhe", (t: TestLib) => {
+test("ecdhe", t => {
const priv = native.EcdhePrivateKey.create();
const pub = priv.getPublicKey();
t.pass();
diff --git a/src/helpers-test.ts b/src/helpers-test.ts
index d252e972..4e9b994d 100644
--- a/src/helpers-test.ts
+++ b/src/helpers-test.ts
@@ -1,21 +1,21 @@
-import {test, TestLib} from "talertest";
+import {test} from "ava";
import * as helpers from "./helpers";
-test("URL canonicalization", (t: TestLib) => {
+test("URL canonicalization", t => {
// converts to relative, adds https
- t.assertEqualsStrict(
+ t.is(
"https://alice.example.com/exchange/",
- helpers.canonicalizeBaseUrl("alice.example.com/exchange"))
+ helpers.canonicalizeBaseUrl("alice.example.com/exchange"));
// keeps http, adds trailing slash
- t.assertEqualsStrict(
+ t.is(
"http://alice.example.com/exchange/",
- helpers.canonicalizeBaseUrl("http://alice.example.com/exchange"))
+ helpers.canonicalizeBaseUrl("http://alice.example.com/exchange"));
// keeps http, adds trailing slash
- t.assertEqualsStrict(
+ t.is(
"http://alice.example.com/exchange/",
- helpers.canonicalizeBaseUrl("http://alice.example.com/exchange#foobar"))
+ helpers.canonicalizeBaseUrl("http://alice.example.com/exchange#foobar"));
t.pass();
});
diff --git a/src/types-test.ts b/src/types-test.ts
index 32e07bd0..bc053b40 100644
--- a/src/types-test.ts
+++ b/src/types-test.ts
@@ -1,44 +1,44 @@
-import {test, TestLib} from "talertest";
+import {test} from "ava";
import {Amounts} from "./types";
import * as types from "./types";
let amt = (value: number, fraction: number, currency: string):
types.AmountJson => ({value, fraction, currency});
-test("amount addition (simple)", (t: TestLib) => {
+test("amount addition (simple)", t => {
let a1 = amt(1,0,"EUR");
let a2 = amt(1,0,"EUR");
let a3 = amt(2,0,"EUR");
- t.assert(0 == types.Amounts.cmp(Amounts.add(a1, a2).amount, a3));
+ t.true(0 == types.Amounts.cmp(Amounts.add(a1, a2).amount, a3));
t.pass();
});
-test("amount addition (saturation)", (t: TestLib) => {
+test("amount addition (saturation)", t => {
let a1 = amt(1,0,"EUR");
let res = Amounts.add(Amounts.getMaxAmount("EUR"), a1);
- t.assert(res.saturated);
+ t.true(res.saturated);
t.pass();
});
-test("amount subtraction (simple)", (t: TestLib) => {
+test("amount subtraction (simple)", t => {
let a1 = amt(2,5,"EUR");
let a2 = amt(1,0,"EUR");
let a3 = amt(1,5,"EUR");
- t.assert(0 == types.Amounts.cmp(Amounts.sub(a1, a2).amount, a3));
+ t.true(0 == types.Amounts.cmp(Amounts.sub(a1, a2).amount, a3));
t.pass();
});
-test("amount subtraction (saturation)", (t: TestLib) => {
+test("amount subtraction (saturation)", t => {
let a1 = amt(0,0,"EUR");
let a2 = amt(1,0,"EUR");
let res = Amounts.sub(a1, a2);
- t.assert(res.saturated);
+ t.true(res.saturated);
res = Amounts.sub(a1, a1);
- t.assert(!res.saturated);
+ t.true(!res.saturated);
t.pass();
});
-test("contract validation", (t: TestLib) => {
+test("contract validation", t => {
let c = {
H_wire: "123",
summary: "hello",
diff --git a/src/wallet-test.ts b/src/wallet-test.ts
index e317c3bd..56b5e602 100644
--- a/src/wallet-test.ts
+++ b/src/wallet-test.ts
@@ -1,9 +1,9 @@
-import {test, TestLib} from "talertest";
+import {test} from "ava";
import {mkAmount} from "./types";
import * as wallet from "./wallet";
-test("coin selection 1", (t: TestLib) => {
+test("coin selection 1", t => {
let cds: any = [];
cds.push({
coin: {
@@ -29,12 +29,12 @@ test("coin selection 1", (t: TestLib) => {
t.fail();
return;
}
- t.assert(res.length == 2);
+ t.true(res.length == 2);
t.pass();
});
-test("coin selection 2", (t: TestLib) => {
+test("coin selection 2", t => {
let cds: any = [];
cds.push({
coin: {
@@ -70,12 +70,12 @@ test("coin selection 2", (t: TestLib) => {
t.fail();
return;
}
- t.assert(res.length == 2);
+ t.true(res.length == 2);
t.pass();
});
-test("coin selection 2", (t: TestLib) => {
+test("coin selection 2", t => {
let cds: any = [];
cds.push({
coin: {
@@ -110,13 +110,13 @@ test("coin selection 2", (t: TestLib) => {
t.fail();
return;
}
- t.assert(res.length == 2);
+ t.true(res.length == 2);
t.pass();
});
-test("coin selection 3", (t: TestLib) => {
+test("coin selection 3", t => {
let cds: any = [];
cds.push({
coin: {
@@ -151,12 +151,12 @@ test("coin selection 3", (t: TestLib) => {
t.fail();
return;
}
- t.assert(res.length == 3);
+ t.true(res.length == 3);
t.pass();
});
-test("coin selection 3", (t: TestLib) => {
+test("coin selection 3", t => {
let cds: any = [];
cds.push({
coin: {
@@ -187,7 +187,7 @@ test("coin selection 3", (t: TestLib) => {
});
let res = wallet.selectCoins(cds, mkAmount(4,0,"EUR"), mkAmount(0,2,"EUR"));
- t.assert(!res);
+ t.true(!res);
t.pass();
});
diff --git a/tooling/talertest/node/runtime.js
b/tooling/talertest/node/runtime.js
deleted file mode 100644
index 8c899337..00000000
--- a/tooling/talertest/node/runtime.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 Inria
-
- TALER is free software; you can redistribute it and/or modify it under the
- terms of the GNU General Public License as published by the Free Software
- Foundation; either version 3, or (at your option) any later version.
-
- TALER is distributed in the hope that it will be useful, but WITHOUT ANY
- WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
- A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License along with
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- *
- * @author Florian Dold
- */
-
-
-"use strict";
-
-let vm = require("vm");
-let fs = require("fs");
-let process = require("process");
-let path = require("path");
-
-let testFile = path.resolve(process.argv[2]);
-
-console.log("TAP version 13");
-console.log("running test", testFile);
-
-process.on('unhandledRejection', function(reason, p){
- console.log("Possibly Unhandled Rejection at: Promise ", p, " reason: ",
reason);
- process.exit(1);
-});
-
-let tt = require("../talertest");
-require(testFile);
-
-tt.run();
diff --git a/tooling/talertest/package.json b/tooling/talertest/package.json
deleted file mode 100644
index ae7e58ee..00000000
--- a/tooling/talertest/package.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "name": "talertest",
- "version": "1.0.0",
- "main": "talertest.js",
- "types": "talertest.d.ts",
- "author": "Florian Dold",
- "license": "GPL-2.0+",
- "scripts": {
- "build": "tsc"
- },
- "files": [
- "node/",
- "selenium/",
- "talertest.d.ts"
- ],
- "devDependencies": {
- "typescript": "^2.2.2"
- }
-}
diff --git a/tooling/talertest/selenium/.gitignore
b/tooling/talertest/selenium/.gitignore
deleted file mode 100644
index 8a8d8911..00000000
--- a/tooling/talertest/selenium/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-coverage/
-coveage-*.json
diff --git a/tooling/talertest/selenium/escodegen.browser.js
b/tooling/talertest/selenium/escodegen.browser.js
deleted file mode 100644
index 5f8f5e5b..00000000
--- a/tooling/talertest/selenium/escodegen.browser.js
+++ /dev/null
@@ -1,4947 +0,0 @@
-// Generated by CommonJS Everywhere 0.9.7
-(function (global) {
- function require(file, parentModule) {
- if ({}.hasOwnProperty.call(require.cache, file))
- return require.cache[file];
- var resolved = require.resolve(file);
- if (!resolved)
- throw new Error('Failed to resolve module ' + file);
- var module$ = {
- id: file,
- require: require,
- filename: file,
- exports: {},
- loaded: false,
- parent: parentModule,
- children: []
- };
- if (parentModule)
- parentModule.children.push(module$);
- var dirname = file.slice(0, file.lastIndexOf('/') + 1);
- require.cache[file] = module$.exports;
- resolved.call(module$.exports, module$, module$.exports, dirname, file);
- module$.loaded = true;
- return require.cache[file] = module$.exports;
- }
- require.modules = {};
- require.cache = {};
- require.resolve = function (file) {
- return {}.hasOwnProperty.call(require.modules, file) ?
require.modules[file] : void 0;
- };
- require.define = function (file, fn) {
- require.modules[file] = fn;
- };
- var process = function () {
- var cwd = '/';
- return {
- title: 'browser',
- version: 'v7.0.0',
- browser: true,
- env: {},
- argv: [],
- nextTick: global.setImmediate || function (fn) {
- setTimeout(fn, 0);
- },
- cwd: function () {
- return cwd;
- },
- chdir: function (dir) {
- cwd = dir;
- }
- };
- }();
- require.define('/tools/entry-point.js', function (module, exports,
__dirname, __filename) {
- (function () {
- 'use strict';
- global.escodegen = require('/escodegen.js', module);
- escodegen.browser = true;
- }());
- });
- require.define('/escodegen.js', function (module, exports, __dirname,
__filename) {
- (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('/node_modules/estraverse/estraverse.js', module);
- esutils = require('/node_modules/esutils/lib/utils.js', module);
- Syntax = estraverse.Syntax;
- function isExpression(node) {
- return CodeGenerator.Expression.hasOwnProperty(node.type);
- }
- 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
- };
- 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;
- 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;
- var S_TFFF = F_ALLOW_IN, S_TFFT = F_ALLOW_IN | F_SEMICOLON_OPT, S_FFFF =
0, S_TFTF = F_ALLOW_IN | F_DIRECTIVE_CTX, S_TTFF = F_ALLOW_IN | F_FUNC_BODY;
- function getDefaultOptions() {
- 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) === 48 && 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) === 48) {
- --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;
- }
- function escapeRegExpCharacter(ch, previousIsBackslash) {
- if ((ch & ~1) === 8232) {
- return (previousIsBackslash ? 'u' : '\\u') + (ch === 8232 ? '2028' :
'2029');
- } else if (ch === 10 || ch === 13) {
- 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) {
- 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 {
- result += escapeRegExpCharacter(ch, previousIsBackslash);
- previousIsBackslash = false;
- }
- }
- return '/' + result + '/' + flags;
- }
- return result;
- }
- function escapeAllowedCharacter(code, next) {
- var hex;
- if (code === 8) {
- return '\\b';
- }
- if (code === 12) {
- return '\\f';
- }
- if (code === 9) {
- return '\\t';
- }
- hex = code.toString(16).toUpperCase();
- if (json || code > 255) {
- return '\\u' + '0000'.slice(hex.length) + hex;
- } else if (code === 0 && !esutils.code.isDecimalDigit(next)) {
- return '\\0';
- } else if (code === 11) {
- return '\\x0B';
- } else {
- return '\\x' + '00'.slice(hex.length) + hex;
- }
- }
- function escapeDisallowedCharacter(code) {
- if (code === 92) {
- return '\\\\';
- }
- if (code === 10) {
- return '\\n';
- }
- if (code === 13) {
- return '\\r';
- }
- if (code === 8232) {
- return '\\u2028';
- }
- if (code === 8233) {
- 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 === 39) {
- quote = '"';
- break;
- } else if (code === 34) {
- quote = "'";
- break;
- } else if (code === 92) {
- ++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 === 39) {
- ++singleQuotes;
- } else if (code === 34) {
- ++doubleQuotes;
- } else if (code === 47 && json) {
- result += '\\';
- } else if (esutils.code.isLineTerminator(code) || code === 92) {
- result += escapeDisallowedCharacter(code);
- continue;
- } else if (!esutils.code.isIdentifierPartES5(code) && (json && code
< 32 || !json && !escapeless && (code < 32 || code > 126))) {
- 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 === 39 && single || code === 34 && !single) {
- result += '\\';
- }
- result += String.fromCharCode(code);
- }
- return result + quote;
- }
- 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;
- }
- function toSourceNodeWhenNeeded(generated, node) {
- if (!sourceMap) {
- 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 === 43 || leftCharCode === 45) && leftCharCode ===
rightCharCode || esutils.code.isIdentifierPartES5(leftCharCode) &&
esutils.code.isIdentifierPartES5(rightCharCode) || leftCharCode === 47 &&
rightCharCode === 105) {
- 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;
- 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') {
- previousBase = base;
- if (array[1][spaces] === '*') {
- specialBase += ' ';
- }
- base = specialBase;
- } else {
- if (spaces & 1) {
- --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 {
- 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) {
- if (i === 0) {
- 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 {
- result = generateVerbatimString(verbatim.content);
- prec = verbatim.precedence != null ? verbatim.precedence :
Precedence.Sequence;
- result = parenthesize(result, prec, precedence);
- }
- return toSourceNodeWhenNeeded(result, expr);
- }
- function CodeGenerator() {
- }
- 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 {
- 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) {
- 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]) {
- 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,
value) {
- var result = [];
- if (computed) {
- result.push('[');
- }
- if (value.type === 'AssignmentPattern') {
- result.push(this.AssignmentPattern(value, Precedence.Sequence,
E_TTT));
- } else {
- 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 ';';
- };
- CodeGenerator.Statement = {
- BlockStatement: function (stmt, flags) {
- var range, content, result = [
- '{',
- newline
- ], that = this;
- withIndent(function () {
- 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) {
- 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);
- }
- }
- 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) {
- if (!stmt.body[i + 1].leadingComments) {
- result.push(newline);
- }
- } else {
- result.push(newline);
- }
- }
- if (preserveBlankLines) {
- 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'];
- if (stmt.id) {
- result = join(result, this.generateExpression(stmt.id,
Precedence.Sequence, E_TTT));
- }
- 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) {
- 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 ';';
- },
- ExportDefaultDeclaration: function (stmt, flags) {
- var result = ['export'], bodyFlags;
- bodyFlags = flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF;
- 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;
- },
- ExportNamedDeclaration: function (stmt, flags) {
- var result = ['export'], bodyFlags, that = this;
- bodyFlags = flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF;
- if (stmt.declaration) {
- return join(result, this.generateStatement(stmt.declaration,
bodyFlags));
- }
- 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,
- this.generateExpression(stmt.source, Precedence.Sequence,
E_TTT),
- this.semicolon(flags)
- ]);
- } else {
- result.push(this.semicolon(flags));
- }
- }
- return result;
- },
- ExportAllDeclaration: function (stmt, flags) {
- return [
- 'export' + space,
- '*' + space,
- 'from' + space,
- this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
- this.semicolon(flags)
- ];
- },
- 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 === 123 || 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 === 40 || esutils.code.isWhiteSpace(code) || code ===
42 || 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 === 40 || esutils.code.isWhiteSpace(code) || code ===
42 || esutils.code.isLineTerminator(code);
- }
- result = [this.generateExpression(stmt.expression,
Precedence.Sequence, E_TTT)];
- fragment = toSourceNodeWhenNeeded(result).toString();
- if (fragment.charCodeAt(0) === 123 || 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) {
- var result, cursor, that = this;
- if (stmt.specifiers.length === 0) {
- return [
- 'import',
- space,
- this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
- this.semicolon(flags)
- ];
- }
- result = ['import'];
- cursor = 0;
- 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) {
- result = join(result, [
- space,
- this.generateExpression(stmt.specifiers[cursor],
Precedence.Sequence, E_TTT)
- ]);
- } else {
- result.push(space + '{');
- if (stmt.specifiers.length - cursor === 1) {
- result.push(space);
- result.push(this.generateExpression(stmt.specifiers[cursor],
Precedence.Sequence, E_TTT));
- result.push(space + '}' + space);
- } else {
- 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,
- 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) {
- 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) {
- 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);
- }
- }
- 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 {
- 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) {
- if (i === 0) {
- if (!stmt.body[0].leadingComments) {
- generateBlankLines(stmt.range[0], stmt.body[i].range[0],
result);
- }
- }
- 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) {
- 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(),
- stmt.id ? 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);
- 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) === 47 &&
esutils.code.isIdentifierPartES5(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) ===
'!--') {
- 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;
- 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;
- 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;
- 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();
- if (fragment.indexOf('.') < 0 && !/[eExX]/.test(fragment) &&
esutils.code.isDecimalDigit(fragment.charCodeAt(fragment.length - 1)) &&
!(fragment.length >= 2 && fragment.charCodeAt(0) === 48)) {
- result.push('.');
- }
- }
- result.push('.');
- result.push(generateIdentifier(expr.property));
- }
- return parenthesize(result, Precedence.Member, precedence);
- },
- MetaProperty: function (expr, precedence, flags) {
- var result;
- result = [];
- result.push(expr.meta);
- result.push('.');
- result.push(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) {
- result = join(result, fragment);
- } else {
- leftSource = toSourceNodeWhenNeeded(result).toString();
- leftCharCode = leftSource.charCodeAt(leftSource.length - 1);
- rightCharCode = fragment.toString().charCodeAt(0);
- if ((leftCharCode === 43 || leftCharCode === 45) && leftCharCode
=== rightCharCode || esutils.code.isIdentifierPartES5(leftCharCode) &&
esutils.code.isIdentifierPartES5(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.all ? '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;
- },
- ArrayPattern: function (expr, precedence, flags) {
- return this.ArrayExpression(expr, precedence, flags, true);
- },
- ArrayExpression: function (expr, precedence, flags, isPattern) {
- var result, multiline, that = this;
- if (!expr.elements.length) {
- return '[]';
- }
- multiline = isPattern ? false : 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;
- },
- RestElement: function (expr, precedence, flags) {
- return '...' + this.generatePattern(expr.argument);
- },
- 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, expr.value)),
- this.generateFunctionBody(expr.value)
- ];
- } else {
- fragment = [
- generateMethodPrefix(expr),
- this.generatePropertyKey(expr.key, expr.computed, expr.value),
- 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, expr.value),
- this.generateFunctionBody(expr.value)
- ];
- }
- if (expr.shorthand) {
- return this.generatePropertyKey(expr.key, expr.computed,
expr.value);
- }
- if (expr.method) {
- return [
- generateMethodPrefix(expr),
- this.generatePropertyKey(expr.key, expr.computed, expr.value),
- this.generateFunctionBody(expr.value)
- ];
- }
- return [
- this.generatePropertyKey(expr.key, expr.computed, expr.value),
- ':' + 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) {
- 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;
- },
- AssignmentPattern: function (expr, precedence, flags) {
- return this.generateAssignment(expr.left, expr.right, '=',
precedence, flags);
- },
- 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';
- },
- Super: function (expr, precedence, flags) {
- return 'super';
- },
- Identifier: function (expr, precedence, flags) {
- return generateIdentifier(expr);
- },
- ImportDefaultSpecifier: function (expr, precedence, flags) {
- return generateIdentifier(expr.id || expr.local);
- },
- ImportNamespaceSpecifier: function (expr, precedence, flags) {
- var result = ['*'];
- var id = expr.id || expr.local;
- if (id) {
- result.push(space + 'as' + noEmptySpace() +
generateIdentifier(id));
- }
- return result;
- },
- ImportSpecifier: function (expr, precedence, flags) {
- var imported = expr.imported;
- var result = [imported.name];
- var local = expr.local;
- if (local && local.name !== imported.name) {
- result.push(noEmptySpace() + 'as' + noEmptySpace() +
generateIdentifier(local));
- }
- return result;
- },
- ExportSpecifier: function (expr, precedence, flags) {
- var local = expr.local;
- var result = [local.name];
- var exported = expr.exported;
- if (exported && exported.name !== local.name) {
- result.push(noEmptySpace() + 'as' + noEmptySpace() +
generateIdentifier(exported));
- }
- 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) {
- }
- }
- 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';
- }
- if (expr.regex) {
- return '/' + expr.regex.pattern + '/' + expr.regex.flags;
- }
- return generateRegExp(expr.value);
- },
- GeneratorExpression: function (expr, precedence, flags) {
- return this.ComprehensionExpression(expr, precedence, flags);
- },
- ComprehensionExpression: function (expr, precedence, flags) {
- 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) {
- 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);
- 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) {
- 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) {
- SourceNode = require('/node_modules/source-map/lib/source-map.js',
module).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', module).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;
- }());
- });
- require.define('/package.json', function (module, exports, __dirname,
__filename) {
- module.exports = {
- 'name': 'escodegen',
- 'description': 'ECMAScript code generator',
- 'homepage': 'http://github.com/estools/escodegen',
- 'main': 'escodegen.js',
- 'bin': {
- 'esgenerate': './bin/esgenerate.js',
- 'escodegen': './bin/escodegen.js'
- },
- 'files': [
- 'LICENSE.BSD',
- 'LICENSE.source-map',
- 'README.md',
- 'bin',
- 'escodegen.js',
- 'package.json'
- ],
- 'version': '1.8.1',
- 'engines': { 'node': '>=0.12.0' },
- 'maintainers': [{
- 'name': 'Yusuke Suzuki',
- 'email': 'address@hidden',
- 'web': 'http://github.com/Constellation'
- }],
- 'repository': {
- 'type': 'git',
- 'url': 'http://github.com/estools/escodegen.git'
- },
- 'dependencies': {
- 'estraverse': '^1.9.1',
- 'esutils': '^2.0.2',
- 'esprima': '^2.7.1',
- 'optionator': '^0.8.1'
- },
- 'optionalDependencies': { 'source-map': '~0.2.0' },
- 'devDependencies': {
- 'acorn': '^2.7.0',
- 'bluebird': '^2.3.11',
- 'bower-registry-client': '^0.2.1',
- 'chai': '^1.10.0',
- 'commonjs-everywhere': '^0.9.7',
- 'gulp': '^3.8.10',
- 'gulp-eslint': '^0.2.0',
- 'gulp-mocha': '^2.0.0',
- 'semver': '^5.1.0'
- },
- 'license': 'BSD-2-Clause',
- 'scripts': {
- 'test': 'gulp travis',
- 'unit-test': 'gulp test',
- 'lint': 'gulp lint',
- 'release': 'node tools/release.js',
- 'build-min': './node_modules/.bin/cjsify -ma path:
tools/entry-point.js > escodegen.browser.min.js',
- 'build': './node_modules/.bin/cjsify -a path: tools/entry-point.js >
escodegen.browser.js'
- }
- };
- });
- require.define('/node_modules/source-map/lib/source-map.js', function
(module, exports, __dirname, __filename) {
- exports.SourceMapGenerator =
require('/node_modules/source-map/lib/source-map/source-map-generator.js',
module).SourceMapGenerator;
- exports.SourceMapConsumer =
require('/node_modules/source-map/lib/source-map/source-map-consumer.js',
module).SourceMapConsumer;
- exports.SourceNode =
require('/node_modules/source-map/lib/source-map/source-node.js',
module).SourceNode;
- });
- require.define('/node_modules/source-map/lib/source-map/source-node.js',
function (module, exports, __dirname, __filename) {
- if (typeof define !== 'function') {
- var define = require('/node_modules/amdefine/amdefine.js',
module)(module, require);
- }
- define(function (require, exports, module) {
- var SourceMapGenerator =
require('/node_modules/source-map/lib/source-map/source-map-generator.js',
module).SourceMapGenerator;
- var util = require('/node_modules/source-map/lib/source-map/util.js',
module);
- var REGEX_NEWLINE = /(\r?\n)/;
- var NEWLINE_CODE = 10;
- var isSourceNode = '$$$isSourceNode$$$';
- function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
- this.children = [];
- this.sourceContents = {};
- this.line = aLine == null ? null : aLine;
- this.column = aColumn == null ? null : aColumn;
- this.source = aSource == null ? null : aSource;
- this.name = aName == null ? null : aName;
- this[isSourceNode] = true;
- if (aChunks != null)
- this.add(aChunks);
- }
- SourceNode.fromStringWithSourceMap = function
SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer,
aRelativePath) {
- var node = new SourceNode;
- var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
- var shiftNextLine = function () {
- var lineContents = remainingLines.shift();
- var newLine = remainingLines.shift() || '';
- return lineContents + newLine;
- };
- var lastGeneratedLine = 1, lastGeneratedColumn = 0;
- var lastMapping = null;
- aSourceMapConsumer.eachMapping(function (mapping) {
- if (lastMapping !== null) {
- if (lastGeneratedLine < mapping.generatedLine) {
- var code = '';
- addMappingWithCode(lastMapping, shiftNextLine());
- lastGeneratedLine++;
- lastGeneratedColumn = 0;
- } else {
- var nextLine = remainingLines[0];
- var code = nextLine.substr(0, mapping.generatedColumn -
lastGeneratedColumn);
- remainingLines[0] = nextLine.substr(mapping.generatedColumn -
lastGeneratedColumn);
- lastGeneratedColumn = mapping.generatedColumn;
- addMappingWithCode(lastMapping, code);
- lastMapping = mapping;
- return;
- }
- }
- while (lastGeneratedLine < mapping.generatedLine) {
- node.add(shiftNextLine());
- lastGeneratedLine++;
- }
- if (lastGeneratedColumn < mapping.generatedColumn) {
- var nextLine = remainingLines[0];
- node.add(nextLine.substr(0, mapping.generatedColumn));
- remainingLines[0] = nextLine.substr(mapping.generatedColumn);
- lastGeneratedColumn = mapping.generatedColumn;
- }
- lastMapping = mapping;
- }, this);
- if (remainingLines.length > 0) {
- if (lastMapping) {
- addMappingWithCode(lastMapping, shiftNextLine());
- }
- node.add(remainingLines.join(''));
- }
- aSourceMapConsumer.sources.forEach(function (sourceFile) {
- var content = aSourceMapConsumer.sourceContentFor(sourceFile);
- if (content != null) {
- if (aRelativePath != null) {
- sourceFile = util.join(aRelativePath, sourceFile);
- }
- node.setSourceContent(sourceFile, content);
- }
- });
- return node;
- function addMappingWithCode(mapping, code) {
- if (mapping === null || mapping.source === undefined) {
- node.add(code);
- } else {
- var source = aRelativePath ? util.join(aRelativePath,
mapping.source) : mapping.source;
- node.add(new SourceNode(mapping.originalLine,
mapping.originalColumn, source, code, mapping.name));
- }
- }
- };
- SourceNode.prototype.add = function SourceNode_add(aChunk) {
- if (Array.isArray(aChunk)) {
- aChunk.forEach(function (chunk) {
- this.add(chunk);
- }, this);
- } else if (aChunk[isSourceNode] || typeof aChunk === 'string') {
- if (aChunk) {
- this.children.push(aChunk);
- }
- } else {
- throw new TypeError('Expected a SourceNode, string, or an array of
SourceNodes and strings. Got ' + aChunk);
- }
- return this;
- };
- SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
- if (Array.isArray(aChunk)) {
- for (var i = aChunk.length - 1; i >= 0; i--) {
- this.prepend(aChunk[i]);
- }
- } else if (aChunk[isSourceNode] || typeof aChunk === 'string') {
- this.children.unshift(aChunk);
- } else {
- throw new TypeError('Expected a SourceNode, string, or an array of
SourceNodes and strings. Got ' + aChunk);
- }
- return this;
- };
- SourceNode.prototype.walk = function SourceNode_walk(aFn) {
- var chunk;
- for (var i = 0, len = this.children.length; i < len; i++) {
- chunk = this.children[i];
- if (chunk[isSourceNode]) {
- chunk.walk(aFn);
- } else {
- if (chunk !== '') {
- aFn(chunk, {
- source: this.source,
- line: this.line,
- column: this.column,
- name: this.name
- });
- }
- }
- }
- };
- SourceNode.prototype.join = function SourceNode_join(aSep) {
- var newChildren;
- var i;
- var len = this.children.length;
- if (len > 0) {
- newChildren = [];
- for (i = 0; i < len - 1; i++) {
- newChildren.push(this.children[i]);
- newChildren.push(aSep);
- }
- newChildren.push(this.children[i]);
- this.children = newChildren;
- }
- return this;
- };
- SourceNode.prototype.replaceRight = function
SourceNode_replaceRight(aPattern, aReplacement) {
- var lastChild = this.children[this.children.length - 1];
- if (lastChild[isSourceNode]) {
- lastChild.replaceRight(aPattern, aReplacement);
- } else if (typeof lastChild === 'string') {
- this.children[this.children.length - 1] =
lastChild.replace(aPattern, aReplacement);
- } else {
- this.children.push(''.replace(aPattern, aReplacement));
- }
- return this;
- };
- SourceNode.prototype.setSourceContent = function
SourceNode_setSourceContent(aSourceFile, aSourceContent) {
- this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
- };
- SourceNode.prototype.walkSourceContents = function
SourceNode_walkSourceContents(aFn) {
- for (var i = 0, len = this.children.length; i < len; i++) {
- if (this.children[i][isSourceNode]) {
- this.children[i].walkSourceContents(aFn);
- }
- }
- var sources = Object.keys(this.sourceContents);
- for (var i = 0, len = sources.length; i < len; i++) {
- aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
- }
- };
- SourceNode.prototype.toString = function SourceNode_toString() {
- var str = '';
- this.walk(function (chunk) {
- str += chunk;
- });
- return str;
- };
- SourceNode.prototype.toStringWithSourceMap = function
SourceNode_toStringWithSourceMap(aArgs) {
- var generated = {
- code: '',
- line: 1,
- column: 0
- };
- var map = new SourceMapGenerator(aArgs);
- var sourceMappingActive = false;
- var lastOriginalSource = null;
- var lastOriginalLine = null;
- var lastOriginalColumn = null;
- var lastOriginalName = null;
- this.walk(function (chunk, original) {
- generated.code += chunk;
- if (original.source !== null && original.line !== null &&
original.column !== null) {
- if (lastOriginalSource !== original.source || lastOriginalLine !==
original.line || lastOriginalColumn !== original.column || lastOriginalName !==
original.name) {
- map.addMapping({
- source: original.source,
- original: {
- line: original.line,
- column: original.column
- },
- generated: {
- line: generated.line,
- column: generated.column
- },
- name: original.name
- });
- }
- lastOriginalSource = original.source;
- lastOriginalLine = original.line;
- lastOriginalColumn = original.column;
- lastOriginalName = original.name;
- sourceMappingActive = true;
- } else if (sourceMappingActive) {
- map.addMapping({
- generated: {
- line: generated.line,
- column: generated.column
- }
- });
- lastOriginalSource = null;
- sourceMappingActive = false;
- }
- for (var idx = 0, length = chunk.length; idx < length; idx++) {
- if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
- generated.line++;
- generated.column = 0;
- if (idx + 1 === length) {
- lastOriginalSource = null;
- sourceMappingActive = false;
- } else if (sourceMappingActive) {
- map.addMapping({
- source: original.source,
- original: {
- line: original.line,
- column: original.column
- },
- generated: {
- line: generated.line,
- column: generated.column
- },
- name: original.name
- });
- }
- } else {
- generated.column++;
- }
- }
- });
- this.walkSourceContents(function (sourceFile, sourceContent) {
- map.setSourceContent(sourceFile, sourceContent);
- });
- return {
- code: generated.code,
- map: map
- };
- };
- exports.SourceNode = SourceNode;
- });
- });
- require.define('/node_modules/source-map/lib/source-map/util.js', function
(module, exports, __dirname, __filename) {
- if (typeof define !== 'function') {
- var define = require('/node_modules/amdefine/amdefine.js',
module)(module, require);
- }
- define(function (require, exports, module) {
- function getArg(aArgs, aName, aDefaultValue) {
- if (aName in aArgs) {
- return aArgs[aName];
- } else if (arguments.length === 3) {
- return aDefaultValue;
- } else {
- throw new Error('"' + aName + '" is a required argument.');
- }
- }
- exports.getArg = getArg;
- var urlRegexp =
/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
- var dataUrlRegexp = /^data:.+\,.+$/;
- function urlParse(aUrl) {
- var match = aUrl.match(urlRegexp);
- if (!match) {
- return null;
- }
- return {
- scheme: match[1],
- auth: match[2],
- host: match[3],
- port: match[4],
- path: match[5]
- };
- }
- exports.urlParse = urlParse;
- function urlGenerate(aParsedUrl) {
- var url = '';
- if (aParsedUrl.scheme) {
- url += aParsedUrl.scheme + ':';
- }
- url += '//';
- if (aParsedUrl.auth) {
- url += aParsedUrl.auth + '@';
- }
- if (aParsedUrl.host) {
- url += aParsedUrl.host;
- }
- if (aParsedUrl.port) {
- url += ':' + aParsedUrl.port;
- }
- if (aParsedUrl.path) {
- url += aParsedUrl.path;
- }
- return url;
- }
- exports.urlGenerate = urlGenerate;
- function normalize(aPath) {
- var path = aPath;
- var url = urlParse(aPath);
- if (url) {
- if (!url.path) {
- return aPath;
- }
- path = url.path;
- }
- var isAbsolute = path.charAt(0) === '/';
- var parts = path.split(/\/+/);
- for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
- part = parts[i];
- if (part === '.') {
- parts.splice(i, 1);
- } else if (part === '..') {
- up++;
- } else if (up > 0) {
- if (part === '') {
- parts.splice(i + 1, up);
- up = 0;
- } else {
- parts.splice(i, 2);
- up--;
- }
- }
- }
- path = parts.join('/');
- if (path === '') {
- path = isAbsolute ? '/' : '.';
- }
- if (url) {
- url.path = path;
- return urlGenerate(url);
- }
- return path;
- }
- exports.normalize = normalize;
- function join(aRoot, aPath) {
- if (aRoot === '') {
- aRoot = '.';
- }
- if (aPath === '') {
- aPath = '.';
- }
- var aPathUrl = urlParse(aPath);
- var aRootUrl = urlParse(aRoot);
- if (aRootUrl) {
- aRoot = aRootUrl.path || '/';
- }
- if (aPathUrl && !aPathUrl.scheme) {
- if (aRootUrl) {
- aPathUrl.scheme = aRootUrl.scheme;
- }
- return urlGenerate(aPathUrl);
- }
- if (aPathUrl || aPath.match(dataUrlRegexp)) {
- return aPath;
- }
- if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
- aRootUrl.host = aPath;
- return urlGenerate(aRootUrl);
- }
- var joined = aPath.charAt(0) === '/' ? aPath :
normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
- if (aRootUrl) {
- aRootUrl.path = joined;
- return urlGenerate(aRootUrl);
- }
- return joined;
- }
- exports.join = join;
- function relative(aRoot, aPath) {
- if (aRoot === '') {
- aRoot = '.';
- }
- aRoot = aRoot.replace(/\/$/, '');
- var url = urlParse(aRoot);
- if (aPath.charAt(0) == '/' && url && url.path == '/') {
- return aPath.slice(1);
- }
- return aPath.indexOf(aRoot + '/') === 0 ? aPath.substr(aRoot.length +
1) : aPath;
- }
- exports.relative = relative;
- function toSetString(aStr) {
- return '$' + aStr;
- }
- exports.toSetString = toSetString;
- function fromSetString(aStr) {
- return aStr.substr(1);
- }
- exports.fromSetString = fromSetString;
- function strcmp(aStr1, aStr2) {
- var s1 = aStr1 || '';
- var s2 = aStr2 || '';
- return (s1 > s2) - (s1 < s2);
- }
- function compareByOriginalPositions(mappingA, mappingB,
onlyCompareOriginal) {
- var cmp;
- cmp = strcmp(mappingA.source, mappingB.source);
- if (cmp) {
- return cmp;
- }
- cmp = mappingA.originalLine - mappingB.originalLine;
- if (cmp) {
- return cmp;
- }
- cmp = mappingA.originalColumn - mappingB.originalColumn;
- if (cmp || onlyCompareOriginal) {
- return cmp;
- }
- cmp = strcmp(mappingA.name, mappingB.name);
- if (cmp) {
- return cmp;
- }
- cmp = mappingA.generatedLine - mappingB.generatedLine;
- if (cmp) {
- return cmp;
- }
- return mappingA.generatedColumn - mappingB.generatedColumn;
- }
- ;
- exports.compareByOriginalPositions = compareByOriginalPositions;
- function compareByGeneratedPositions(mappingA, mappingB,
onlyCompareGenerated) {
- var cmp;
- cmp = mappingA.generatedLine - mappingB.generatedLine;
- if (cmp) {
- return cmp;
- }
- cmp = mappingA.generatedColumn - mappingB.generatedColumn;
- if (cmp || onlyCompareGenerated) {
- return cmp;
- }
- cmp = strcmp(mappingA.source, mappingB.source);
- if (cmp) {
- return cmp;
- }
- cmp = mappingA.originalLine - mappingB.originalLine;
- if (cmp) {
- return cmp;
- }
- cmp = mappingA.originalColumn - mappingB.originalColumn;
- if (cmp) {
- return cmp;
- }
- return strcmp(mappingA.name, mappingB.name);
- }
- ;
- exports.compareByGeneratedPositions = compareByGeneratedPositions;
- });
- });
- require.define('/node_modules/amdefine/amdefine.js', function (module,
exports, __dirname, __filename) {
- 'use strict';
- function amdefine(module, requireFn) {
- 'use strict';
- var defineCache = {}, loaderCache = {}, alreadyCalled = false, path =
require('path', module), makeRequire, stringRequire;
- function trimDots(ary) {
- var i, part;
- for (i = 0; ary[i]; i += 1) {
- part = ary[i];
- if (part === '.') {
- ary.splice(i, 1);
- i -= 1;
- } else if (part === '..') {
- if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
- break;
- } else if (i > 0) {
- ary.splice(i - 1, 2);
- i -= 2;
- }
- }
- }
- }
- function normalize(name, baseName) {
- var baseParts;
- if (name && name.charAt(0) === '.') {
- if (baseName) {
- baseParts = baseName.split('/');
- baseParts = baseParts.slice(0, baseParts.length - 1);
- baseParts = baseParts.concat(name.split('/'));
- trimDots(baseParts);
- name = baseParts.join('/');
- }
- }
- return name;
- }
- function makeNormalize(relName) {
- return function (name) {
- return normalize(name, relName);
- };
- }
- function makeLoad(id) {
- function load(value) {
- loaderCache[id] = value;
- }
- load.fromText = function (id, text) {
- throw new Error('amdefine does not implement load.fromText');
- };
- return load;
- }
- makeRequire = function (systemRequire, exports, module, relId) {
- function amdRequire(deps, callback) {
- if (typeof deps === 'string') {
- return stringRequire(systemRequire, exports, module, deps, relId);
- } else {
- deps = deps.map(function (depName) {
- return stringRequire(systemRequire, exports, module, depName,
relId);
- });
- if (callback) {
- process.nextTick(function () {
- callback.apply(null, deps);
- });
- }
- }
- }
- amdRequire.toUrl = function (filePath) {
- if (filePath.indexOf('.') === 0) {
- return normalize(filePath, path.dirname(module.filename));
- } else {
- return filePath;
- }
- };
- return amdRequire;
- };
- requireFn = requireFn || function req() {
- return module.require.apply(module, arguments);
- };
- function runFactory(id, deps, factory) {
- var r, e, m, result;
- if (id) {
- e = loaderCache[id] = {};
- m = {
- id: id,
- uri: __filename,
- exports: e
- };
- r = makeRequire(requireFn, e, m, id);
- } else {
- if (alreadyCalled) {
- throw new Error('amdefine with no module ID cannot be called more
than once per file.');
- }
- alreadyCalled = true;
- e = module.exports;
- m = module;
- r = makeRequire(requireFn, e, m, module.id);
- }
- if (deps) {
- deps = deps.map(function (depName) {
- return r(depName);
- });
- }
- if (typeof factory === 'function') {
- result = factory.apply(m.exports, deps);
- } else {
- result = factory;
- }
- if (result !== undefined) {
- m.exports = result;
- if (id) {
- loaderCache[id] = m.exports;
- }
- }
- }
- stringRequire = function (systemRequire, exports, module, id, relId) {
- var index = id.indexOf('!'), originalId = id, prefix, plugin;
- if (index === -1) {
- id = normalize(id, relId);
- if (id === 'require') {
- return makeRequire(systemRequire, exports, module, relId);
- } else if (id === 'exports') {
- return exports;
- } else if (id === 'module') {
- return module;
- } else if (loaderCache.hasOwnProperty(id)) {
- return loaderCache[id];
- } else if (defineCache[id]) {
- runFactory.apply(null, defineCache[id]);
- return loaderCache[id];
- } else {
- if (systemRequire) {
- return systemRequire(originalId);
- } else {
- throw new Error('No module with ID: ' + id);
- }
- }
- } else {
- prefix = id.substring(0, index);
- id = id.substring(index + 1, id.length);
- plugin = stringRequire(systemRequire, exports, module, prefix,
relId);
- if (plugin.normalize) {
- id = plugin.normalize(id, makeNormalize(relId));
- } else {
- id = normalize(id, relId);
- }
- if (loaderCache[id]) {
- return loaderCache[id];
- } else {
- plugin.load(id, makeRequire(systemRequire, exports, module,
relId), makeLoad(id), {});
- return loaderCache[id];
- }
- }
- };
- function define(id, deps, factory) {
- if (Array.isArray(id)) {
- factory = deps;
- deps = id;
- id = undefined;
- } else if (typeof id !== 'string') {
- factory = id;
- id = deps = undefined;
- }
- if (deps && !Array.isArray(deps)) {
- factory = deps;
- deps = undefined;
- }
- if (!deps) {
- deps = [
- 'require',
- 'exports',
- 'module'
- ];
- }
- if (id) {
- defineCache[id] = [
- id,
- deps,
- factory
- ];
- } else {
- runFactory(id, deps, factory);
- }
- }
- define.require = function (id) {
- if (loaderCache[id]) {
- return loaderCache[id];
- }
- if (defineCache[id]) {
- runFactory.apply(null, defineCache[id]);
- return loaderCache[id];
- }
- };
- define.amd = {};
- return define;
- }
- module.exports = amdefine;
- });
-
require.define('/node_modules/source-map/lib/source-map/source-map-generator.js',
function (module, exports, __dirname, __filename) {
- if (typeof define !== 'function') {
- var define = require('/node_modules/amdefine/amdefine.js',
module)(module, require);
- }
- define(function (require, exports, module) {
- var base64VLQ =
require('/node_modules/source-map/lib/source-map/base64-vlq.js', module);
- var util = require('/node_modules/source-map/lib/source-map/util.js',
module);
- var ArraySet =
require('/node_modules/source-map/lib/source-map/array-set.js',
module).ArraySet;
- var MappingList =
require('/node_modules/source-map/lib/source-map/mapping-list.js',
module).MappingList;
- function SourceMapGenerator(aArgs) {
- if (!aArgs) {
- aArgs = {};
- }
- this._file = util.getArg(aArgs, 'file', null);
- this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
- this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
- this._sources = new ArraySet;
- this._names = new ArraySet;
- this._mappings = new MappingList;
- this._sourcesContents = null;
- }
- SourceMapGenerator.prototype._version = 3;
- SourceMapGenerator.fromSourceMap = function
SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
- var sourceRoot = aSourceMapConsumer.sourceRoot;
- var generator = new SourceMapGenerator({
- file: aSourceMapConsumer.file,
- sourceRoot: sourceRoot
- });
- aSourceMapConsumer.eachMapping(function (mapping) {
- var newMapping = {
- generated: {
- line: mapping.generatedLine,
- column: mapping.generatedColumn
- }
- };
- if (mapping.source != null) {
- newMapping.source = mapping.source;
- if (sourceRoot != null) {
- newMapping.source = util.relative(sourceRoot, newMapping.source);
- }
- newMapping.original = {
- line: mapping.originalLine,
- column: mapping.originalColumn
- };
- if (mapping.name != null) {
- newMapping.name = mapping.name;
- }
- }
- generator.addMapping(newMapping);
- });
- aSourceMapConsumer.sources.forEach(function (sourceFile) {
- var content = aSourceMapConsumer.sourceContentFor(sourceFile);
- if (content != null) {
- generator.setSourceContent(sourceFile, content);
- }
- });
- return generator;
- };
- SourceMapGenerator.prototype.addMapping = function
SourceMapGenerator_addMapping(aArgs) {
- var generated = util.getArg(aArgs, 'generated');
- var original = util.getArg(aArgs, 'original', null);
- var source = util.getArg(aArgs, 'source', null);
- var name = util.getArg(aArgs, 'name', null);
- if (!this._skipValidation) {
- this._validateMapping(generated, original, source, name);
- }
- if (source != null && !this._sources.has(source)) {
- this._sources.add(source);
- }
- if (name != null && !this._names.has(name)) {
- this._names.add(name);
- }
- this._mappings.add({
- generatedLine: generated.line,
- generatedColumn: generated.column,
- originalLine: original != null && original.line,
- originalColumn: original != null && original.column,
- source: source,
- name: name
- });
- };
- SourceMapGenerator.prototype.setSourceContent = function
SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
- var source = aSourceFile;
- if (this._sourceRoot != null) {
- source = util.relative(this._sourceRoot, source);
- }
- if (aSourceContent != null) {
- if (!this._sourcesContents) {
- this._sourcesContents = {};
- }
- this._sourcesContents[util.toSetString(source)] = aSourceContent;
- } else if (this._sourcesContents) {
- delete this._sourcesContents[util.toSetString(source)];
- if (Object.keys(this._sourcesContents).length === 0) {
- this._sourcesContents = null;
- }
- }
- };
- SourceMapGenerator.prototype.applySourceMap = function
SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile,
aSourceMapPath) {
- var sourceFile = aSourceFile;
- if (aSourceFile == null) {
- if (aSourceMapConsumer.file == null) {
- throw new Error('SourceMapGenerator.prototype.applySourceMap
requires either an explicit source file, ' + 'or the source map\'s "file"
property. Both were omitted.');
- }
- sourceFile = aSourceMapConsumer.file;
- }
- var sourceRoot = this._sourceRoot;
- if (sourceRoot != null) {
- sourceFile = util.relative(sourceRoot, sourceFile);
- }
- var newSources = new ArraySet;
- var newNames = new ArraySet;
- this._mappings.unsortedForEach(function (mapping) {
- if (mapping.source === sourceFile && mapping.originalLine != null) {
- var original = aSourceMapConsumer.originalPositionFor({
- line: mapping.originalLine,
- column: mapping.originalColumn
- });
- if (original.source != null) {
- mapping.source = original.source;
- if (aSourceMapPath != null) {
- mapping.source = util.join(aSourceMapPath, mapping.source);
- }
- if (sourceRoot != null) {
- mapping.source = util.relative(sourceRoot, mapping.source);
- }
- mapping.originalLine = original.line;
- mapping.originalColumn = original.column;
- if (original.name != null) {
- mapping.name = original.name;
- }
- }
- }
- var source = mapping.source;
- if (source != null && !newSources.has(source)) {
- newSources.add(source);
- }
- var name = mapping.name;
- if (name != null && !newNames.has(name)) {
- newNames.add(name);
- }
- }, this);
- this._sources = newSources;
- this._names = newNames;
- aSourceMapConsumer.sources.forEach(function (sourceFile) {
- var content = aSourceMapConsumer.sourceContentFor(sourceFile);
- if (content != null) {
- if (aSourceMapPath != null) {
- sourceFile = util.join(aSourceMapPath, sourceFile);
- }
- if (sourceRoot != null) {
- sourceFile = util.relative(sourceRoot, sourceFile);
- }
- this.setSourceContent(sourceFile, content);
- }
- }, this);
- };
- SourceMapGenerator.prototype._validateMapping = function
SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) {
- if (aGenerated && 'line' in aGenerated && 'column' in aGenerated &&
aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource &&
!aName) {
- return;
- } else if (aGenerated && 'line' in aGenerated && 'column' in
aGenerated && aOriginal && 'line' in aOriginal && 'column' in aOriginal &&
aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 &&
aOriginal.column >= 0 && aSource) {
- return;
- } else {
- throw new Error('Invalid mapping: ' + JSON.stringify({
- generated: aGenerated,
- source: aSource,
- original: aOriginal,
- name: aName
- }));
- }
- };
- SourceMapGenerator.prototype._serializeMappings = function
SourceMapGenerator_serializeMappings() {
- var previousGeneratedColumn = 0;
- var previousGeneratedLine = 1;
- var previousOriginalColumn = 0;
- var previousOriginalLine = 0;
- var previousName = 0;
- var previousSource = 0;
- var result = '';
- var mapping;
- var mappings = this._mappings.toArray();
- for (var i = 0, len = mappings.length; i < len; i++) {
- mapping = mappings[i];
- if (mapping.generatedLine !== previousGeneratedLine) {
- previousGeneratedColumn = 0;
- while (mapping.generatedLine !== previousGeneratedLine) {
- result += ';';
- previousGeneratedLine++;
- }
- } else {
- if (i > 0) {
- if (!util.compareByGeneratedPositions(mapping, mappings[i - 1]))
{
- continue;
- }
- result += ',';
- }
- }
- result += base64VLQ.encode(mapping.generatedColumn -
previousGeneratedColumn);
- previousGeneratedColumn = mapping.generatedColumn;
- if (mapping.source != null) {
- result += base64VLQ.encode(this._sources.indexOf(mapping.source) -
previousSource);
- previousSource = this._sources.indexOf(mapping.source);
- result += base64VLQ.encode(mapping.originalLine - 1 -
previousOriginalLine);
- previousOriginalLine = mapping.originalLine - 1;
- result += base64VLQ.encode(mapping.originalColumn -
previousOriginalColumn);
- previousOriginalColumn = mapping.originalColumn;
- if (mapping.name != null) {
- result += base64VLQ.encode(this._names.indexOf(mapping.name) -
previousName);
- previousName = this._names.indexOf(mapping.name);
- }
- }
- }
- return result;
- };
- SourceMapGenerator.prototype._generateSourcesContent = function
SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
- return aSources.map(function (source) {
- if (!this._sourcesContents) {
- return null;
- }
- if (aSourceRoot != null) {
- source = util.relative(aSourceRoot, source);
- }
- var key = util.toSetString(source);
- return Object.prototype.hasOwnProperty.call(this._sourcesContents,
key) ? this._sourcesContents[key] : null;
- }, this);
- };
- SourceMapGenerator.prototype.toJSON = function
SourceMapGenerator_toJSON() {
- var map = {
- version: this._version,
- sources: this._sources.toArray(),
- names: this._names.toArray(),
- mappings: this._serializeMappings()
- };
- if (this._file != null) {
- map.file = this._file;
- }
- if (this._sourceRoot != null) {
- map.sourceRoot = this._sourceRoot;
- }
- if (this._sourcesContents) {
- map.sourcesContent = this._generateSourcesContent(map.sources,
map.sourceRoot);
- }
- return map;
- };
- SourceMapGenerator.prototype.toString = function
SourceMapGenerator_toString() {
- return JSON.stringify(this);
- };
- exports.SourceMapGenerator = SourceMapGenerator;
- });
- });
- require.define('/node_modules/source-map/lib/source-map/mapping-list.js',
function (module, exports, __dirname, __filename) {
- if (typeof define !== 'function') {
- var define = require('/node_modules/amdefine/amdefine.js',
module)(module, require);
- }
- define(function (require, exports, module) {
- var util = require('/node_modules/source-map/lib/source-map/util.js',
module);
- function generatedPositionAfter(mappingA, mappingB) {
- var lineA = mappingA.generatedLine;
- var lineB = mappingB.generatedLine;
- var columnA = mappingA.generatedColumn;
- var columnB = mappingB.generatedColumn;
- return lineB > lineA || lineB == lineA && columnB >= columnA ||
util.compareByGeneratedPositions(mappingA, mappingB) <= 0;
- }
- function MappingList() {
- this._array = [];
- this._sorted = true;
- this._last = {
- generatedLine: -1,
- generatedColumn: 0
- };
- }
- MappingList.prototype.unsortedForEach = function
MappingList_forEach(aCallback, aThisArg) {
- this._array.forEach(aCallback, aThisArg);
- };
- MappingList.prototype.add = function MappingList_add(aMapping) {
- var mapping;
- if (generatedPositionAfter(this._last, aMapping)) {
- this._last = aMapping;
- this._array.push(aMapping);
- } else {
- this._sorted = false;
- this._array.push(aMapping);
- }
- };
- MappingList.prototype.toArray = function MappingList_toArray() {
- if (!this._sorted) {
- this._array.sort(util.compareByGeneratedPositions);
- this._sorted = true;
- }
- return this._array;
- };
- exports.MappingList = MappingList;
- });
- });
- require.define('/node_modules/source-map/lib/source-map/array-set.js',
function (module, exports, __dirname, __filename) {
- if (typeof define !== 'function') {
- var define = require('/node_modules/amdefine/amdefine.js',
module)(module, require);
- }
- define(function (require, exports, module) {
- var util = require('/node_modules/source-map/lib/source-map/util.js',
module);
- function ArraySet() {
- this._array = [];
- this._set = {};
- }
- ArraySet.fromArray = function ArraySet_fromArray(aArray,
aAllowDuplicates) {
- var set = new ArraySet;
- for (var i = 0, len = aArray.length; i < len; i++) {
- set.add(aArray[i], aAllowDuplicates);
- }
- return set;
- };
- ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
- var isDuplicate = this.has(aStr);
- var idx = this._array.length;
- if (!isDuplicate || aAllowDuplicates) {
- this._array.push(aStr);
- }
- if (!isDuplicate) {
- this._set[util.toSetString(aStr)] = idx;
- }
- };
- ArraySet.prototype.has = function ArraySet_has(aStr) {
- return Object.prototype.hasOwnProperty.call(this._set,
util.toSetString(aStr));
- };
- ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
- if (this.has(aStr)) {
- return this._set[util.toSetString(aStr)];
- }
- throw new Error('"' + aStr + '" is not in the set.');
- };
- ArraySet.prototype.at = function ArraySet_at(aIdx) {
- if (aIdx >= 0 && aIdx < this._array.length) {
- return this._array[aIdx];
- }
- throw new Error('No element indexed by ' + aIdx);
- };
- ArraySet.prototype.toArray = function ArraySet_toArray() {
- return this._array.slice();
- };
- exports.ArraySet = ArraySet;
- });
- });
- require.define('/node_modules/source-map/lib/source-map/base64-vlq.js',
function (module, exports, __dirname, __filename) {
- if (typeof define !== 'function') {
- var define = require('/node_modules/amdefine/amdefine.js',
module)(module, require);
- }
- define(function (require, exports, module) {
- var base64 =
require('/node_modules/source-map/lib/source-map/base64.js', module);
- var VLQ_BASE_SHIFT = 5;
- var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
- var VLQ_BASE_MASK = VLQ_BASE - 1;
- var VLQ_CONTINUATION_BIT = VLQ_BASE;
- function toVLQSigned(aValue) {
- return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0;
- }
- function fromVLQSigned(aValue) {
- var isNegative = (aValue & 1) === 1;
- var shifted = aValue >> 1;
- return isNegative ? -shifted : shifted;
- }
- exports.encode = function base64VLQ_encode(aValue) {
- var encoded = '';
- var digit;
- var vlq = toVLQSigned(aValue);
- do {
- digit = vlq & VLQ_BASE_MASK;
- vlq >>>= VLQ_BASE_SHIFT;
- if (vlq > 0) {
- digit |= VLQ_CONTINUATION_BIT;
- }
- encoded += base64.encode(digit);
- } while (vlq > 0);
- return encoded;
- };
- exports.decode = function base64VLQ_decode(aStr, aOutParam) {
- var i = 0;
- var strLen = aStr.length;
- var result = 0;
- var shift = 0;
- var continuation, digit;
- do {
- if (i >= strLen) {
- throw new Error('Expected more digits in base 64 VLQ value.');
- }
- digit = base64.decode(aStr.charAt(i++));
- continuation = !!(digit & VLQ_CONTINUATION_BIT);
- digit &= VLQ_BASE_MASK;
- result = result + (digit << shift);
- shift += VLQ_BASE_SHIFT;
- } while (continuation);
- aOutParam.value = fromVLQSigned(result);
- aOutParam.rest = aStr.slice(i);
- };
- });
- });
- require.define('/node_modules/source-map/lib/source-map/base64.js', function
(module, exports, __dirname, __filename) {
- if (typeof define !== 'function') {
- var define = require('/node_modules/amdefine/amdefine.js',
module)(module, require);
- }
- define(function (require, exports, module) {
- var charToIntMap = {};
- var intToCharMap = {};
-
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('').forEach(function
(ch, index) {
- charToIntMap[ch] = index;
- intToCharMap[index] = ch;
- });
- exports.encode = function base64_encode(aNumber) {
- if (aNumber in intToCharMap) {
- return intToCharMap[aNumber];
- }
- throw new TypeError('Must be between 0 and 63: ' + aNumber);
- };
- exports.decode = function base64_decode(aChar) {
- if (aChar in charToIntMap) {
- return charToIntMap[aChar];
- }
- throw new TypeError('Not a valid base 64 digit: ' + aChar);
- };
- });
- });
-
require.define('/node_modules/source-map/lib/source-map/source-map-consumer.js',
function (module, exports, __dirname, __filename) {
- if (typeof define !== 'function') {
- var define = require('/node_modules/amdefine/amdefine.js',
module)(module, require);
- }
- define(function (require, exports, module) {
- var util = require('/node_modules/source-map/lib/source-map/util.js',
module);
- function SourceMapConsumer(aSourceMap) {
- var sourceMap = aSourceMap;
- if (typeof aSourceMap === 'string') {
- sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
- }
- if (sourceMap.sections != null) {
- var indexedSourceMapConsumer =
require('/node_modules/source-map/lib/source-map/indexed-source-map-consumer.js',
module);
- return new
indexedSourceMapConsumer.IndexedSourceMapConsumer(sourceMap);
- } else {
- var basicSourceMapConsumer =
require('/node_modules/source-map/lib/source-map/basic-source-map-consumer.js',
module);
- return new basicSourceMapConsumer.BasicSourceMapConsumer(sourceMap);
- }
- }
- SourceMapConsumer.fromSourceMap = function (aSourceMap) {
- var basicSourceMapConsumer =
require('/node_modules/source-map/lib/source-map/basic-source-map-consumer.js',
module);
- return
basicSourceMapConsumer.BasicSourceMapConsumer.fromSourceMap(aSourceMap);
- };
- SourceMapConsumer.prototype._version = 3;
- SourceMapConsumer.prototype.__generatedMappings = null;
- Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings',
{
- get: function () {
- if (!this.__generatedMappings) {
- this.__generatedMappings = [];
- this.__originalMappings = [];
- this._parseMappings(this._mappings, this.sourceRoot);
- }
- return this.__generatedMappings;
- }
- });
- SourceMapConsumer.prototype.__originalMappings = null;
- Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
- get: function () {
- if (!this.__originalMappings) {
- this.__generatedMappings = [];
- this.__originalMappings = [];
- this._parseMappings(this._mappings, this.sourceRoot);
- }
- return this.__originalMappings;
- }
- });
- SourceMapConsumer.prototype._nextCharIsMappingSeparator = function
SourceMapConsumer_nextCharIsMappingSeparator(aStr) {
- var c = aStr.charAt(0);
- return c === ';' || c === ',';
- };
- SourceMapConsumer.prototype._parseMappings = function
SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
- throw new Error('Subclasses must implement _parseMappings');
- };
- SourceMapConsumer.GENERATED_ORDER = 1;
- SourceMapConsumer.ORIGINAL_ORDER = 2;
- SourceMapConsumer.prototype.eachMapping = function
SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
- var context = aContext || null;
- var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
- var mappings;
- switch (order) {
- case SourceMapConsumer.GENERATED_ORDER:
- mappings = this._generatedMappings;
- break;
- case SourceMapConsumer.ORIGINAL_ORDER:
- mappings = this._originalMappings;
- break;
- default:
- throw new Error('Unknown order of iteration.');
- }
- var sourceRoot = this.sourceRoot;
- mappings.map(function (mapping) {
- var source = mapping.source;
- if (source != null && sourceRoot != null) {
- source = util.join(sourceRoot, source);
- }
- return {
- source: source,
- generatedLine: mapping.generatedLine,
- generatedColumn: mapping.generatedColumn,
- originalLine: mapping.originalLine,
- originalColumn: mapping.originalColumn,
- name: mapping.name
- };
- }).forEach(aCallback, context);
- };
- SourceMapConsumer.prototype.allGeneratedPositionsFor = function
SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
- var needle = {
- source: util.getArg(aArgs, 'source'),
- originalLine: util.getArg(aArgs, 'line'),
- originalColumn: Infinity
- };
- if (this.sourceRoot != null) {
- needle.source = util.relative(this.sourceRoot, needle.source);
- }
- var mappings = [];
- var index = this._findMapping(needle, this._originalMappings,
'originalLine', 'originalColumn', util.compareByOriginalPositions);
- if (index >= 0) {
- var mapping = this._originalMappings[index];
- while (mapping && mapping.originalLine === needle.originalLine) {
- mappings.push({
- line: util.getArg(mapping, 'generatedLine', null),
- column: util.getArg(mapping, 'generatedColumn', null),
- lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
- });
- mapping = this._originalMappings[--index];
- }
- }
- return mappings.reverse();
- };
- exports.SourceMapConsumer = SourceMapConsumer;
- });
- });
-
require.define('/node_modules/source-map/lib/source-map/basic-source-map-consumer.js',
function (module, exports, __dirname, __filename) {
- if (typeof define !== 'function') {
- var define = require('/node_modules/amdefine/amdefine.js',
module)(module, require);
- }
- define(function (require, exports, module) {
- var util = require('/node_modules/source-map/lib/source-map/util.js',
module);
- var binarySearch =
require('/node_modules/source-map/lib/source-map/binary-search.js', module);
- var ArraySet =
require('/node_modules/source-map/lib/source-map/array-set.js',
module).ArraySet;
- var base64VLQ =
require('/node_modules/source-map/lib/source-map/base64-vlq.js', module);
- var SourceMapConsumer =
require('/node_modules/source-map/lib/source-map/source-map-consumer.js',
module).SourceMapConsumer;
- function BasicSourceMapConsumer(aSourceMap) {
- var sourceMap = aSourceMap;
- if (typeof aSourceMap === 'string') {
- sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
- }
- var version = util.getArg(sourceMap, 'version');
- var sources = util.getArg(sourceMap, 'sources');
- var names = util.getArg(sourceMap, 'names', []);
- var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
- var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
- var mappings = util.getArg(sourceMap, 'mappings');
- var file = util.getArg(sourceMap, 'file', null);
- if (version != this._version) {
- throw new Error('Unsupported version: ' + version);
- }
- sources = sources.map(util.normalize);
- this._names = ArraySet.fromArray(names, true);
- this._sources = ArraySet.fromArray(sources, true);
- this.sourceRoot = sourceRoot;
- this.sourcesContent = sourcesContent;
- this._mappings = mappings;
- this.file = file;
- }
- BasicSourceMapConsumer.prototype =
Object.create(SourceMapConsumer.prototype);
- BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
- BasicSourceMapConsumer.fromSourceMap = function
SourceMapConsumer_fromSourceMap(aSourceMap) {
- var smc = Object.create(BasicSourceMapConsumer.prototype);
- smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
- smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
- smc.sourceRoot = aSourceMap._sourceRoot;
- smc.sourcesContent =
aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot);
- smc.file = aSourceMap._file;
- smc.__generatedMappings = aSourceMap._mappings.toArray().slice();
- smc.__originalMappings =
aSourceMap._mappings.toArray().slice().sort(util.compareByOriginalPositions);
- return smc;
- };
- BasicSourceMapConsumer.prototype._version = 3;
- Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
- get: function () {
- return this._sources.toArray().map(function (s) {
- return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s;
- }, this);
- }
- });
- BasicSourceMapConsumer.prototype._parseMappings = function
SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
- var generatedLine = 1;
- var previousGeneratedColumn = 0;
- var previousOriginalLine = 0;
- var previousOriginalColumn = 0;
- var previousSource = 0;
- var previousName = 0;
- var str = aStr;
- var temp = {};
- var mapping;
- while (str.length > 0) {
- if (str.charAt(0) === ';') {
- generatedLine++;
- str = str.slice(1);
- previousGeneratedColumn = 0;
- } else if (str.charAt(0) === ',') {
- str = str.slice(1);
- } else {
- mapping = {};
- mapping.generatedLine = generatedLine;
- base64VLQ.decode(str, temp);
- mapping.generatedColumn = previousGeneratedColumn + temp.value;
- previousGeneratedColumn = mapping.generatedColumn;
- str = temp.rest;
- if (str.length > 0 && !this._nextCharIsMappingSeparator(str)) {
- base64VLQ.decode(str, temp);
- mapping.source = this._sources.at(previousSource + temp.value);
- previousSource += temp.value;
- str = temp.rest;
- if (str.length === 0 || this._nextCharIsMappingSeparator(str)) {
- throw new Error('Found a source, but no line and column');
- }
- base64VLQ.decode(str, temp);
- mapping.originalLine = previousOriginalLine + temp.value;
- previousOriginalLine = mapping.originalLine;
- mapping.originalLine += 1;
- str = temp.rest;
- if (str.length === 0 || this._nextCharIsMappingSeparator(str)) {
- throw new Error('Found a source and line, but no column');
- }
- base64VLQ.decode(str, temp);
- mapping.originalColumn = previousOriginalColumn + temp.value;
- previousOriginalColumn = mapping.originalColumn;
- str = temp.rest;
- if (str.length > 0 && !this._nextCharIsMappingSeparator(str)) {
- base64VLQ.decode(str, temp);
- mapping.name = this._names.at(previousName + temp.value);
- previousName += temp.value;
- str = temp.rest;
- }
- }
- this.__generatedMappings.push(mapping);
- if (typeof mapping.originalLine === 'number') {
- this.__originalMappings.push(mapping);
- }
- }
- }
- this.__generatedMappings.sort(util.compareByGeneratedPositions);
- this.__originalMappings.sort(util.compareByOriginalPositions);
- };
- BasicSourceMapConsumer.prototype._findMapping = function
SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName,
aComparator) {
- if (aNeedle[aLineName] <= 0) {
- throw new TypeError('Line must be greater than or equal to 1, got '
+ aNeedle[aLineName]);
- }
- if (aNeedle[aColumnName] < 0) {
- throw new TypeError('Column must be greater than or equal to 0, got
' + aNeedle[aColumnName]);
- }
- return binarySearch.search(aNeedle, aMappings, aComparator);
- };
- BasicSourceMapConsumer.prototype.computeColumnSpans = function
SourceMapConsumer_computeColumnSpans() {
- for (var index = 0; index < this._generatedMappings.length; ++index) {
- var mapping = this._generatedMappings[index];
- if (index + 1 < this._generatedMappings.length) {
- var nextMapping = this._generatedMappings[index + 1];
- if (mapping.generatedLine === nextMapping.generatedLine) {
- mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
- continue;
- }
- }
- mapping.lastGeneratedColumn = Infinity;
- }
- };
- BasicSourceMapConsumer.prototype.originalPositionFor = function
SourceMapConsumer_originalPositionFor(aArgs) {
- var needle = {
- generatedLine: util.getArg(aArgs, 'line'),
- generatedColumn: util.getArg(aArgs, 'column')
- };
- var index = this._findMapping(needle, this._generatedMappings,
'generatedLine', 'generatedColumn', util.compareByGeneratedPositions);
- if (index >= 0) {
- var mapping = this._generatedMappings[index];
- if (mapping.generatedLine === needle.generatedLine) {
- var source = util.getArg(mapping, 'source', null);
- if (source != null && this.sourceRoot != null) {
- source = util.join(this.sourceRoot, source);
- }
- return {
- source: source,
- line: util.getArg(mapping, 'originalLine', null),
- column: util.getArg(mapping, 'originalColumn', null),
- name: util.getArg(mapping, 'name', null)
- };
- }
- }
- return {
- source: null,
- line: null,
- column: null,
- name: null
- };
- };
- BasicSourceMapConsumer.prototype.sourceContentFor = function
SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
- if (!this.sourcesContent) {
- return null;
- }
- if (this.sourceRoot != null) {
- aSource = util.relative(this.sourceRoot, aSource);
- }
- if (this._sources.has(aSource)) {
- return this.sourcesContent[this._sources.indexOf(aSource)];
- }
- var url;
- if (this.sourceRoot != null && (url = util.urlParse(this.sourceRoot)))
{
- var fileUriAbsPath = aSource.replace(/^file:\/\//, '');
- if (url.scheme == 'file' && this._sources.has(fileUriAbsPath)) {
- return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)];
- }
- if ((!url.path || url.path == '/') && this._sources.has('/' +
aSource)) {
- return this.sourcesContent[this._sources.indexOf('/' + aSource)];
- }
- }
- if (nullOnMissing) {
- return null;
- } else {
- throw new Error('"' + aSource + '" is not in the SourceMap.');
- }
- };
- BasicSourceMapConsumer.prototype.generatedPositionFor = function
SourceMapConsumer_generatedPositionFor(aArgs) {
- var needle = {
- source: util.getArg(aArgs, 'source'),
- originalLine: util.getArg(aArgs, 'line'),
- originalColumn: util.getArg(aArgs, 'column')
- };
- if (this.sourceRoot != null) {
- needle.source = util.relative(this.sourceRoot, needle.source);
- }
- var index = this._findMapping(needle, this._originalMappings,
'originalLine', 'originalColumn', util.compareByOriginalPositions);
- if (index >= 0) {
- var mapping = this._originalMappings[index];
- return {
- line: util.getArg(mapping, 'generatedLine', null),
- column: util.getArg(mapping, 'generatedColumn', null),
- lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
- };
- }
- return {
- line: null,
- column: null,
- lastColumn: null
- };
- };
- exports.BasicSourceMapConsumer = BasicSourceMapConsumer;
- });
- });
- require.define('/node_modules/source-map/lib/source-map/binary-search.js',
function (module, exports, __dirname, __filename) {
- if (typeof define !== 'function') {
- var define = require('/node_modules/amdefine/amdefine.js',
module)(module, require);
- }
- define(function (require, exports, module) {
- function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {
- var mid = Math.floor((aHigh - aLow) / 2) + aLow;
- var cmp = aCompare(aNeedle, aHaystack[mid], true);
- if (cmp === 0) {
- return mid;
- } else if (cmp > 0) {
- if (aHigh - mid > 1) {
- return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);
- }
- return mid;
- } else {
- if (mid - aLow > 1) {
- return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);
- }
- return aLow < 0 ? -1 : aLow;
- }
- }
- exports.search = function search(aNeedle, aHaystack, aCompare) {
- if (aHaystack.length === 0) {
- return -1;
- }
- return recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
aCompare);
- };
- });
- });
-
require.define('/node_modules/source-map/lib/source-map/indexed-source-map-consumer.js',
function (module, exports, __dirname, __filename) {
- if (typeof define !== 'function') {
- var define = require('/node_modules/amdefine/amdefine.js',
module)(module, require);
- }
- define(function (require, exports, module) {
- var util = require('/node_modules/source-map/lib/source-map/util.js',
module);
- var binarySearch =
require('/node_modules/source-map/lib/source-map/binary-search.js', module);
- var SourceMapConsumer =
require('/node_modules/source-map/lib/source-map/source-map-consumer.js',
module).SourceMapConsumer;
- var BasicSourceMapConsumer =
require('/node_modules/source-map/lib/source-map/basic-source-map-consumer.js',
module).BasicSourceMapConsumer;
- function IndexedSourceMapConsumer(aSourceMap) {
- var sourceMap = aSourceMap;
- if (typeof aSourceMap === 'string') {
- sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
- }
- var version = util.getArg(sourceMap, 'version');
- var sections = util.getArg(sourceMap, 'sections');
- if (version != this._version) {
- throw new Error('Unsupported version: ' + version);
- }
- var lastOffset = {
- line: -1,
- column: 0
- };
- this._sections = sections.map(function (s) {
- if (s.url) {
- throw new Error('Support for url field in sections not
implemented.');
- }
- var offset = util.getArg(s, 'offset');
- var offsetLine = util.getArg(offset, 'line');
- var offsetColumn = util.getArg(offset, 'column');
- if (offsetLine < lastOffset.line || offsetLine === lastOffset.line
&& offsetColumn < lastOffset.column) {
- throw new Error('Section offsets must be ordered and
non-overlapping.');
- }
- lastOffset = offset;
- return {
- generatedOffset: {
- generatedLine: offsetLine + 1,
- generatedColumn: offsetColumn + 1
- },
- consumer: new SourceMapConsumer(util.getArg(s, 'map'))
- };
- });
- }
- IndexedSourceMapConsumer.prototype =
Object.create(SourceMapConsumer.prototype);
- IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
- IndexedSourceMapConsumer.prototype._version = 3;
- Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
- get: function () {
- var sources = [];
- for (var i = 0; i < this._sections.length; i++) {
- for (var j = 0; j < this._sections[i].consumer.sources.length;
j++) {
- sources.push(this._sections[i].consumer.sources[j]);
- }
- }
- ;
- return sources;
- }
- });
- IndexedSourceMapConsumer.prototype.originalPositionFor = function
IndexedSourceMapConsumer_originalPositionFor(aArgs) {
- var needle = {
- generatedLine: util.getArg(aArgs, 'line'),
- generatedColumn: util.getArg(aArgs, 'column')
- };
- var sectionIndex = binarySearch.search(needle, this._sections,
function (needle, section) {
- var cmp = needle.generatedLine -
section.generatedOffset.generatedLine;
- if (cmp) {
- return cmp;
- }
- return needle.generatedColumn -
section.generatedOffset.generatedColumn;
- });
- var section = this._sections[sectionIndex];
- if (!section) {
- return {
- source: null,
- line: null,
- column: null,
- name: null
- };
- }
- return section.consumer.originalPositionFor({
- line: needle.generatedLine - (section.generatedOffset.generatedLine
- 1),
- column: needle.generatedColumn -
(section.generatedOffset.generatedLine === needle.generatedLine ?
section.generatedOffset.generatedColumn - 1 : 0)
- });
- };
- IndexedSourceMapConsumer.prototype.sourceContentFor = function
IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
- for (var i = 0; i < this._sections.length; i++) {
- var section = this._sections[i];
- var content = section.consumer.sourceContentFor(aSource, true);
- if (content) {
- return content;
- }
- }
- if (nullOnMissing) {
- return null;
- } else {
- throw new Error('"' + aSource + '" is not in the SourceMap.');
- }
- };
- IndexedSourceMapConsumer.prototype.generatedPositionFor = function
IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
- for (var i = 0; i < this._sections.length; i++) {
- var section = this._sections[i];
- if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source'))
=== -1) {
- continue;
- }
- var generatedPosition = section.consumer.generatedPositionFor(aArgs);
- if (generatedPosition) {
- var ret = {
- line: generatedPosition.line +
(section.generatedOffset.generatedLine - 1),
- column: generatedPosition.column +
(section.generatedOffset.generatedLine === generatedPosition.line ?
section.generatedOffset.generatedColumn - 1 : 0)
- };
- return ret;
- }
- }
- return {
- line: null,
- column: null
- };
- };
- IndexedSourceMapConsumer.prototype._parseMappings = function
IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
- this.__generatedMappings = [];
- this.__originalMappings = [];
- for (var i = 0; i < this._sections.length; i++) {
- var section = this._sections[i];
- var sectionMappings = section.consumer._generatedMappings;
- for (var j = 0; j < sectionMappings.length; j++) {
- var mapping = sectionMappings[i];
- var source = mapping.source;
- var sourceRoot = section.consumer.sourceRoot;
- if (source != null && sourceRoot != null) {
- source = util.join(sourceRoot, source);
- }
- var adjustedMapping = {
- source: source,
- generatedLine: mapping.generatedLine +
(section.generatedOffset.generatedLine - 1),
- generatedColumn: mapping.column +
(section.generatedOffset.generatedLine === mapping.generatedLine) ?
section.generatedOffset.generatedColumn - 1 : 0,
- originalLine: mapping.originalLine,
- originalColumn: mapping.originalColumn,
- name: mapping.name
- };
- this.__generatedMappings.push(adjustedMapping);
- if (typeof adjustedMapping.originalLine === 'number') {
- this.__originalMappings.push(adjustedMapping);
- }
- }
- ;
- }
- ;
- this.__generatedMappings.sort(util.compareByGeneratedPositions);
- this.__originalMappings.sort(util.compareByOriginalPositions);
- };
- exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
- });
- });
- require.define('/node_modules/esutils/lib/utils.js', function (module,
exports, __dirname, __filename) {
- (function () {
- 'use strict';
- exports.ast = require('/node_modules/esutils/lib/ast.js', module);
- exports.code = require('/node_modules/esutils/lib/code.js', module);
- exports.keyword = require('/node_modules/esutils/lib/keyword.js',
module);
- }());
- });
- require.define('/node_modules/esutils/lib/keyword.js', function (module,
exports, __dirname, __filename) {
- (function () {
- 'use strict';
- var code = require('/node_modules/esutils/lib/code.js', module);
- function isStrictModeReservedWordES6(id) {
- switch (id) {
- case 'implements':
- case 'interface':
- case 'package':
- case 'private':
- case 'protected':
- case 'public':
- case 'static':
- case 'let':
- return true;
- default:
- return false;
- }
- }
- function isKeywordES5(id, strict) {
- if (!strict && id === 'yield') {
- return false;
- }
- return isKeywordES6(id, strict);
- }
- function isKeywordES6(id, strict) {
- if (strict && isStrictModeReservedWordES6(id)) {
- return true;
- }
- switch (id.length) {
- case 2:
- return id === 'if' || id === 'in' || id === 'do';
- case 3:
- return id === 'var' || id === 'for' || id === 'new' || id === 'try';
- 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;
- }
- }
- function isReservedWordES5(id, strict) {
- return id === 'null' || id === 'true' || id === 'false' ||
isKeywordES5(id, strict);
- }
- function isReservedWordES6(id, strict) {
- return id === 'null' || id === 'true' || id === 'false' ||
isKeywordES6(id, strict);
- }
- function isRestrictedWord(id) {
- return id === 'eval' || id === 'arguments';
- }
- function isIdentifierNameES5(id) {
- var i, iz, ch;
- if (id.length === 0) {
- return false;
- }
- ch = id.charCodeAt(0);
- if (!code.isIdentifierStartES5(ch)) {
- return false;
- }
- for (i = 1, iz = id.length; i < iz; ++i) {
- ch = id.charCodeAt(i);
- if (!code.isIdentifierPartES5(ch)) {
- return false;
- }
- }
- return true;
- }
- function decodeUtf16(lead, trail) {
- return (lead - 55296) * 1024 + (trail - 56320) + 65536;
- }
- function isIdentifierNameES6(id) {
- var i, iz, ch, lowCh, check;
- if (id.length === 0) {
- return false;
- }
- check = code.isIdentifierStartES6;
- for (i = 0, iz = id.length; i < iz; ++i) {
- ch = id.charCodeAt(i);
- if (55296 <= ch && ch <= 56319) {
- ++i;
- if (i >= iz) {
- return false;
- }
- lowCh = id.charCodeAt(i);
- if (!(56320 <= lowCh && lowCh <= 57343)) {
- return false;
- }
- ch = decodeUtf16(ch, lowCh);
- }
- if (!check(ch)) {
- return false;
- }
- check = code.isIdentifierPartES6;
- }
- return true;
- }
- function isIdentifierES5(id, strict) {
- return isIdentifierNameES5(id) && !isReservedWordES5(id, strict);
- }
- function isIdentifierES6(id, strict) {
- return isIdentifierNameES6(id) && !isReservedWordES6(id, strict);
- }
- module.exports = {
- isKeywordES5: isKeywordES5,
- isKeywordES6: isKeywordES6,
- isReservedWordES5: isReservedWordES5,
- isReservedWordES6: isReservedWordES6,
- isRestrictedWord: isRestrictedWord,
- isIdentifierNameES5: isIdentifierNameES5,
- isIdentifierNameES6: isIdentifierNameES6,
- isIdentifierES5: isIdentifierES5,
- isIdentifierES6: isIdentifierES6
- };
- }());
- });
- require.define('/node_modules/esutils/lib/code.js', function (module,
exports, __dirname, __filename) {
- (function () {
- 'use strict';
- var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START,
IDENTIFIER_PART, ch;
- ES5Regex = {
- NonAsciiIdentifierStart:
/[\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-\u085
[...]
- NonAsciiIdentifierPart:
/[\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-\u
[...]
- };
- ES6Regex = {
- NonAsciiIdentifierStart:
/[\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-\u085
[...]
- NonAsciiIdentifierPart:
/[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\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-\u08
[...]
- };
- function isDecimalDigit(ch) {
- return 48 <= ch && ch <= 57;
- }
- function isHexDigit(ch) {
- return 48 <= ch && ch <= 57 || 97 <= ch && ch <= 102 || 65 <= ch && ch
<= 70;
- }
- function isOctalDigit(ch) {
- return ch >= 48 && ch <= 55;
- }
- NON_ASCII_WHITESPACES = [
- 5760,
- 6158,
- 8192,
- 8193,
- 8194,
- 8195,
- 8196,
- 8197,
- 8198,
- 8199,
- 8200,
- 8201,
- 8202,
- 8239,
- 8287,
- 12288,
- 65279
- ];
- function isWhiteSpace(ch) {
- return ch === 32 || ch === 9 || ch === 11 || ch === 12 || ch === 160
|| ch >= 5760 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0;
- }
- function isLineTerminator(ch) {
- return ch === 10 || ch === 13 || ch === 8232 || ch === 8233;
- }
- function fromCodePoint(cp) {
- if (cp <= 65535) {
- return String.fromCharCode(cp);
- }
- var cu1 = String.fromCharCode(Math.floor((cp - 65536) / 1024) + 55296);
- var cu2 = String.fromCharCode((cp - 65536) % 1024 + 56320);
- return cu1 + cu2;
- }
- IDENTIFIER_START = new Array(128);
- for (ch = 0; ch < 128; ++ch) {
- IDENTIFIER_START[ch] = ch >= 97 && ch <= 122 || ch >= 65 && ch <= 90
|| ch === 36 || ch === 95;
- }
- IDENTIFIER_PART = new Array(128);
- for (ch = 0; ch < 128; ++ch) {
- IDENTIFIER_PART[ch] = ch >= 97 && ch <= 122 || ch >= 65 && ch <= 90 ||
ch >= 48 && ch <= 57 || ch === 36 || ch === 95;
- }
- function isIdentifierStartES5(ch) {
- return ch < 128 ? IDENTIFIER_START[ch] :
ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
- }
- function isIdentifierPartES5(ch) {
- return ch < 128 ? IDENTIFIER_PART[ch] :
ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
- }
- function isIdentifierStartES6(ch) {
- return ch < 128 ? IDENTIFIER_START[ch] :
ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
- }
- function isIdentifierPartES6(ch) {
- return ch < 128 ? IDENTIFIER_PART[ch] :
ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
- }
- module.exports = {
- isDecimalDigit: isDecimalDigit,
- isHexDigit: isHexDigit,
- isOctalDigit: isOctalDigit,
- isWhiteSpace: isWhiteSpace,
- isLineTerminator: isLineTerminator,
- isIdentifierStartES5: isIdentifierStartES5,
- isIdentifierPartES5: isIdentifierPartES5,
- isIdentifierStartES6: isIdentifierStartES6,
- isIdentifierPartES6: isIdentifierPartES6
- };
- }());
- });
- require.define('/node_modules/esutils/lib/ast.js', function (module,
exports, __dirname, __filename) {
- (function () {
- 'use strict';
- function isExpression(node) {
- if (node == null) {
- return false;
- }
- switch (node.type) {
- case 'ArrayExpression':
- case 'AssignmentExpression':
- case 'BinaryExpression':
- case 'CallExpression':
- case 'ConditionalExpression':
- case 'FunctionExpression':
- case 'Identifier':
- case 'Literal':
- case 'LogicalExpression':
- case 'MemberExpression':
- case 'NewExpression':
- case 'ObjectExpression':
- case 'SequenceExpression':
- case 'ThisExpression':
- case 'UnaryExpression':
- case 'UpdateExpression':
- return true;
- }
- return false;
- }
- function isIterationStatement(node) {
- if (node == null) {
- return false;
- }
- switch (node.type) {
- case 'DoWhileStatement':
- case 'ForInStatement':
- case 'ForStatement':
- case 'WhileStatement':
- return true;
- }
- return false;
- }
- function isStatement(node) {
- if (node == null) {
- return false;
- }
- switch (node.type) {
- case 'BlockStatement':
- case 'BreakStatement':
- case 'ContinueStatement':
- case 'DebuggerStatement':
- case 'DoWhileStatement':
- case 'EmptyStatement':
- case 'ExpressionStatement':
- case 'ForInStatement':
- case 'ForStatement':
- case 'IfStatement':
- case 'LabeledStatement':
- case 'ReturnStatement':
- case 'SwitchStatement':
- case 'ThrowStatement':
- case 'TryStatement':
- case 'VariableDeclaration':
- case 'WhileStatement':
- case 'WithStatement':
- return true;
- }
- return false;
- }
- function isSourceElement(node) {
- return isStatement(node) || node != null && node.type ===
'FunctionDeclaration';
- }
- function trailingStatement(node) {
- switch (node.type) {
- case 'IfStatement':
- if (node.alternate != null) {
- return node.alternate;
- }
- return node.consequent;
- case 'LabeledStatement':
- case 'ForStatement':
- case 'ForInStatement':
- case 'WhileStatement':
- case 'WithStatement':
- return node.body;
- }
- return null;
- }
- function isProblematicIfStatement(node) {
- var current;
- if (node.type !== 'IfStatement') {
- return false;
- }
- if (node.alternate == null) {
- return false;
- }
- current = node.consequent;
- do {
- if (current.type === 'IfStatement') {
- if (current.alternate == null) {
- return true;
- }
- }
- current = trailingStatement(current);
- } while (current);
- return false;
- }
- module.exports = {
- isExpression: isExpression,
- isStatement: isStatement,
- isIterationStatement: isIterationStatement,
- isSourceElement: isSourceElement,
- isProblematicIfStatement: isProblematicIfStatement,
- trailingStatement: trailingStatement
- };
- }());
- });
- require.define('/node_modules/estraverse/estraverse.js', function (module,
exports, __dirname, __filename) {
- (function (root, factory) {
- 'use strict';
- 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);
- 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) {
- var keys = objectKeys(from), key, i, len;
- for (i = 0, len = keys.length; i < len; i += 1) {
- key = keys[i];
- to[key] = from[key];
- }
- return to;
- }
- Syntax = {
- AssignmentExpression: 'AssignmentExpression',
- ArrayExpression: 'ArrayExpression',
- ArrayPattern: 'ArrayPattern',
- ArrowFunctionExpression: 'ArrowFunctionExpression',
- AwaitExpression: 'AwaitExpression',
- BlockStatement: 'BlockStatement',
- BinaryExpression: 'BinaryExpression',
- BreakStatement: 'BreakStatement',
- CallExpression: 'CallExpression',
- CatchClause: 'CatchClause',
- ClassBody: 'ClassBody',
- ClassDeclaration: 'ClassDeclaration',
- ClassExpression: 'ClassExpression',
- ComprehensionBlock: 'ComprehensionBlock',
- ComprehensionExpression: 'ComprehensionExpression',
- 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',
- 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'],
- 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'
- ],
- ComprehensionExpression: [
- 'blocks',
- 'filter',
- 'body'
- ],
- 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'
- ],
- 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']
- };
- 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() {
- }
- 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);
- }
- }
- if (!this.__current.path) {
- return null;
- }
- 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;
- };
- Controller.prototype.type = function () {
- var node = this.current();
- return node.type || this.__current.wrap;
- };
- Controller.prototype.parents = function parents() {
- var i, iz, result;
- result = [];
- for (i = 1, iz = this.__leavelist.length; i < iz; ++i) {
- result.push(this.__leavelist[i].node);
- }
- return result;
- };
- 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;
- };
- Controller.prototype.notify = function notify(flag) {
- this.__state = flag;
- };
- Controller.prototype.skip = function () {
- this.notify(SKIP);
- };
- Controller.prototype['break'] = function () {
- this.notify(BREAK);
- };
- 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 = {};
- worklist = this.__worklist;
- leavelist = this.__leavelist;
- 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()) {
- key = element.ref.key;
- parent = element.ref.parent;
- 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 = {};
- worklist = this.__worklist;
- leavelist = this.__leavelist;
- 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);
- if (target !== undefined && target !== BREAK && target !== SKIP &&
target !== REMOVE) {
- 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);
- if (target !== undefined && target !== BREAK && target !== SKIP &&
target !== REMOVE) {
- 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 = 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) {
- var comments = [], comment, len, i, cursor;
- if (!tree.range) {
- throw new Error('attachComments needs range information');
- }
- 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));
- }
- 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;
- }
- }
- 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;
- }
- }
- 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;
- }));
- });
- require('/tools/entry-point.js');
-}.call(this, this));
diff --git a/tooling/talertest/selenium/esprima.js
b/tooling/talertest/selenium/esprima.js
deleted file mode 100644
index d95f56eb..00000000
--- a/tooling/talertest/selenium/esprima.js
+++ /dev/null
@@ -1,6605 +0,0 @@
-(function webpackUniversalModuleDefinition(root, factory) {
-/* istanbul ignore next */
- if(typeof exports === 'object' && typeof module === 'object')
- module.exports = factory();
- else if(typeof define === 'function' && define.amd)
- define([], factory);
-/* istanbul ignore next */
- else if(typeof exports === 'object')
- exports["esprima"] = factory();
- else
- root["esprima"] = factory();
-})(this, function() {
-return /******/ (function(modules) { // webpackBootstrap
-/******/ // The module cache
-/******/ var installedModules = {};
-
-/******/ // The require function
-/******/ function __webpack_require__(moduleId) {
-
-/******/ // Check if module is in cache
-/* istanbul ignore if */
-/******/ if(installedModules[moduleId])
-/******/ return installedModules[moduleId].exports;
-
-/******/ // Create a new module (and put it into the cache)
-/******/ var module = installedModules[moduleId] = {
-/******/ exports: {},
-/******/ id: moduleId,
-/******/ loaded: false
-/******/ };
-
-/******/ // Execute the module function
-/******/ modules[moduleId].call(module.exports, module,
module.exports, __webpack_require__);
-
-/******/ // Flag the module as loaded
-/******/ module.loaded = true;
-
-/******/ // Return the exports of the module
-/******/ return module.exports;
-/******/ }
-
-
-/******/ // expose the modules object (__webpack_modules__)
-/******/ __webpack_require__.m = modules;
-
-/******/ // expose the module cache
-/******/ __webpack_require__.c = installedModules;
-
-/******/ // __webpack_public_path__
-/******/ __webpack_require__.p = "";
-
-/******/ // Load entry module and return exports
-/******/ return __webpack_require__(0);
-/******/ })
-/************************************************************************/
-/******/ ([
-/* 0 */
-/***/ function(module, exports, __webpack_require__) {
-
- /*
- Copyright JS Foundation and other contributors, https://js.foundation/
-
- 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY
- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES
- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES;
- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND
- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
- "use strict";
- var comment_handler_1 = __webpack_require__(1);
- var parser_1 = __webpack_require__(3);
- var jsx_parser_1 = __webpack_require__(11);
- var tokenizer_1 = __webpack_require__(15);
- function parse(code, options, delegate) {
- var commentHandler = null;
- var proxyDelegate = function (node, metadata) {
- if (delegate) {
- delegate(node, metadata);
- }
- if (commentHandler) {
- commentHandler.visit(node, metadata);
- }
- };
- var parserDelegate = (typeof delegate === 'function') ?
proxyDelegate : null;
- var collectComment = false;
- if (options) {
- collectComment = (typeof options.comment === 'boolean' &&
options.comment);
- var attachComment = (typeof options.attachComment === 'boolean'
&& options.attachComment);
- if (collectComment || attachComment) {
- commentHandler = new comment_handler_1.CommentHandler();
- commentHandler.attach = attachComment;
- options.comment = true;
- parserDelegate = proxyDelegate;
- }
- }
- var isModule = false;
- if (options && typeof options.sourceType === 'string') {
- isModule = (options.sourceType === 'module');
- }
- var parser;
- if (options && typeof options.jsx === 'boolean' && options.jsx) {
- parser = new jsx_parser_1.JSXParser(code, options,
parserDelegate);
- }
- else {
- parser = new parser_1.Parser(code, options, parserDelegate);
- }
- var program = isModule ? parser.parseModule() :
parser.parseScript();
- var ast = (program);
- if (collectComment && commentHandler) {
- ast.comments = commentHandler.comments;
- }
- if (parser.config.tokens) {
- ast.tokens = parser.tokens;
- }
- if (parser.config.tolerant) {
- ast.errors = parser.errorHandler.errors;
- }
- return ast;
- }
- exports.parse = parse;
- function parseModule(code, options, delegate) {
- var parsingOptions = options || {};
- parsingOptions.sourceType = 'module';
- return parse(code, parsingOptions, delegate);
- }
- exports.parseModule = parseModule;
- function parseScript(code, options, delegate) {
- var parsingOptions = options || {};
- parsingOptions.sourceType = 'script';
- return parse(code, parsingOptions, delegate);
- }
- exports.parseScript = parseScript;
- function tokenize(code, options, delegate) {
- var tokenizer = new tokenizer_1.Tokenizer(code, options);
- var tokens;
- tokens = [];
- try {
- while (true) {
- var token = tokenizer.getNextToken();
- if (!token) {
- break;
- }
- if (delegate) {
- token = delegate(token);
- }
- tokens.push(token);
- }
- }
- catch (e) {
- tokenizer.errorHandler.tolerate(e);
- }
- if (tokenizer.errorHandler.tolerant) {
- tokens.errors = tokenizer.errors();
- }
- return tokens;
- }
- exports.tokenize = tokenize;
- var syntax_1 = __webpack_require__(2);
- exports.Syntax = syntax_1.Syntax;
- // Sync with *.json manifests.
- exports.version = '4.0.0-dev';
-
-
-/***/ },
-/* 1 */
-/***/ function(module, exports, __webpack_require__) {
-
- "use strict";
- var syntax_1 = __webpack_require__(2);
- var CommentHandler = (function () {
- function CommentHandler() {
- this.attach = false;
- this.comments = [];
- this.stack = [];
- this.leading = [];
- this.trailing = [];
- }
- CommentHandler.prototype.insertInnerComments = function (node,
metadata) {
- // innnerComments for properties empty block
- // `function a() {/** comments **\/}`
- if (node.type === syntax_1.Syntax.BlockStatement &&
node.body.length === 0) {
- var innerComments = [];
- for (var i = this.leading.length - 1; i >= 0; --i) {
- var entry = this.leading[i];
- if (metadata.end.offset >= entry.start) {
- innerComments.unshift(entry.comment);
- this.leading.splice(i, 1);
- this.trailing.splice(i, 1);
- }
- }
- if (innerComments.length) {
- node.innerComments = innerComments;
- }
- }
- };
- CommentHandler.prototype.findTrailingComments = function (metadata)
{
- var trailingComments = [];
- if (this.trailing.length > 0) {
- for (var i = this.trailing.length - 1; i >= 0; --i) {
- var entry_1 = this.trailing[i];
- if (entry_1.start >= metadata.end.offset) {
- trailingComments.unshift(entry_1.comment);
- }
- }
- this.trailing.length = 0;
- return trailingComments;
- }
- var entry = this.stack[this.stack.length - 1];
- if (entry && entry.node.trailingComments) {
- var firstComment = entry.node.trailingComments[0];
- if (firstComment && firstComment.range[0] >=
metadata.end.offset) {
- trailingComments = entry.node.trailingComments;
- delete entry.node.trailingComments;
- }
- }
- return trailingComments;
- };
- CommentHandler.prototype.findLeadingComments = function (metadata) {
- var leadingComments = [];
- var target;
- while (this.stack.length > 0) {
- var entry = this.stack[this.stack.length - 1];
- if (entry && entry.start >= metadata.start.offset) {
- target = entry.node;
- this.stack.pop();
- }
- else {
- break;
- }
- }
- if (target) {
- var count = target.leadingComments ?
target.leadingComments.length : 0;
- for (var i = count - 1; i >= 0; --i) {
- var comment = target.leadingComments[i];
- if (comment.range[1] <= metadata.start.offset) {
- leadingComments.unshift(comment);
- target.leadingComments.splice(i, 1);
- }
- }
- if (target.leadingComments && target.leadingComments.length
=== 0) {
- delete target.leadingComments;
- }
- return leadingComments;
- }
- for (var i = this.leading.length - 1; i >= 0; --i) {
- var entry = this.leading[i];
- if (entry.start <= metadata.start.offset) {
- leadingComments.unshift(entry.comment);
- this.leading.splice(i, 1);
- }
- }
- return leadingComments;
- };
- CommentHandler.prototype.visitNode = function (node, metadata) {
- if (node.type === syntax_1.Syntax.Program && node.body.length >
0) {
- return;
- }
- this.insertInnerComments(node, metadata);
- var trailingComments = this.findTrailingComments(metadata);
- var leadingComments = this.findLeadingComments(metadata);
- if (leadingComments.length > 0) {
- node.leadingComments = leadingComments;
- }
- if (trailingComments.length > 0) {
- node.trailingComments = trailingComments;
- }
- this.stack.push({
- node: node,
- start: metadata.start.offset
- });
- };
- CommentHandler.prototype.visitComment = function (node, metadata) {
- var type = (node.type[0] === 'L') ? 'Line' : 'Block';
- var comment = {
- type: type,
- value: node.value
- };
- if (node.range) {
- comment.range = node.range;
- }
- if (node.loc) {
- comment.loc = node.loc;
- }
- this.comments.push(comment);
- if (this.attach) {
- var entry = {
- comment: {
- type: type,
- value: node.value,
- range: [metadata.start.offset, metadata.end.offset]
- },
- start: metadata.start.offset
- };
- if (node.loc) {
- entry.comment.loc = node.loc;
- }
- node.type = type;
- this.leading.push(entry);
- this.trailing.push(entry);
- }
- };
- CommentHandler.prototype.visit = function (node, metadata) {
- if (node.type === 'LineComment') {
- this.visitComment(node, metadata);
- }
- else if (node.type === 'BlockComment') {
- this.visitComment(node, metadata);
- }
- else if (this.attach) {
- this.visitNode(node, metadata);
- }
- };
- return CommentHandler;
- }());
- exports.CommentHandler = CommentHandler;
-
-
-/***/ },
-/* 2 */
-/***/ function(module, exports) {
-
- "use strict";
- exports.Syntax = {
- AssignmentExpression: 'AssignmentExpression',
- AssignmentPattern: 'AssignmentPattern',
- ArrayExpression: 'ArrayExpression',
- ArrayPattern: 'ArrayPattern',
- ArrowFunctionExpression: 'ArrowFunctionExpression',
- AwaitExpression: 'AwaitExpression',
- BlockStatement: 'BlockStatement',
- BinaryExpression: 'BinaryExpression',
- BreakStatement: 'BreakStatement',
- CallExpression: 'CallExpression',
- CatchClause: 'CatchClause',
- ClassBody: 'ClassBody',
- ClassDeclaration: 'ClassDeclaration',
- ClassExpression: 'ClassExpression',
- ConditionalExpression: 'ConditionalExpression',
- ContinueStatement: 'ContinueStatement',
- DoWhileStatement: 'DoWhileStatement',
- DebuggerStatement: 'DebuggerStatement',
- EmptyStatement: 'EmptyStatement',
- ExportAllDeclaration: 'ExportAllDeclaration',
- ExportDefaultDeclaration: 'ExportDefaultDeclaration',
- ExportNamedDeclaration: 'ExportNamedDeclaration',
- ExportSpecifier: 'ExportSpecifier',
- ExpressionStatement: 'ExpressionStatement',
- ForStatement: 'ForStatement',
- ForOfStatement: 'ForOfStatement',
- ForInStatement: 'ForInStatement',
- FunctionDeclaration: 'FunctionDeclaration',
- FunctionExpression: 'FunctionExpression',
- Identifier: 'Identifier',
- IfStatement: 'IfStatement',
- ImportDeclaration: 'ImportDeclaration',
- ImportDefaultSpecifier: 'ImportDefaultSpecifier',
- ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
- ImportSpecifier: 'ImportSpecifier',
- Literal: 'Literal',
- LabeledStatement: 'LabeledStatement',
- LogicalExpression: 'LogicalExpression',
- MemberExpression: 'MemberExpression',
- MetaProperty: 'MetaProperty',
- MethodDefinition: 'MethodDefinition',
- NewExpression: 'NewExpression',
- ObjectExpression: 'ObjectExpression',
- ObjectPattern: 'ObjectPattern',
- Program: 'Program',
- Property: 'Property',
- RestElement: 'RestElement',
- ReturnStatement: 'ReturnStatement',
- SequenceExpression: 'SequenceExpression',
- SpreadElement: 'SpreadElement',
- Super: 'Super',
- SwitchCase: 'SwitchCase',
- SwitchStatement: 'SwitchStatement',
- 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'
- };
-
-
-/***/ },
-/* 3 */
-/***/ function(module, exports, __webpack_require__) {
-
- "use strict";
- var assert_1 = __webpack_require__(4);
- var messages_1 = __webpack_require__(5);
- var error_handler_1 = __webpack_require__(6);
- var token_1 = __webpack_require__(7);
- var scanner_1 = __webpack_require__(8);
- var syntax_1 = __webpack_require__(2);
- var Node = __webpack_require__(10);
- var ArrowParameterPlaceHolder = 'ArrowParameterPlaceHolder';
- var Parser = (function () {
- function Parser(code, options, delegate) {
- if (options === void 0) { options = {}; }
- this.config = {
- range: (typeof options.range === 'boolean') &&
options.range,
- loc: (typeof options.loc === 'boolean') && options.loc,
- source: null,
- tokens: (typeof options.tokens === 'boolean') &&
options.tokens,
- comment: (typeof options.comment === 'boolean') &&
options.comment,
- tolerant: (typeof options.tolerant === 'boolean') &&
options.tolerant
- };
- if (this.config.loc && options.source && options.source !==
null) {
- this.config.source = String(options.source);
- }
- this.delegate = delegate;
- this.errorHandler = new error_handler_1.ErrorHandler();
- this.errorHandler.tolerant = this.config.tolerant;
- this.scanner = new scanner_1.Scanner(code, this.errorHandler);
- this.scanner.trackComment = this.config.comment;
- this.operatorPrecedence = {
- ')': 0,
- ';': 0,
- ',': 0,
- '=': 0,
- ']': 0,
- '||': 1,
- '&&': 2,
- '|': 3,
- '^': 4,
- '&': 5,
- '==': 6,
- '!=': 6,
- '===': 6,
- '!==': 6,
- '<': 7,
- '>': 7,
- '<=': 7,
- '>=': 7,
- '<<': 8,
- '>>': 8,
- '>>>': 8,
- '+': 9,
- '-': 9,
- '*': 11,
- '/': 11,
- '%': 11
- };
- this.lookahead = null;
- this.hasLineTerminator = false;
- this.context = {
- isModule: false,
- await: false,
- allowIn: true,
- allowYield: true,
- firstCoverInitializedNameError: null,
- isAssignmentTarget: false,
- isBindingElement: false,
- inFunctionBody: false,
- inIteration: false,
- inSwitch: false,
- labelSet: {},
- strict: false
- };
- this.tokens = [];
- this.startMarker = {
- index: 0,
- lineNumber: this.scanner.lineNumber,
- lineStart: 0
- };
- this.lastMarker = {
- index: 0,
- lineNumber: this.scanner.lineNumber,
- lineStart: 0
- };
- this.nextToken();
- this.lastMarker = {
- index: this.scanner.index,
- lineNumber: this.scanner.lineNumber,
- lineStart: this.scanner.lineStart
- };
- }
- Parser.prototype.throwError = function (messageFormat) {
- var values = [];
- for (var _i = 1; _i < arguments.length; _i++) {
- values[_i - 1] = arguments[_i];
- }
- var args = Array.prototype.slice.call(arguments, 1);
- var msg = messageFormat.replace(/%(\d)/g, function (whole, idx)
{
- assert_1.assert(idx < args.length, 'Message reference must
be in range');
- return args[idx];
- });
- var index = this.lastMarker.index;
- var line = this.lastMarker.lineNumber;
- var column = this.lastMarker.index - this.lastMarker.lineStart
+ 1;
- throw this.errorHandler.createError(index, line, column, msg);
- };
- Parser.prototype.tolerateError = function (messageFormat) {
- var values = [];
- for (var _i = 1; _i < arguments.length; _i++) {
- values[_i - 1] = arguments[_i];
- }
- var args = Array.prototype.slice.call(arguments, 1);
- var msg = messageFormat.replace(/%(\d)/g, function (whole, idx)
{
- assert_1.assert(idx < args.length, 'Message reference must
be in range');
- return args[idx];
- });
- var index = this.lastMarker.index;
- var line = this.scanner.lineNumber;
- var column = this.lastMarker.index - this.lastMarker.lineStart
+ 1;
- this.errorHandler.tolerateError(index, line, column, msg);
- };
- // Throw an exception because of the token.
- Parser.prototype.unexpectedTokenError = function (token, message) {
- var msg = message || messages_1.Messages.UnexpectedToken;
- var value;
- if (token) {
- if (!message) {
- msg = (token.type === token_1.Token.EOF) ?
messages_1.Messages.UnexpectedEOS :
- (token.type === token_1.Token.Identifier) ?
messages_1.Messages.UnexpectedIdentifier :
- (token.type === token_1.Token.NumericLiteral) ?
messages_1.Messages.UnexpectedNumber :
- (token.type ===
token_1.Token.StringLiteral) ? messages_1.Messages.UnexpectedString :
- (token.type === token_1.Token.Template)
? messages_1.Messages.UnexpectedTemplate :
- messages_1.Messages.UnexpectedToken;
- if (token.type === token_1.Token.Keyword) {
- if (this.scanner.isFutureReservedWord(token.value))
{
- msg = messages_1.Messages.UnexpectedReserved;
- }
- else if (this.context.strict &&
this.scanner.isStrictModeReservedWord(token.value)) {
- msg = messages_1.Messages.StrictReservedWord;
- }
- }
- }
- value = (token.type === token_1.Token.Template) ?
token.value.raw : token.value;
- }
- else {
- value = 'ILLEGAL';
- }
- msg = msg.replace('%0', value);
- if (token && typeof token.lineNumber === 'number') {
- var index = token.start;
- var line = token.lineNumber;
- var column = token.start - this.lastMarker.lineStart + 1;
- return this.errorHandler.createError(index, line, column,
msg);
- }
- else {
- var index = this.lastMarker.index;
- var line = this.lastMarker.lineNumber;
- var column = index - this.lastMarker.lineStart + 1;
- return this.errorHandler.createError(index, line, column,
msg);
- }
- };
- Parser.prototype.throwUnexpectedToken = function (token, message) {
- throw this.unexpectedTokenError(token, message);
- };
- Parser.prototype.tolerateUnexpectedToken = function (token,
message) {
- this.errorHandler.tolerate(this.unexpectedTokenError(token,
message));
- };
- Parser.prototype.collectComments = function () {
- if (!this.config.comment) {
- this.scanner.scanComments();
- }
- else {
- var comments = this.scanner.scanComments();
- if (comments.length > 0 && this.delegate) {
- for (var i = 0; i < comments.length; ++i) {
- var e = comments[i];
- var node = void 0;
- node = {
- type: e.multiLine ? 'BlockComment' :
'LineComment',
- value: this.scanner.source.slice(e.slice[0],
e.slice[1])
- };
- if (this.config.range) {
- node.range = e.range;
- }
- if (this.config.loc) {
- node.loc = e.loc;
- }
- var metadata = {
- start: {
- line: e.loc.start.line,
- column: e.loc.start.column,
- offset: e.range[0]
- },
- end: {
- line: e.loc.end.line,
- column: e.loc.end.column,
- offset: e.range[1]
- }
- };
- this.delegate(node, metadata);
- }
- }
- }
- };
- // From internal representation to an external structure
- Parser.prototype.getTokenRaw = function (token) {
- return this.scanner.source.slice(token.start, token.end);
- };
- Parser.prototype.convertToken = function (token) {
- var t;
- t = {
- type: token_1.TokenName[token.type],
- value: this.getTokenRaw(token)
- };
- if (this.config.range) {
- t.range = [token.start, token.end];
- }
- if (this.config.loc) {
- t.loc = {
- start: {
- line: this.startMarker.lineNumber,
- column: this.startMarker.index -
this.startMarker.lineStart
- },
- end: {
- line: this.scanner.lineNumber,
- column: this.scanner.index - this.scanner.lineStart
- }
- };
- }
- if (token.regex) {
- t.regex = token.regex;
- }
- return t;
- };
- Parser.prototype.nextToken = function () {
- var token = this.lookahead;
- this.lastMarker.index = this.scanner.index;
- this.lastMarker.lineNumber = this.scanner.lineNumber;
- this.lastMarker.lineStart = this.scanner.lineStart;
- this.collectComments();
- this.startMarker.index = this.scanner.index;
- this.startMarker.lineNumber = this.scanner.lineNumber;
- this.startMarker.lineStart = this.scanner.lineStart;
- var next;
- next = this.scanner.lex();
- this.hasLineTerminator = (token && next) ? (token.lineNumber
!== next.lineNumber) : false;
- if (next && this.context.strict && next.type ===
token_1.Token.Identifier) {
- if (this.scanner.isStrictModeReservedWord(next.value)) {
- next.type = token_1.Token.Keyword;
- }
- }
- this.lookahead = next;
- if (this.config.tokens && next.type !== token_1.Token.EOF) {
- this.tokens.push(this.convertToken(next));
- }
- return token;
- };
- Parser.prototype.nextRegexToken = function () {
- this.collectComments();
- var token = this.scanner.scanRegExp();
- if (this.config.tokens) {
- // Pop the previous token, '/' or '/='
- // This is added from the lookahead token.
- this.tokens.pop();
- this.tokens.push(this.convertToken(token));
- }
- // Prime the next lookahead.
- this.lookahead = token;
- this.nextToken();
- return token;
- };
- Parser.prototype.createNode = function () {
- return {
- index: this.startMarker.index,
- line: this.startMarker.lineNumber,
- column: this.startMarker.index - this.startMarker.lineStart
- };
- };
- Parser.prototype.startNode = function (token) {
- return {
- index: token.start,
- line: token.lineNumber,
- column: token.start - token.lineStart
- };
- };
- Parser.prototype.finalize = function (meta, node) {
- if (this.config.range) {
- node.range = [meta.index, this.lastMarker.index];
- }
- if (this.config.loc) {
- node.loc = {
- start: {
- line: meta.line,
- column: meta.column
- },
- end: {
- line: this.lastMarker.lineNumber,
- column: this.lastMarker.index -
this.lastMarker.lineStart
- }
- };
- if (this.config.source) {
- node.loc.source = this.config.source;
- }
- }
- if (this.delegate) {
- var metadata = {
- start: {
- line: meta.line,
- column: meta.column,
- offset: meta.index
- },
- end: {
- line: this.lastMarker.lineNumber,
- column: this.lastMarker.index -
this.lastMarker.lineStart,
- offset: this.lastMarker.index
- }
- };
- this.delegate(node, metadata);
- }
- return node;
- };
- // Expect the next token to match the specified punctuator.
- // If not, an exception will be thrown.
- Parser.prototype.expect = function (value) {
- var token = this.nextToken();
- if (token.type !== token_1.Token.Punctuator || token.value !==
value) {
- this.throwUnexpectedToken(token);
- }
- };
- // Quietly expect a comma when in tolerant mode, otherwise
delegates to expect().
- Parser.prototype.expectCommaSeparator = function () {
- if (this.config.tolerant) {
- var token = this.lookahead;
- if (token.type === token_1.Token.Punctuator && token.value
=== ',') {
- this.nextToken();
- }
- else if (token.type === token_1.Token.Punctuator &&
token.value === ';') {
- this.nextToken();
- this.tolerateUnexpectedToken(token);
- }
- else {
- this.tolerateUnexpectedToken(token,
messages_1.Messages.UnexpectedToken);
- }
- }
- else {
- this.expect(',');
- }
- };
- // Expect the next token to match the specified keyword.
- // If not, an exception will be thrown.
- Parser.prototype.expectKeyword = function (keyword) {
- var token = this.nextToken();
- if (token.type !== token_1.Token.Keyword || token.value !==
keyword) {
- this.throwUnexpectedToken(token);
- }
- };
- // Return true if the next token matches the specified punctuator.
- Parser.prototype.match = function (value) {
- return this.lookahead.type === token_1.Token.Punctuator &&
this.lookahead.value === value;
- };
- // Return true if the next token matches the specified keyword
- Parser.prototype.matchKeyword = function (keyword) {
- return this.lookahead.type === token_1.Token.Keyword &&
this.lookahead.value === keyword;
- };
- // Return true if the next token matches the specified contextual
keyword
- // (where an identifier is sometimes a keyword depending on the
context)
- Parser.prototype.matchContextualKeyword = function (keyword) {
- return this.lookahead.type === token_1.Token.Identifier &&
this.lookahead.value === keyword;
- };
- // Return true if the next token is an assignment operator
- Parser.prototype.matchAssign = function () {
- if (this.lookahead.type !== token_1.Token.Punctuator) {
- return false;
- }
- var op = this.lookahead.value;
- return op === '=' ||
- op === '*=' ||
- op === '**=' ||
- op === '/=' ||
- op === '%=' ||
- op === '+=' ||
- op === '-=' ||
- op === '<<=' ||
- op === '>>=' ||
- op === '>>>=' ||
- op === '&=' ||
- op === '^=' ||
- op === '|=';
- };
- // Cover grammar support.
- //
- // When an assignment expression position starts with an left
parenthesis, the determination of the type
- // of the syntax is to be deferred arbitrarily long until the end
of the parentheses pair (plus a lookahead)
- // or the first comma. This situation also defers the determination
of all the expressions nested in the pair.
- //
- // There are three productions that can be parsed in a parentheses
pair that needs to be determined
- // after the outermost pair is closed. They are:
- //
- // 1. AssignmentExpression
- // 2. BindingElements
- // 3. AssignmentTargets
- //
- // In order to avoid exponential backtracking, we use two flags to
denote if the production can be
- // binding element or assignment target.
- //
- // The three productions have the relationship:
- //
- // BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression
- //
- // with a single exception that CoverInitializedName when used
directly in an Expression, generates
- // an early error. Therefore, we need the third state,
firstCoverInitializedNameError, to track the
- // first usage of CoverInitializedName and report it when we
reached the end of the parentheses pair.
- //
- // isolateCoverGrammar function runs the given parser function with
a new cover grammar context, and it does not
- // effect the current flags. This means the production the parser
parses is only used as an expression. Therefore
- // the CoverInitializedName check is conducted.
- //
- // inheritCoverGrammar function runs the given parse function with
a new cover grammar context, and it propagates
- // the flags outside of the parser. This means the production the
parser parses is used as a part of a potential
- // pattern. The CoverInitializedName check is deferred.
- Parser.prototype.isolateCoverGrammar = function (parseFunction) {
- var previousIsBindingElement = this.context.isBindingElement;
- var previousIsAssignmentTarget =
this.context.isAssignmentTarget;
- var previousFirstCoverInitializedNameError =
this.context.firstCoverInitializedNameError;
- this.context.isBindingElement = true;
- this.context.isAssignmentTarget = true;
- this.context.firstCoverInitializedNameError = null;
- var result = parseFunction.call(this);
- if (this.context.firstCoverInitializedNameError !== null) {
-
this.throwUnexpectedToken(this.context.firstCoverInitializedNameError);
- }
- this.context.isBindingElement = previousIsBindingElement;
- this.context.isAssignmentTarget = previousIsAssignmentTarget;
- this.context.firstCoverInitializedNameError =
previousFirstCoverInitializedNameError;
- return result;
- };
- Parser.prototype.inheritCoverGrammar = function (parseFunction) {
- var previousIsBindingElement = this.context.isBindingElement;
- var previousIsAssignmentTarget =
this.context.isAssignmentTarget;
- var previousFirstCoverInitializedNameError =
this.context.firstCoverInitializedNameError;
- this.context.isBindingElement = true;
- this.context.isAssignmentTarget = true;
- this.context.firstCoverInitializedNameError = null;
- var result = parseFunction.call(this);
- this.context.isBindingElement = this.context.isBindingElement
&& previousIsBindingElement;
- this.context.isAssignmentTarget =
this.context.isAssignmentTarget && previousIsAssignmentTarget;
- this.context.firstCoverInitializedNameError =
previousFirstCoverInitializedNameError ||
this.context.firstCoverInitializedNameError;
- return result;
- };
- Parser.prototype.consumeSemicolon = function () {
- if (this.match(';')) {
- this.nextToken();
- }
- else if (!this.hasLineTerminator) {
- if (this.lookahead.type !== token_1.Token.EOF &&
!this.match('}')) {
- this.throwUnexpectedToken(this.lookahead);
- }
- this.lastMarker.index = this.startMarker.index;
- this.lastMarker.lineNumber = this.startMarker.lineNumber;
- this.lastMarker.lineStart = this.startMarker.lineStart;
- }
- };
- // ECMA-262 12.2 Primary Expressions
- Parser.prototype.parsePrimaryExpression = function () {
- var node = this.createNode();
- var expr;
- var value, token, raw;
- switch (this.lookahead.type) {
- case token_1.Token.Identifier:
- if ((this.context.isModule || this.context.await) &&
this.lookahead.value === 'await') {
- this.tolerateUnexpectedToken(this.lookahead);
- }
- expr = this.matchAsyncFunction() ?
this.parseFunctionExpression() : this.finalize(node, new
Node.Identifier(this.nextToken().value));
- break;
- case token_1.Token.NumericLiteral:
- case token_1.Token.StringLiteral:
- if (this.context.strict && this.lookahead.octal) {
- this.tolerateUnexpectedToken(this.lookahead,
messages_1.Messages.StrictOctalLiteral);
- }
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- token = this.nextToken();
- raw = this.getTokenRaw(token);
- expr = this.finalize(node, new
Node.Literal(token.value, raw));
- break;
- case token_1.Token.BooleanLiteral:
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- token = this.nextToken();
- token.value = (token.value === 'true');
- raw = this.getTokenRaw(token);
- expr = this.finalize(node, new
Node.Literal(token.value, raw));
- break;
- case token_1.Token.NullLiteral:
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- token = this.nextToken();
- token.value = null;
- raw = this.getTokenRaw(token);
- expr = this.finalize(node, new
Node.Literal(token.value, raw));
- break;
- case token_1.Token.Template:
- expr = this.parseTemplateLiteral();
- break;
- case token_1.Token.Punctuator:
- value = this.lookahead.value;
- switch (value) {
- case '(':
- this.context.isBindingElement = false;
- expr =
this.inheritCoverGrammar(this.parseGroupExpression);
- break;
- case '[':
- expr =
this.inheritCoverGrammar(this.parseArrayInitializer);
- break;
- case '{':
- expr =
this.inheritCoverGrammar(this.parseObjectInitializer);
- break;
- case '/':
- case '/=':
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- this.scanner.index = this.startMarker.index;
- token = this.nextRegexToken();
- raw = this.getTokenRaw(token);
- expr = this.finalize(node, new
Node.RegexLiteral(token.value, raw, token.regex));
- break;
- default:
- expr =
this.throwUnexpectedToken(this.nextToken());
- }
- break;
- case token_1.Token.Keyword:
- if (!this.context.strict && this.context.allowYield &&
this.matchKeyword('yield')) {
- expr = this.parseIdentifierName();
- }
- else if (!this.context.strict &&
this.matchKeyword('let')) {
- expr = this.finalize(node, new
Node.Identifier(this.nextToken().value));
- }
- else {
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- if (this.matchKeyword('function')) {
- expr = this.parseFunctionExpression();
- }
- else if (this.matchKeyword('this')) {
- this.nextToken();
- expr = this.finalize(node, new
Node.ThisExpression());
- }
- else if (this.matchKeyword('class')) {
- expr = this.parseClassExpression();
- }
- else {
- expr =
this.throwUnexpectedToken(this.nextToken());
- }
- }
- break;
- default:
- expr = this.throwUnexpectedToken(this.nextToken());
- }
- return expr;
- };
- // ECMA-262 12.2.5 Array Initializer
- Parser.prototype.parseSpreadElement = function () {
- var node = this.createNode();
- this.expect('...');
- var arg =
this.inheritCoverGrammar(this.parseAssignmentExpression);
- return this.finalize(node, new Node.SpreadElement(arg));
- };
- Parser.prototype.parseArrayInitializer = function () {
- var node = this.createNode();
- var elements = [];
- this.expect('[');
- while (!this.match(']')) {
- if (this.match(',')) {
- this.nextToken();
- elements.push(null);
- }
- else if (this.match('...')) {
- var element = this.parseSpreadElement();
- if (!this.match(']')) {
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- this.expect(',');
- }
- elements.push(element);
- }
- else {
-
elements.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
- if (!this.match(']')) {
- this.expect(',');
- }
- }
- }
- this.expect(']');
- return this.finalize(node, new Node.ArrayExpression(elements));
- };
- // ECMA-262 12.2.6 Object Initializer
- Parser.prototype.parsePropertyMethod = function (params) {
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- var previousStrict = this.context.strict;
- var body =
this.isolateCoverGrammar(this.parseFunctionSourceElements);
- if (this.context.strict && params.firstRestricted) {
- this.tolerateUnexpectedToken(params.firstRestricted,
params.message);
- }
- if (this.context.strict && params.stricted) {
- this.tolerateUnexpectedToken(params.stricted,
params.message);
- }
- this.context.strict = previousStrict;
- return body;
- };
- Parser.prototype.parsePropertyMethodFunction = function () {
- var isGenerator = false;
- var node = this.createNode();
- var previousAllowYield = this.context.allowYield;
- this.context.allowYield = false;
- var params = this.parseFormalParameters();
- var method = this.parsePropertyMethod(params);
- this.context.allowYield = previousAllowYield;
- return this.finalize(node, new Node.FunctionExpression(null,
params.params, method, isGenerator));
- };
- Parser.prototype.parsePropertyMethodAsyncFunction = function () {
- var node = this.createNode();
- var previousAllowYield = this.context.allowYield;
- var previousAwait = this.context.await;
- this.context.allowYield = false;
- this.context.await = true;
- var params = this.parseFormalParameters();
- var method = this.parsePropertyMethod(params);
- this.context.allowYield = previousAllowYield;
- this.context.await = previousAwait;
- return this.finalize(node, new
Node.AsyncFunctionExpression(null, params.params, method));
- };
- Parser.prototype.parseObjectPropertyKey = function () {
- var node = this.createNode();
- var token = this.nextToken();
- var key;
- switch (token.type) {
- case token_1.Token.StringLiteral:
- case token_1.Token.NumericLiteral:
- if (this.context.strict && token.octal) {
- this.tolerateUnexpectedToken(token,
messages_1.Messages.StrictOctalLiteral);
- }
- var raw = this.getTokenRaw(token);
- key = this.finalize(node, new Node.Literal(token.value,
raw));
- break;
- case token_1.Token.Identifier:
- case token_1.Token.BooleanLiteral:
- case token_1.Token.NullLiteral:
- case token_1.Token.Keyword:
- key = this.finalize(node, new
Node.Identifier(token.value));
- break;
- case token_1.Token.Punctuator:
- if (token.value === '[') {
- key =
this.isolateCoverGrammar(this.parseAssignmentExpression);
- this.expect(']');
- }
- else {
- key = this.throwUnexpectedToken(token);
- }
- break;
- default:
- key = this.throwUnexpectedToken(token);
- }
- return key;
- };
- Parser.prototype.isPropertyKey = function (key, value) {
- return (key.type === syntax_1.Syntax.Identifier && key.name ===
value) ||
- (key.type === syntax_1.Syntax.Literal && key.value ===
value);
- };
- Parser.prototype.parseObjectProperty = function (hasProto) {
- var node = this.createNode();
- var token = this.lookahead;
- var kind;
- var key = null;
- var value = null;
- var computed = false;
- var method = false;
- var shorthand = false;
- var isAsync = false;
- if (token.type === token_1.Token.Identifier) {
- var id = token.value;
- this.nextToken();
- if (id === 'async') {
- isAsync = !this.hasLineTerminator &&
(this.lookahead.type === token_1.Token.Identifier);
- if (isAsync) {
- token = this.lookahead;
- id = token.value;
- this.nextToken();
- }
- }
- key = this.finalize(node, new Node.Identifier(id));
- }
- else if (this.match('*')) {
- this.nextToken();
- }
- else {
- computed = this.match('[');
- key = this.parseObjectPropertyKey();
- }
- var lookaheadPropertyKey =
this.qualifiedPropertyName(this.lookahead);
- if (token.type === token_1.Token.Identifier && !isAsync &&
token.value === 'get' && lookaheadPropertyKey) {
- kind = 'get';
- computed = this.match('[');
- key = this.parseObjectPropertyKey();
- this.context.allowYield = false;
- value = this.parseGetterMethod();
- }
- else if (token.type === token_1.Token.Identifier && !isAsync &&
token.value === 'set' && lookaheadPropertyKey) {
- kind = 'set';
- computed = this.match('[');
- key = this.parseObjectPropertyKey();
- value = this.parseSetterMethod();
- }
- else if (token.type === token_1.Token.Punctuator && token.value
=== '*' && lookaheadPropertyKey) {
- kind = 'init';
- computed = this.match('[');
- key = this.parseObjectPropertyKey();
- value = this.parseGeneratorMethod();
- method = true;
- }
- else {
- if (!key) {
- this.throwUnexpectedToken(this.lookahead);
- }
- kind = 'init';
- if (this.match(':')) {
- if (!computed && this.isPropertyKey(key, '__proto__')) {
- if (hasProto.value) {
-
this.tolerateError(messages_1.Messages.DuplicateProtoProperty);
- }
- hasProto.value = true;
- }
- this.nextToken();
- value =
this.inheritCoverGrammar(this.parseAssignmentExpression);
- }
- else if (this.match('(')) {
- value = isAsync ?
this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction();
- method = true;
- }
- else if (token.type === token_1.Token.Identifier) {
- var id = this.finalize(node, new
Node.Identifier(token.value));
- if (this.match('=')) {
- this.context.firstCoverInitializedNameError =
this.lookahead;
- this.nextToken();
- shorthand = true;
- var init =
this.isolateCoverGrammar(this.parseAssignmentExpression);
- value = this.finalize(node, new
Node.AssignmentPattern(id, init));
- }
- else {
- shorthand = true;
- value = id;
- }
- }
- else {
- this.throwUnexpectedToken(this.nextToken());
- }
- }
- return this.finalize(node, new Node.Property(kind, (key),
computed, value, method, shorthand));
- };
- Parser.prototype.parseObjectInitializer = function () {
- var node = this.createNode();
- this.expect('{');
- var properties = [];
- var hasProto = { value: false };
- while (!this.match('}')) {
- properties.push(this.parseObjectProperty(hasProto));
- if (!this.match('}')) {
- this.expectCommaSeparator();
- }
- }
- this.expect('}');
- return this.finalize(node, new
Node.ObjectExpression(properties));
- };
- // ECMA-262 12.2.9 Template Literals
- Parser.prototype.parseTemplateHead = function () {
- assert_1.assert(this.lookahead.head, 'Template literal must
start with a template head');
- var node = this.createNode();
- var token = this.nextToken();
- var value = {
- raw: token.value.raw,
- cooked: token.value.cooked
- };
- return this.finalize(node, new Node.TemplateElement(value,
token.tail));
- };
- Parser.prototype.parseTemplateElement = function () {
- if (this.lookahead.type !== token_1.Token.Template) {
- this.throwUnexpectedToken();
- }
- var node = this.createNode();
- var token = this.nextToken();
- var value = {
- raw: token.value.raw,
- cooked: token.value.cooked
- };
- return this.finalize(node, new Node.TemplateElement(value,
token.tail));
- };
- Parser.prototype.parseTemplateLiteral = function () {
- var node = this.createNode();
- var expressions = [];
- var quasis = [];
- var quasi = this.parseTemplateHead();
- quasis.push(quasi);
- while (!quasi.tail) {
- expressions.push(this.parseExpression());
- quasi = this.parseTemplateElement();
- quasis.push(quasi);
- }
- return this.finalize(node, new Node.TemplateLiteral(quasis,
expressions));
- };
- // ECMA-262 12.2.10 The Grouping Operator
- Parser.prototype.reinterpretExpressionAsPattern = function (expr) {
- switch (expr.type) {
- case syntax_1.Syntax.Identifier:
- case syntax_1.Syntax.MemberExpression:
- case syntax_1.Syntax.RestElement:
- case syntax_1.Syntax.AssignmentPattern:
- break;
- case syntax_1.Syntax.SpreadElement:
- expr.type = syntax_1.Syntax.RestElement;
- this.reinterpretExpressionAsPattern(expr.argument);
- break;
- case syntax_1.Syntax.ArrayExpression:
- expr.type = syntax_1.Syntax.ArrayPattern;
- for (var i = 0; i < expr.elements.length; i++) {
- if (expr.elements[i] !== null) {
-
this.reinterpretExpressionAsPattern(expr.elements[i]);
- }
- }
- break;
- case syntax_1.Syntax.ObjectExpression:
- expr.type = syntax_1.Syntax.ObjectPattern;
- for (var i = 0; i < expr.properties.length; i++) {
-
this.reinterpretExpressionAsPattern(expr.properties[i].value);
- }
- break;
- case syntax_1.Syntax.AssignmentExpression:
- expr.type = syntax_1.Syntax.AssignmentPattern;
- delete expr.operator;
- this.reinterpretExpressionAsPattern(expr.left);
- break;
- default:
- // Allow other node type for tolerant parsing.
- break;
- }
- };
- Parser.prototype.parseGroupExpression = function () {
- var expr;
- this.expect('(');
- if (this.match(')')) {
- this.nextToken();
- if (!this.match('=>')) {
- this.expect('=>');
- }
- expr = {
- type: ArrowParameterPlaceHolder,
- params: [],
- async: false
- };
- }
- else {
- var startToken = this.lookahead;
- var params = [];
- if (this.match('...')) {
- expr = this.parseRestElement(params);
- this.expect(')');
- if (!this.match('=>')) {
- this.expect('=>');
- }
- expr = {
- type: ArrowParameterPlaceHolder,
- params: [expr],
- async: false
- };
- }
- else {
- var arrow = false;
- this.context.isBindingElement = true;
- expr =
this.inheritCoverGrammar(this.parseAssignmentExpression);
- if (this.match(',')) {
- var expressions = [];
- this.context.isAssignmentTarget = false;
- expressions.push(expr);
- while (this.startMarker.index <
this.scanner.length) {
- if (!this.match(',')) {
- break;
- }
- this.nextToken();
- if (this.match(')')) {
- this.nextToken();
- for (var i = 0; i < expressions.length;
i++) {
-
this.reinterpretExpressionAsPattern(expressions[i]);
- }
- arrow = true;
- expr = {
- type: ArrowParameterPlaceHolder,
- params: expressions,
- async: false
- };
- }
- else if (this.match('...')) {
- if (!this.context.isBindingElement) {
-
this.throwUnexpectedToken(this.lookahead);
- }
-
expressions.push(this.parseRestElement(params));
- this.expect(')');
- if (!this.match('=>')) {
- this.expect('=>');
- }
- this.context.isBindingElement = false;
- for (var i = 0; i < expressions.length;
i++) {
-
this.reinterpretExpressionAsPattern(expressions[i]);
- }
- arrow = true;
- expr = {
- type: ArrowParameterPlaceHolder,
- params: expressions,
- async: false
- };
- }
- else {
-
expressions.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
- }
- if (arrow) {
- break;
- }
- }
- if (!arrow) {
- expr =
this.finalize(this.startNode(startToken), new
Node.SequenceExpression(expressions));
- }
- }
- if (!arrow) {
- this.expect(')');
- if (this.match('=>')) {
- if (expr.type === syntax_1.Syntax.Identifier &&
expr.name === 'yield') {
- arrow = true;
- expr = {
- type: ArrowParameterPlaceHolder,
- params: [expr],
- async: false
- };
- }
- if (!arrow) {
- if (!this.context.isBindingElement) {
-
this.throwUnexpectedToken(this.lookahead);
- }
- if (expr.type ===
syntax_1.Syntax.SequenceExpression) {
- for (var i = 0; i <
expr.expressions.length; i++) {
-
this.reinterpretExpressionAsPattern(expr.expressions[i]);
- }
- }
- else {
-
this.reinterpretExpressionAsPattern(expr);
- }
- var params_1 = (expr.type ===
syntax_1.Syntax.SequenceExpression ? expr.expressions : [expr]);
- expr = {
- type: ArrowParameterPlaceHolder,
- params: params_1,
- async: false
- };
- }
- }
- this.context.isBindingElement = false;
- }
- }
- }
- return expr;
- };
- // ECMA-262 12.3 Left-Hand-Side Expressions
- Parser.prototype.parseArguments = function () {
- this.expect('(');
- var args = [];
- if (!this.match(')')) {
- while (true) {
- var expr = this.match('...') ?
this.parseSpreadElement() :
-
this.isolateCoverGrammar(this.parseAssignmentExpression);
- args.push(expr);
- if (this.match(')')) {
- break;
- }
- this.expectCommaSeparator();
- if (this.match(')')) {
- break;
- }
- }
- }
- this.expect(')');
- return args;
- };
- Parser.prototype.isIdentifierName = function (token) {
- return token.type === token_1.Token.Identifier ||
- token.type === token_1.Token.Keyword ||
- token.type === token_1.Token.BooleanLiteral ||
- token.type === token_1.Token.NullLiteral;
- };
- Parser.prototype.parseIdentifierName = function () {
- var node = this.createNode();
- var token = this.nextToken();
- if (!this.isIdentifierName(token)) {
- this.throwUnexpectedToken(token);
- }
- return this.finalize(node, new Node.Identifier(token.value));
- };
- Parser.prototype.parseNewExpression = function () {
- var node = this.createNode();
- var id = this.parseIdentifierName();
- assert_1.assert(id.name === 'new', 'New expression must start
with `new`');
- var expr;
- if (this.match('.')) {
- this.nextToken();
- if (this.lookahead.type === token_1.Token.Identifier &&
this.context.inFunctionBody && this.lookahead.value === 'target') {
- var property = this.parseIdentifierName();
- expr = new Node.MetaProperty(id, property);
- }
- else {
- this.throwUnexpectedToken(this.lookahead);
- }
- }
- else {
- var callee =
this.isolateCoverGrammar(this.parseLeftHandSideExpression);
- var args = this.match('(') ? this.parseArguments() : [];
- expr = new Node.NewExpression(callee, args);
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- }
- return this.finalize(node, expr);
- };
- Parser.prototype.parseAsyncArgument = function () {
- var arg = this.parseAssignmentExpression();
- this.context.firstCoverInitializedNameError = null;
- return arg;
- };
- Parser.prototype.parseAsyncArguments = function () {
- this.expect('(');
- var args = [];
- if (!this.match(')')) {
- while (true) {
- var expr = this.match('...') ?
this.parseSpreadElement() :
- this.isolateCoverGrammar(this.parseAsyncArgument);
- args.push(expr);
- if (this.match(')')) {
- break;
- }
- this.expectCommaSeparator();
- if (this.match(')')) {
- break;
- }
- }
- }
- this.expect(')');
- return args;
- };
- Parser.prototype.parseLeftHandSideExpressionAllowCall = function ()
{
- var startToken = this.lookahead;
- var maybeAsync = this.matchContextualKeyword('async');
- var previousAllowIn = this.context.allowIn;
- this.context.allowIn = true;
- var expr;
- if (this.matchKeyword('super') && this.context.inFunctionBody) {
- expr = this.createNode();
- this.nextToken();
- expr = this.finalize(expr, new Node.Super());
- if (!this.match('(') && !this.match('.') &&
!this.match('[')) {
- this.throwUnexpectedToken(this.lookahead);
- }
- }
- else {
- expr = this.inheritCoverGrammar(this.matchKeyword('new') ?
this.parseNewExpression : this.parsePrimaryExpression);
- }
- while (true) {
- if (this.match('.')) {
- this.context.isBindingElement = false;
- this.context.isAssignmentTarget = true;
- this.expect('.');
- var property = this.parseIdentifierName();
- expr = this.finalize(this.startNode(startToken), new
Node.StaticMemberExpression(expr, property));
- }
- else if (this.match('(')) {
- var asyncArrow = maybeAsync && (startToken.lineNumber
=== this.lookahead.lineNumber);
- this.context.isBindingElement = false;
- this.context.isAssignmentTarget = false;
- var args = asyncArrow ? this.parseAsyncArguments() :
this.parseArguments();
- expr = this.finalize(this.startNode(startToken), new
Node.CallExpression(expr, args));
- if (asyncArrow && this.match('=>')) {
- expr = {
- type: ArrowParameterPlaceHolder,
- params: args,
- async: true
- };
- }
- }
- else if (this.match('[')) {
- this.context.isBindingElement = false;
- this.context.isAssignmentTarget = true;
- this.expect('[');
- var property =
this.isolateCoverGrammar(this.parseExpression);
- this.expect(']');
- expr = this.finalize(this.startNode(startToken), new
Node.ComputedMemberExpression(expr, property));
- }
- else if (this.lookahead.type === token_1.Token.Template &&
this.lookahead.head) {
- var quasi = this.parseTemplateLiteral();
- expr = this.finalize(this.startNode(startToken), new
Node.TaggedTemplateExpression(expr, quasi));
- }
- else {
- break;
- }
- }
- this.context.allowIn = previousAllowIn;
- return expr;
- };
- Parser.prototype.parseSuper = function () {
- var node = this.createNode();
- this.expectKeyword('super');
- if (!this.match('[') && !this.match('.')) {
- this.throwUnexpectedToken(this.lookahead);
- }
- return this.finalize(node, new Node.Super());
- };
- Parser.prototype.parseLeftHandSideExpression = function () {
- assert_1.assert(this.context.allowIn, 'callee of new expression
always allow in keyword.');
- var node = this.startNode(this.lookahead);
- var expr = (this.matchKeyword('super') &&
this.context.inFunctionBody) ? this.parseSuper() :
- this.inheritCoverGrammar(this.matchKeyword('new') ?
this.parseNewExpression : this.parsePrimaryExpression);
- while (true) {
- if (this.match('[')) {
- this.context.isBindingElement = false;
- this.context.isAssignmentTarget = true;
- this.expect('[');
- var property =
this.isolateCoverGrammar(this.parseExpression);
- this.expect(']');
- expr = this.finalize(node, new
Node.ComputedMemberExpression(expr, property));
- }
- else if (this.match('.')) {
- this.context.isBindingElement = false;
- this.context.isAssignmentTarget = true;
- this.expect('.');
- var property = this.parseIdentifierName();
- expr = this.finalize(node, new
Node.StaticMemberExpression(expr, property));
- }
- else if (this.lookahead.type === token_1.Token.Template &&
this.lookahead.head) {
- var quasi = this.parseTemplateLiteral();
- expr = this.finalize(node, new
Node.TaggedTemplateExpression(expr, quasi));
- }
- else {
- break;
- }
- }
- return expr;
- };
- // ECMA-262 12.4 Update Expressions
- Parser.prototype.parseUpdateExpression = function () {
- var expr;
- var startToken = this.lookahead;
- if (this.match('++') || this.match('--')) {
- var node = this.startNode(startToken);
- var token = this.nextToken();
- expr = this.inheritCoverGrammar(this.parseUnaryExpression);
- if (this.context.strict && expr.type ===
syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) {
- this.tolerateError(messages_1.Messages.StrictLHSPrefix);
- }
- if (!this.context.isAssignmentTarget) {
-
this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
- }
- var prefix = true;
- expr = this.finalize(node, new
Node.UpdateExpression(token.value, expr, prefix));
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- }
- else {
- expr =
this.inheritCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
- if (!this.hasLineTerminator && this.lookahead.type ===
token_1.Token.Punctuator) {
- if (this.match('++') || this.match('--')) {
- if (this.context.strict && expr.type ===
syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) {
-
this.tolerateError(messages_1.Messages.StrictLHSPostfix);
- }
- if (!this.context.isAssignmentTarget) {
-
this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
- }
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- var operator = this.nextToken().value;
- var prefix = false;
- expr = this.finalize(this.startNode(startToken),
new Node.UpdateExpression(operator, expr, prefix));
- }
- }
- }
- return expr;
- };
- // ECMA-262 12.5 Unary Operators
- Parser.prototype.parseAwaitExpression = function () {
- var node = this.createNode();
- this.nextToken();
- var argument = this.parseUnaryExpression();
- return this.finalize(node, new Node.AwaitExpression(argument));
- };
- Parser.prototype.parseUnaryExpression = function () {
- var expr;
- if (this.match('+') || this.match('-') || this.match('~') ||
this.match('!') ||
- this.matchKeyword('delete') || this.matchKeyword('void') ||
this.matchKeyword('typeof')) {
- var node = this.startNode(this.lookahead);
- var token = this.nextToken();
- expr = this.inheritCoverGrammar(this.parseUnaryExpression);
- expr = this.finalize(node, new
Node.UnaryExpression(token.value, expr));
- if (this.context.strict && expr.operator === 'delete' &&
expr.argument.type === syntax_1.Syntax.Identifier) {
- this.tolerateError(messages_1.Messages.StrictDelete);
- }
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- }
- else if (this.context.await &&
this.matchContextualKeyword('await')) {
- expr = this.parseAwaitExpression();
- }
- else {
- expr = this.parseUpdateExpression();
- }
- return expr;
- };
- Parser.prototype.parseExponentiationExpression = function () {
- var startToken = this.lookahead;
- var expr = this.inheritCoverGrammar(this.parseUnaryExpression);
- if (expr.type !== syntax_1.Syntax.UnaryExpression &&
this.match('**')) {
- this.nextToken();
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- var left = expr;
- var right =
this.isolateCoverGrammar(this.parseExponentiationExpression);
- expr = this.finalize(this.startNode(startToken), new
Node.BinaryExpression('**', left, right));
- }
- return expr;
- };
- // ECMA-262 12.6 Exponentiation Operators
- // ECMA-262 12.7 Multiplicative Operators
- // ECMA-262 12.8 Additive Operators
- // ECMA-262 12.9 Bitwise Shift Operators
- // ECMA-262 12.10 Relational Operators
- // ECMA-262 12.11 Equality Operators
- // ECMA-262 12.12 Binary Bitwise Operators
- // ECMA-262 12.13 Binary Logical Operators
- Parser.prototype.binaryPrecedence = function (token) {
- var op = token.value;
- var precedence;
- if (token.type === token_1.Token.Punctuator) {
- precedence = this.operatorPrecedence[op] || 0;
- }
- else if (token.type === token_1.Token.Keyword) {
- precedence = (op === 'instanceof' || (this.context.allowIn
&& op === 'in')) ? 7 : 0;
- }
- else {
- precedence = 0;
- }
- return precedence;
- };
- Parser.prototype.parseBinaryExpression = function () {
- var startToken = this.lookahead;
- var expr =
this.inheritCoverGrammar(this.parseExponentiationExpression);
- var token = this.lookahead;
- var prec = this.binaryPrecedence(token);
- if (prec > 0) {
- this.nextToken();
- token.prec = prec;
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- var markers = [startToken, this.lookahead];
- var left = expr;
- var right =
this.isolateCoverGrammar(this.parseExponentiationExpression);
- var stack = [left, token, right];
- while (true) {
- prec = this.binaryPrecedence(this.lookahead);
- if (prec <= 0) {
- break;
- }
- // Reduce: make a binary expression from the three
topmost entries.
- while ((stack.length > 2) && (prec <=
stack[stack.length - 2].prec)) {
- right = stack.pop();
- var operator = stack.pop().value;
- left = stack.pop();
- markers.pop();
- var node = this.startNode(markers[markers.length -
1]);
- stack.push(this.finalize(node, new
Node.BinaryExpression(operator, left, right)));
- }
- // Shift.
- token = this.nextToken();
- token.prec = prec;
- stack.push(token);
- markers.push(this.lookahead);
-
stack.push(this.isolateCoverGrammar(this.parseExponentiationExpression));
- }
- // Final reduce to clean-up the stack.
- var i = stack.length - 1;
- expr = stack[i];
- markers.pop();
- while (i > 1) {
- var node = this.startNode(markers.pop());
- expr = this.finalize(node, new
Node.BinaryExpression(stack[i - 1].value, stack[i - 2], expr));
- i -= 2;
- }
- }
- return expr;
- };
- // ECMA-262 12.14 Conditional Operator
- Parser.prototype.parseConditionalExpression = function () {
- var startToken = this.lookahead;
- var expr = this.inheritCoverGrammar(this.parseBinaryExpression);
- if (this.match('?')) {
- this.nextToken();
- var previousAllowIn = this.context.allowIn;
- this.context.allowIn = true;
- var consequent =
this.isolateCoverGrammar(this.parseAssignmentExpression);
- this.context.allowIn = previousAllowIn;
- this.expect(':');
- var alternate =
this.isolateCoverGrammar(this.parseAssignmentExpression);
- expr = this.finalize(this.startNode(startToken), new
Node.ConditionalExpression(expr, consequent, alternate));
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- }
- return expr;
- };
- // ECMA-262 12.15 Assignment Operators
- Parser.prototype.checkPatternParam = function (options, param) {
- switch (param.type) {
- case syntax_1.Syntax.Identifier:
- this.validateParam(options, param, param.name);
- break;
- case syntax_1.Syntax.RestElement:
- this.checkPatternParam(options, param.argument);
- break;
- case syntax_1.Syntax.AssignmentPattern:
- this.checkPatternParam(options, param.left);
- break;
- case syntax_1.Syntax.ArrayPattern:
- for (var i = 0; i < param.elements.length; i++) {
- if (param.elements[i] !== null) {
- this.checkPatternParam(options,
param.elements[i]);
- }
- }
- break;
- case syntax_1.Syntax.ObjectPattern:
- for (var i = 0; i < param.properties.length; i++) {
- this.checkPatternParam(options,
param.properties[i].value);
- }
- break;
- default:
- break;
- }
- };
- Parser.prototype.reinterpretAsCoverFormalsList = function (expr) {
- var params = [expr];
- var options;
- var asyncArrow = false;
- switch (expr.type) {
- case syntax_1.Syntax.Identifier:
- break;
- case ArrowParameterPlaceHolder:
- params = expr.params;
- asyncArrow = expr.async;
- break;
- default:
- return null;
- }
- options = {
- paramSet: {}
- };
- for (var i = 0; i < params.length; ++i) {
- var param = params[i];
- if (param.type === syntax_1.Syntax.AssignmentPattern) {
- if (param.right.type ===
syntax_1.Syntax.YieldExpression) {
- if (param.right.argument) {
- this.throwUnexpectedToken(this.lookahead);
- }
- param.right.type = syntax_1.Syntax.Identifier;
- param.right.name = 'yield';
- delete param.right.argument;
- delete param.right.delegate;
- }
- }
- else if (asyncArrow && param.type ===
syntax_1.Syntax.Identifier && param.name === 'await') {
- this.throwUnexpectedToken(this.lookahead);
- }
- this.checkPatternParam(options, param);
- params[i] = param;
- }
- if (this.context.strict || !this.context.allowYield) {
- for (var i = 0; i < params.length; ++i) {
- var param = params[i];
- if (param.type === syntax_1.Syntax.YieldExpression) {
- this.throwUnexpectedToken(this.lookahead);
- }
- }
- }
- if (options.message === messages_1.Messages.StrictParamDupe) {
- var token = this.context.strict ? options.stricted :
options.firstRestricted;
- this.throwUnexpectedToken(token, options.message);
- }
- return {
- params: params,
- stricted: options.stricted,
- firstRestricted: options.firstRestricted,
- message: options.message
- };
- };
- Parser.prototype.parseAssignmentExpression = function () {
- var expr;
- if (!this.context.allowYield && this.matchKeyword('yield')) {
- expr = this.parseYieldExpression();
- }
- else {
- var startToken = this.lookahead;
- var token = startToken;
- expr = this.parseConditionalExpression();
- if (token.type === token_1.Token.Identifier &&
(token.lineNumber === this.lookahead.lineNumber) && token.value === 'async' &&
(this.lookahead.type === token_1.Token.Identifier)) {
- var arg = this.parsePrimaryExpression();
- expr = {
- type: ArrowParameterPlaceHolder,
- params: [arg],
- async: true
- };
- }
- if (expr.type === ArrowParameterPlaceHolder ||
this.match('=>')) {
- // ECMA-262 14.2 Arrow Function Definitions
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- var isAsync = expr.async;
- var list = this.reinterpretAsCoverFormalsList(expr);
- if (list) {
- if (this.hasLineTerminator) {
- this.tolerateUnexpectedToken(this.lookahead);
- }
- this.context.firstCoverInitializedNameError = null;
- var previousStrict = this.context.strict;
- var previousAllowYield = this.context.allowYield;
- var previousAwait = this.context.await;
- this.context.allowYield = true;
- this.context.await = isAsync;
- var node = this.startNode(startToken);
- this.expect('=>');
- var body = this.match('{') ?
this.parseFunctionSourceElements() :
-
this.isolateCoverGrammar(this.parseAssignmentExpression);
- var expression = body.type !==
syntax_1.Syntax.BlockStatement;
- if (this.context.strict && list.firstRestricted) {
- this.throwUnexpectedToken(list.firstRestricted,
list.message);
- }
- if (this.context.strict && list.stricted) {
- this.tolerateUnexpectedToken(list.stricted,
list.message);
- }
- expr = isAsync ? this.finalize(node, new
Node.AsyncArrowFunctionExpression(list.params, body, expression)) :
- this.finalize(node, new
Node.ArrowFunctionExpression(list.params, body, expression));
- this.context.strict = previousStrict;
- this.context.allowYield = previousAllowYield;
- this.context.await = previousAwait;
- }
- }
- else {
- if (this.matchAssign()) {
- if (!this.context.isAssignmentTarget) {
-
this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
- }
- if (this.context.strict && expr.type ===
syntax_1.Syntax.Identifier) {
- var id = (expr);
- if (this.scanner.isRestrictedWord(id.name)) {
- this.tolerateUnexpectedToken(token,
messages_1.Messages.StrictLHSAssignment);
- }
- if
(this.scanner.isStrictModeReservedWord(id.name)) {
- this.tolerateUnexpectedToken(token,
messages_1.Messages.StrictReservedWord);
- }
- }
- if (!this.match('=')) {
- this.context.isAssignmentTarget = false;
- this.context.isBindingElement = false;
- }
- else {
- this.reinterpretExpressionAsPattern(expr);
- }
- token = this.nextToken();
- var right =
this.isolateCoverGrammar(this.parseAssignmentExpression);
- expr = this.finalize(this.startNode(startToken),
new Node.AssignmentExpression(token.value, expr, right));
- this.context.firstCoverInitializedNameError = null;
- }
- }
- }
- return expr;
- };
- // ECMA-262 12.16 Comma Operator
- Parser.prototype.parseExpression = function () {
- var startToken = this.lookahead;
- var expr =
this.isolateCoverGrammar(this.parseAssignmentExpression);
- if (this.match(',')) {
- var expressions = [];
- expressions.push(expr);
- while (this.startMarker.index < this.scanner.length) {
- if (!this.match(',')) {
- break;
- }
- this.nextToken();
-
expressions.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
- }
- expr = this.finalize(this.startNode(startToken), new
Node.SequenceExpression(expressions));
- }
- return expr;
- };
- // ECMA-262 13.2 Block
- Parser.prototype.parseStatementListItem = function () {
- var statement;
- this.context.isAssignmentTarget = true;
- this.context.isBindingElement = true;
- if (this.lookahead.type === token_1.Token.Keyword) {
- switch (this.lookahead.value) {
- case 'export':
- if (!this.context.isModule) {
- this.tolerateUnexpectedToken(this.lookahead,
messages_1.Messages.IllegalExportDeclaration);
- }
- statement = this.parseExportDeclaration();
- break;
- case 'import':
- if (!this.context.isModule) {
- this.tolerateUnexpectedToken(this.lookahead,
messages_1.Messages.IllegalImportDeclaration);
- }
- statement = this.parseImportDeclaration();
- break;
- case 'const':
- statement = this.parseLexicalDeclaration({ inFor:
false });
- break;
- case 'function':
- statement = this.parseFunctionDeclaration();
- break;
- case 'class':
- statement = this.parseClassDeclaration();
- break;
- case 'let':
- statement = this.isLexicalDeclaration() ?
this.parseLexicalDeclaration({ inFor: false }) : this.parseStatement();
- break;
- default:
- statement = this.parseStatement();
- break;
- }
- }
- else {
- statement = this.parseStatement();
- }
- return statement;
- };
- Parser.prototype.parseBlock = function () {
- var node = this.createNode();
- this.expect('{');
- var block = [];
- while (true) {
- if (this.match('}')) {
- break;
- }
- block.push(this.parseStatementListItem());
- }
- this.expect('}');
- return this.finalize(node, new Node.BlockStatement(block));
- };
- // ECMA-262 13.3.1 Let and Const Declarations
- Parser.prototype.parseLexicalBinding = function (kind, options) {
- var node = this.createNode();
- var params = [];
- var id = this.parsePattern(params, kind);
- // ECMA-262 12.2.1
- if (this.context.strict && id.type ===
syntax_1.Syntax.Identifier) {
- if (this.scanner.isRestrictedWord((id).name)) {
- this.tolerateError(messages_1.Messages.StrictVarName);
- }
- }
- var init = null;
- if (kind === 'const') {
- if (!this.matchKeyword('in') &&
!this.matchContextualKeyword('of')) {
- if (this.match('=')) {
- this.nextToken();
- init =
this.isolateCoverGrammar(this.parseAssignmentExpression);
- }
- else {
-
this.throwError(messages_1.Messages.DeclarationMissingInitializer, 'const');
- }
- }
- }
- else if ((!options.inFor && id.type !==
syntax_1.Syntax.Identifier) || this.match('=')) {
- this.expect('=');
- init =
this.isolateCoverGrammar(this.parseAssignmentExpression);
- }
- return this.finalize(node, new Node.VariableDeclarator(id,
init));
- };
- Parser.prototype.parseBindingList = function (kind, options) {
- var list = [this.parseLexicalBinding(kind, options)];
- while (this.match(',')) {
- this.nextToken();
- list.push(this.parseLexicalBinding(kind, options));
- }
- return list;
- };
- Parser.prototype.isLexicalDeclaration = function () {
- var previousIndex = this.scanner.index;
- var previousLineNumber = this.scanner.lineNumber;
- var previousLineStart = this.scanner.lineStart;
- this.collectComments();
- var next = this.scanner.lex();
- this.scanner.index = previousIndex;
- this.scanner.lineNumber = previousLineNumber;
- this.scanner.lineStart = previousLineStart;
- return (next.type === token_1.Token.Identifier) ||
- (next.type === token_1.Token.Punctuator && next.value ===
'[') ||
- (next.type === token_1.Token.Punctuator && next.value ===
'{') ||
- (next.type === token_1.Token.Keyword && next.value ===
'let') ||
- (next.type === token_1.Token.Keyword && next.value ===
'yield');
- };
- Parser.prototype.parseLexicalDeclaration = function (options) {
- var node = this.createNode();
- var kind = this.nextToken().value;
- assert_1.assert(kind === 'let' || kind === 'const', 'Lexical
declaration must be either let or const');
- var declarations = this.parseBindingList(kind, options);
- this.consumeSemicolon();
- return this.finalize(node, new
Node.VariableDeclaration(declarations, kind));
- };
- // ECMA-262 13.3.3 Destructuring Binding Patterns
- Parser.prototype.parseBindingRestElement = function (params, kind) {
- var node = this.createNode();
- this.expect('...');
- params.push(this.lookahead);
- var arg = this.parseVariableIdentifier(kind);
- return this.finalize(node, new Node.RestElement(arg));
- };
- Parser.prototype.parseArrayPattern = function (params, kind) {
- var node = this.createNode();
- this.expect('[');
- var elements = [];
- while (!this.match(']')) {
- if (this.match(',')) {
- this.nextToken();
- elements.push(null);
- }
- else {
- if (this.match('...')) {
- elements.push(this.parseBindingRestElement(params,
kind));
- break;
- }
- else {
- elements.push(this.parsePatternWithDefault(params,
kind));
- }
- if (!this.match(']')) {
- this.expect(',');
- }
- }
- }
- this.expect(']');
- return this.finalize(node, new Node.ArrayPattern(elements));
- };
- Parser.prototype.parsePropertyPattern = function (params, kind) {
- var node = this.createNode();
- var computed = false;
- var shorthand = false;
- var method = false;
- var key;
- var value;
- if (this.lookahead.type === token_1.Token.Identifier) {
- var keyToken = this.lookahead;
- key = this.parseVariableIdentifier();
- var init = this.finalize(node, new
Node.Identifier(keyToken.value));
- if (this.match('=')) {
- params.push(keyToken);
- shorthand = true;
- this.nextToken();
- var expr = this.parseAssignmentExpression();
- value = this.finalize(this.startNode(keyToken), new
Node.AssignmentPattern(init, expr));
- }
- else if (!this.match(':')) {
- params.push(keyToken);
- shorthand = true;
- value = init;
- }
- else {
- this.expect(':');
- value = this.parsePatternWithDefault(params, kind);
- }
- }
- else {
- computed = this.match('[');
- key = this.parseObjectPropertyKey();
- this.expect(':');
- value = this.parsePatternWithDefault(params, kind);
- }
- return this.finalize(node, new Node.Property('init', key,
computed, value, method, shorthand));
- };
- Parser.prototype.parseObjectPattern = function (params, kind) {
- var node = this.createNode();
- var properties = [];
- this.expect('{');
- while (!this.match('}')) {
- properties.push(this.parsePropertyPattern(params, kind));
- if (!this.match('}')) {
- this.expect(',');
- }
- }
- this.expect('}');
- return this.finalize(node, new Node.ObjectPattern(properties));
- };
- Parser.prototype.parsePattern = function (params, kind) {
- var pattern;
- if (this.match('[')) {
- pattern = this.parseArrayPattern(params, kind);
- }
- else if (this.match('{')) {
- pattern = this.parseObjectPattern(params, kind);
- }
- else {
- if (this.matchKeyword('let') && (kind === 'const' || kind
=== 'let')) {
- this.tolerateUnexpectedToken(this.lookahead,
messages_1.Messages.LetInLexicalBinding);
- }
- params.push(this.lookahead);
- pattern = this.parseVariableIdentifier(kind);
- }
- return pattern;
- };
- Parser.prototype.parsePatternWithDefault = function (params, kind) {
- var startToken = this.lookahead;
- var pattern = this.parsePattern(params, kind);
- if (this.match('=')) {
- this.nextToken();
- var previousAllowYield = this.context.allowYield;
- this.context.allowYield = true;
- var right =
this.isolateCoverGrammar(this.parseAssignmentExpression);
- this.context.allowYield = previousAllowYield;
- pattern = this.finalize(this.startNode(startToken), new
Node.AssignmentPattern(pattern, right));
- }
- return pattern;
- };
- // ECMA-262 13.3.2 Variable Statement
- Parser.prototype.parseVariableIdentifier = function (kind) {
- var node = this.createNode();
- var token = this.nextToken();
- if (token.type === token_1.Token.Keyword && token.value ===
'yield') {
- if (this.context.strict) {
- this.tolerateUnexpectedToken(token,
messages_1.Messages.StrictReservedWord);
- }
- if (!this.context.allowYield) {
- this.throwUnexpectedToken(token);
- }
- }
- else if (token.type !== token_1.Token.Identifier) {
- if (this.context.strict && token.type ===
token_1.Token.Keyword && this.scanner.isStrictModeReservedWord(token.value)) {
- this.tolerateUnexpectedToken(token,
messages_1.Messages.StrictReservedWord);
- }
- else {
- if (this.context.strict || token.value !== 'let' ||
kind !== 'var') {
- this.throwUnexpectedToken(token);
- }
- }
- }
- else if ((this.context.isModule || this.context.await) &&
token.type === token_1.Token.Identifier && token.value === 'await') {
- this.tolerateUnexpectedToken(token);
- }
- return this.finalize(node, new Node.Identifier(token.value));
- };
- Parser.prototype.parseVariableDeclaration = function (options) {
- var node = this.createNode();
- var params = [];
- var id = this.parsePattern(params, 'var');
- // ECMA-262 12.2.1
- if (this.context.strict && id.type ===
syntax_1.Syntax.Identifier) {
- if (this.scanner.isRestrictedWord((id).name)) {
- this.tolerateError(messages_1.Messages.StrictVarName);
- }
- }
- var init = null;
- if (this.match('=')) {
- this.nextToken();
- init =
this.isolateCoverGrammar(this.parseAssignmentExpression);
- }
- else if (id.type !== syntax_1.Syntax.Identifier &&
!options.inFor) {
- this.expect('=');
- }
- return this.finalize(node, new Node.VariableDeclarator(id,
init));
- };
- Parser.prototype.parseVariableDeclarationList = function (options) {
- var opt = { inFor: options.inFor };
- var list = [];
- list.push(this.parseVariableDeclaration(opt));
- while (this.match(',')) {
- this.nextToken();
- list.push(this.parseVariableDeclaration(opt));
- }
- return list;
- };
- Parser.prototype.parseVariableStatement = function () {
- var node = this.createNode();
- this.expectKeyword('var');
- var declarations = this.parseVariableDeclarationList({ inFor:
false });
- this.consumeSemicolon();
- return this.finalize(node, new
Node.VariableDeclaration(declarations, 'var'));
- };
- // ECMA-262 13.4 Empty Statement
- Parser.prototype.parseEmptyStatement = function () {
- var node = this.createNode();
- this.expect(';');
- return this.finalize(node, new Node.EmptyStatement());
- };
- // ECMA-262 13.5 Expression Statement
- Parser.prototype.parseExpressionStatement = function () {
- var node = this.createNode();
- var expr = this.parseExpression();
- this.consumeSemicolon();
- return this.finalize(node, new Node.ExpressionStatement(expr));
- };
- // ECMA-262 13.6 If statement
- Parser.prototype.parseIfStatement = function () {
- var node = this.createNode();
- var consequent;
- var alternate = null;
- this.expectKeyword('if');
- this.expect('(');
- var test = this.parseExpression();
- if (!this.match(')') && this.config.tolerant) {
- this.tolerateUnexpectedToken(this.nextToken());
- consequent = this.finalize(this.createNode(), new
Node.EmptyStatement());
- }
- else {
- this.expect(')');
- consequent = this.parseStatement();
- if (this.matchKeyword('else')) {
- this.nextToken();
- alternate = this.parseStatement();
- }
- }
- return this.finalize(node, new Node.IfStatement(test,
consequent, alternate));
- };
- // ECMA-262 13.7.2 The do-while Statement
- Parser.prototype.parseDoWhileStatement = function () {
- var node = this.createNode();
- this.expectKeyword('do');
- var previousInIteration = this.context.inIteration;
- this.context.inIteration = true;
- var body = this.parseStatement();
- this.context.inIteration = previousInIteration;
- this.expectKeyword('while');
- this.expect('(');
- var test = this.parseExpression();
- this.expect(')');
- if (this.match(';')) {
- this.nextToken();
- }
- return this.finalize(node, new Node.DoWhileStatement(body,
test));
- };
- // ECMA-262 13.7.3 The while Statement
- Parser.prototype.parseWhileStatement = function () {
- var node = this.createNode();
- var body;
- this.expectKeyword('while');
- this.expect('(');
- var test = this.parseExpression();
- if (!this.match(')') && this.config.tolerant) {
- this.tolerateUnexpectedToken(this.nextToken());
- body = this.finalize(this.createNode(), new
Node.EmptyStatement());
- }
- else {
- this.expect(')');
- var previousInIteration = this.context.inIteration;
- this.context.inIteration = true;
- body = this.parseStatement();
- this.context.inIteration = previousInIteration;
- }
- return this.finalize(node, new Node.WhileStatement(test, body));
- };
- // ECMA-262 13.7.4 The for Statement
- // ECMA-262 13.7.5 The for-in and for-of Statements
- Parser.prototype.parseForStatement = function () {
- var init = null;
- var test = null;
- var update = null;
- var forIn = true;
- var left, right;
- var node = this.createNode();
- this.expectKeyword('for');
- this.expect('(');
- if (this.match(';')) {
- this.nextToken();
- }
- else {
- if (this.matchKeyword('var')) {
- init = this.createNode();
- this.nextToken();
- var previousAllowIn = this.context.allowIn;
- this.context.allowIn = false;
- var declarations = this.parseVariableDeclarationList({
inFor: true });
- this.context.allowIn = previousAllowIn;
- if (declarations.length === 1 &&
this.matchKeyword('in')) {
- var decl = declarations[0];
- if (decl.init && (decl.id.type ===
syntax_1.Syntax.ArrayPattern || decl.id.type === syntax_1.Syntax.ObjectPattern
|| this.context.strict)) {
-
this.tolerateError(messages_1.Messages.ForInOfLoopInitializer, 'for-in');
- }
- init = this.finalize(init, new
Node.VariableDeclaration(declarations, 'var'));
- this.nextToken();
- left = init;
- right = this.parseExpression();
- init = null;
- }
- else if (declarations.length === 1 &&
declarations[0].init === null && this.matchContextualKeyword('of')) {
- init = this.finalize(init, new
Node.VariableDeclaration(declarations, 'var'));
- this.nextToken();
- left = init;
- right = this.parseAssignmentExpression();
- init = null;
- forIn = false;
- }
- else {
- init = this.finalize(init, new
Node.VariableDeclaration(declarations, 'var'));
- this.expect(';');
- }
- }
- else if (this.matchKeyword('const') ||
this.matchKeyword('let')) {
- init = this.createNode();
- var kind = this.nextToken().value;
- if (!this.context.strict && this.lookahead.value ===
'in') {
- init = this.finalize(init, new
Node.Identifier(kind));
- this.nextToken();
- left = init;
- right = this.parseExpression();
- init = null;
- }
- else {
- var previousAllowIn = this.context.allowIn;
- this.context.allowIn = false;
- var declarations = this.parseBindingList(kind, {
inFor: true });
- this.context.allowIn = previousAllowIn;
- if (declarations.length === 1 &&
declarations[0].init === null && this.matchKeyword('in')) {
- init = this.finalize(init, new
Node.VariableDeclaration(declarations, kind));
- this.nextToken();
- left = init;
- right = this.parseExpression();
- init = null;
- }
- else if (declarations.length === 1 &&
declarations[0].init === null && this.matchContextualKeyword('of')) {
- init = this.finalize(init, new
Node.VariableDeclaration(declarations, kind));
- this.nextToken();
- left = init;
- right = this.parseAssignmentExpression();
- init = null;
- forIn = false;
- }
- else {
- this.consumeSemicolon();
- init = this.finalize(init, new
Node.VariableDeclaration(declarations, kind));
- }
- }
- }
- else {
- var initStartToken = this.lookahead;
- var previousAllowIn = this.context.allowIn;
- this.context.allowIn = false;
- init =
this.inheritCoverGrammar(this.parseAssignmentExpression);
- this.context.allowIn = previousAllowIn;
- if (this.matchKeyword('in')) {
- if (!this.context.isAssignmentTarget || init.type
=== syntax_1.Syntax.AssignmentExpression) {
-
this.tolerateError(messages_1.Messages.InvalidLHSInForIn);
- }
- this.nextToken();
- this.reinterpretExpressionAsPattern(init);
- left = init;
- right = this.parseExpression();
- init = null;
- }
- else if (this.matchContextualKeyword('of')) {
- if (!this.context.isAssignmentTarget || init.type
=== syntax_1.Syntax.AssignmentExpression) {
-
this.tolerateError(messages_1.Messages.InvalidLHSInForLoop);
- }
- this.nextToken();
- this.reinterpretExpressionAsPattern(init);
- left = init;
- right = this.parseAssignmentExpression();
- init = null;
- forIn = false;
- }
- else {
- if (this.match(',')) {
- var initSeq = [init];
- while (this.match(',')) {
- this.nextToken();
-
initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
- }
- init =
this.finalize(this.startNode(initStartToken), new
Node.SequenceExpression(initSeq));
- }
- this.expect(';');
- }
- }
- }
- if (typeof left === 'undefined') {
- if (!this.match(';')) {
- test = this.parseExpression();
- }
- this.expect(';');
- if (!this.match(')')) {
- update = this.parseExpression();
- }
- }
- var body;
- if (!this.match(')') && this.config.tolerant) {
- this.tolerateUnexpectedToken(this.nextToken());
- body = this.finalize(this.createNode(), new
Node.EmptyStatement());
- }
- else {
- this.expect(')');
- var previousInIteration = this.context.inIteration;
- this.context.inIteration = true;
- body = this.isolateCoverGrammar(this.parseStatement);
- this.context.inIteration = previousInIteration;
- }
- return (typeof left === 'undefined') ?
- this.finalize(node, new Node.ForStatement(init, test,
update, body)) :
- forIn ? this.finalize(node, new Node.ForInStatement(left,
right, body)) :
- this.finalize(node, new Node.ForOfStatement(left,
right, body));
- };
- // ECMA-262 13.8 The continue statement
- Parser.prototype.parseContinueStatement = function () {
- var node = this.createNode();
- this.expectKeyword('continue');
- var label = null;
- if (this.lookahead.type === token_1.Token.Identifier &&
!this.hasLineTerminator) {
- var id = this.parseVariableIdentifier();
- label = id;
- var key = '$' + id.name;
- if
(!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
- this.throwError(messages_1.Messages.UnknownLabel,
id.name);
- }
- }
- this.consumeSemicolon();
- if (label === null && !this.context.inIteration) {
- this.throwError(messages_1.Messages.IllegalContinue);
- }
- return this.finalize(node, new Node.ContinueStatement(label));
- };
- // ECMA-262 13.9 The break statement
- Parser.prototype.parseBreakStatement = function () {
- var node = this.createNode();
- this.expectKeyword('break');
- var label = null;
- if (this.lookahead.type === token_1.Token.Identifier &&
!this.hasLineTerminator) {
- var id = this.parseVariableIdentifier();
- var key = '$' + id.name;
- if
(!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
- this.throwError(messages_1.Messages.UnknownLabel,
id.name);
- }
- label = id;
- }
- this.consumeSemicolon();
- if (label === null && !this.context.inIteration &&
!this.context.inSwitch) {
- this.throwError(messages_1.Messages.IllegalBreak);
- }
- return this.finalize(node, new Node.BreakStatement(label));
- };
- // ECMA-262 13.10 The return statement
- Parser.prototype.parseReturnStatement = function () {
- if (!this.context.inFunctionBody) {
- this.tolerateError(messages_1.Messages.IllegalReturn);
- }
- var node = this.createNode();
- this.expectKeyword('return');
- var hasArgument = !this.match(';') && !this.match('}') &&
- !this.hasLineTerminator && this.lookahead.type !==
token_1.Token.EOF;
- var argument = hasArgument ? this.parseExpression() : null;
- this.consumeSemicolon();
- return this.finalize(node, new Node.ReturnStatement(argument));
- };
- // ECMA-262 13.11 The with statement
- Parser.prototype.parseWithStatement = function () {
- if (this.context.strict) {
- this.tolerateError(messages_1.Messages.StrictModeWith);
- }
- var node = this.createNode();
- this.expectKeyword('with');
- this.expect('(');
- var object = this.parseExpression();
- this.expect(')');
- var body = this.parseStatement();
- return this.finalize(node, new Node.WithStatement(object,
body));
- };
- // ECMA-262 13.12 The switch statement
- Parser.prototype.parseSwitchCase = function () {
- var node = this.createNode();
- var test;
- if (this.matchKeyword('default')) {
- this.nextToken();
- test = null;
- }
- else {
- this.expectKeyword('case');
- test = this.parseExpression();
- }
- this.expect(':');
- var consequent = [];
- while (true) {
- if (this.match('}') || this.matchKeyword('default') ||
this.matchKeyword('case')) {
- break;
- }
- consequent.push(this.parseStatementListItem());
- }
- return this.finalize(node, new Node.SwitchCase(test,
consequent));
- };
- Parser.prototype.parseSwitchStatement = function () {
- var node = this.createNode();
- this.expectKeyword('switch');
- this.expect('(');
- var discriminant = this.parseExpression();
- this.expect(')');
- var previousInSwitch = this.context.inSwitch;
- this.context.inSwitch = true;
- var cases = [];
- var defaultFound = false;
- this.expect('{');
- while (true) {
- if (this.match('}')) {
- break;
- }
- var clause = this.parseSwitchCase();
- if (clause.test === null) {
- if (defaultFound) {
-
this.throwError(messages_1.Messages.MultipleDefaultsInSwitch);
- }
- defaultFound = true;
- }
- cases.push(clause);
- }
- this.expect('}');
- this.context.inSwitch = previousInSwitch;
- return this.finalize(node, new
Node.SwitchStatement(discriminant, cases));
- };
- // ECMA-262 13.13 Labelled Statements
- Parser.prototype.parseLabelledStatement = function () {
- var node = this.createNode();
- var expr = this.parseExpression();
- var statement;
- if ((expr.type === syntax_1.Syntax.Identifier) &&
this.match(':')) {
- this.nextToken();
- var id = (expr);
- var key = '$' + id.name;
- if
(Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
- this.throwError(messages_1.Messages.Redeclaration,
'Label', id.name);
- }
- this.context.labelSet[key] = true;
- var labeledBody = this.parseStatement();
- delete this.context.labelSet[key];
- statement = new Node.LabeledStatement(id, labeledBody);
- }
- else {
- this.consumeSemicolon();
- statement = new Node.ExpressionStatement(expr);
- }
- return this.finalize(node, statement);
- };
- // ECMA-262 13.14 The throw statement
- Parser.prototype.parseThrowStatement = function () {
- var node = this.createNode();
- this.expectKeyword('throw');
- if (this.hasLineTerminator) {
- this.throwError(messages_1.Messages.NewlineAfterThrow);
- }
- var argument = this.parseExpression();
- this.consumeSemicolon();
- return this.finalize(node, new Node.ThrowStatement(argument));
- };
- // ECMA-262 13.15 The try statement
- Parser.prototype.parseCatchClause = function () {
- var node = this.createNode();
- this.expectKeyword('catch');
- this.expect('(');
- if (this.match(')')) {
- this.throwUnexpectedToken(this.lookahead);
- }
- var params = [];
- var param = this.parsePattern(params);
- var paramMap = {};
- for (var i = 0; i < params.length; i++) {
- var key = '$' + params[i].value;
- if (Object.prototype.hasOwnProperty.call(paramMap, key)) {
-
this.tolerateError(messages_1.Messages.DuplicateBinding, params[i].value);
- }
- paramMap[key] = true;
- }
- if (this.context.strict && param.type ===
syntax_1.Syntax.Identifier) {
- if (this.scanner.isRestrictedWord((param).name)) {
-
this.tolerateError(messages_1.Messages.StrictCatchVariable);
- }
- }
- this.expect(')');
- var body = this.parseBlock();
- return this.finalize(node, new Node.CatchClause(param, body));
- };
- Parser.prototype.parseFinallyClause = function () {
- this.expectKeyword('finally');
- return this.parseBlock();
- };
- Parser.prototype.parseTryStatement = function () {
- var node = this.createNode();
- this.expectKeyword('try');
- var block = this.parseBlock();
- var handler = this.matchKeyword('catch') ?
this.parseCatchClause() : null;
- var finalizer = this.matchKeyword('finally') ?
this.parseFinallyClause() : null;
- if (!handler && !finalizer) {
- this.throwError(messages_1.Messages.NoCatchOrFinally);
- }
- return this.finalize(node, new Node.TryStatement(block,
handler, finalizer));
- };
- // ECMA-262 13.16 The debugger statement
- Parser.prototype.parseDebuggerStatement = function () {
- var node = this.createNode();
- this.expectKeyword('debugger');
- this.consumeSemicolon();
- return this.finalize(node, new Node.DebuggerStatement());
- };
- // ECMA-262 13 Statements
- Parser.prototype.parseStatement = function () {
- var statement;
- switch (this.lookahead.type) {
- case token_1.Token.BooleanLiteral:
- case token_1.Token.NullLiteral:
- case token_1.Token.NumericLiteral:
- case token_1.Token.StringLiteral:
- case token_1.Token.Template:
- case token_1.Token.RegularExpression:
- statement = this.parseExpressionStatement();
- break;
- case token_1.Token.Punctuator:
- var value = this.lookahead.value;
- if (value === '{') {
- statement = this.parseBlock();
- }
- else if (value === '(') {
- statement = this.parseExpressionStatement();
- }
- else if (value === ';') {
- statement = this.parseEmptyStatement();
- }
- else {
- statement = this.parseExpressionStatement();
- }
- break;
- case token_1.Token.Identifier:
- statement = this.matchAsyncFunction() ?
this.parseFunctionDeclaration() : this.parseLabelledStatement();
- break;
- case token_1.Token.Keyword:
- switch (this.lookahead.value) {
- case 'break':
- statement = this.parseBreakStatement();
- break;
- case 'continue':
- statement = this.parseContinueStatement();
- break;
- case 'debugger':
- statement = this.parseDebuggerStatement();
- break;
- case 'do':
- statement = this.parseDoWhileStatement();
- break;
- case 'for':
- statement = this.parseForStatement();
- break;
- case 'function':
- statement = this.parseFunctionDeclaration();
- break;
- case 'if':
- statement = this.parseIfStatement();
- break;
- case 'return':
- statement = this.parseReturnStatement();
- break;
- case 'switch':
- statement = this.parseSwitchStatement();
- break;
- case 'throw':
- statement = this.parseThrowStatement();
- break;
- case 'try':
- statement = this.parseTryStatement();
- break;
- case 'var':
- statement = this.parseVariableStatement();
- break;
- case 'while':
- statement = this.parseWhileStatement();
- break;
- case 'with':
- statement = this.parseWithStatement();
- break;
- default:
- statement = this.parseExpressionStatement();
- break;
- }
- break;
- default:
- statement = this.throwUnexpectedToken(this.lookahead);
- }
- return statement;
- };
- // ECMA-262 14.1 Function Definition
- Parser.prototype.parseFunctionSourceElements = function () {
- var node = this.createNode();
- this.expect('{');
- var body = this.parseDirectivePrologues();
- var previousLabelSet = this.context.labelSet;
- var previousInIteration = this.context.inIteration;
- var previousInSwitch = this.context.inSwitch;
- var previousInFunctionBody = this.context.inFunctionBody;
- this.context.labelSet = {};
- this.context.inIteration = false;
- this.context.inSwitch = false;
- this.context.inFunctionBody = true;
- while (this.startMarker.index < this.scanner.length) {
- if (this.match('}')) {
- break;
- }
- body.push(this.parseStatementListItem());
- }
- this.expect('}');
- this.context.labelSet = previousLabelSet;
- this.context.inIteration = previousInIteration;
- this.context.inSwitch = previousInSwitch;
- this.context.inFunctionBody = previousInFunctionBody;
- return this.finalize(node, new Node.BlockStatement(body));
- };
- Parser.prototype.validateParam = function (options, param, name) {
- var key = '$' + name;
- if (this.context.strict) {
- if (this.scanner.isRestrictedWord(name)) {
- options.stricted = param;
- options.message = messages_1.Messages.StrictParamName;
- }
- if (Object.prototype.hasOwnProperty.call(options.paramSet,
key)) {
- options.stricted = param;
- options.message = messages_1.Messages.StrictParamDupe;
- }
- }
- else if (!options.firstRestricted) {
- if (this.scanner.isRestrictedWord(name)) {
- options.firstRestricted = param;
- options.message = messages_1.Messages.StrictParamName;
- }
- else if (this.scanner.isStrictModeReservedWord(name)) {
- options.firstRestricted = param;
- options.message =
messages_1.Messages.StrictReservedWord;
- }
- else if
(Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
- options.stricted = param;
- options.message = messages_1.Messages.StrictParamDupe;
- }
- }
- /* istanbul ignore next */
- if (typeof Object.defineProperty === 'function') {
- Object.defineProperty(options.paramSet, key, { value: true,
enumerable: true, writable: true, configurable: true });
- }
- else {
- options.paramSet[key] = true;
- }
- };
- Parser.prototype.parseRestElement = function (params) {
- var node = this.createNode();
- this.nextToken();
- if (this.match('{')) {
-
this.throwError(messages_1.Messages.ObjectPatternAsRestParameter);
- }
- params.push(this.lookahead);
- var param = this.parseVariableIdentifier();
- if (this.match('=')) {
- this.throwError(messages_1.Messages.DefaultRestParameter);
- }
- if (!this.match(')')) {
-
this.throwError(messages_1.Messages.ParameterAfterRestParameter);
- }
- return this.finalize(node, new Node.RestElement(param));
- };
- Parser.prototype.parseFormalParameter = function (options) {
- var param;
- var params = [];
- var token = this.lookahead;
- if (token.value === '...') {
- param = this.parseRestElement(params);
- this.validateParam(options, param.argument,
param.argument.name);
- options.params.push(param);
- return;
- }
- param = this.parsePatternWithDefault(params);
- for (var i = 0; i < params.length; i++) {
- this.validateParam(options, params[i], params[i].value);
- }
- options.params.push(param);
- };
- Parser.prototype.parseFormalParameters = function (firstRestricted)
{
- var options;
- options = {
- params: [],
- firstRestricted: firstRestricted
- };
- this.expect('(');
- if (!this.match(')')) {
- options.paramSet = {};
- while (this.startMarker.index < this.scanner.length) {
- this.parseFormalParameter(options);
- if (this.match(')')) {
- break;
- }
- this.expect(',');
- if (this.match(')')) {
- break;
- }
- }
- }
- this.expect(')');
- return {
- params: options.params,
- stricted: options.stricted,
- firstRestricted: options.firstRestricted,
- message: options.message
- };
- };
- Parser.prototype.matchAsyncFunction = function () {
- var match = this.matchContextualKeyword('async');
- if (match) {
- var previousIndex = this.scanner.index;
- var previousLineNumber = this.scanner.lineNumber;
- var previousLineStart = this.scanner.lineStart;
- this.collectComments();
- var next = this.scanner.lex();
- this.scanner.index = previousIndex;
- this.scanner.lineNumber = previousLineNumber;
- this.scanner.lineStart = previousLineStart;
- match = (previousLineNumber === next.lineNumber) &&
((next.type === token_1.Token.Keyword) || (next.value === 'function'));
- }
- return match;
- };
- Parser.prototype.parseFunctionDeclaration = function
(identifierIsOptional) {
- var node = this.createNode();
- var isAsync = this.matchContextualKeyword('async');
- if (isAsync) {
- this.nextToken();
- }
- this.expectKeyword('function');
- var isGenerator = isAsync ? false : this.match('*');
- if (isGenerator) {
- this.nextToken();
- }
- var message;
- var id = null;
- var firstRestricted = null;
- if (!identifierIsOptional || !this.match('(')) {
- var token = this.lookahead;
- id = this.parseVariableIdentifier();
- if (this.context.strict) {
- if (this.scanner.isRestrictedWord(token.value)) {
- this.tolerateUnexpectedToken(token,
messages_1.Messages.StrictFunctionName);
- }
- }
- else {
- if (this.scanner.isRestrictedWord(token.value)) {
- firstRestricted = token;
- message = messages_1.Messages.StrictFunctionName;
- }
- else if
(this.scanner.isStrictModeReservedWord(token.value)) {
- firstRestricted = token;
- message = messages_1.Messages.StrictReservedWord;
- }
- }
- }
- var previousAllowAwait = this.context.await;
- var previousAllowYield = this.context.allowYield;
- this.context.await = isAsync;
- this.context.allowYield = !isGenerator;
- var formalParameters =
this.parseFormalParameters(firstRestricted);
- var params = formalParameters.params;
- var stricted = formalParameters.stricted;
- firstRestricted = formalParameters.firstRestricted;
- if (formalParameters.message) {
- message = formalParameters.message;
- }
- var previousStrict = this.context.strict;
- var body = this.parseFunctionSourceElements();
- if (this.context.strict && firstRestricted) {
- this.throwUnexpectedToken(firstRestricted, message);
- }
- if (this.context.strict && stricted) {
- this.tolerateUnexpectedToken(stricted, message);
- }
- this.context.strict = previousStrict;
- this.context.await = previousAllowAwait;
- this.context.allowYield = previousAllowYield;
- return isAsync ? this.finalize(node, new
Node.AsyncFunctionDeclaration(id, params, body)) :
- this.finalize(node, new Node.FunctionDeclaration(id,
params, body, isGenerator));
- };
- Parser.prototype.parseFunctionExpression = function () {
- var node = this.createNode();
- var isAsync = this.matchContextualKeyword('async');
- if (isAsync) {
- this.nextToken();
- }
- this.expectKeyword('function');
- var isGenerator = isAsync ? false : this.match('*');
- if (isGenerator) {
- this.nextToken();
- }
- var message;
- var id = null;
- var firstRestricted;
- var previousAllowAwait = this.context.await;
- var previousAllowYield = this.context.allowYield;
- this.context.await = isAsync;
- this.context.allowYield = !isGenerator;
- if (!this.match('(')) {
- var token = this.lookahead;
- id = (!this.context.strict && !isGenerator &&
this.matchKeyword('yield')) ? this.parseIdentifierName() :
this.parseVariableIdentifier();
- if (this.context.strict) {
- if (this.scanner.isRestrictedWord(token.value)) {
- this.tolerateUnexpectedToken(token,
messages_1.Messages.StrictFunctionName);
- }
- }
- else {
- if (this.scanner.isRestrictedWord(token.value)) {
- firstRestricted = token;
- message = messages_1.Messages.StrictFunctionName;
- }
- else if
(this.scanner.isStrictModeReservedWord(token.value)) {
- firstRestricted = token;
- message = messages_1.Messages.StrictReservedWord;
- }
- }
- }
- var formalParameters =
this.parseFormalParameters(firstRestricted);
- var params = formalParameters.params;
- var stricted = formalParameters.stricted;
- firstRestricted = formalParameters.firstRestricted;
- if (formalParameters.message) {
- message = formalParameters.message;
- }
- var previousStrict = this.context.strict;
- var body = this.parseFunctionSourceElements();
- if (this.context.strict && firstRestricted) {
- this.throwUnexpectedToken(firstRestricted, message);
- }
- if (this.context.strict && stricted) {
- this.tolerateUnexpectedToken(stricted, message);
- }
- this.context.strict = previousStrict;
- this.context.await = previousAllowAwait;
- this.context.allowYield = previousAllowYield;
- return isAsync ? this.finalize(node, new
Node.AsyncFunctionExpression(id, params, body)) :
- this.finalize(node, new Node.FunctionExpression(id, params,
body, isGenerator));
- };
- // ECMA-262 14.1.1 Directive Prologues
- Parser.prototype.parseDirective = function () {
- var token = this.lookahead;
- var node = this.createNode();
- var expr = this.parseExpression();
- var directive = (expr.type === syntax_1.Syntax.Literal) ?
this.getTokenRaw(token).slice(1, -1) : null;
- this.consumeSemicolon();
- return this.finalize(node, directive ? new Node.Directive(expr,
directive) : new Node.ExpressionStatement(expr));
- };
- Parser.prototype.parseDirectivePrologues = function () {
- var firstRestricted = null;
- var body = [];
- while (true) {
- var token = this.lookahead;
- if (token.type !== token_1.Token.StringLiteral) {
- break;
- }
- var statement = this.parseDirective();
- body.push(statement);
- var directive = statement.directive;
- if (typeof directive !== 'string') {
- break;
- }
- if (directive === 'use strict') {
- this.context.strict = true;
- if (firstRestricted) {
- this.tolerateUnexpectedToken(firstRestricted,
messages_1.Messages.StrictOctalLiteral);
- }
- }
- else {
- if (!firstRestricted && token.octal) {
- firstRestricted = token;
- }
- }
- }
- return body;
- };
- // ECMA-262 14.3 Method Definitions
- Parser.prototype.qualifiedPropertyName = function (token) {
- switch (token.type) {
- case token_1.Token.Identifier:
- case token_1.Token.StringLiteral:
- case token_1.Token.BooleanLiteral:
- case token_1.Token.NullLiteral:
- case token_1.Token.NumericLiteral:
- case token_1.Token.Keyword:
- return true;
- case token_1.Token.Punctuator:
- return token.value === '[';
- }
- return false;
- };
- Parser.prototype.parseGetterMethod = function () {
- var node = this.createNode();
- this.expect('(');
- this.expect(')');
- var isGenerator = false;
- var params = {
- params: [],
- stricted: null,
- firstRestricted: null,
- message: null
- };
- var previousAllowYield = this.context.allowYield;
- this.context.allowYield = false;
- var method = this.parsePropertyMethod(params);
- this.context.allowYield = previousAllowYield;
- return this.finalize(node, new Node.FunctionExpression(null,
params.params, method, isGenerator));
- };
- Parser.prototype.parseSetterMethod = function () {
- var node = this.createNode();
- var options = {
- params: [],
- firstRestricted: null,
- paramSet: {}
- };
- var isGenerator = false;
- var previousAllowYield = this.context.allowYield;
- this.context.allowYield = false;
- this.expect('(');
- if (this.match(')')) {
- this.tolerateUnexpectedToken(this.lookahead);
- }
- else {
- this.parseFormalParameter(options);
- }
- this.expect(')');
- var method = this.parsePropertyMethod(options);
- this.context.allowYield = previousAllowYield;
- return this.finalize(node, new Node.FunctionExpression(null,
options.params, method, isGenerator));
- };
- Parser.prototype.parseGeneratorMethod = function () {
- var node = this.createNode();
- var isGenerator = true;
- var previousAllowYield = this.context.allowYield;
- this.context.allowYield = true;
- var params = this.parseFormalParameters();
- this.context.allowYield = false;
- var method = this.parsePropertyMethod(params);
- this.context.allowYield = previousAllowYield;
- return this.finalize(node, new Node.FunctionExpression(null,
params.params, method, isGenerator));
- };
- // ECMA-262 14.4 Generator Function Definitions
- Parser.prototype.parseYieldExpression = function () {
- var node = this.createNode();
- this.expectKeyword('yield');
- var argument = null;
- var delegate = false;
- if (!this.hasLineTerminator) {
- var previousAllowYield = this.context.allowYield;
- this.context.allowYield = false;
- delegate = this.match('*');
- if (delegate) {
- this.nextToken();
- argument = this.parseAssignmentExpression();
- }
- else {
- if (!this.match(';') && !this.match('}') &&
!this.match(')') && this.lookahead.type !== token_1.Token.EOF) {
- argument = this.parseAssignmentExpression();
- }
- }
- this.context.allowYield = previousAllowYield;
- }
- return this.finalize(node, new Node.YieldExpression(argument,
delegate));
- };
- // ECMA-262 14.5 Class Definitions
- Parser.prototype.parseClassElement = function (hasConstructor) {
- var token = this.lookahead;
- var node = this.createNode();
- var kind = '';
- var key = null;
- var value = null;
- var computed = false;
- var method = false;
- var isStatic = false;
- var isAsync = false;
- if (this.match('*')) {
- this.nextToken();
- }
- else {
- computed = this.match('[');
- key = this.parseObjectPropertyKey();
- var id = key;
- if (id.name === 'static' &&
(this.qualifiedPropertyName(this.lookahead) || this.match('*'))) {
- token = this.lookahead;
- isStatic = true;
- computed = this.match('[');
- if (this.match('*')) {
- this.nextToken();
- }
- else {
- key = this.parseObjectPropertyKey();
- }
- }
- isAsync = (token.type === token_1.Token.Identifier) &&
!this.hasLineTerminator && (this.lookahead.type === token_1.Token.Identifier)
&& (token.value === 'async');
- if (isAsync) {
- token = this.lookahead;
- key = this.parseObjectPropertyKey();
- if (token.type === token_1.Token.Identifier && ['get',
'set', 'constructor'].indexOf(token.value) >= 0) {
- this.tolerateUnexpectedToken(token);
- }
- }
- }
- var lookaheadPropertyKey =
this.qualifiedPropertyName(this.lookahead);
- if (token.type === token_1.Token.Identifier) {
- if (token.value === 'get' && lookaheadPropertyKey) {
- kind = 'get';
- computed = this.match('[');
- key = this.parseObjectPropertyKey();
- this.context.allowYield = false;
- value = this.parseGetterMethod();
- }
- else if (token.value === 'set' && lookaheadPropertyKey) {
- kind = 'set';
- computed = this.match('[');
- key = this.parseObjectPropertyKey();
- value = this.parseSetterMethod();
- }
- }
- else if (token.type === token_1.Token.Punctuator && token.value
=== '*' && lookaheadPropertyKey) {
- kind = 'init';
- computed = this.match('[');
- key = this.parseObjectPropertyKey();
- value = this.parseGeneratorMethod();
- method = true;
- }
- if (!kind && key && this.match('(')) {
- kind = 'init';
- value = isAsync ? this.parsePropertyMethodAsyncFunction() :
this.parsePropertyMethodFunction();
- method = true;
- }
- if (!kind) {
- this.throwUnexpectedToken(this.lookahead);
- }
- if (kind === 'init') {
- kind = 'method';
- }
- if (!computed) {
- if (isStatic && this.isPropertyKey(key, 'prototype')) {
- this.throwUnexpectedToken(token,
messages_1.Messages.StaticPrototype);
- }
- if (!isStatic && this.isPropertyKey(key, 'constructor')) {
- if (kind !== 'method' || !method || (value &&
value.generator)) {
- this.throwUnexpectedToken(token,
messages_1.Messages.ConstructorSpecialMethod);
- }
- if (hasConstructor.value) {
- this.throwUnexpectedToken(token,
messages_1.Messages.DuplicateConstructor);
- }
- else {
- hasConstructor.value = true;
- }
- kind = 'constructor';
- }
- }
- return this.finalize(node, new Node.MethodDefinition(key,
computed, value, kind, isStatic));
- };
- Parser.prototype.parseClassElementList = function () {
- var body = [];
- var hasConstructor = { value: false };
- this.expect('{');
- while (!this.match('}')) {
- if (this.match(';')) {
- this.nextToken();
- }
- else {
- body.push(this.parseClassElement(hasConstructor));
- }
- }
- this.expect('}');
- return body;
- };
- Parser.prototype.parseClassBody = function () {
- var node = this.createNode();
- var elementList = this.parseClassElementList();
- return this.finalize(node, new Node.ClassBody(elementList));
- };
- Parser.prototype.parseClassDeclaration = function
(identifierIsOptional) {
- var node = this.createNode();
- var previousStrict = this.context.strict;
- this.context.strict = true;
- this.expectKeyword('class');
- var id = (identifierIsOptional && (this.lookahead.type !==
token_1.Token.Identifier)) ? null : this.parseVariableIdentifier();
- var superClass = null;
- if (this.matchKeyword('extends')) {
- this.nextToken();
- superClass =
this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
- }
- var classBody = this.parseClassBody();
- this.context.strict = previousStrict;
- return this.finalize(node, new Node.ClassDeclaration(id,
superClass, classBody));
- };
- Parser.prototype.parseClassExpression = function () {
- var node = this.createNode();
- var previousStrict = this.context.strict;
- this.context.strict = true;
- this.expectKeyword('class');
- var id = (this.lookahead.type === token_1.Token.Identifier) ?
this.parseVariableIdentifier() : null;
- var superClass = null;
- if (this.matchKeyword('extends')) {
- this.nextToken();
- superClass =
this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
- }
- var classBody = this.parseClassBody();
- this.context.strict = previousStrict;
- return this.finalize(node, new Node.ClassExpression(id,
superClass, classBody));
- };
- // ECMA-262 15.1 Scripts
- // ECMA-262 15.2 Modules
- Parser.prototype.parseModule = function () {
- this.context.strict = true;
- this.context.isModule = true;
- var node = this.createNode();
- var body = this.parseDirectivePrologues();
- while (this.startMarker.index < this.scanner.length) {
- body.push(this.parseStatementListItem());
- }
- return this.finalize(node, new Node.Module(body));
- };
- Parser.prototype.parseScript = function () {
- var node = this.createNode();
- var body = this.parseDirectivePrologues();
- while (this.startMarker.index < this.scanner.length) {
- body.push(this.parseStatementListItem());
- }
- return this.finalize(node, new Node.Script(body));
- };
- // ECMA-262 15.2.2 Imports
- Parser.prototype.parseModuleSpecifier = function () {
- var node = this.createNode();
- if (this.lookahead.type !== token_1.Token.StringLiteral) {
- this.throwError(messages_1.Messages.InvalidModuleSpecifier);
- }
- var token = this.nextToken();
- var raw = this.getTokenRaw(token);
- return this.finalize(node, new Node.Literal(token.value, raw));
- };
- // import {<foo as bar>} ...;
- Parser.prototype.parseImportSpecifier = function () {
- var node = this.createNode();
- var imported;
- var local;
- if (this.lookahead.type === token_1.Token.Identifier) {
- imported = this.parseVariableIdentifier();
- local = imported;
- if (this.matchContextualKeyword('as')) {
- this.nextToken();
- local = this.parseVariableIdentifier();
- }
- }
- else {
- imported = this.parseIdentifierName();
- local = imported;
- if (this.matchContextualKeyword('as')) {
- this.nextToken();
- local = this.parseVariableIdentifier();
- }
- else {
- this.throwUnexpectedToken(this.nextToken());
- }
- }
- return this.finalize(node, new Node.ImportSpecifier(local,
imported));
- };
- // {foo, bar as bas}
- Parser.prototype.parseNamedImports = function () {
- this.expect('{');
- var specifiers = [];
- while (!this.match('}')) {
- specifiers.push(this.parseImportSpecifier());
- if (!this.match('}')) {
- this.expect(',');
- }
- }
- this.expect('}');
- return specifiers;
- };
- // import <foo> ...;
- Parser.prototype.parseImportDefaultSpecifier = function () {
- var node = this.createNode();
- var local = this.parseIdentifierName();
- return this.finalize(node, new
Node.ImportDefaultSpecifier(local));
- };
- // import <* as foo> ...;
- Parser.prototype.parseImportNamespaceSpecifier = function () {
- var node = this.createNode();
- this.expect('*');
- if (!this.matchContextualKeyword('as')) {
-
this.throwError(messages_1.Messages.NoAsAfterImportNamespace);
- }
- this.nextToken();
- var local = this.parseIdentifierName();
- return this.finalize(node, new
Node.ImportNamespaceSpecifier(local));
- };
- Parser.prototype.parseImportDeclaration = function () {
- if (this.context.inFunctionBody) {
-
this.throwError(messages_1.Messages.IllegalImportDeclaration);
- }
- var node = this.createNode();
- this.expectKeyword('import');
- var src;
- var specifiers = [];
- if (this.lookahead.type === token_1.Token.StringLiteral) {
- // import 'foo';
- src = this.parseModuleSpecifier();
- }
- else {
- if (this.match('{')) {
- // import {bar}
- specifiers =
specifiers.concat(this.parseNamedImports());
- }
- else if (this.match('*')) {
- // import * as foo
- specifiers.push(this.parseImportNamespaceSpecifier());
- }
- else if (this.isIdentifierName(this.lookahead) &&
!this.matchKeyword('default')) {
- // import foo
- specifiers.push(this.parseImportDefaultSpecifier());
- if (this.match(',')) {
- this.nextToken();
- if (this.match('*')) {
- // import foo, * as foo
-
specifiers.push(this.parseImportNamespaceSpecifier());
- }
- else if (this.match('{')) {
- // import foo, {bar}
- specifiers =
specifiers.concat(this.parseNamedImports());
- }
- else {
- this.throwUnexpectedToken(this.lookahead);
- }
- }
- }
- else {
- this.throwUnexpectedToken(this.nextToken());
- }
- if (!this.matchContextualKeyword('from')) {
- var message = this.lookahead.value ?
messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
- this.throwError(message, this.lookahead.value);
- }
- this.nextToken();
- src = this.parseModuleSpecifier();
- }
- this.consumeSemicolon();
- return this.finalize(node, new
Node.ImportDeclaration(specifiers, src));
- };
- // ECMA-262 15.2.3 Exports
- Parser.prototype.parseExportSpecifier = function () {
- var node = this.createNode();
- var local = this.parseIdentifierName();
- var exported = local;
- if (this.matchContextualKeyword('as')) {
- this.nextToken();
- exported = this.parseIdentifierName();
- }
- return this.finalize(node, new Node.ExportSpecifier(local,
exported));
- };
- Parser.prototype.parseExportDeclaration = function () {
- if (this.context.inFunctionBody) {
-
this.throwError(messages_1.Messages.IllegalExportDeclaration);
- }
- var node = this.createNode();
- this.expectKeyword('export');
- var exportDeclaration;
- if (this.matchKeyword('default')) {
- // export default ...
- this.nextToken();
- if (this.matchKeyword('function')) {
- // export default function foo () {}
- // export default function () {}
- var declaration = this.parseFunctionDeclaration(true);
- exportDeclaration = this.finalize(node, new
Node.ExportDefaultDeclaration(declaration));
- }
- else if (this.matchKeyword('class')) {
- // export default class foo {}
- var declaration = this.parseClassDeclaration(true);
- exportDeclaration = this.finalize(node, new
Node.ExportDefaultDeclaration(declaration));
- }
- else {
- if (this.matchContextualKeyword('from')) {
-
this.throwError(messages_1.Messages.UnexpectedToken, this.lookahead.value);
- }
- // export default {};
- // export default [];
- // export default (1 + 2);
- var declaration = this.match('{') ?
this.parseObjectInitializer() :
- this.match('[') ? this.parseArrayInitializer() :
this.parseAssignmentExpression();
- this.consumeSemicolon();
- exportDeclaration = this.finalize(node, new
Node.ExportDefaultDeclaration(declaration));
- }
- }
- else if (this.match('*')) {
- // export * from 'foo';
- this.nextToken();
- if (!this.matchContextualKeyword('from')) {
- var message = this.lookahead.value ?
messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
- this.throwError(message, this.lookahead.value);
- }
- this.nextToken();
- var src = this.parseModuleSpecifier();
- this.consumeSemicolon();
- exportDeclaration = this.finalize(node, new
Node.ExportAllDeclaration(src));
- }
- else if (this.lookahead.type === token_1.Token.Keyword) {
- // export var f = 1;
- var declaration = void 0;
- switch (this.lookahead.value) {
- case 'let':
- case 'const':
- declaration = this.parseLexicalDeclaration({ inFor:
false });
- break;
- case 'var':
- case 'class':
- case 'function':
- declaration = this.parseStatementListItem();
- break;
- default:
- this.throwUnexpectedToken(this.lookahead);
- }
- exportDeclaration = this.finalize(node, new
Node.ExportNamedDeclaration(declaration, [], null));
- }
- else if (this.matchAsyncFunction()) {
- var declaration = this.parseFunctionDeclaration();
- exportDeclaration = this.finalize(node, new
Node.ExportNamedDeclaration(declaration, [], null));
- }
- else {
- var specifiers = [];
- var source = null;
- var isExportFromIdentifier = false;
- this.expect('{');
- while (!this.match('}')) {
- isExportFromIdentifier = isExportFromIdentifier ||
this.matchKeyword('default');
- specifiers.push(this.parseExportSpecifier());
- if (!this.match('}')) {
- this.expect(',');
- }
- }
- this.expect('}');
- if (this.matchContextualKeyword('from')) {
- // export {default} from 'foo';
- // export {foo} from 'foo';
- this.nextToken();
- source = this.parseModuleSpecifier();
- this.consumeSemicolon();
- }
- else if (isExportFromIdentifier) {
- // export {default}; // missing fromClause
- var message = this.lookahead.value ?
messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
- this.throwError(message, this.lookahead.value);
- }
- else {
- // export {foo};
- this.consumeSemicolon();
- }
- exportDeclaration = this.finalize(node, new
Node.ExportNamedDeclaration(null, specifiers, source));
- }
- return exportDeclaration;
- };
- return Parser;
- }());
- exports.Parser = Parser;
-
-
-/***/ },
-/* 4 */
-/***/ function(module, exports) {
-
- // 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.
- "use strict";
- function assert(condition, message) {
- /* istanbul ignore if */
- if (!condition) {
- throw new Error('ASSERT: ' + message);
- }
- }
- exports.assert = assert;
-
-
-/***/ },
-/* 5 */
-/***/ function(module, exports) {
-
- "use strict";
- // Error messages should be identical to V8.
- exports.Messages = {
- UnexpectedToken: 'Unexpected token %0',
- UnexpectedTokenIllegal: 'Unexpected token ILLEGAL',
- UnexpectedNumber: 'Unexpected number',
- UnexpectedString: 'Unexpected string',
- UnexpectedIdentifier: 'Unexpected identifier',
- UnexpectedReserved: 'Unexpected reserved word',
- UnexpectedTemplate: 'Unexpected quasi %0',
- 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',
- InvalidLHSInForLoop: 'Invalid left-hand side in for-loop',
- 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.',
- 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',
- TemplateOctalLiteral: 'Octal literals are not allowed in template
strings.',
- ParameterAfterRestParameter: 'Rest parameter must be last formal
parameter',
- DefaultRestParameter: 'Unexpected token =',
- ObjectPatternAsRestParameter: 'Unexpected token {',
- DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed
in object literals',
- ConstructorSpecialMethod: 'Class constructor may not be an
accessor',
- DuplicateConstructor: 'A class may only have one constructor',
- StaticPrototype: 'Classes may not have static property named
prototype',
- MissingFromClause: 'Unexpected token',
- NoAsAfterImportNamespace: 'Unexpected token',
- InvalidModuleSpecifier: 'Unexpected token',
- IllegalImportDeclaration: 'Unexpected token',
- IllegalExportDeclaration: 'Unexpected token',
- DuplicateBinding: 'Duplicate binding %0',
- DeclarationMissingInitializer: 'Missing initializer in %0
declaration',
- LetInLexicalBinding: 'let is disallowed as a lexically bound name',
- ForInOfLoopInitializer: '%0 loop variable declaration may not have
an initializer'
- };
-
-
-/***/ },
-/* 6 */
-/***/ function(module, exports) {
-
- "use strict";
- var ErrorHandler = (function () {
- function ErrorHandler() {
- this.errors = [];
- this.tolerant = false;
- }
- ;
- ErrorHandler.prototype.recordError = function (error) {
- this.errors.push(error);
- };
- ;
- ErrorHandler.prototype.tolerate = function (error) {
- if (this.tolerant) {
- this.recordError(error);
- }
- else {
- throw error;
- }
- };
- ;
- ErrorHandler.prototype.constructError = function (msg, column) {
- var error = new Error(msg);
- try {
- throw error;
- }
- catch (base) {
- /* istanbul ignore else */
- if (Object.create && Object.defineProperty) {
- error = Object.create(base);
- Object.defineProperty(error, 'column', { value: column
});
- }
- }
- finally {
- return error;
- }
- /* istanbul ignore next */
- return error;
- };
- ;
- ErrorHandler.prototype.createError = function (index, line, col,
description) {
- var msg = 'Line ' + line + ': ' + description;
- var error = this.constructError(msg, col);
- error.index = index;
- error.lineNumber = line;
- error.description = description;
- return error;
- };
- ;
- ErrorHandler.prototype.throwError = function (index, line, col,
description) {
- throw this.createError(index, line, col, description);
- };
- ;
- ErrorHandler.prototype.tolerateError = function (index, line, col,
description) {
- var error = this.createError(index, line, col, description);
- if (this.tolerant) {
- this.recordError(error);
- }
- else {
- throw error;
- }
- };
- ;
- return ErrorHandler;
- }());
- exports.ErrorHandler = ErrorHandler;
-
-
-/***/ },
-/* 7 */
-/***/ function(module, exports) {
-
- "use strict";
- (function (Token) {
- Token[Token["BooleanLiteral"] = 1] = "BooleanLiteral";
- Token[Token["EOF"] = 2] = "EOF";
- Token[Token["Identifier"] = 3] = "Identifier";
- Token[Token["Keyword"] = 4] = "Keyword";
- Token[Token["NullLiteral"] = 5] = "NullLiteral";
- Token[Token["NumericLiteral"] = 6] = "NumericLiteral";
- Token[Token["Punctuator"] = 7] = "Punctuator";
- Token[Token["StringLiteral"] = 8] = "StringLiteral";
- Token[Token["RegularExpression"] = 9] = "RegularExpression";
- Token[Token["Template"] = 10] = "Template";
- })(exports.Token || (exports.Token = {}));
- var Token = exports.Token;
- ;
- exports.TokenName = {};
- exports.TokenName[Token.BooleanLiteral] = 'Boolean';
- exports.TokenName[Token.EOF] = '<end>';
- exports.TokenName[Token.Identifier] = 'Identifier';
- exports.TokenName[Token.Keyword] = 'Keyword';
- exports.TokenName[Token.NullLiteral] = 'Null';
- exports.TokenName[Token.NumericLiteral] = 'Numeric';
- exports.TokenName[Token.Punctuator] = 'Punctuator';
- exports.TokenName[Token.StringLiteral] = 'String';
- exports.TokenName[Token.RegularExpression] = 'RegularExpression';
- exports.TokenName[Token.Template] = 'Template';
-
-
-/***/ },
-/* 8 */
-/***/ function(module, exports, __webpack_require__) {
-
- "use strict";
- var assert_1 = __webpack_require__(4);
- var messages_1 = __webpack_require__(5);
- var character_1 = __webpack_require__(9);
- var token_1 = __webpack_require__(7);
- function hexValue(ch) {
- return '0123456789abcdef'.indexOf(ch.toLowerCase());
- }
- function octalValue(ch) {
- return '01234567'.indexOf(ch);
- }
- var Scanner = (function () {
- function Scanner(code, handler) {
- this.source = code;
- this.errorHandler = handler;
- this.trackComment = false;
- this.length = code.length;
- this.index = 0;
- this.lineNumber = (code.length > 0) ? 1 : 0;
- this.lineStart = 0;
- this.curlyStack = [];
- }
- ;
- Scanner.prototype.eof = function () {
- return this.index >= this.length;
- };
- ;
- Scanner.prototype.throwUnexpectedToken = function (message) {
- if (message === void 0) { message =
messages_1.Messages.UnexpectedTokenIllegal; }
- this.errorHandler.throwError(this.index, this.lineNumber,
this.index - this.lineStart + 1, message);
- };
- ;
- Scanner.prototype.tolerateUnexpectedToken = function () {
- this.errorHandler.tolerateError(this.index, this.lineNumber,
this.index - this.lineStart + 1, messages_1.Messages.UnexpectedTokenIllegal);
- };
- ;
- // ECMA-262 11.4 Comments
- Scanner.prototype.skipSingleLineComment = function (offset) {
- var comments = [];
- var start, loc;
- if (this.trackComment) {
- comments = [];
- start = this.index - offset;
- loc = {
- start: {
- line: this.lineNumber,
- column: this.index - this.lineStart - offset
- },
- end: {}
- };
- }
- while (!this.eof()) {
- var ch = this.source.charCodeAt(this.index);
- ++this.index;
- if (character_1.Character.isLineTerminator(ch)) {
- if (this.trackComment) {
- loc.end = {
- line: this.lineNumber,
- column: this.index - this.lineStart - 1
- };
- var entry = {
- multiLine: false,
- slice: [start + offset, this.index - 1],
- range: [start, this.index - 1],
- loc: loc
- };
- comments.push(entry);
- }
- if (ch === 13 && this.source.charCodeAt(this.index) ===
10) {
- ++this.index;
- }
- ++this.lineNumber;
- this.lineStart = this.index;
- return comments;
- }
- }
- if (this.trackComment) {
- loc.end = {
- line: this.lineNumber,
- column: this.index - this.lineStart
- };
- var entry = {
- multiLine: false,
- slice: [start + offset, this.index],
- range: [start, this.index],
- loc: loc
- };
- comments.push(entry);
- }
- return comments;
- };
- ;
- Scanner.prototype.skipMultiLineComment = function () {
- var comments = [];
- var start, loc;
- if (this.trackComment) {
- comments = [];
- start = this.index - 2;
- loc = {
- start: {
- line: this.lineNumber,
- column: this.index - this.lineStart - 2
- },
- end: {}
- };
- }
- while (!this.eof()) {
- var ch = this.source.charCodeAt(this.index);
- if (character_1.Character.isLineTerminator(ch)) {
- if (ch === 0x0D && this.source.charCodeAt(this.index +
1) === 0x0A) {
- ++this.index;
- }
- ++this.lineNumber;
- ++this.index;
- this.lineStart = this.index;
- }
- else if (ch === 0x2A) {
- // Block comment ends with '*/'.
- if (this.source.charCodeAt(this.index + 1) === 0x2F) {
- this.index += 2;
- if (this.trackComment) {
- loc.end = {
- line: this.lineNumber,
- column: this.index - this.lineStart
- };
- var entry = {
- multiLine: true,
- slice: [start + 2, this.index - 2],
- range: [start, this.index],
- loc: loc
- };
- comments.push(entry);
- }
- return comments;
- }
- ++this.index;
- }
- else {
- ++this.index;
- }
- }
- // Ran off the end of the file - the whole thing is a comment
- if (this.trackComment) {
- loc.end = {
- line: this.lineNumber,
- column: this.index - this.lineStart
- };
- var entry = {
- multiLine: true,
- slice: [start + 2, this.index],
- range: [start, this.index],
- loc: loc
- };
- comments.push(entry);
- }
- this.tolerateUnexpectedToken();
- return comments;
- };
- ;
- Scanner.prototype.scanComments = function () {
- var comments;
- if (this.trackComment) {
- comments = [];
- }
- var start = (this.index === 0);
- while (!this.eof()) {
- var ch = this.source.charCodeAt(this.index);
- if (character_1.Character.isWhiteSpace(ch)) {
- ++this.index;
- }
- else if (character_1.Character.isLineTerminator(ch)) {
- ++this.index;
- if (ch === 0x0D && this.source.charCodeAt(this.index)
=== 0x0A) {
- ++this.index;
- }
- ++this.lineNumber;
- this.lineStart = this.index;
- start = true;
- }
- else if (ch === 0x2F) {
- ch = this.source.charCodeAt(this.index + 1);
- if (ch === 0x2F) {
- this.index += 2;
- var comment = this.skipSingleLineComment(2);
- if (this.trackComment) {
- comments = comments.concat(comment);
- }
- start = true;
- }
- else if (ch === 0x2A) {
- this.index += 2;
- var comment = this.skipMultiLineComment();
- if (this.trackComment) {
- comments = comments.concat(comment);
- }
- }
- else {
- break;
- }
- }
- else if (start && ch === 0x2D) {
- // U+003E is '>'
- if ((this.source.charCodeAt(this.index + 1) === 0x2D)
&& (this.source.charCodeAt(this.index + 2) === 0x3E)) {
- // '-->' is a single-line comment
- this.index += 3;
- var comment = this.skipSingleLineComment(3);
- if (this.trackComment) {
- comments = comments.concat(comment);
- }
- }
- else {
- break;
- }
- }
- else if (ch === 0x3C) {
- if (this.source.slice(this.index + 1, this.index + 4)
=== '!--') {
- this.index += 4; // `<!--`
- var comment = this.skipSingleLineComment(4);
- if (this.trackComment) {
- comments = comments.concat(comment);
- }
- }
- else {
- break;
- }
- }
- else {
- break;
- }
- }
- return comments;
- };
- ;
- // ECMA-262 11.6.2.2 Future Reserved Words
- Scanner.prototype.isFutureReservedWord = function (id) {
- switch (id) {
- case 'enum':
- case 'export':
- case 'import':
- case 'super':
- return true;
- default:
- return false;
- }
- };
- ;
- Scanner.prototype.isStrictModeReservedWord = function (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;
- }
- };
- ;
- Scanner.prototype.isRestrictedWord = function (id) {
- return id === 'eval' || id === 'arguments';
- };
- ;
- // ECMA-262 11.6.2.1 Keywords
- Scanner.prototype.isKeyword = function (id) {
- 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;
- }
- };
- ;
- Scanner.prototype.codePointAt = function (i) {
- var cp = this.source.charCodeAt(i);
- if (cp >= 0xD800 && cp <= 0xDBFF) {
- var second = this.source.charCodeAt(i + 1);
- if (second >= 0xDC00 && second <= 0xDFFF) {
- var first = cp;
- cp = (first - 0xD800) * 0x400 + second - 0xDC00 +
0x10000;
- }
- }
- return cp;
- };
- ;
- Scanner.prototype.scanHexEscape = function (prefix) {
- var len = (prefix === 'u') ? 4 : 2;
- var code = 0;
- for (var i = 0; i < len; ++i) {
- if (!this.eof() &&
character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
- code = code * 16 + hexValue(this.source[this.index++]);
- }
- else {
- return '';
- }
- }
- return String.fromCharCode(code);
- };
- ;
- Scanner.prototype.scanUnicodeCodePointEscape = function () {
- var ch = this.source[this.index];
- var code = 0;
- // At least, one hex digit is required.
- if (ch === '}') {
- this.throwUnexpectedToken();
- }
- while (!this.eof()) {
- ch = this.source[this.index++];
- if (!character_1.Character.isHexDigit(ch.charCodeAt(0))) {
- break;
- }
- code = code * 16 + hexValue(ch);
- }
- if (code > 0x10FFFF || ch !== '}') {
- this.throwUnexpectedToken();
- }
- return character_1.Character.fromCodePoint(code);
- };
- ;
- Scanner.prototype.getIdentifier = function () {
- var start = this.index++;
- while (!this.eof()) {
- var ch = this.source.charCodeAt(this.index);
- if (ch === 0x5C) {
- // Blackslash (U+005C) marks Unicode escape sequence.
- this.index = start;
- return this.getComplexIdentifier();
- }
- else if (ch >= 0xD800 && ch < 0xDFFF) {
- // Need to handle surrogate pairs.
- this.index = start;
- return this.getComplexIdentifier();
- }
- if (character_1.Character.isIdentifierPart(ch)) {
- ++this.index;
- }
- else {
- break;
- }
- }
- return this.source.slice(start, this.index);
- };
- ;
- Scanner.prototype.getComplexIdentifier = function () {
- var cp = this.codePointAt(this.index);
- var id = character_1.Character.fromCodePoint(cp);
- this.index += id.length;
- // '\u' (U+005C, U+0075) denotes an escaped character.
- var ch;
- if (cp === 0x5C) {
- if (this.source.charCodeAt(this.index) !== 0x75) {
- this.throwUnexpectedToken();
- }
- ++this.index;
- if (this.source[this.index] === '{') {
- ++this.index;
- ch = this.scanUnicodeCodePointEscape();
- }
- else {
- ch = this.scanHexEscape('u');
- cp = ch.charCodeAt(0);
- if (!ch || ch === '\\' ||
!character_1.Character.isIdentifierStart(cp)) {
- this.throwUnexpectedToken();
- }
- }
- id = ch;
- }
- while (!this.eof()) {
- cp = this.codePointAt(this.index);
- if (!character_1.Character.isIdentifierPart(cp)) {
- break;
- }
- ch = character_1.Character.fromCodePoint(cp);
- id += ch;
- this.index += ch.length;
- // '\u' (U+005C, U+0075) denotes an escaped character.
- if (cp === 0x5C) {
- id = id.substr(0, id.length - 1);
- if (this.source.charCodeAt(this.index) !== 0x75) {
- this.throwUnexpectedToken();
- }
- ++this.index;
- if (this.source[this.index] === '{') {
- ++this.index;
- ch = this.scanUnicodeCodePointEscape();
- }
- else {
- ch = this.scanHexEscape('u');
- cp = ch.charCodeAt(0);
- if (!ch || ch === '\\' ||
!character_1.Character.isIdentifierPart(cp)) {
- this.throwUnexpectedToken();
- }
- }
- id += ch;
- }
- }
- return id;
- };
- ;
- Scanner.prototype.octalToDecimal = function (ch) {
- // \0 is not octal escape sequence
- var octal = (ch !== '0');
- var code = octalValue(ch);
- if (!this.eof() &&
character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
- octal = true;
- code = code * 8 + octalValue(this.source[this.index++]);
- // 3 digits are only allowed when string starts
- // with 0, 1, 2, 3
- if ('0123'.indexOf(ch) >= 0 && !this.eof() &&
character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
- code = code * 8 + octalValue(this.source[this.index++]);
- }
- }
- return {
- code: code,
- octal: octal
- };
- };
- ;
- // ECMA-262 11.6 Names and Keywords
- Scanner.prototype.scanIdentifier = function () {
- var type;
- var start = this.index;
- // Backslash (U+005C) starts an escaped character.
- var id = (this.source.charCodeAt(start) === 0x5C) ?
this.getComplexIdentifier() : this.getIdentifier();
- // There is no keyword or literal with only one character.
- // Thus, it must be an identifier.
- if (id.length === 1) {
- type = token_1.Token.Identifier;
- }
- else if (this.isKeyword(id)) {
- type = token_1.Token.Keyword;
- }
- else if (id === 'null') {
- type = token_1.Token.NullLiteral;
- }
- else if (id === 'true' || id === 'false') {
- type = token_1.Token.BooleanLiteral;
- }
- else {
- type = token_1.Token.Identifier;
- }
- return {
- type: type,
- value: id,
- lineNumber: this.lineNumber,
- lineStart: this.lineStart,
- start: start,
- end: this.index
- };
- };
- ;
- // ECMA-262 11.7 Punctuators
- Scanner.prototype.scanPunctuator = function () {
- var token = {
- type: token_1.Token.Punctuator,
- value: '',
- lineNumber: this.lineNumber,
- lineStart: this.lineStart,
- start: this.index,
- end: this.index
- };
- // Check for most common single-character punctuators.
- var str = this.source[this.index];
- switch (str) {
- case '(':
- case '{':
- if (str === '{') {
- this.curlyStack.push('{');
- }
- ++this.index;
- break;
- case '.':
- ++this.index;
- if (this.source[this.index] === '.' &&
this.source[this.index + 1] === '.') {
- // Spread operator: ...
- this.index += 2;
- str = '...';
- }
- break;
- case '}':
- ++this.index;
- this.curlyStack.pop();
- break;
- case ')':
- case ';':
- case ',':
- case '[':
- case ']':
- case ':':
- case '?':
- case '~':
- ++this.index;
- break;
- default:
- // 4-character punctuator.
- str = this.source.substr(this.index, 4);
- if (str === '>>>=') {
- this.index += 4;
- }
- else {
- // 3-character punctuators.
- str = str.substr(0, 3);
- if (str === '===' || str === '!==' || str === '>>>'
||
- str === '<<=' || str === '>>=' || str ===
'**=') {
- this.index += 3;
- }
- else {
- // 2-character punctuators.
- str = str.substr(0, 2);
- if (str === '&&' || str === '||' || str ===
'==' || str === '!=' ||
- str === '+=' || str === '-=' || str ===
'*=' || str === '/=' ||
- str === '++' || str === '--' || str ===
'<<' || str === '>>' ||
- str === '&=' || str === '|=' || str ===
'^=' || str === '%=' ||
- str === '<=' || str === '>=' || str ===
'=>' || str === '**') {
- this.index += 2;
- }
- else {
- // 1-character punctuators.
- str = this.source[this.index];
- if ('<>=!+-*%&|^/'.indexOf(str) >= 0) {
- ++this.index;
- }
- }
- }
- }
- }
- if (this.index === token.start) {
- this.throwUnexpectedToken();
- }
- token.end = this.index;
- token.value = str;
- return token;
- };
- ;
- // ECMA-262 11.8.3 Numeric Literals
- Scanner.prototype.scanHexLiteral = function (start) {
- var number = '';
- while (!this.eof()) {
- if
(!character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
- break;
- }
- number += this.source[this.index++];
- }
- if (number.length === 0) {
- this.throwUnexpectedToken();
- }
- if
(character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
- this.throwUnexpectedToken();
- }
- return {
- type: token_1.Token.NumericLiteral,
- value: parseInt('0x' + number, 16),
- lineNumber: this.lineNumber,
- lineStart: this.lineStart,
- start: start,
- end: this.index
- };
- };
- ;
- Scanner.prototype.scanBinaryLiteral = function (start) {
- var number = '';
- var ch;
- while (!this.eof()) {
- ch = this.source[this.index];
- if (ch !== '0' && ch !== '1') {
- break;
- }
- number += this.source[this.index++];
- }
- if (number.length === 0) {
- // only 0b or 0B
- this.throwUnexpectedToken();
- }
- if (!this.eof()) {
- ch = this.source.charCodeAt(this.index);
- /* istanbul ignore else */
- if (character_1.Character.isIdentifierStart(ch) ||
character_1.Character.isDecimalDigit(ch)) {
- this.throwUnexpectedToken();
- }
- }
- return {
- type: token_1.Token.NumericLiteral,
- value: parseInt(number, 2),
- lineNumber: this.lineNumber,
- lineStart: this.lineStart,
- start: start,
- end: this.index
- };
- };
- ;
- Scanner.prototype.scanOctalLiteral = function (prefix, start) {
- var number = '';
- var octal = false;
- if (character_1.Character.isOctalDigit(prefix.charCodeAt(0))) {
- octal = true;
- number = '0' + this.source[this.index++];
- }
- else {
- ++this.index;
- }
- while (!this.eof()) {
- if
(!character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
- break;
- }
- number += this.source[this.index++];
- }
- if (!octal && number.length === 0) {
- // only 0o or 0O
- this.throwUnexpectedToken();
- }
- if
(character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index)) ||
character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
- this.throwUnexpectedToken();
- }
- return {
- type: token_1.Token.NumericLiteral,
- value: parseInt(number, 8),
- octal: octal,
- lineNumber: this.lineNumber,
- lineStart: this.lineStart,
- start: start,
- end: this.index
- };
- };
- ;
- Scanner.prototype.isImplicitOctalLiteral = function () {
- // Implicit octal, unless there is a non-octal digit.
- // (Annex B.1.1 on Numeric Literals)
- for (var i = this.index + 1; i < this.length; ++i) {
- var ch = this.source[i];
- if (ch === '8' || ch === '9') {
- return false;
- }
- if (!character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
- return true;
- }
- }
- return true;
- };
- ;
- Scanner.prototype.scanNumericLiteral = function () {
- var start = this.index;
- var ch = this.source[start];
-
assert_1.assert(character_1.Character.isDecimalDigit(ch.charCodeAt(0)) || (ch
=== '.'), 'Numeric literal must start with a decimal digit or a decimal point');
- var number = '';
- if (ch !== '.') {
- number = this.source[this.index++];
- ch = this.source[this.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') {
- ++this.index;
- return this.scanHexLiteral(start);
- }
- if (ch === 'b' || ch === 'B') {
- ++this.index;
- return this.scanBinaryLiteral(start);
- }
- if (ch === 'o' || ch === 'O') {
- return this.scanOctalLiteral(ch, start);
- }
- if (ch &&
character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
- if (this.isImplicitOctalLiteral()) {
- return this.scanOctalLiteral(ch, start);
- }
- }
- }
- while
(character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
- number += this.source[this.index++];
- }
- ch = this.source[this.index];
- }
- if (ch === '.') {
- number += this.source[this.index++];
- while
(character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
- number += this.source[this.index++];
- }
- ch = this.source[this.index];
- }
- if (ch === 'e' || ch === 'E') {
- number += this.source[this.index++];
- ch = this.source[this.index];
- if (ch === '+' || ch === '-') {
- number += this.source[this.index++];
- }
- if
(character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
- while
(character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
- number += this.source[this.index++];
- }
- }
- else {
- this.throwUnexpectedToken();
- }
- }
- if
(character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
- this.throwUnexpectedToken();
- }
- return {
- type: token_1.Token.NumericLiteral,
- value: parseFloat(number),
- lineNumber: this.lineNumber,
- lineStart: this.lineStart,
- start: start,
- end: this.index
- };
- };
- ;
- // ECMA-262 11.8.4 String Literals
- Scanner.prototype.scanStringLiteral = function () {
- var start = this.index;
- var quote = this.source[start];
- assert_1.assert((quote === '\'' || quote === '"'), 'String
literal must starts with a quote');
- ++this.index;
- var octal = false;
- var str = '';
- while (!this.eof()) {
- var ch = this.source[this.index++];
- if (ch === quote) {
- quote = '';
- break;
- }
- else if (ch === '\\') {
- ch = this.source[this.index++];
- if (!ch ||
!character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
- switch (ch) {
- case 'u':
- case 'x':
- if (this.source[this.index] === '{') {
- ++this.index;
- str +=
this.scanUnicodeCodePointEscape();
- }
- else {
- var unescaped = this.scanHexEscape(ch);
- if (!unescaped) {
- this.throwUnexpectedToken();
- }
- str += unescaped;
- }
- break;
- case 'n':
- str += '\n';
- break;
- case 'r':
- str += '\r';
- break;
- case 't':
- str += '\t';
- break;
- case 'b':
- str += '\b';
- break;
- case 'f':
- str += '\f';
- break;
- case 'v':
- str += '\x0B';
- break;
- case '8':
- case '9':
- str += ch;
- this.tolerateUnexpectedToken();
- break;
- default:
- if (ch &&
character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
- var octToDec = this.octalToDecimal(ch);
- octal = octToDec.octal || octal;
- str +=
String.fromCharCode(octToDec.code);
- }
- else {
- str += ch;
- }
- break;
- }
- }
- else {
- ++this.lineNumber;
- if (ch === '\r' && this.source[this.index] ===
'\n') {
- ++this.index;
- }
- this.lineStart = this.index;
- }
- }
- else if
(character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
- break;
- }
- else {
- str += ch;
- }
- }
- if (quote !== '') {
- this.index = start;
- this.throwUnexpectedToken();
- }
- return {
- type: token_1.Token.StringLiteral,
- value: str,
- octal: octal,
- lineNumber: this.lineNumber,
- lineStart: this.lineStart,
- start: start,
- end: this.index
- };
- };
- ;
- // ECMA-262 11.8.6 Template Literal Lexical Components
- Scanner.prototype.scanTemplate = function () {
- var cooked = '';
- var terminated = false;
- var start = this.index;
- var head = (this.source[start] === '`');
- var tail = false;
- var rawOffset = 2;
- ++this.index;
- while (!this.eof()) {
- var ch = this.source[this.index++];
- if (ch === '`') {
- rawOffset = 1;
- tail = true;
- terminated = true;
- break;
- }
- else if (ch === '$') {
- if (this.source[this.index] === '{') {
- this.curlyStack.push('${');
- ++this.index;
- terminated = true;
- break;
- }
- cooked += ch;
- }
- else if (ch === '\\') {
- ch = this.source[this.index++];
- if
(!character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
- switch (ch) {
- case 'n':
- cooked += '\n';
- break;
- case 'r':
- cooked += '\r';
- break;
- case 't':
- cooked += '\t';
- break;
- case 'u':
- case 'x':
- if (this.source[this.index] === '{') {
- ++this.index;
- cooked +=
this.scanUnicodeCodePointEscape();
- }
- else {
- var restore = this.index;
- var unescaped = this.scanHexEscape(ch);
- if (unescaped) {
- cooked += unescaped;
- }
- else {
- this.index = restore;
- cooked += ch;
- }
- }
- break;
- case 'b':
- cooked += '\b';
- break;
- case 'f':
- cooked += '\f';
- break;
- case 'v':
- cooked += '\v';
- break;
- default:
- if (ch === '0') {
- if
(character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
- // Illegal: \01 \02 and so on
-
this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
- }
- cooked += '\0';
- }
- else if
(character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
- // Illegal: \1 \2
-
this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
- }
- else {
- cooked += ch;
- }
- break;
- }
- }
- else {
- ++this.lineNumber;
- if (ch === '\r' && this.source[this.index] ===
'\n') {
- ++this.index;
- }
- this.lineStart = this.index;
- }
- }
- else if
(character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
- ++this.lineNumber;
- if (ch === '\r' && this.source[this.index] === '\n') {
- ++this.index;
- }
- this.lineStart = this.index;
- cooked += '\n';
- }
- else {
- cooked += ch;
- }
- }
- if (!terminated) {
- this.throwUnexpectedToken();
- }
- if (!head) {
- this.curlyStack.pop();
- }
- return {
- type: token_1.Token.Template,
- value: {
- cooked: cooked,
- raw: this.source.slice(start + 1, this.index -
rawOffset)
- },
- head: head,
- tail: tail,
- lineNumber: this.lineNumber,
- lineStart: this.lineStart,
- start: start,
- end: this.index
- };
- };
- ;
- // ECMA-262 11.8.5 Regular Expression Literals
- Scanner.prototype.testRegExp = function (pattern, flags) {
- // The BMP character to use as a replacement for astral symbols
when
- // translating an ES6 "u"-flagged pattern to an ES5-compatible
- // approximation.
- // Note: replacing with '\uFFFF' enables false positives in
unlikely
- // scenarios. For example, `[\u{1044f}-\u{10440}]` is an invalid
- // pattern that would not be detected by this substitution.
- var astralSubstitute = '\uFFFF';
- var tmp = pattern;
- var self = this;
- if (flags.indexOf('u') >= 0) {
- tmp = tmp
- .replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g,
function ($0, $1, $2) {
- var codePoint = parseInt($1 || $2, 16);
- if (codePoint > 0x10FFFF) {
-
self.throwUnexpectedToken(messages_1.Messages.InvalidRegExp);
- }
- if (codePoint <= 0xFFFF) {
- return String.fromCharCode(codePoint);
- }
- return astralSubstitute;
- })
- .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
astralSubstitute);
- }
- // First, detect invalid regular expressions.
- try {
- RegExp(tmp);
- }
- catch (e) {
-
this.throwUnexpectedToken(messages_1.Messages.InvalidRegExp);
- }
- // Return a regular expression object for this pattern-flag
pair, or
- // `null` in case the current environment doesn't support the
flags it
- // uses.
- try {
- return new RegExp(pattern, flags);
- }
- catch (exception) {
- /* istanbul ignore next */
- return null;
- }
- };
- ;
- Scanner.prototype.scanRegExpBody = function () {
- var ch = this.source[this.index];
- assert_1.assert(ch === '/', 'Regular expression literal must
start with a slash');
- var str = this.source[this.index++];
- var classMarker = false;
- var terminated = false;
- while (!this.eof()) {
- ch = this.source[this.index++];
- str += ch;
- if (ch === '\\') {
- ch = this.source[this.index++];
- // ECMA-262 7.8.5
- if
(character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
-
this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
- }
- str += ch;
- }
- else if
(character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
-
this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
- }
- else if (classMarker) {
- if (ch === ']') {
- classMarker = false;
- }
- }
- else {
- if (ch === '/') {
- terminated = true;
- break;
- }
- else if (ch === '[') {
- classMarker = true;
- }
- }
- }
- if (!terminated) {
-
this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
- }
- // Exclude leading and trailing slash.
- var body = str.substr(1, str.length - 2);
- return {
- value: body,
- literal: str
- };
- };
- ;
- Scanner.prototype.scanRegExpFlags = function () {
- var str = '';
- var flags = '';
- while (!this.eof()) {
- var ch = this.source[this.index];
- if
(!character_1.Character.isIdentifierPart(ch.charCodeAt(0))) {
- break;
- }
- ++this.index;
- if (ch === '\\' && !this.eof()) {
- ch = this.source[this.index];
- if (ch === 'u') {
- ++this.index;
- var restore = this.index;
- ch = this.scanHexEscape('u');
- if (ch) {
- flags += ch;
- for (str += '\\u'; restore < this.index;
++restore) {
- str += this.source[restore];
- }
- }
- else {
- this.index = restore;
- flags += 'u';
- str += '\\u';
- }
- this.tolerateUnexpectedToken();
- }
- else {
- str += '\\';
- this.tolerateUnexpectedToken();
- }
- }
- else {
- flags += ch;
- str += ch;
- }
- }
- return {
- value: flags,
- literal: str
- };
- };
- ;
- Scanner.prototype.scanRegExp = function () {
- var start = this.index;
- var body = this.scanRegExpBody();
- var flags = this.scanRegExpFlags();
- var value = this.testRegExp(body.value, flags.value);
- return {
- type: token_1.Token.RegularExpression,
- value: value,
- literal: body.literal + flags.literal,
- regex: {
- pattern: body.value,
- flags: flags.value
- },
- lineNumber: this.lineNumber,
- lineStart: this.lineStart,
- start: start,
- end: this.index
- };
- };
- ;
- Scanner.prototype.lex = function () {
- if (this.eof()) {
- return {
- type: token_1.Token.EOF,
- lineNumber: this.lineNumber,
- lineStart: this.lineStart,
- start: this.index,
- end: this.index
- };
- }
- var cp = this.source.charCodeAt(this.index);
- if (character_1.Character.isIdentifierStart(cp)) {
- return this.scanIdentifier();
- }
- // Very common: ( and ) and ;
- if (cp === 0x28 || cp === 0x29 || cp === 0x3B) {
- return this.scanPunctuator();
- }
- // String literal starts with single quote (U+0027) or double
quote (U+0022).
- if (cp === 0x27 || cp === 0x22) {
- return this.scanStringLiteral();
- }
- // Dot (.) U+002E can also start a floating-point number, hence
the need
- // to check the next character.
- if (cp === 0x2E) {
- if
(character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index + 1))) {
- return this.scanNumericLiteral();
- }
- return this.scanPunctuator();
- }
- if (character_1.Character.isDecimalDigit(cp)) {
- return this.scanNumericLiteral();
- }
- // Template literals start with ` (U+0060) for template head
- // or } (U+007D) for template middle or template tail.
- if (cp === 0x60 || (cp === 0x7D &&
this.curlyStack[this.curlyStack.length - 1] === '${')) {
- return this.scanTemplate();
- }
- // Possible identifier start in a surrogate pair.
- if (cp >= 0xD800 && cp < 0xDFFF) {
- if
(character_1.Character.isIdentifierStart(this.codePointAt(this.index))) {
- return this.scanIdentifier();
- }
- }
- return this.scanPunctuator();
- };
- ;
- return Scanner;
- }());
- exports.Scanner = Scanner;
-
-
-/***/ },
-/* 9 */
-/***/ function(module, exports) {
-
- "use strict";
- // See also tools/generate-unicode-regex.js.
- var Regex = {
- // Unicode v8.0.0 NonAsciiIdentifierStart:
- NonAsciiIdentifierStart:
/[\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\u
[...]
- // Unicode v8.0.0 NonAsciiIdentifierPart:
- NonAsciiIdentifierPart:
/[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\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\
[...]
- };
- exports.Character = {
- fromCodePoint: function (cp) {
- return (cp < 0x10000) ? String.fromCharCode(cp) :
- String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) +
- String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023));
- },
- // ECMA-262 11.2 White Space
- isWhiteSpace: function (cp) {
- return (cp === 0x20) || (cp === 0x09) || (cp === 0x0B) || (cp
=== 0x0C) || (cp === 0xA0) ||
- (cp >= 0x1680 && [0x1680, 0x2000, 0x2001, 0x2002, 0x2003,
0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000,
0xFEFF].indexOf(cp) >= 0);
- },
- // ECMA-262 11.3 Line Terminators
- isLineTerminator: function (cp) {
- return (cp === 0x0A) || (cp === 0x0D) || (cp === 0x2028) || (cp
=== 0x2029);
- },
- // ECMA-262 11.6 Identifier Names and Identifiers
- isIdentifierStart: function (cp) {
- return (cp === 0x24) || (cp === 0x5F) ||
- (cp >= 0x41 && cp <= 0x5A) ||
- (cp >= 0x61 && cp <= 0x7A) ||
- (cp === 0x5C) ||
- ((cp >= 0x80) &&
Regex.NonAsciiIdentifierStart.test(exports.Character.fromCodePoint(cp)));
- },
- isIdentifierPart: function (cp) {
- return (cp === 0x24) || (cp === 0x5F) ||
- (cp >= 0x41 && cp <= 0x5A) ||
- (cp >= 0x61 && cp <= 0x7A) ||
- (cp >= 0x30 && cp <= 0x39) ||
- (cp === 0x5C) ||
- ((cp >= 0x80) &&
Regex.NonAsciiIdentifierPart.test(exports.Character.fromCodePoint(cp)));
- },
- // ECMA-262 11.8.3 Numeric Literals
- isDecimalDigit: function (cp) {
- return (cp >= 0x30 && cp <= 0x39); // 0..9
- },
- isHexDigit: function (cp) {
- return (cp >= 0x30 && cp <= 0x39) ||
- (cp >= 0x41 && cp <= 0x46) ||
- (cp >= 0x61 && cp <= 0x66); // a..f
- },
- isOctalDigit: function (cp) {
- return (cp >= 0x30 && cp <= 0x37); // 0..7
- }
- };
-
-
-/***/ },
-/* 10 */
-/***/ function(module, exports, __webpack_require__) {
-
- "use strict";
- var syntax_1 = __webpack_require__(2);
- var ArrayExpression = (function () {
- function ArrayExpression(elements) {
- this.type = syntax_1.Syntax.ArrayExpression;
- this.elements = elements;
- }
- return ArrayExpression;
- }());
- exports.ArrayExpression = ArrayExpression;
- var ArrayPattern = (function () {
- function ArrayPattern(elements) {
- this.type = syntax_1.Syntax.ArrayPattern;
- this.elements = elements;
- }
- return ArrayPattern;
- }());
- exports.ArrayPattern = ArrayPattern;
- var ArrowFunctionExpression = (function () {
- function ArrowFunctionExpression(params, body, expression) {
- this.type = syntax_1.Syntax.ArrowFunctionExpression;
- this.id = null;
- this.params = params;
- this.body = body;
- this.generator = false;
- this.expression = expression;
- this.async = false;
- }
- return ArrowFunctionExpression;
- }());
- exports.ArrowFunctionExpression = ArrowFunctionExpression;
- var AssignmentExpression = (function () {
- function AssignmentExpression(operator, left, right) {
- this.type = syntax_1.Syntax.AssignmentExpression;
- this.operator = operator;
- this.left = left;
- this.right = right;
- }
- return AssignmentExpression;
- }());
- exports.AssignmentExpression = AssignmentExpression;
- var AssignmentPattern = (function () {
- function AssignmentPattern(left, right) {
- this.type = syntax_1.Syntax.AssignmentPattern;
- this.left = left;
- this.right = right;
- }
- return AssignmentPattern;
- }());
- exports.AssignmentPattern = AssignmentPattern;
- var AsyncArrowFunctionExpression = (function () {
- function AsyncArrowFunctionExpression(params, body, expression) {
- this.type = syntax_1.Syntax.ArrowFunctionExpression;
- this.id = null;
- this.params = params;
- this.body = body;
- this.generator = false;
- this.expression = expression;
- this.async = true;
- }
- return AsyncArrowFunctionExpression;
- }());
- exports.AsyncArrowFunctionExpression = AsyncArrowFunctionExpression;
- var AsyncFunctionDeclaration = (function () {
- function AsyncFunctionDeclaration(id, params, body) {
- this.type = syntax_1.Syntax.FunctionDeclaration;
- this.id = id;
- this.params = params;
- this.body = body;
- this.generator = false;
- this.expression = false;
- this.async = true;
- }
- return AsyncFunctionDeclaration;
- }());
- exports.AsyncFunctionDeclaration = AsyncFunctionDeclaration;
- var AsyncFunctionExpression = (function () {
- function AsyncFunctionExpression(id, params, body) {
- this.type = syntax_1.Syntax.FunctionExpression;
- this.id = id;
- this.params = params;
- this.body = body;
- this.generator = false;
- this.expression = false;
- this.async = true;
- }
- return AsyncFunctionExpression;
- }());
- exports.AsyncFunctionExpression = AsyncFunctionExpression;
- var AwaitExpression = (function () {
- function AwaitExpression(argument) {
- this.type = syntax_1.Syntax.AwaitExpression;
- this.argument = argument;
- }
- return AwaitExpression;
- }());
- exports.AwaitExpression = AwaitExpression;
- var BinaryExpression = (function () {
- function BinaryExpression(operator, left, right) {
- var logical = (operator === '||' || operator === '&&');
- this.type = logical ? syntax_1.Syntax.LogicalExpression :
syntax_1.Syntax.BinaryExpression;
- this.operator = operator;
- this.left = left;
- this.right = right;
- }
- return BinaryExpression;
- }());
- exports.BinaryExpression = BinaryExpression;
- var BlockStatement = (function () {
- function BlockStatement(body) {
- this.type = syntax_1.Syntax.BlockStatement;
- this.body = body;
- }
- return BlockStatement;
- }());
- exports.BlockStatement = BlockStatement;
- var BreakStatement = (function () {
- function BreakStatement(label) {
- this.type = syntax_1.Syntax.BreakStatement;
- this.label = label;
- }
- return BreakStatement;
- }());
- exports.BreakStatement = BreakStatement;
- var CallExpression = (function () {
- function CallExpression(callee, args) {
- this.type = syntax_1.Syntax.CallExpression;
- this.callee = callee;
- this.arguments = args;
- }
- return CallExpression;
- }());
- exports.CallExpression = CallExpression;
- var CatchClause = (function () {
- function CatchClause(param, body) {
- this.type = syntax_1.Syntax.CatchClause;
- this.param = param;
- this.body = body;
- }
- return CatchClause;
- }());
- exports.CatchClause = CatchClause;
- var ClassBody = (function () {
- function ClassBody(body) {
- this.type = syntax_1.Syntax.ClassBody;
- this.body = body;
- }
- return ClassBody;
- }());
- exports.ClassBody = ClassBody;
- var ClassDeclaration = (function () {
- function ClassDeclaration(id, superClass, body) {
- this.type = syntax_1.Syntax.ClassDeclaration;
- this.id = id;
- this.superClass = superClass;
- this.body = body;
- }
- return ClassDeclaration;
- }());
- exports.ClassDeclaration = ClassDeclaration;
- var ClassExpression = (function () {
- function ClassExpression(id, superClass, body) {
- this.type = syntax_1.Syntax.ClassExpression;
- this.id = id;
- this.superClass = superClass;
- this.body = body;
- }
- return ClassExpression;
- }());
- exports.ClassExpression = ClassExpression;
- var ComputedMemberExpression = (function () {
- function ComputedMemberExpression(object, property) {
- this.type = syntax_1.Syntax.MemberExpression;
- this.computed = true;
- this.object = object;
- this.property = property;
- }
- return ComputedMemberExpression;
- }());
- exports.ComputedMemberExpression = ComputedMemberExpression;
- var ConditionalExpression = (function () {
- function ConditionalExpression(test, consequent, alternate) {
- this.type = syntax_1.Syntax.ConditionalExpression;
- this.test = test;
- this.consequent = consequent;
- this.alternate = alternate;
- }
- return ConditionalExpression;
- }());
- exports.ConditionalExpression = ConditionalExpression;
- var ContinueStatement = (function () {
- function ContinueStatement(label) {
- this.type = syntax_1.Syntax.ContinueStatement;
- this.label = label;
- }
- return ContinueStatement;
- }());
- exports.ContinueStatement = ContinueStatement;
- var DebuggerStatement = (function () {
- function DebuggerStatement() {
- this.type = syntax_1.Syntax.DebuggerStatement;
- }
- return DebuggerStatement;
- }());
- exports.DebuggerStatement = DebuggerStatement;
- var Directive = (function () {
- function Directive(expression, directive) {
- this.type = syntax_1.Syntax.ExpressionStatement;
- this.expression = expression;
- this.directive = directive;
- }
- return Directive;
- }());
- exports.Directive = Directive;
- var DoWhileStatement = (function () {
- function DoWhileStatement(body, test) {
- this.type = syntax_1.Syntax.DoWhileStatement;
- this.body = body;
- this.test = test;
- }
- return DoWhileStatement;
- }());
- exports.DoWhileStatement = DoWhileStatement;
- var EmptyStatement = (function () {
- function EmptyStatement() {
- this.type = syntax_1.Syntax.EmptyStatement;
- }
- return EmptyStatement;
- }());
- exports.EmptyStatement = EmptyStatement;
- var ExportAllDeclaration = (function () {
- function ExportAllDeclaration(source) {
- this.type = syntax_1.Syntax.ExportAllDeclaration;
- this.source = source;
- }
- return ExportAllDeclaration;
- }());
- exports.ExportAllDeclaration = ExportAllDeclaration;
- var ExportDefaultDeclaration = (function () {
- function ExportDefaultDeclaration(declaration) {
- this.type = syntax_1.Syntax.ExportDefaultDeclaration;
- this.declaration = declaration;
- }
- return ExportDefaultDeclaration;
- }());
- exports.ExportDefaultDeclaration = ExportDefaultDeclaration;
- var ExportNamedDeclaration = (function () {
- function ExportNamedDeclaration(declaration, specifiers, source) {
- this.type = syntax_1.Syntax.ExportNamedDeclaration;
- this.declaration = declaration;
- this.specifiers = specifiers;
- this.source = source;
- }
- return ExportNamedDeclaration;
- }());
- exports.ExportNamedDeclaration = ExportNamedDeclaration;
- var ExportSpecifier = (function () {
- function ExportSpecifier(local, exported) {
- this.type = syntax_1.Syntax.ExportSpecifier;
- this.exported = exported;
- this.local = local;
- }
- return ExportSpecifier;
- }());
- exports.ExportSpecifier = ExportSpecifier;
- var ExpressionStatement = (function () {
- function ExpressionStatement(expression) {
- this.type = syntax_1.Syntax.ExpressionStatement;
- this.expression = expression;
- }
- return ExpressionStatement;
- }());
- exports.ExpressionStatement = ExpressionStatement;
- var ForInStatement = (function () {
- function ForInStatement(left, right, body) {
- this.type = syntax_1.Syntax.ForInStatement;
- this.left = left;
- this.right = right;
- this.body = body;
- this.each = false;
- }
- return ForInStatement;
- }());
- exports.ForInStatement = ForInStatement;
- var ForOfStatement = (function () {
- function ForOfStatement(left, right, body) {
- this.type = syntax_1.Syntax.ForOfStatement;
- this.left = left;
- this.right = right;
- this.body = body;
- }
- return ForOfStatement;
- }());
- exports.ForOfStatement = ForOfStatement;
- var ForStatement = (function () {
- function ForStatement(init, test, update, body) {
- this.type = syntax_1.Syntax.ForStatement;
- this.init = init;
- this.test = test;
- this.update = update;
- this.body = body;
- }
- return ForStatement;
- }());
- exports.ForStatement = ForStatement;
- var FunctionDeclaration = (function () {
- function FunctionDeclaration(id, params, body, generator) {
- this.type = syntax_1.Syntax.FunctionDeclaration;
- this.id = id;
- this.params = params;
- this.body = body;
- this.generator = generator;
- this.expression = false;
- this.async = false;
- }
- return FunctionDeclaration;
- }());
- exports.FunctionDeclaration = FunctionDeclaration;
- var FunctionExpression = (function () {
- function FunctionExpression(id, params, body, generator) {
- this.type = syntax_1.Syntax.FunctionExpression;
- this.id = id;
- this.params = params;
- this.body = body;
- this.generator = generator;
- this.expression = false;
- this.async = false;
- }
- return FunctionExpression;
- }());
- exports.FunctionExpression = FunctionExpression;
- var Identifier = (function () {
- function Identifier(name) {
- this.type = syntax_1.Syntax.Identifier;
- this.name = name;
- }
- return Identifier;
- }());
- exports.Identifier = Identifier;
- var IfStatement = (function () {
- function IfStatement(test, consequent, alternate) {
- this.type = syntax_1.Syntax.IfStatement;
- this.test = test;
- this.consequent = consequent;
- this.alternate = alternate;
- }
- return IfStatement;
- }());
- exports.IfStatement = IfStatement;
- var ImportDeclaration = (function () {
- function ImportDeclaration(specifiers, source) {
- this.type = syntax_1.Syntax.ImportDeclaration;
- this.specifiers = specifiers;
- this.source = source;
- }
- return ImportDeclaration;
- }());
- exports.ImportDeclaration = ImportDeclaration;
- var ImportDefaultSpecifier = (function () {
- function ImportDefaultSpecifier(local) {
- this.type = syntax_1.Syntax.ImportDefaultSpecifier;
- this.local = local;
- }
- return ImportDefaultSpecifier;
- }());
- exports.ImportDefaultSpecifier = ImportDefaultSpecifier;
- var ImportNamespaceSpecifier = (function () {
- function ImportNamespaceSpecifier(local) {
- this.type = syntax_1.Syntax.ImportNamespaceSpecifier;
- this.local = local;
- }
- return ImportNamespaceSpecifier;
- }());
- exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier;
- var ImportSpecifier = (function () {
- function ImportSpecifier(local, imported) {
- this.type = syntax_1.Syntax.ImportSpecifier;
- this.local = local;
- this.imported = imported;
- }
- return ImportSpecifier;
- }());
- exports.ImportSpecifier = ImportSpecifier;
- var LabeledStatement = (function () {
- function LabeledStatement(label, body) {
- this.type = syntax_1.Syntax.LabeledStatement;
- this.label = label;
- this.body = body;
- }
- return LabeledStatement;
- }());
- exports.LabeledStatement = LabeledStatement;
- var Literal = (function () {
- function Literal(value, raw) {
- this.type = syntax_1.Syntax.Literal;
- this.value = value;
- this.raw = raw;
- }
- return Literal;
- }());
- exports.Literal = Literal;
- var MetaProperty = (function () {
- function MetaProperty(meta, property) {
- this.type = syntax_1.Syntax.MetaProperty;
- this.meta = meta;
- this.property = property;
- }
- return MetaProperty;
- }());
- exports.MetaProperty = MetaProperty;
- var MethodDefinition = (function () {
- function MethodDefinition(key, computed, value, kind, isStatic) {
- this.type = syntax_1.Syntax.MethodDefinition;
- this.key = key;
- this.computed = computed;
- this.value = value;
- this.kind = kind;
- this.static = isStatic;
- }
- return MethodDefinition;
- }());
- exports.MethodDefinition = MethodDefinition;
- var Module = (function () {
- function Module(body) {
- this.type = syntax_1.Syntax.Program;
- this.body = body;
- this.sourceType = 'module';
- }
- return Module;
- }());
- exports.Module = Module;
- var NewExpression = (function () {
- function NewExpression(callee, args) {
- this.type = syntax_1.Syntax.NewExpression;
- this.callee = callee;
- this.arguments = args;
- }
- return NewExpression;
- }());
- exports.NewExpression = NewExpression;
- var ObjectExpression = (function () {
- function ObjectExpression(properties) {
- this.type = syntax_1.Syntax.ObjectExpression;
- this.properties = properties;
- }
- return ObjectExpression;
- }());
- exports.ObjectExpression = ObjectExpression;
- var ObjectPattern = (function () {
- function ObjectPattern(properties) {
- this.type = syntax_1.Syntax.ObjectPattern;
- this.properties = properties;
- }
- return ObjectPattern;
- }());
- exports.ObjectPattern = ObjectPattern;
- var Property = (function () {
- function Property(kind, key, computed, value, method, shorthand) {
- this.type = syntax_1.Syntax.Property;
- this.key = key;
- this.computed = computed;
- this.value = value;
- this.kind = kind;
- this.method = method;
- this.shorthand = shorthand;
- }
- return Property;
- }());
- exports.Property = Property;
- var RegexLiteral = (function () {
- function RegexLiteral(value, raw, regex) {
- this.type = syntax_1.Syntax.Literal;
- this.value = value;
- this.raw = raw;
- this.regex = regex;
- }
- return RegexLiteral;
- }());
- exports.RegexLiteral = RegexLiteral;
- var RestElement = (function () {
- function RestElement(argument) {
- this.type = syntax_1.Syntax.RestElement;
- this.argument = argument;
- }
- return RestElement;
- }());
- exports.RestElement = RestElement;
- var ReturnStatement = (function () {
- function ReturnStatement(argument) {
- this.type = syntax_1.Syntax.ReturnStatement;
- this.argument = argument;
- }
- return ReturnStatement;
- }());
- exports.ReturnStatement = ReturnStatement;
- var Script = (function () {
- function Script(body) {
- this.type = syntax_1.Syntax.Program;
- this.body = body;
- this.sourceType = 'script';
- }
- return Script;
- }());
- exports.Script = Script;
- var SequenceExpression = (function () {
- function SequenceExpression(expressions) {
- this.type = syntax_1.Syntax.SequenceExpression;
- this.expressions = expressions;
- }
- return SequenceExpression;
- }());
- exports.SequenceExpression = SequenceExpression;
- var SpreadElement = (function () {
- function SpreadElement(argument) {
- this.type = syntax_1.Syntax.SpreadElement;
- this.argument = argument;
- }
- return SpreadElement;
- }());
- exports.SpreadElement = SpreadElement;
- var StaticMemberExpression = (function () {
- function StaticMemberExpression(object, property) {
- this.type = syntax_1.Syntax.MemberExpression;
- this.computed = false;
- this.object = object;
- this.property = property;
- }
- return StaticMemberExpression;
- }());
- exports.StaticMemberExpression = StaticMemberExpression;
- var Super = (function () {
- function Super() {
- this.type = syntax_1.Syntax.Super;
- }
- return Super;
- }());
- exports.Super = Super;
- var SwitchCase = (function () {
- function SwitchCase(test, consequent) {
- this.type = syntax_1.Syntax.SwitchCase;
- this.test = test;
- this.consequent = consequent;
- }
- return SwitchCase;
- }());
- exports.SwitchCase = SwitchCase;
- var SwitchStatement = (function () {
- function SwitchStatement(discriminant, cases) {
- this.type = syntax_1.Syntax.SwitchStatement;
- this.discriminant = discriminant;
- this.cases = cases;
- }
- return SwitchStatement;
- }());
- exports.SwitchStatement = SwitchStatement;
- var TaggedTemplateExpression = (function () {
- function TaggedTemplateExpression(tag, quasi) {
- this.type = syntax_1.Syntax.TaggedTemplateExpression;
- this.tag = tag;
- this.quasi = quasi;
- }
- return TaggedTemplateExpression;
- }());
- exports.TaggedTemplateExpression = TaggedTemplateExpression;
- var TemplateElement = (function () {
- function TemplateElement(value, tail) {
- this.type = syntax_1.Syntax.TemplateElement;
- this.value = value;
- this.tail = tail;
- }
- return TemplateElement;
- }());
- exports.TemplateElement = TemplateElement;
- var TemplateLiteral = (function () {
- function TemplateLiteral(quasis, expressions) {
- this.type = syntax_1.Syntax.TemplateLiteral;
- this.quasis = quasis;
- this.expressions = expressions;
- }
- return TemplateLiteral;
- }());
- exports.TemplateLiteral = TemplateLiteral;
- var ThisExpression = (function () {
- function ThisExpression() {
- this.type = syntax_1.Syntax.ThisExpression;
- }
- return ThisExpression;
- }());
- exports.ThisExpression = ThisExpression;
- var ThrowStatement = (function () {
- function ThrowStatement(argument) {
- this.type = syntax_1.Syntax.ThrowStatement;
- this.argument = argument;
- }
- return ThrowStatement;
- }());
- exports.ThrowStatement = ThrowStatement;
- var TryStatement = (function () {
- function TryStatement(block, handler, finalizer) {
- this.type = syntax_1.Syntax.TryStatement;
- this.block = block;
- this.handler = handler;
- this.finalizer = finalizer;
- }
- return TryStatement;
- }());
- exports.TryStatement = TryStatement;
- var UnaryExpression = (function () {
- function UnaryExpression(operator, argument) {
- this.type = syntax_1.Syntax.UnaryExpression;
- this.operator = operator;
- this.argument = argument;
- this.prefix = true;
- }
- return UnaryExpression;
- }());
- exports.UnaryExpression = UnaryExpression;
- var UpdateExpression = (function () {
- function UpdateExpression(operator, argument, prefix) {
- this.type = syntax_1.Syntax.UpdateExpression;
- this.operator = operator;
- this.argument = argument;
- this.prefix = prefix;
- }
- return UpdateExpression;
- }());
- exports.UpdateExpression = UpdateExpression;
- var VariableDeclaration = (function () {
- function VariableDeclaration(declarations, kind) {
- this.type = syntax_1.Syntax.VariableDeclaration;
- this.declarations = declarations;
- this.kind = kind;
- }
- return VariableDeclaration;
- }());
- exports.VariableDeclaration = VariableDeclaration;
- var VariableDeclarator = (function () {
- function VariableDeclarator(id, init) {
- this.type = syntax_1.Syntax.VariableDeclarator;
- this.id = id;
- this.init = init;
- }
- return VariableDeclarator;
- }());
- exports.VariableDeclarator = VariableDeclarator;
- var WhileStatement = (function () {
- function WhileStatement(test, body) {
- this.type = syntax_1.Syntax.WhileStatement;
- this.test = test;
- this.body = body;
- }
- return WhileStatement;
- }());
- exports.WhileStatement = WhileStatement;
- var WithStatement = (function () {
- function WithStatement(object, body) {
- this.type = syntax_1.Syntax.WithStatement;
- this.object = object;
- this.body = body;
- }
- return WithStatement;
- }());
- exports.WithStatement = WithStatement;
- var YieldExpression = (function () {
- function YieldExpression(argument, delegate) {
- this.type = syntax_1.Syntax.YieldExpression;
- this.argument = argument;
- this.delegate = delegate;
- }
- return YieldExpression;
- }());
- exports.YieldExpression = YieldExpression;
-
-
-/***/ },
-/* 11 */
-/***/ function(module, exports, __webpack_require__) {
-
- "use strict";
-/* istanbul ignore next */
- var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype =
b.prototype, new __());
- };
- var character_1 = __webpack_require__(9);
- var token_1 = __webpack_require__(7);
- var parser_1 = __webpack_require__(3);
- var xhtml_entities_1 = __webpack_require__(12);
- var jsx_syntax_1 = __webpack_require__(13);
- var Node = __webpack_require__(10);
- var JSXNode = __webpack_require__(14);
- var JSXToken;
- (function (JSXToken) {
- JSXToken[JSXToken["Identifier"] = 100] = "Identifier";
- JSXToken[JSXToken["Text"] = 101] = "Text";
- })(JSXToken || (JSXToken = {}));
- token_1.TokenName[JSXToken.Identifier] = 'JSXIdentifier';
- token_1.TokenName[JSXToken.Text] = 'JSXText';
- // Fully qualified element name, e.g. <svg:path> returns "svg:path"
- function getQualifiedElementName(elementName) {
- var qualifiedName;
- switch (elementName.type) {
- case jsx_syntax_1.JSXSyntax.JSXIdentifier:
- var id = (elementName);
- qualifiedName = id.name;
- break;
- case jsx_syntax_1.JSXSyntax.JSXNamespacedName:
- var ns = (elementName);
- qualifiedName = getQualifiedElementName(ns.namespace) + ':'
+
- getQualifiedElementName(ns.name);
- break;
- case jsx_syntax_1.JSXSyntax.JSXMemberExpression:
- var expr = (elementName);
- qualifiedName = getQualifiedElementName(expr.object) + '.' +
- getQualifiedElementName(expr.property);
- break;
- }
- return qualifiedName;
- }
- var JSXParser = (function (_super) {
- __extends(JSXParser, _super);
- function JSXParser(code, options, delegate) {
- _super.call(this, code, options, delegate);
- }
- JSXParser.prototype.parsePrimaryExpression = function () {
- return this.match('<') ? this.parseJSXRoot() :
_super.prototype.parsePrimaryExpression.call(this);
- };
- JSXParser.prototype.startJSX = function () {
- // Unwind the scanner before the lookahead token.
- this.scanner.index = this.startMarker.index;
- this.scanner.lineNumber = this.startMarker.lineNumber;
- this.scanner.lineStart = this.startMarker.lineStart;
- };
- JSXParser.prototype.finishJSX = function () {
- // Prime the next lookahead.
- this.nextToken();
- };
- JSXParser.prototype.reenterJSX = function () {
- this.startJSX();
- this.expectJSX('}');
- // Pop the closing '}' added from the lookahead.
- if (this.config.tokens) {
- this.tokens.pop();
- }
- };
- JSXParser.prototype.createJSXNode = function () {
- this.collectComments();
- return {
- index: this.scanner.index,
- line: this.scanner.lineNumber,
- column: this.scanner.index - this.scanner.lineStart
- };
- };
- JSXParser.prototype.createJSXChildNode = function () {
- return {
- index: this.scanner.index,
- line: this.scanner.lineNumber,
- column: this.scanner.index - this.scanner.lineStart
- };
- };
- JSXParser.prototype.scanXHTMLEntity = function () {
- var result = '&';
- var str = '';
- while (!this.scanner.eof()) {
- var ch = this.scanner.source[this.scanner.index++];
- if (ch === ';') {
- if (str[0] === '#') {
- str = str.substr(1);
- var hex = (str[0] === 'x');
- var cp = hex ? parseInt('0' + str, 16) :
parseInt(str, 10);
- result = String.fromCharCode(cp);
- }
- else if (xhtml_entities_1.XHTMLEntities[str]) {
- result = xhtml_entities_1.XHTMLEntities[str];
- }
- else {
- result += ch;
- }
- break;
- }
- str += ch;
- result += ch;
- }
- return result;
- };
- // Scan the next JSX token. This replaces Scanner#lex when in JSX
mode.
- JSXParser.prototype.lexJSX = function () {
- var cp = this.scanner.source.charCodeAt(this.scanner.index);
- // < > / : = { }
- if (cp === 60 || cp === 62 || cp === 47 || cp === 58 || cp ===
61 || cp === 123 || cp === 125) {
- var value = this.scanner.source[this.scanner.index++];
- return {
- type: token_1.Token.Punctuator,
- value: value,
- lineNumber: this.scanner.lineNumber,
- lineStart: this.scanner.lineStart,
- start: this.scanner.index - 1,
- end: this.scanner.index
- };
- }
- // " '
- if (cp === 34 || cp === 39) {
- var start = this.scanner.index;
- var quote = this.scanner.source[this.scanner.index++];
- var str = '';
- while (!this.scanner.eof()) {
- var ch = this.scanner.source[this.scanner.index++];
- if (ch === quote) {
- break;
- }
- else if (ch === '&') {
- str += this.scanXHTMLEntity();
- }
- else {
- str += ch;
- }
- }
- return {
- type: token_1.Token.StringLiteral,
- value: str,
- lineNumber: this.scanner.lineNumber,
- lineStart: this.scanner.lineStart,
- start: start,
- end: this.scanner.index
- };
- }
- // ... or .
- if (cp === 46) {
- var n1 = this.scanner.source.charCodeAt(this.scanner.index
+ 1);
- var n2 = this.scanner.source.charCodeAt(this.scanner.index
+ 2);
- var value = (n1 === 46 && n2 === 46) ? '...' : '.';
- var start = this.scanner.index;
- this.scanner.index += value.length;
- return {
- type: token_1.Token.Punctuator,
- value: value,
- lineNumber: this.scanner.lineNumber,
- lineStart: this.scanner.lineStart,
- start: start,
- end: this.scanner.index
- };
- }
- // Identifer can not contain backslash (char code 92).
- if (character_1.Character.isIdentifierStart(cp) && (cp !== 92))
{
- var start = this.scanner.index;
- ++this.scanner.index;
- while (!this.scanner.eof()) {
- var ch =
this.scanner.source.charCodeAt(this.scanner.index);
- if (character_1.Character.isIdentifierPart(ch) && (ch
!== 92)) {
- ++this.scanner.index;
- }
- else if (ch === 45) {
- // Hyphen (char code 45) can be part of an
identifier.
- ++this.scanner.index;
- }
- else {
- break;
- }
- }
- var id = this.scanner.source.slice(start,
this.scanner.index);
- return {
- type: JSXToken.Identifier,
- value: id,
- lineNumber: this.scanner.lineNumber,
- lineStart: this.scanner.lineStart,
- start: start,
- end: this.scanner.index
- };
- }
- this.scanner.throwUnexpectedToken();
- };
- JSXParser.prototype.nextJSXToken = function () {
- this.collectComments();
- this.startMarker.index = this.scanner.index;
- this.startMarker.lineNumber = this.scanner.lineNumber;
- this.startMarker.lineStart = this.scanner.lineStart;
- var token = this.lexJSX();
- this.lastMarker.index = this.scanner.index;
- this.lastMarker.lineNumber = this.scanner.lineNumber;
- this.lastMarker.lineStart = this.scanner.lineStart;
- if (this.config.tokens) {
- this.tokens.push(this.convertToken(token));
- }
- return token;
- };
- JSXParser.prototype.nextJSXText = function () {
- this.startMarker.index = this.scanner.index;
- this.startMarker.lineNumber = this.scanner.lineNumber;
- this.startMarker.lineStart = this.scanner.lineStart;
- var start = this.scanner.index;
- var text = '';
- while (!this.scanner.eof()) {
- var ch = this.scanner.source[this.scanner.index];
- if (ch === '{' || ch === '<') {
- break;
- }
- ++this.scanner.index;
- text += ch;
- if
(character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
- ++this.scanner.lineNumber;
- if (ch === '\r' &&
this.scanner.source[this.scanner.index] === '\n') {
- ++this.scanner.index;
- }
- this.scanner.lineStart = this.scanner.index;
- }
- }
- this.lastMarker.index = this.scanner.index;
- this.lastMarker.lineNumber = this.scanner.lineNumber;
- this.lastMarker.lineStart = this.scanner.lineStart;
- var token = {
- type: JSXToken.Text,
- value: text,
- lineNumber: this.scanner.lineNumber,
- lineStart: this.scanner.lineStart,
- start: start,
- end: this.scanner.index
- };
- if ((text.length > 0) && this.config.tokens) {
- this.tokens.push(this.convertToken(token));
- }
- return token;
- };
- JSXParser.prototype.peekJSXToken = function () {
- var previousIndex = this.scanner.index;
- var previousLineNumber = this.scanner.lineNumber;
- var previousLineStart = this.scanner.lineStart;
- this.scanner.scanComments();
- var next = this.lexJSX();
- this.scanner.index = previousIndex;
- this.scanner.lineNumber = previousLineNumber;
- this.scanner.lineStart = previousLineStart;
- return next;
- };
- // Expect the next JSX token to match the specified punctuator.
- // If not, an exception will be thrown.
- JSXParser.prototype.expectJSX = function (value) {
- var token = this.nextJSXToken();
- if (token.type !== token_1.Token.Punctuator || token.value !==
value) {
- this.throwUnexpectedToken(token);
- }
- };
- // Return true if the next JSX token matches the specified
punctuator.
- JSXParser.prototype.matchJSX = function (value) {
- var next = this.peekJSXToken();
- return next.type === token_1.Token.Punctuator && next.value ===
value;
- };
- JSXParser.prototype.parseJSXIdentifier = function () {
- var node = this.createJSXNode();
- var token = this.nextJSXToken();
- if (token.type !== JSXToken.Identifier) {
- this.throwUnexpectedToken(token);
- }
- return this.finalize(node, new
JSXNode.JSXIdentifier(token.value));
- };
- JSXParser.prototype.parseJSXElementName = function () {
- var node = this.createJSXNode();
- var elementName = this.parseJSXIdentifier();
- if (this.matchJSX(':')) {
- var namespace = elementName;
- this.expectJSX(':');
- var name_1 = this.parseJSXIdentifier();
- elementName = this.finalize(node, new
JSXNode.JSXNamespacedName(namespace, name_1));
- }
- else if (this.matchJSX('.')) {
- while (this.matchJSX('.')) {
- var object = elementName;
- this.expectJSX('.');
- var property = this.parseJSXIdentifier();
- elementName = this.finalize(node, new
JSXNode.JSXMemberExpression(object, property));
- }
- }
- return elementName;
- };
- JSXParser.prototype.parseJSXAttributeName = function () {
- var node = this.createJSXNode();
- var attributeName;
- var identifier = this.parseJSXIdentifier();
- if (this.matchJSX(':')) {
- var namespace = identifier;
- this.expectJSX(':');
- var name_2 = this.parseJSXIdentifier();
- attributeName = this.finalize(node, new
JSXNode.JSXNamespacedName(namespace, name_2));
- }
- else {
- attributeName = identifier;
- }
- return attributeName;
- };
- JSXParser.prototype.parseJSXStringLiteralAttribute = function () {
- var node = this.createJSXNode();
- var token = this.nextJSXToken();
- if (token.type !== token_1.Token.StringLiteral) {
- this.throwUnexpectedToken(token);
- }
- var raw = this.getTokenRaw(token);
- return this.finalize(node, new Node.Literal(token.value, raw));
- };
- JSXParser.prototype.parseJSXExpressionAttribute = function () {
- var node = this.createJSXNode();
- this.expectJSX('{');
- this.finishJSX();
- if (this.match('}')) {
- this.tolerateError('JSX attributes must only be assigned a
non-empty expression');
- }
- var expression = this.parseAssignmentExpression();
- this.reenterJSX();
- return this.finalize(node, new
JSXNode.JSXExpressionContainer(expression));
- };
- JSXParser.prototype.parseJSXAttributeValue = function () {
- return this.matchJSX('{') ? this.parseJSXExpressionAttribute() :
- this.matchJSX('<') ? this.parseJSXElement() :
this.parseJSXStringLiteralAttribute();
- };
- JSXParser.prototype.parseJSXNameValueAttribute = function () {
- var node = this.createJSXNode();
- var name = this.parseJSXAttributeName();
- var value = null;
- if (this.matchJSX('=')) {
- this.expectJSX('=');
- value = this.parseJSXAttributeValue();
- }
- return this.finalize(node, new JSXNode.JSXAttribute(name,
value));
- };
- JSXParser.prototype.parseJSXSpreadAttribute = function () {
- var node = this.createJSXNode();
- this.expectJSX('{');
- this.expectJSX('...');
- this.finishJSX();
- var argument = this.parseAssignmentExpression();
- this.reenterJSX();
- return this.finalize(node, new
JSXNode.JSXSpreadAttribute(argument));
- };
- JSXParser.prototype.parseJSXAttributes = function () {
- var attributes = [];
- while (!this.matchJSX('/') && !this.matchJSX('>')) {
- var attribute = this.matchJSX('{') ?
this.parseJSXSpreadAttribute() :
- this.parseJSXNameValueAttribute();
- attributes.push(attribute);
- }
- return attributes;
- };
- JSXParser.prototype.parseJSXOpeningElement = function () {
- var node = this.createJSXNode();
- this.expectJSX('<');
- var name = this.parseJSXElementName();
- var attributes = this.parseJSXAttributes();
- var selfClosing = this.matchJSX('/');
- if (selfClosing) {
- this.expectJSX('/');
- }
- this.expectJSX('>');
- return this.finalize(node, new JSXNode.JSXOpeningElement(name,
selfClosing, attributes));
- };
- JSXParser.prototype.parseJSXBoundaryElement = function () {
- var node = this.createJSXNode();
- this.expectJSX('<');
- if (this.matchJSX('/')) {
- this.expectJSX('/');
- var name_3 = this.parseJSXElementName();
- this.expectJSX('>');
- return this.finalize(node, new
JSXNode.JSXClosingElement(name_3));
- }
- var name = this.parseJSXElementName();
- var attributes = this.parseJSXAttributes();
- var selfClosing = this.matchJSX('/');
- if (selfClosing) {
- this.expectJSX('/');
- }
- this.expectJSX('>');
- return this.finalize(node, new JSXNode.JSXOpeningElement(name,
selfClosing, attributes));
- };
- JSXParser.prototype.parseJSXEmptyExpression = function () {
- var node = this.createJSXChildNode();
- this.collectComments();
- this.lastMarker.index = this.scanner.index;
- this.lastMarker.lineNumber = this.scanner.lineNumber;
- this.lastMarker.lineStart = this.scanner.lineStart;
- return this.finalize(node, new JSXNode.JSXEmptyExpression());
- };
- JSXParser.prototype.parseJSXExpressionContainer = function () {
- var node = this.createJSXNode();
- this.expectJSX('{');
- var expression;
- if (this.matchJSX('}')) {
- expression = this.parseJSXEmptyExpression();
- this.expectJSX('}');
- }
- else {
- this.finishJSX();
- expression = this.parseAssignmentExpression();
- this.reenterJSX();
- }
- return this.finalize(node, new
JSXNode.JSXExpressionContainer(expression));
- };
- JSXParser.prototype.parseJSXChildren = function () {
- var children = [];
- while (!this.scanner.eof()) {
- var node = this.createJSXChildNode();
- var token = this.nextJSXText();
- if (token.start < token.end) {
- var raw = this.getTokenRaw(token);
- var child = this.finalize(node, new
JSXNode.JSXText(token.value, raw));
- children.push(child);
- }
- if (this.scanner.source[this.scanner.index] === '{') {
- var container = this.parseJSXExpressionContainer();
- children.push(container);
- }
- else {
- break;
- }
- }
- return children;
- };
- JSXParser.prototype.parseComplexJSXElement = function (el) {
- var stack = [];
- while (!this.scanner.eof()) {
- el.children = el.children.concat(this.parseJSXChildren());
- var node = this.createJSXChildNode();
- var element = this.parseJSXBoundaryElement();
- if (element.type ===
jsx_syntax_1.JSXSyntax.JSXOpeningElement) {
- var opening = (element);
- if (opening.selfClosing) {
- var child = this.finalize(node, new
JSXNode.JSXElement(opening, [], null));
- el.children.push(child);
- }
- else {
- stack.push(el);
- el = { node: node, opening: opening, closing: null,
children: [] };
- }
- }
- if (element.type ===
jsx_syntax_1.JSXSyntax.JSXClosingElement) {
- el.closing = (element);
- var open_1 = getQualifiedElementName(el.opening.name);
- var close_1 = getQualifiedElementName(el.closing.name);
- if (open_1 !== close_1) {
- this.tolerateError('Expected corresponding JSX
closing tag for %0', open_1);
- }
- if (stack.length > 0) {
- var child = this.finalize(el.node, new
JSXNode.JSXElement(el.opening, el.children, el.closing));
- el = stack[stack.length - 1];
- el.children.push(child);
- stack.pop();
- }
- else {
- break;
- }
- }
- }
- return el;
- };
- JSXParser.prototype.parseJSXElement = function () {
- var node = this.createJSXNode();
- var opening = this.parseJSXOpeningElement();
- var children = [];
- var closing = null;
- if (!opening.selfClosing) {
- var el = this.parseComplexJSXElement({ node: node, opening:
opening, closing: closing, children: children });
- children = el.children;
- closing = el.closing;
- }
- return this.finalize(node, new JSXNode.JSXElement(opening,
children, closing));
- };
- JSXParser.prototype.parseJSXRoot = function () {
- // Pop the opening '<' added from the lookahead.
- if (this.config.tokens) {
- this.tokens.pop();
- }
- this.startJSX();
- var element = this.parseJSXElement();
- this.finishJSX();
- return element;
- };
- return JSXParser;
- }(parser_1.Parser));
- exports.JSXParser = JSXParser;
-
-
-/***/ },
-/* 12 */
-/***/ function(module, exports) {
-
- // Generated by generate-xhtml-entities.js. DO NOT MODIFY!
- "use strict";
- exports.XHTMLEntities = {
- quot: '\u0022',
- amp: '\u0026',
- apos: '\u0027',
- gt: '\u003E',
- nbsp: '\u00A0',
- iexcl: '\u00A1',
- cent: '\u00A2',
- pound: '\u00A3',
- curren: '\u00A4',
- yen: '\u00A5',
- brvbar: '\u00A6',
- sect: '\u00A7',
- uml: '\u00A8',
- copy: '\u00A9',
- ordf: '\u00AA',
- laquo: '\u00AB',
- not: '\u00AC',
- shy: '\u00AD',
- reg: '\u00AE',
- macr: '\u00AF',
- deg: '\u00B0',
- plusmn: '\u00B1',
- sup2: '\u00B2',
- sup3: '\u00B3',
- acute: '\u00B4',
- micro: '\u00B5',
- para: '\u00B6',
- middot: '\u00B7',
- cedil: '\u00B8',
- sup1: '\u00B9',
- ordm: '\u00BA',
- raquo: '\u00BB',
- frac14: '\u00BC',
- frac12: '\u00BD',
- frac34: '\u00BE',
- iquest: '\u00BF',
- Agrave: '\u00C0',
- Aacute: '\u00C1',
- Acirc: '\u00C2',
- Atilde: '\u00C3',
- Auml: '\u00C4',
- Aring: '\u00C5',
- AElig: '\u00C6',
- Ccedil: '\u00C7',
- Egrave: '\u00C8',
- Eacute: '\u00C9',
- Ecirc: '\u00CA',
- Euml: '\u00CB',
- Igrave: '\u00CC',
- Iacute: '\u00CD',
- Icirc: '\u00CE',
- Iuml: '\u00CF',
- ETH: '\u00D0',
- Ntilde: '\u00D1',
- Ograve: '\u00D2',
- Oacute: '\u00D3',
- Ocirc: '\u00D4',
- Otilde: '\u00D5',
- Ouml: '\u00D6',
- times: '\u00D7',
- Oslash: '\u00D8',
- Ugrave: '\u00D9',
- Uacute: '\u00DA',
- Ucirc: '\u00DB',
- Uuml: '\u00DC',
- Yacute: '\u00DD',
- THORN: '\u00DE',
- szlig: '\u00DF',
- agrave: '\u00E0',
- aacute: '\u00E1',
- acirc: '\u00E2',
- atilde: '\u00E3',
- auml: '\u00E4',
- aring: '\u00E5',
- aelig: '\u00E6',
- ccedil: '\u00E7',
- egrave: '\u00E8',
- eacute: '\u00E9',
- ecirc: '\u00EA',
- euml: '\u00EB',
- igrave: '\u00EC',
- iacute: '\u00ED',
- icirc: '\u00EE',
- iuml: '\u00EF',
- eth: '\u00F0',
- ntilde: '\u00F1',
- ograve: '\u00F2',
- oacute: '\u00F3',
- ocirc: '\u00F4',
- otilde: '\u00F5',
- ouml: '\u00F6',
- divide: '\u00F7',
- oslash: '\u00F8',
- ugrave: '\u00F9',
- uacute: '\u00FA',
- ucirc: '\u00FB',
- uuml: '\u00FC',
- yacute: '\u00FD',
- thorn: '\u00FE',
- yuml: '\u00FF',
- OElig: '\u0152',
- oelig: '\u0153',
- Scaron: '\u0160',
- scaron: '\u0161',
- Yuml: '\u0178',
- fnof: '\u0192',
- circ: '\u02C6',
- tilde: '\u02DC',
- Alpha: '\u0391',
- Beta: '\u0392',
- Gamma: '\u0393',
- Delta: '\u0394',
- Epsilon: '\u0395',
- Zeta: '\u0396',
- Eta: '\u0397',
- Theta: '\u0398',
- Iota: '\u0399',
- Kappa: '\u039A',
- Lambda: '\u039B',
- Mu: '\u039C',
- Nu: '\u039D',
- Xi: '\u039E',
- Omicron: '\u039F',
- Pi: '\u03A0',
- Rho: '\u03A1',
- Sigma: '\u03A3',
- Tau: '\u03A4',
- Upsilon: '\u03A5',
- Phi: '\u03A6',
- Chi: '\u03A7',
- Psi: '\u03A8',
- Omega: '\u03A9',
- alpha: '\u03B1',
- beta: '\u03B2',
- gamma: '\u03B3',
- delta: '\u03B4',
- epsilon: '\u03B5',
- zeta: '\u03B6',
- eta: '\u03B7',
- theta: '\u03B8',
- iota: '\u03B9',
- kappa: '\u03BA',
- lambda: '\u03BB',
- mu: '\u03BC',
- nu: '\u03BD',
- xi: '\u03BE',
- omicron: '\u03BF',
- pi: '\u03C0',
- rho: '\u03C1',
- sigmaf: '\u03C2',
- sigma: '\u03C3',
- tau: '\u03C4',
- upsilon: '\u03C5',
- phi: '\u03C6',
- chi: '\u03C7',
- psi: '\u03C8',
- omega: '\u03C9',
- thetasym: '\u03D1',
- upsih: '\u03D2',
- piv: '\u03D6',
- ensp: '\u2002',
- emsp: '\u2003',
- thinsp: '\u2009',
- zwnj: '\u200C',
- zwj: '\u200D',
- lrm: '\u200E',
- rlm: '\u200F',
- ndash: '\u2013',
- mdash: '\u2014',
- lsquo: '\u2018',
- rsquo: '\u2019',
- sbquo: '\u201A',
- ldquo: '\u201C',
- rdquo: '\u201D',
- bdquo: '\u201E',
- dagger: '\u2020',
- Dagger: '\u2021',
- bull: '\u2022',
- hellip: '\u2026',
- permil: '\u2030',
- prime: '\u2032',
- Prime: '\u2033',
- lsaquo: '\u2039',
- rsaquo: '\u203A',
- oline: '\u203E',
- frasl: '\u2044',
- euro: '\u20AC',
- image: '\u2111',
- weierp: '\u2118',
- real: '\u211C',
- trade: '\u2122',
- alefsym: '\u2135',
- larr: '\u2190',
- uarr: '\u2191',
- rarr: '\u2192',
- darr: '\u2193',
- harr: '\u2194',
- crarr: '\u21B5',
- lArr: '\u21D0',
- uArr: '\u21D1',
- rArr: '\u21D2',
- dArr: '\u21D3',
- hArr: '\u21D4',
- forall: '\u2200',
- part: '\u2202',
- exist: '\u2203',
- empty: '\u2205',
- nabla: '\u2207',
- isin: '\u2208',
- notin: '\u2209',
- ni: '\u220B',
- prod: '\u220F',
- sum: '\u2211',
- minus: '\u2212',
- lowast: '\u2217',
- radic: '\u221A',
- prop: '\u221D',
- infin: '\u221E',
- ang: '\u2220',
- and: '\u2227',
- or: '\u2228',
- cap: '\u2229',
- cup: '\u222A',
- int: '\u222B',
- there4: '\u2234',
- sim: '\u223C',
- cong: '\u2245',
- asymp: '\u2248',
- ne: '\u2260',
- equiv: '\u2261',
- le: '\u2264',
- ge: '\u2265',
- sub: '\u2282',
- sup: '\u2283',
- nsub: '\u2284',
- sube: '\u2286',
- supe: '\u2287',
- oplus: '\u2295',
- otimes: '\u2297',
- perp: '\u22A5',
- sdot: '\u22C5',
- lceil: '\u2308',
- rceil: '\u2309',
- lfloor: '\u230A',
- rfloor: '\u230B',
- loz: '\u25CA',
- spades: '\u2660',
- clubs: '\u2663',
- hearts: '\u2665',
- diams: '\u2666',
- lang: '\u27E8',
- rang: '\u27E9'
- };
-
-
-/***/ },
-/* 13 */
-/***/ function(module, exports) {
-
- "use strict";
- exports.JSXSyntax = {
- JSXAttribute: 'JSXAttribute',
- JSXClosingElement: 'JSXClosingElement',
- JSXElement: 'JSXElement',
- JSXEmptyExpression: 'JSXEmptyExpression',
- JSXExpressionContainer: 'JSXExpressionContainer',
- JSXIdentifier: 'JSXIdentifier',
- JSXMemberExpression: 'JSXMemberExpression',
- JSXNamespacedName: 'JSXNamespacedName',
- JSXOpeningElement: 'JSXOpeningElement',
- JSXSpreadAttribute: 'JSXSpreadAttribute',
- JSXText: 'JSXText'
- };
-
-
-/***/ },
-/* 14 */
-/***/ function(module, exports, __webpack_require__) {
-
- "use strict";
- var jsx_syntax_1 = __webpack_require__(13);
- var JSXClosingElement = (function () {
- function JSXClosingElement(name) {
- this.type = jsx_syntax_1.JSXSyntax.JSXClosingElement;
- this.name = name;
- }
- return JSXClosingElement;
- }());
- exports.JSXClosingElement = JSXClosingElement;
- var JSXElement = (function () {
- function JSXElement(openingElement, children, closingElement) {
- this.type = jsx_syntax_1.JSXSyntax.JSXElement;
- this.openingElement = openingElement;
- this.children = children;
- this.closingElement = closingElement;
- }
- return JSXElement;
- }());
- exports.JSXElement = JSXElement;
- var JSXEmptyExpression = (function () {
- function JSXEmptyExpression() {
- this.type = jsx_syntax_1.JSXSyntax.JSXEmptyExpression;
- }
- return JSXEmptyExpression;
- }());
- exports.JSXEmptyExpression = JSXEmptyExpression;
- var JSXExpressionContainer = (function () {
- function JSXExpressionContainer(expression) {
- this.type = jsx_syntax_1.JSXSyntax.JSXExpressionContainer;
- this.expression = expression;
- }
- return JSXExpressionContainer;
- }());
- exports.JSXExpressionContainer = JSXExpressionContainer;
- var JSXIdentifier = (function () {
- function JSXIdentifier(name) {
- this.type = jsx_syntax_1.JSXSyntax.JSXIdentifier;
- this.name = name;
- }
- return JSXIdentifier;
- }());
- exports.JSXIdentifier = JSXIdentifier;
- var JSXMemberExpression = (function () {
- function JSXMemberExpression(object, property) {
- this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression;
- this.object = object;
- this.property = property;
- }
- return JSXMemberExpression;
- }());
- exports.JSXMemberExpression = JSXMemberExpression;
- var JSXAttribute = (function () {
- function JSXAttribute(name, value) {
- this.type = jsx_syntax_1.JSXSyntax.JSXAttribute;
- this.name = name;
- this.value = value;
- }
- return JSXAttribute;
- }());
- exports.JSXAttribute = JSXAttribute;
- var JSXNamespacedName = (function () {
- function JSXNamespacedName(namespace, name) {
- this.type = jsx_syntax_1.JSXSyntax.JSXNamespacedName;
- this.namespace = namespace;
- this.name = name;
- }
- return JSXNamespacedName;
- }());
- exports.JSXNamespacedName = JSXNamespacedName;
- var JSXOpeningElement = (function () {
- function JSXOpeningElement(name, selfClosing, attributes) {
- this.type = jsx_syntax_1.JSXSyntax.JSXOpeningElement;
- this.name = name;
- this.selfClosing = selfClosing;
- this.attributes = attributes;
- }
- return JSXOpeningElement;
- }());
- exports.JSXOpeningElement = JSXOpeningElement;
- var JSXSpreadAttribute = (function () {
- function JSXSpreadAttribute(argument) {
- this.type = jsx_syntax_1.JSXSyntax.JSXSpreadAttribute;
- this.argument = argument;
- }
- return JSXSpreadAttribute;
- }());
- exports.JSXSpreadAttribute = JSXSpreadAttribute;
- var JSXText = (function () {
- function JSXText(value, raw) {
- this.type = jsx_syntax_1.JSXSyntax.JSXText;
- this.value = value;
- this.raw = raw;
- }
- return JSXText;
- }());
- exports.JSXText = JSXText;
-
-
-/***/ },
-/* 15 */
-/***/ function(module, exports, __webpack_require__) {
-
- "use strict";
- var scanner_1 = __webpack_require__(8);
- var error_handler_1 = __webpack_require__(6);
- var token_1 = __webpack_require__(7);
- var Reader = (function () {
- function Reader() {
- this.values = [];
- this.curly = this.paren = -1;
- }
- ;
- // A function following one of those tokens is an expression.
- Reader.prototype.beforeFunctionExpression = function (t) {
- return ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
- 'return', 'case', 'delete', 'throw', 'void',
- // assignment operators
- '=', '+=', '-=', '*=', '**=', '/=', '%=', '<<=', '>>=',
'>>>=',
- '&=', '|=', '^=', ',',
- // binary/unary operators
- '+', '-', '*', '**', '/', '%', '++', '--', '<<', '>>',
'>>>', '&',
- '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
- '<=', '<', '>', '!=', '!=='].indexOf(t) >= 0;
- };
- ;
- // Determine if forward slash (/) is an operator or part of a
regular expression
- // https://github.com/mozilla/sweet.js/wiki/design
- Reader.prototype.isRegexStart = function () {
- var previous = this.values[this.values.length - 1];
- var regex = (previous !== null);
- switch (previous) {
- case 'this':
- case ']':
- regex = false;
- break;
- case ')':
- var check = this.values[this.paren - 1];
- regex = (check === 'if' || check === 'while' || check
=== 'for' || check === 'with');
- break;
- case '}':
- // Dividing a function by anything makes little sense,
- // but we have to check for that.
- regex = false;
- if (this.values[this.curly - 3] === 'function') {
- // Anonymous function, e.g. function(){} /42
- var check_1 = this.values[this.curly - 4];
- regex = check_1 ?
!this.beforeFunctionExpression(check_1) : false;
- }
- else if (this.values[this.curly - 4] === 'function') {
- // Named function, e.g. function f(){} /42/
- var check_2 = this.values[this.curly - 5];
- regex = check_2 ?
!this.beforeFunctionExpression(check_2) : true;
- }
- }
- return regex;
- };
- ;
- Reader.prototype.push = function (token) {
- if (token.type === token_1.Token.Punctuator || token.type ===
token_1.Token.Keyword) {
- if (token.value === '{') {
- this.curly = this.values.length;
- }
- else if (token.value === '(') {
- this.paren = this.values.length;
- }
- this.values.push(token.value);
- }
- else {
- this.values.push(null);
- }
- };
- ;
- return Reader;
- }());
- var Tokenizer = (function () {
- function Tokenizer(code, config) {
- this.errorHandler = new error_handler_1.ErrorHandler();
- this.errorHandler.tolerant = config ? (typeof config.tolerant
=== 'boolean' && config.tolerant) : false;
- this.scanner = new scanner_1.Scanner(code, this.errorHandler);
- this.scanner.trackComment = config ? (typeof config.comment ===
'boolean' && config.comment) : false;
- this.trackRange = config ? (typeof config.range === 'boolean'
&& config.range) : false;
- this.trackLoc = config ? (typeof config.loc === 'boolean' &&
config.loc) : false;
- this.buffer = [];
- this.reader = new Reader();
- }
- ;
- Tokenizer.prototype.errors = function () {
- return this.errorHandler.errors;
- };
- ;
- Tokenizer.prototype.getNextToken = function () {
- if (this.buffer.length === 0) {
- var comments = this.scanner.scanComments();
- if (this.scanner.trackComment) {
- for (var i = 0; i < comments.length; ++i) {
- var e = comments[i];
- var comment = void 0;
- var value = this.scanner.source.slice(e.slice[0],
e.slice[1]);
- comment = {
- type: e.multiLine ? 'BlockComment' :
'LineComment',
- value: value
- };
- if (this.trackRange) {
- comment.range = e.range;
- }
- if (this.trackLoc) {
- comment.loc = e.loc;
- }
- this.buffer.push(comment);
- }
- }
- if (!this.scanner.eof()) {
- var loc = void 0;
- if (this.trackLoc) {
- loc = {
- start: {
- line: this.scanner.lineNumber,
- column: this.scanner.index -
this.scanner.lineStart
- },
- end: {}
- };
- }
- var token = void 0;
- if (this.scanner.source[this.scanner.index] === '/') {
- token = this.reader.isRegexStart() ?
this.scanner.scanRegExp() : this.scanner.scanPunctuator();
- }
- else {
- token = this.scanner.lex();
- }
- this.reader.push(token);
- var entry = void 0;
- entry = {
- type: token_1.TokenName[token.type],
- value: this.scanner.source.slice(token.start,
token.end)
- };
- if (this.trackRange) {
- entry.range = [token.start, token.end];
- }
- if (this.trackLoc) {
- loc.end = {
- line: this.scanner.lineNumber,
- column: this.scanner.index -
this.scanner.lineStart
- };
- entry.loc = loc;
- }
- if (token.regex) {
- entry.regex = token.regex;
- }
- this.buffer.push(entry);
- }
- }
- return this.buffer.shift();
- };
- ;
- return Tokenizer;
- }());
- exports.Tokenizer = Tokenizer;
-
-
-/***/ }
-/******/ ])
-});
-;
\ No newline at end of file
diff --git a/tooling/talertest/selenium/instrumenter.js
b/tooling/talertest/selenium/instrumenter.js
deleted file mode 100644
index 61c02cf0..00000000
--- a/tooling/talertest/selenium/instrumenter.js
+++ /dev/null
@@ -1,1097 +0,0 @@
-/*
- Copyright (c) 2012, Yahoo! Inc. All rights reserved.
- Copyrights licensed under the New BSD License. See the accompanying LICENSE
file for terms.
- */
-
-/*global esprima, escodegen, window */
-(function (isNode) {
- "use strict";
- var SYNTAX,
- nodeType,
- ESP = isNode ? require('esprima') : esprima,
- ESPGEN = isNode ? require('escodegen') : escodegen, //TODO - package
as dependency
- crypto = isNode ? require('crypto') : null,
- LEADER_WRAP = '(function () { ',
- TRAILER_WRAP = '\n}());',
- COMMENT_RE = /^\s*istanbul\s+ignore\s+(if|else|next)(?=\W|$)/,
- astgen,
- preconditions,
- cond,
- isArray = Array.isArray;
-
- /* istanbul ignore if: untestable */
- if (!isArray) {
- isArray = function (thing) { return thing &&
Object.prototype.toString.call(thing) === '[object Array]'; };
- }
-
- if (!isNode) {
- preconditions = {
- 'Could not find esprima': ESP,
- 'Could not find escodegen': ESPGEN,
- 'JSON object not in scope': JSON,
- 'Array does not implement push': [].push,
- 'Array does not implement unshift': [].unshift
- };
- /* istanbul ignore next: untestable */
- for (cond in preconditions) {
- if (preconditions.hasOwnProperty(cond)) {
- if (!preconditions[cond]) { throw new Error(cond); }
- }
- }
- }
-
- function generateTrackerVar(filename, omitSuffix) {
- var hash, suffix;
- if (crypto !== null) {
- hash = crypto.createHash('md5');
- hash.update(filename);
- suffix = hash.digest('base64');
- //trim trailing equal signs, turn identifier unsafe chars to safe
ones + => _ and / => $
- suffix = suffix.replace(new RegExp('=', 'g'), '')
- .replace(new RegExp('\\+', 'g'), '_')
- .replace(new RegExp('/', 'g'), '$');
- } else {
- window.__cov_seq = window.__cov_seq || 0;
- window.__cov_seq += 1;
- suffix = window.__cov_seq;
- }
- return '__cov_' + (omitSuffix ? '' : suffix);
- }
-
- function pushAll(ary, thing) {
- if (!isArray(thing)) {
- thing = [ thing ];
- }
- Array.prototype.push.apply(ary, thing);
- }
-
- SYNTAX = {
- // keep in sync with estraverse's VisitorKeys
- AssignmentExpression: ['left', 'right'],
- AssignmentPattern: ['left', 'right'],
- ArrayExpression: ['elements'],
- ArrayPattern: ['elements'],
- ArrowFunctionExpression: ['params', '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', 'superClass', 'body'],
- ClassExpression: ['id', 'superClass', 'body'],
- 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: [],
- ExportAllDeclaration: ['source'],
- ExportDefaultDeclaration: ['declaration'],
- ExportNamedDeclaration: ['declaration', 'specifiers', 'source'],
- ExportSpecifier: ['exported', 'local'],
- ExpressionStatement: ['expression'],
- ForStatement: ['init', 'test', 'update', 'body'],
- ForInStatement: ['left', 'right', 'body'],
- ForOfStatement: ['left', 'right', 'body'],
- FunctionDeclaration: ['id', 'params', 'body'],
- FunctionExpression: ['id', 'params', 'body'],
- GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's
deferred to ES7.
- Identifier: [],
- IfStatement: ['test', 'consequent', 'alternate'],
- ImportDeclaration: ['specifiers', 'source'],
- ImportDefaultSpecifier: ['local'],
- ImportNamespaceSpecifier: ['local'],
- ImportSpecifier: ['imported', 'local'],
- Literal: [],
- LabeledStatement: ['label', 'body'],
- LogicalExpression: ['left', 'right'],
- MetaProperty: ['meta', 'property'],
- MemberExpression: ['object', 'property'],
- MethodDefinition: ['key', 'value'],
- ModuleSpecifier: [],
- NewExpression: ['callee', 'arguments'],
- ObjectExpression: ['properties'],
- ObjectPattern: ['properties'],
- Program: ['body'],
- Property: ['key', 'value'],
- RestElement: [ 'argument' ],
- ReturnStatement: ['argument'],
- SequenceExpression: ['expressions'],
- SpreadElement: ['argument'],
- Super: [],
- SwitchStatement: ['discriminant', 'cases'],
- SwitchCase: ['test', 'consequent'],
- TaggedTemplateExpression: ['tag', 'quasi'],
- TemplateElement: [],
- TemplateLiteral: ['quasis', 'expressions'],
- ThisExpression: [],
- ThrowStatement: ['argument'],
- TryStatement: ['block', 'handler', 'finalizer'],
- UnaryExpression: ['argument'],
- UpdateExpression: ['argument'],
- VariableDeclaration: ['declarations'],
- VariableDeclarator: ['id', 'init'],
- WhileStatement: ['test', 'body'],
- WithStatement: ['object', 'body'],
- YieldExpression: ['argument']
- };
-
- for (nodeType in SYNTAX) {
- /* istanbul ignore else: has own property */
- if (SYNTAX.hasOwnProperty(nodeType)) {
- SYNTAX[nodeType] = { name: nodeType, children: SYNTAX[nodeType] };
- }
- }
-
- astgen = {
- variable: function (name) { return { type: SYNTAX.Identifier.name,
name: name }; },
- stringLiteral: function (str) { return { type: SYNTAX.Literal.name,
value: String(str) }; },
- numericLiteral: function (num) { return { type: SYNTAX.Literal.name,
value: Number(num) }; },
- statement: function (contents) { return { type:
SYNTAX.ExpressionStatement.name, expression: contents }; },
- dot: function (obj, field) { return { type:
SYNTAX.MemberExpression.name, computed: false, object: obj, property: field };
},
- subscript: function (obj, sub) { return { type:
SYNTAX.MemberExpression.name, computed: true, object: obj, property: sub }; },
- postIncrement: function (obj) { return { type:
SYNTAX.UpdateExpression.name, operator: '++', prefix: false, argument: obj }; },
- sequence: function (one, two) { return { type:
SYNTAX.SequenceExpression.name, expressions: [one, two] }; },
- returnStatement: function (expr) { return { type:
SYNTAX.ReturnStatement.name, argument: expr }; }
- };
-
- function Walker(walkMap, preprocessor, scope, debug) {
- this.walkMap = walkMap;
- this.preprocessor = preprocessor;
- this.scope = scope;
- this.debug = debug;
- if (this.debug) {
- this.level = 0;
- this.seq = true;
- }
- }
-
- function defaultWalker(node, walker) {
-
- var type = node.type,
- preprocessor,
- postprocessor,
- children = SYNTAX[type],
- // don't run generated nodes thru custom walks otherwise we will
attempt to instrument the instrumentation code :)
- applyCustomWalker = !!node.loc || node.type ===
SYNTAX.Program.name,
- walkerFn = applyCustomWalker ? walker.walkMap[type] : null,
- i,
- j,
- walkFnIndex,
- childType,
- childNode,
- ret,
- childArray,
- childElement,
- pathElement,
- assignNode,
- isLast;
-
- if (!SYNTAX[type]) {
- console.error(node);
- console.error('Unsupported node type:' + type);
- return;
- }
- children = SYNTAX[type].children;
- /* istanbul ignore if: guard */
- if (node.walking) { throw new Error('Infinite regress: Custom walkers
may NOT call walker.apply(node)'); }
- node.walking = true;
-
- ret = walker.apply(node, walker.preprocessor);
-
- preprocessor = ret.preprocessor;
- if (preprocessor) {
- delete ret.preprocessor;
- ret = walker.apply(node, preprocessor);
- }
-
- if (isArray(walkerFn)) {
- for (walkFnIndex = 0; walkFnIndex < walkerFn.length; walkFnIndex
+= 1) {
- isLast = walkFnIndex === walkerFn.length - 1;
- ret = walker.apply(ret, walkerFn[walkFnIndex]);
- /*istanbul ignore next: paranoid check */
- if (ret.type !== type && !isLast) {
- throw new Error('Only the last walker is allowed to change
the node type: [type was: ' + type + ' ]');
- }
- }
- } else {
- if (walkerFn) {
- ret = walker.apply(node, walkerFn);
- }
- }
-
- if (node.skipSelf) {
- return;
- }
-
- for (i = 0; i < children.length; i += 1) {
- childType = children[i];
- childNode = node[childType];
- if (childNode && !childNode.skipWalk) {
- pathElement = { node: node, property: childType };
- if (isArray(childNode)) {
- childArray = [];
- for (j = 0; j < childNode.length; j += 1) {
- childElement = childNode[j];
- pathElement.index = j;
- if (childElement) {
- assignNode = walker.apply(childElement, null,
pathElement);
- if (isArray(assignNode.prepend)) {
- pushAll(childArray, assignNode.prepend);
- delete assignNode.prepend;
- }
- } else {
- assignNode = undefined;
- }
- pushAll(childArray, assignNode);
- }
- node[childType] = childArray;
- } else {
- assignNode = walker.apply(childNode, null, pathElement);
- /*istanbul ignore if: paranoid check */
- if (isArray(assignNode.prepend)) {
- throw new Error('Internal error: attempt to prepend
statements in disallowed (non-array) context');
- /* if this should be allowed, this is how to solve it
- tmpNode = { type: 'BlockStatement', body: [] };
- pushAll(tmpNode.body, assignNode.prepend);
- pushAll(tmpNode.body, assignNode);
- node[childType] = tmpNode;
- delete assignNode.prepend;
- */
- } else {
- node[childType] = assignNode;
- }
- }
- }
- }
-
- postprocessor = ret.postprocessor;
- if (postprocessor) {
- delete ret.postprocessor;
- ret = walker.apply(ret, postprocessor);
- }
-
- delete node.walking;
-
- return ret;
- }
-
- Walker.prototype = {
- startWalk: function (node) {
- this.path = [];
- this.apply(node);
- },
-
- apply: function (node, walkFn, pathElement) {
- var ret, i, seq, prefix;
-
- walkFn = walkFn || defaultWalker;
- if (this.debug) {
- this.seq += 1;
- this.level += 1;
- seq = this.seq;
- prefix = '';
- for (i = 0; i < this.level; i += 1) { prefix += ' '; }
- console.log(prefix + 'Enter (' + seq + '):' + node.type);
- }
- if (pathElement) { this.path.push(pathElement); }
- ret = walkFn.call(this.scope, node, this);
- if (pathElement) { this.path.pop(); }
- if (this.debug) {
- this.level -= 1;
- console.log(prefix + 'Return (' + seq + '):' + node.type);
- }
- return ret || node;
- },
-
- startLineForNode: function (node) {
- return node && node.loc && node.loc.start ? node.loc.start.line :
/* istanbul ignore next: guard */ null;
- },
-
- ancestor: function (n) {
- return this.path.length > n - 1 ? this.path[this.path.length - n]
: /* istanbul ignore next: guard */ null;
- },
-
- parent: function () {
- return this.ancestor(1);
- },
-
- isLabeled: function () {
- var el = this.parent();
- return el && el.node.type === SYNTAX.LabeledStatement.name;
- }
- };
-
- /**
- * mechanism to instrument code for coverage. It uses the `esprima` and
- * `escodegen` libraries for JS parsing and code generation respectively.
- *
- * Works on `node` as well as the browser.
- *
- * Usage on nodejs
- * ---------------
- *
- * var instrumenter = new require('istanbul').Instrumenter(),
- * changed = instrumenter.instrumentSync('function
meaningOfLife() { return 42; }', 'filename.js');
- *
- * Usage in a browser
- * ------------------
- *
- * Load `esprima.js`, `escodegen.js` and `instrumenter.js` (this file)
using `script` tags or other means.
- *
- * Create an instrumenter object as:
- *
- * var instrumenter = new Instrumenter(),
- * changed = instrumenter.instrumentSync('function
meaningOfLife() { return 42; }', 'filename.js');
- *
- * Aside from demonstration purposes, it is unclear why you would want to
instrument code in a browser.
- *
- * @class Instrumenter
- * @constructor
- * @param {Object} options Optional. Configuration options.
- * @param {String} [options.coverageVariable] the global variable name to
use for
- * tracking coverage. Defaults to `__coverage__`
- * @param {Boolean} [options.embedSource] whether to embed the source code
of every
- * file as an array in the file coverage object for that file.
Defaults to `false`
- * @param {Boolean} [options.preserveComments] whether comments should be
preserved in the output. Defaults to `false`
- * @param {Boolean} [options.noCompact] emit readable code when set.
Defaults to `false`
- * @param {Boolean} [options.esModules] whether the code to instrument
contains uses es
- * imports or exports.
- * @param {Boolean} [options.noAutoWrap] do not automatically wrap the
source in
- * an anonymous function before covering it. By default, code is
wrapped in
- * an anonymous function before it is parsed. This is done because
- * some nodejs libraries have `return` statements outside of
- * a function which is technically invalid Javascript and causes the
parser to fail.
- * This construct, however, works correctly in node since module
loading
- * is done in the context of an anonymous function.
- *
- * Note that the semantics of the code *returned* by the instrumenter does
not change in any way.
- * The function wrapper is "unwrapped" before the instrumented code is
generated.
- * @param {Object} [options.codeGenerationOptions] an object that is
directly passed to the `escodegen`
- * library as configuration for code generation. The `noCompact`
setting is not honored when this
- * option is specified
- * @param {Boolean} [options.debug] assist in debugging. Currently, the
only effect of
- * setting this option is a pretty-print of the coverage variable.
Defaults to `false`
- * @param {Boolean} [options.walkDebug] assist in debugging of the AST
walker used by this class.
- *
- */
- function Instrumenter(options) {
- this.opts = options || {
- debug: false,
- walkDebug: false,
- coverageVariable: '__coverage__',
- codeGenerationOptions: undefined,
- noAutoWrap: false,
- noCompact: false,
- embedSource: false,
- preserveComments: false,
- esModules: false
- };
-
- if (this.opts.esModules && !this.opts.noAutoWrap) {
- this.opts.noAutoWrap = true;
- if (this.opts.debug) {
- console.log('Setting noAutoWrap to true as required by
esModules');
- }
- }
-
- this.walker = new Walker({
- ArrowFunctionExpression: [ this.arrowBlockConverter ],
- ExpressionStatement: this.coverStatement,
- ExportNamedDeclaration: this.coverExport,
- BreakStatement: this.coverStatement,
- ContinueStatement: this.coverStatement,
- DebuggerStatement: this.coverStatement,
- ReturnStatement: this.coverStatement,
- ThrowStatement: this.coverStatement,
- TryStatement: [ this.paranoidHandlerCheck, this.coverStatement],
- VariableDeclaration: this.coverStatement,
- IfStatement: [ this.ifBlockConverter, this.coverStatement,
this.ifBranchInjector ],
- ForStatement: [ this.skipInit, this.loopBlockConverter,
this.coverStatement ],
- ForInStatement: [ this.skipLeft, this.loopBlockConverter,
this.coverStatement ],
- ForOfStatement: [ this.skipLeft, this.loopBlockConverter,
this.coverStatement ],
- WhileStatement: [ this.loopBlockConverter, this.coverStatement ],
- DoWhileStatement: [ this.loopBlockConverter, this.coverStatement ],
- SwitchStatement: [ this.coverStatement, this.switchBranchInjector
],
- SwitchCase: [ this.switchCaseInjector ],
- WithStatement: [ this.withBlockConverter, this.coverStatement ],
- FunctionDeclaration: [ this.coverFunction, this.coverStatement ],
- FunctionExpression: this.coverFunction,
- LabeledStatement: this.coverStatement,
- ConditionalExpression: this.conditionalBranchInjector,
- LogicalExpression: this.logicalExpressionBranchInjector,
- ObjectExpression: this.maybeAddType,
- MetaProperty: this.coverMetaProperty,
- }, this.extractCurrentHint, this, this.opts.walkDebug);
-
- //unit testing purposes only
- if (this.opts.backdoor && this.opts.backdoor.omitTrackerSuffix) {
- this.omitTrackerSuffix = true;
- }
- }
-
- Instrumenter.prototype = {
- /**
- * synchronous instrumentation method. Throws when illegal code is
passed to it
- * @method instrumentSync
- * @param {String} code the code to be instrumented as a String
- * @param {String} filename Optional. The name of the file from which
- * the code was read. A temporary filename is generated when not
specified.
- * Not specifying a filename is only useful for unit tests and
demonstrations
- * of this library.
- */
- instrumentSync: function (code, filename) {
- var program;
-
- //protect from users accidentally passing in a Buffer object
instead
- if (typeof code !== 'string') { throw new Error('Code must be
string'); }
- if (code.charAt(0) === '#') { //shebang, 'comment' it out, won't
affect syntax tree locations for things we care about
- code = '//' + code;
- }
- if (!this.opts.noAutoWrap) {
- code = LEADER_WRAP + code + TRAILER_WRAP;
- }
- try {
- program = ESP.parse(code, {
- loc: true,
- range: true,
- tokens: this.opts.preserveComments,
- comment: true,
- sourceType: this.opts.esModules ? 'module' : 'script'
- });
- } catch (e) {
- console.log('Failed to parse file: ' + filename);
- throw e;
- }
- if (this.opts.preserveComments) {
- program = ESPGEN.attachComments(program, program.comments,
program.tokens);
- }
- if (!this.opts.noAutoWrap) {
- program = {
- type: SYNTAX.Program.name,
- body: program.body[0].expression.callee.body.body,
- comments: program.comments
- };
- }
- return this.instrumentASTSync(program, filename, code);
- },
- filterHints: function (comments) {
- var ret = [],
- i,
- comment,
- groups;
- if (!(comments && isArray(comments))) {
- return ret;
- }
- for (i = 0; i < comments.length; i += 1) {
- comment = comments[i];
- /* istanbul ignore else: paranoid check */
- if (comment && comment.value && comment.range &&
isArray(comment.range)) {
- groups = String(comment.value).match(COMMENT_RE);
- if (groups) {
- ret.push({ type: groups[1], start: comment.range[0],
end: comment.range[1] });
- }
- }
- }
- return ret;
- },
- extractCurrentHint: function (node) {
- if (!node.range) { return; }
- var i = this.currentState.lastHintPosition + 1,
- hints = this.currentState.hints,
- nodeStart = node.range[0],
- hint;
- this.currentState.currentHint = null;
- while (i < hints.length) {
- hint = hints[i];
- if (hint.end < nodeStart) {
- this.currentState.currentHint = hint;
- this.currentState.lastHintPosition = i;
- i += 1;
- } else {
- break;
- }
- }
- },
- /**
- * synchronous instrumentation method that instruments an AST instead.
- * @method instrumentASTSync
- * @param {String} program the AST to be instrumented
- * @param {String} filename Optional. The name of the file from which
- * the code was read. A temporary filename is generated when not
specified.
- * Not specifying a filename is only useful for unit tests and
demonstrations
- * of this library.
- * @param {String} originalCode the original code corresponding to
the AST,
- * used for embedding the source into the coverage object
- */
- instrumentASTSync: function (program, filename, originalCode) {
- var usingStrict = false,
- codegenOptions,
- generated,
- preamble,
- lineCount,
- i;
- filename = filename || String(new Date().getTime()) + '.js';
- this.sourceMap = null;
- this.coverState = {
- path: filename,
- s: {},
- b: {},
- f: {},
- fnMap: {},
- statementMap: {},
- branchMap: {}
- };
- this.currentState = {
- trackerVar: generateTrackerVar(filename,
this.omitTrackerSuffix),
- func: 0,
- branch: 0,
- variable: 0,
- statement: 0,
- hints: this.filterHints(program.comments),
- currentHint: null,
- lastHintPosition: -1,
- ignoring: 0
- };
- if (program.body && program.body.length > 0 &&
this.isUseStrictExpression(program.body[0])) {
- //nuke it
- program.body.shift();
- //and add it back at code generation time
- usingStrict = true;
- }
- this.walker.startWalk(program);
- codegenOptions = this.opts.codeGenerationOptions || { format: {
compact: !this.opts.noCompact }};
- codegenOptions.comment = this.opts.preserveComments;
- //console.log(JSON.stringify(program, undefined, 2));
-
- generated = ESPGEN.generate(program, codegenOptions);
- preamble = this.getPreamble(originalCode || '', usingStrict);
-
- if (generated.map && generated.code) {
- lineCount = preamble.split(/\r\n|\r|\n/).length;
- // offset all the generated line numbers by the number of
lines in the preamble
- for (i = 0; i < generated.map._mappings._array.length; i += 1)
{
- generated.map._mappings._array[i].generatedLine +=
lineCount;
- }
- this.sourceMap = generated.map;
- generated = generated.code;
- }
-
- return preamble + '\n' + generated + '\n';
- },
- /**
- * Callback based instrumentation. Note that this still executes
synchronously in the same process tick
- * and calls back immediately. It only provides the options for
callback style error handling as
- * opposed to a `try-catch` style and nothing more. Implemented as a
wrapper over `instrumentSync`
- *
- * @method instrument
- * @param {String} code the code to be instrumented as a String
- * @param {String} filename Optional. The name of the file from which
- * the code was read. A temporary filename is generated when not
specified.
- * Not specifying a filename is only useful for unit tests and
demonstrations
- * of this library.
- * @param {Function(err, instrumentedCode)} callback - the callback
function
- */
- instrument: function (code, filename, callback) {
-
- if (!callback && typeof filename === 'function') {
- callback = filename;
- filename = null;
- }
- try {
- callback(null, this.instrumentSync(code, filename));
- } catch (ex) {
- callback(ex);
- }
- },
- /**
- * returns the file coverage object for the code that was instrumented
- * just before calling this method. Note that this represents a
- * "zero-coverage" object which is not even representative of the code
- * being loaded in node or a browser (which would increase the
statement
- * counts for mainline code).
- * @method lastFileCoverage
- * @return {Object} a "zero-coverage" file coverage object for the
code last instrumented
- * by this instrumenter
- */
- lastFileCoverage: function () {
- return this.coverState;
- },
- /**
- * returns the source map object for the code that was instrumented
- * just before calling this method.
- * @method lastSourceMap
- * @return {Object} a source map object for the code last instrumented
- * by this instrumenter
- */
- lastSourceMap: function () {
- return this.sourceMap;
- },
- fixColumnPositions: function (coverState) {
- var offset = LEADER_WRAP.length,
- fixer = function (loc) {
- if (loc.start.line === 1) {
- loc.start.column -= offset;
- }
- if (loc.end.line === 1) {
- loc.end.column -= offset;
- }
- },
- k,
- obj,
- i,
- locations;
-
- obj = coverState.statementMap;
- for (k in obj) {
- /* istanbul ignore else: has own property */
- if (obj.hasOwnProperty(k)) { fixer(obj[k]); }
- }
- obj = coverState.fnMap;
- for (k in obj) {
- /* istanbul ignore else: has own property */
- if (obj.hasOwnProperty(k)) { fixer(obj[k].loc); }
- }
- obj = coverState.branchMap;
- for (k in obj) {
- /* istanbul ignore else: has own property */
- if (obj.hasOwnProperty(k)) {
- locations = obj[k].locations;
- for (i = 0; i < locations.length; i += 1) {
- fixer(locations[i]);
- }
- }
- }
- },
-
- getPreamble: function (sourceCode, emitUseStrict) {
- var varName = this.opts.coverageVariable || '__coverage__',
- file = this.coverState.path.replace(/\\/g, '\\\\'),
- tracker = this.currentState.trackerVar,
- coverState,
- strictLine = emitUseStrict ? '"use strict";' : '',
- // return replacements using the function to ensure that the
replacement is
- // treated like a dumb string and not as a string with RE
replacement patterns
- replacer = function (s) {
- return function () { return s; };
- },
- code;
- if (!this.opts.noAutoWrap) {
- this.fixColumnPositions(this.coverState);
- }
- if (this.opts.embedSource) {
- this.coverState.code = sourceCode.split(/(?:\r?\n)|\r/);
- }
- coverState = this.opts.debug ? JSON.stringify(this.coverState,
undefined, 4) : JSON.stringify(this.coverState);
- code = [
- "%STRICT%",
- "var %VAR% = (Function('return this'))();",
- "if (!%VAR%.%GLOBAL%) { %VAR%.%GLOBAL% = {}; }",
- "%VAR% = %VAR%.%GLOBAL%;",
- "if (!(%VAR%['%FILE%'])) {",
- " %VAR%['%FILE%'] = %OBJECT%;",
- "}",
- "%VAR% = %VAR%['%FILE%'];"
- ].join("\n")
- .replace(/%STRICT%/g, replacer(strictLine))
- .replace(/%VAR%/g, replacer(tracker))
- .replace(/%GLOBAL%/g, replacer(varName))
- .replace(/%FILE%/g, replacer(file))
- .replace(/%OBJECT%/g, replacer(coverState));
- return code;
- },
-
- startIgnore: function () {
- this.currentState.ignoring += 1;
- },
-
- endIgnore: function () {
- this.currentState.ignoring -= 1;
- },
-
- convertToBlock: function (node) {
- if (!node) {
- return { type: 'BlockStatement', body: [] };
- } else if (node.type === 'BlockStatement') {
- return node;
- } else {
- return { type: 'BlockStatement', body: [ node ] };
- }
- },
-
- arrowBlockConverter: function (node) {
- var retStatement;
- if (node.expression) { // turn expression nodes into a block with
a return statement
- retStatement = astgen.returnStatement(node.body);
- // ensure the generated return statement is covered
- retStatement.loc = node.body.loc;
- node.body = this.convertToBlock(retStatement);
- node.expression = false;
- }
- },
-
- paranoidHandlerCheck: function (node) {
- // if someone is using an older esprima on the browser
- // convert handlers array to single handler attribute
- // containing its first element
- /* istanbul ignore next */
- if (!node.handler && node.handlers) {
- node.handler = node.handlers[0];
- }
- },
-
- ifBlockConverter: function (node) {
- node.consequent = this.convertToBlock(node.consequent);
- node.alternate = this.convertToBlock(node.alternate);
- },
-
- loopBlockConverter: function (node) {
- node.body = this.convertToBlock(node.body);
- },
-
- withBlockConverter: function (node) {
- node.body = this.convertToBlock(node.body);
- },
-
- statementName: function (location, initValue) {
- var sName,
- ignoring = !!this.currentState.ignoring;
-
- location.skip = ignoring || undefined;
- initValue = initValue || 0;
- this.currentState.statement += 1;
- sName = this.currentState.statement;
- this.coverState.statementMap[sName] = location;
- this.coverState.s[sName] = initValue;
- return sName;
- },
-
- skipInit: function (node /*, walker */) {
- if (node.init) {
- node.init.skipWalk = true;
- }
- },
-
- skipLeft: function (node /*, walker */) {
- node.left.skipWalk = true;
- },
-
- isUseStrictExpression: function (node) {
- return node && node.type === SYNTAX.ExpressionStatement.name &&
- node.expression && node.expression.type ===
SYNTAX.Literal.name &&
- node.expression.value === 'use strict';
- },
-
- maybeSkipNode: function (node, type) {
- var alreadyIgnoring = !!this.currentState.ignoring,
- hint = this.currentState.currentHint,
- ignoreThis = !alreadyIgnoring && hint && hint.type === type;
-
- if (ignoreThis) {
- this.startIgnore();
- node.postprocessor = this.endIgnore;
- return true;
- }
- return false;
- },
-
- coverMetaProperty: function(node /* , walker */) {
- node.skipSelf = true;
- },
-
- coverStatement: function (node, walker) {
- var sName,
- incrStatementCount,
- parent,
- grandParent;
-
- this.maybeSkipNode(node, 'next');
-
- if (this.isUseStrictExpression(node)) {
- grandParent = walker.ancestor(2);
- /* istanbul ignore else: difficult to test */
- if (grandParent) {
- if ((grandParent.node.type ===
SYNTAX.FunctionExpression.name ||
- grandParent.node.type ===
SYNTAX.FunctionDeclaration.name) &&
- walker.parent().node.body[0] === node) {
- return;
- }
- }
- }
-
- if (node.type === SYNTAX.FunctionDeclaration.name) {
- // Called for the side-effect of setting the function's
statement count to 1.
- this.statementName(node.loc, 1);
- } else {
- // We let `coverExport` handle ExportNamedDeclarations.
- parent = walker.parent();
- if (parent && parent.node.type ===
SYNTAX.ExportNamedDeclaration.name) {
- return;
- }
-
- sName = this.statementName(node.loc);
-
- incrStatementCount = astgen.statement(
- astgen.postIncrement(
- astgen.subscript(
-
astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('s')),
- astgen.stringLiteral(sName)
- )
- )
- );
-
- this.splice(incrStatementCount, node, walker);
- }
- },
-
- coverExport: function (node, walker) {
- var sName, incrStatementCount;
-
- if ( !node.declaration || !node.declaration.declarations ) {
return; }
-
- this.maybeSkipNode(node, 'next');
-
- sName = this.statementName(node.declaration.loc);
- incrStatementCount = astgen.statement(
- astgen.postIncrement(
- astgen.subscript(
-
astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('s')),
- astgen.stringLiteral(sName)
- )
- )
- );
-
- this.splice(incrStatementCount, node, walker);
- },
-
- splice: function (statements, node, walker) {
- var targetNode = walker.isLabeled() ? walker.parent().node : node;
- targetNode.prepend = targetNode.prepend || [];
- pushAll(targetNode.prepend, statements);
- },
-
- functionName: function (node, line, location) {
- this.currentState.func += 1;
- var id = this.currentState.func,
- ignoring = !!this.currentState.ignoring,
- name = node.id ? node.id.name : '(anonymous_' + id + ')',
- clone = function (attr) {
- var obj = location[attr] || /* istanbul ignore next */ {};
- return { line: obj.line, column: obj.column };
- };
- this.coverState.fnMap[id] = {
- name: name, line: line,
- loc: {
- start: clone('start'),
- end: clone('end')
- },
- skip: ignoring || undefined
- };
- this.coverState.f[id] = 0;
- return id;
- },
-
- coverFunction: function (node, walker) {
- var id,
- body = node.body,
- blockBody = body.body,
- popped;
-
- this.maybeSkipNode(node, 'next');
-
- id = this.functionName(node, walker.startLineForNode(node), {
- start: node.loc.start,
- end: { line: node.body.loc.start.line, column:
node.body.loc.start.column }
- });
-
- if (blockBody.length > 0 &&
this.isUseStrictExpression(blockBody[0])) {
- popped = blockBody.shift();
- }
- blockBody.unshift(
- astgen.statement(
- astgen.postIncrement(
- astgen.subscript(
-
astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('f')),
- astgen.stringLiteral(id)
- )
- )
- )
- );
- if (popped) {
- blockBody.unshift(popped);
- }
- },
-
- branchName: function (type, startLine, pathLocations) {
- var bName,
- paths = [],
- locations = [],
- i,
- ignoring = !!this.currentState.ignoring;
- this.currentState.branch += 1;
- bName = this.currentState.branch;
- for (i = 0; i < pathLocations.length; i += 1) {
- pathLocations[i].skip = pathLocations[i].skip || ignoring ||
undefined;
- locations.push(pathLocations[i]);
- paths.push(0);
- }
- this.coverState.b[bName] = paths;
- this.coverState.branchMap[bName] = { line: startLine, type: type,
locations: locations };
- return bName;
- },
-
- branchIncrementExprAst: function (varName, branchIndex, down) {
- var ret = astgen.postIncrement(
- astgen.subscript(
- astgen.subscript(
-
astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('b')),
- astgen.stringLiteral(varName)
- ),
- astgen.numericLiteral(branchIndex)
- ),
- down
- );
- return ret;
- },
-
- locationsForNodes: function (nodes) {
- var ret = [],
- i;
- for (i = 0; i < nodes.length; i += 1) {
- ret.push(nodes[i].loc);
- }
- return ret;
- },
-
- ifBranchInjector: function (node, walker) {
- var alreadyIgnoring = !!this.currentState.ignoring,
- hint = this.currentState.currentHint,
- ignoreThen = !alreadyIgnoring && hint && hint.type === 'if',
- ignoreElse = !alreadyIgnoring && hint && hint.type === 'else',
- line = node.loc.start.line,
- col = node.loc.start.column,
- makeLoc = function () { return { line: line, column: col }; },
- bName = this.branchName('if', walker.startLineForNode(node), [
- { start: makeLoc(), end: makeLoc(), skip: ignoreThen ||
undefined },
- { start: makeLoc(), end: makeLoc(), skip: ignoreElse ||
undefined }
- ]),
- thenBody = node.consequent.body,
- elseBody = node.alternate.body,
- child;
-
thenBody.unshift(astgen.statement(this.branchIncrementExprAst(bName, 0)));
-
elseBody.unshift(astgen.statement(this.branchIncrementExprAst(bName, 1)));
- if (ignoreThen) { child = node.consequent; child.preprocessor =
this.startIgnore; child.postprocessor = this.endIgnore; }
- if (ignoreElse) { child = node.alternate; child.preprocessor =
this.startIgnore; child.postprocessor = this.endIgnore; }
- },
-
- branchLocationFor: function (name, index) {
- return this.coverState.branchMap[name].locations[index];
- },
-
- switchBranchInjector: function (node, walker) {
- var cases = node.cases,
- bName,
- i;
-
- if (!(cases && cases.length > 0)) {
- return;
- }
- bName = this.branchName('switch', walker.startLineForNode(node),
this.locationsForNodes(cases));
- for (i = 0; i < cases.length; i += 1) {
- cases[i].branchLocation = this.branchLocationFor(bName, i);
-
cases[i].consequent.unshift(astgen.statement(this.branchIncrementExprAst(bName,
i)));
- }
- },
-
- switchCaseInjector: function (node) {
- var location = node.branchLocation;
- delete node.branchLocation;
- if (this.maybeSkipNode(node, 'next')) {
- location.skip = true;
- }
- },
-
- conditionalBranchInjector: function (node, walker) {
- var bName = this.branchName('cond-expr',
walker.startLineForNode(node), this.locationsForNodes([ node.consequent,
node.alternate ])),
- ast1 = this.branchIncrementExprAst(bName, 0),
- ast2 = this.branchIncrementExprAst(bName, 1);
-
- node.consequent.preprocessor =
this.maybeAddSkip(this.branchLocationFor(bName, 0));
- node.alternate.preprocessor =
this.maybeAddSkip(this.branchLocationFor(bName, 1));
- node.consequent = astgen.sequence(ast1, node.consequent);
- node.alternate = astgen.sequence(ast2, node.alternate);
- },
-
- maybeAddSkip: function (branchLocation) {
- return function (node) {
- var alreadyIgnoring = !!this.currentState.ignoring,
- hint = this.currentState.currentHint,
- ignoreThis = !alreadyIgnoring && hint && hint.type ===
'next';
- if (ignoreThis) {
- this.startIgnore();
- node.postprocessor = this.endIgnore;
- }
- if (ignoreThis || alreadyIgnoring) {
- branchLocation.skip = true;
- }
- };
- },
-
- logicalExpressionBranchInjector: function (node, walker) {
- var parent = walker.parent(),
- leaves = [],
- bName,
- tuple,
- i;
-
- this.maybeSkipNode(node, 'next');
-
- if (parent && parent.node.type === SYNTAX.LogicalExpression.name) {
- //already covered
- return;
- }
-
- this.findLeaves(node, leaves);
- bName = this.branchName('binary-expr',
- walker.startLineForNode(node),
- this.locationsForNodes(leaves.map(function (item) { return
item.node; }))
- );
- for (i = 0; i < leaves.length; i += 1) {
- tuple = leaves[i];
- tuple.parent[tuple.property] =
astgen.sequence(this.branchIncrementExprAst(bName, i), tuple.node);
- tuple.node.preprocessor =
this.maybeAddSkip(this.branchLocationFor(bName, i));
- }
- },
-
- findLeaves: function (node, accumulator, parent, property) {
- if (node.type === SYNTAX.LogicalExpression.name) {
- this.findLeaves(node.left, accumulator, node, 'left');
- this.findLeaves(node.right, accumulator, node, 'right');
- } else {
- accumulator.push({ node: node, parent: parent, property:
property });
- }
- },
- maybeAddType: function (node /*, walker */) {
- var props = node.properties,
- i,
- child;
- for (i = 0; i < props.length; i += 1) {
- child = props[i];
- if (!child.type) {
- child.type = SYNTAX.Property.name;
- }
- }
- },
- };
-
- if (isNode) {
- module.exports = Instrumenter;
- } else {
- window.Instrumenter = Instrumenter;
- }
-
-}(typeof module !== 'undefined' && typeof module.exports !== 'undefined' &&
typeof exports !== 'undefined'));
diff --git a/tooling/talertest/selenium/runtime.js
b/tooling/talertest/selenium/runtime.js
deleted file mode 100644
index e0067117..00000000
--- a/tooling/talertest/selenium/runtime.js
+++ /dev/null
@@ -1,206 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 Inria
-
- TALER is free software; you can redistribute it and/or modify it under the
- terms of the GNU General Public License as published by the Free Software
- Foundation; either version 3, or (at your option) any later version.
-
- TALER is distributed in the hope that it will be useful, but WITHOUT ANY
- WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
- A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License along with
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- *
- * @author Florian Dold
- */
-
-"use strict";
-
-var webdriver = require('selenium-webdriver');
-var chrome = require('selenium-webdriver/chrome');
-var path = require("path");
-var process = require("process");
-var fs = require("fs");
-var globSync = require("glob").sync;
-
-var connect = require('connect');
-var serveStatic = require('serve-static');
-
-// Port of the web server used to serve the test files
-var httpPort = 8080;
-
-var p = `http://localhost:${httpPort}/testlib/selenium/testhost.html`;
-
-var argv = require('minimist')(process.argv.slice(2), {"boolean":
["keep-open", "coverage"]});
-
-function printUsage() {
- console.log(`Usage: [--keep-open] TESTSCRIPT`);
-}
-
-function randId(n) {
- let s = "";
- var choices =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
-
- for (let i = 0; i < n; i++) {
- s += choices.charAt(Math.floor(Math.random() * choices.length));
- }
-
- return s;
-}
-
-if (argv._.length != 1) {
- console.log("exactly one test script must be given");
- printUsage();
- process.exit(1);
-}
-
-var testScriptName = path.resolve(argv._[0]);
-var testName = path.basename(testScriptName, ".js");
-var projectRoot = path.resolve(__dirname, "../../") + "/";
-if (!testScriptName.startsWith(projectRoot)) {
- console.log("test file must be inside wallet project root");
- process.exit(1);
-}
-
-var testScript = testScriptName.substring(projectRoot.length);
-
-try {
- var stats = fs.lstatSync(path.resolve(projectRoot, "./" + testScript));
- if (!stats.isFile()) {
- throw Error("test must be a file");
- }
-} catch (e) {
- console.log("can't execute test");
- console.log(e);
- process.exit(e);
-}
-
-
-var script = `
- function onStatus(s) {
- document.body.appendChild(document.createTextNode(s));
- document.body.appendChild(document.createElement("br"));
- }
- function f() {
- if ("undefined" == typeof System) {
- console.log("can't access module loader");
- return
- }
- System.import("testlib/talertest")
- .then(tt => {
- SystemJS.import("http://localhost:${httpPort}/${testScript}")
- .then(() => {
- return tt.run(onStatus);
- })
- .then(() => {
- window.__test_over = true;
- })
- .catch((e) => {
- window.__test_over = true;
- });
- })
- .catch((e) => {
- console.error("can't locate talertest");
- console.error(e);
- });
- }
- if (document.readyState == "complete") {
- f();
- } else {
- document.addEventListener("DOMContentLoaded", f);
- }
-`;
-
-function untilTestOver() {
- return driver.executeScript("return window.__test_over");
-}
-
-console.log("TAP version 13");
-
-let srv = connect().use(serveStatic(__dirname + "/../../"));
-let l = srv.listen(8080);
-
-var driver = new webdriver.Builder()
- .setLoggingPrefs({browser: 'ALL'})
- .forBrowser('chrome')
- .build();
-
-driver.get(p);
-if (argv["coverage"]) {
- driver.executeScript("window.requestCoverage = true;");
-}
-driver.executeScript(script);
-driver.wait(untilTestOver);
-
-
-/**
- * Instrument and get a coverage stub for all
- * files we don't have coverage for, so they show
- * up in the report.
- */
-function augmentCoverage(cov) {
- for (let file of globSync(projectRoot + "/src/**/*.js")) {
- let suffix = file.substring(0, projectRoot.lenth);
- if (/.*\/vendor\/.*/.test(suffix)) {
- continue;
- }
- if (/.*\/taler-emscripten-lib.js/.test(suffix)) {
- continue;
- }
- if (file in cov) {
- continue;
- }
- let instrumenter = new (require("istanbul").Instrumenter)();
- let source = fs.readFileSync(file, "utf-8");
- let instrumentedSrc = instrumenter.instrumentSync(source, file);
- let covStubRE = /\{.*"path".*"fnMap".*"statementMap".*"branchMap".*\}/g;
- let covStubMatch = covStubRE.exec(instrumentedSrc);
-
- if (covStubMatch !== null) {
- let covStub = JSON.parse(covStubMatch[0]);
- cov[file] = covStub;
- }
- }
-}
-
-
-driver.manage().logs().get("browser").then((logs) => {
- for (let l of logs) {
- if (l.message.startsWith("{")) {
- // format not understood, sometimes messages are logged
- // with more structure, just pass it on
- console.log(l.message);
- continue;
- }
- let s1 = l.message.indexOf(" ") + 1;
- let s2 = l.message.indexOf(" ", s1) + 1;
- // Skip file url and LINE:COL
- console.log(l.message.substring(s2));
- }
-
- let coverage = driver.executeScript("return
JSON.stringify(window.__coverage__);");
- coverage.then((covStr) => {
- let cov = JSON.parse(covStr);
- if (cov) {
- let covTranslated = {};
- for (let f in cov) {
- let p = path.resolve(projectRoot, f);
- let c = covTranslated[p] = cov[f];
- c.path = p;
- }
- augmentCoverage(covTranslated);
- fs.writeFileSync(`coverage-${testName}-${randId(5)}.json`,
JSON.stringify(covTranslated));
- }
- if (!argv["keep-open"]) {
- driver.quit();
- l.close();
- }
- })
-
-});
-
diff --git a/tooling/talertest/selenium/system.js
b/tooling/talertest/selenium/system.js
deleted file mode 100644
index 1b7c1f82..00000000
--- a/tooling/talertest/selenium/system.js
+++ /dev/null
@@ -1,6 +0,0 @@
-/*
- * SystemJS v0.19.41
- */
-!function(){function e(){!function(e){function t(e,r){if("string"!=typeof
e)throw new TypeError("URL must be a string");var
n=String(e).replace(/^\s+|\s+$/g,"").match(/^([^:\/?#]+:)?(?:\/\/(?:([^:@\/?#]*)(?::([^:@\/?#]*))?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);if(!n)throw
new RangeError("Invalid URL format");var
a=n[1]||"",o=n[2]||"",i=n[3]||"",s=n[4]||"",l=n[5]||"",u=n[6]||"",d=n[7]||"",c=n[8]||"",f=n[9]||"";if(void
0!==r){var m=r instanceof t?r:new t(r),p=!a&&!s&& [...]
-if(!v)return h+(p?".js":"");var b=h.substr(v.length+1);return
r(s,s.packages[v]||{},v,b,i)}}),i("normalize",function(t){return
function(r,n,a){var o=this;return
a=a===!0,Promise.resolve().then(function(){if(n)var
t=e(o,n)||o.defaultJSExtensions&&".js"==n.substr(n.length-3,3)&&e(o,n.substr(0,n.length-3));var
i=t&&o.packages[t];if(i&&"./"!=r.substr(0,2)){var
s=i.map,l=s&&S(s,r);if(l)return d(o,i,t,l,r,a)}return
Promise.resolve()}).then(function(i){if(i)return i;var s=o.defaultJSExtensions&
[...]
-//# sourceMappingURL=system.js.map
diff --git a/tooling/talertest/selenium/testhost.html
b/tooling/talertest/selenium/testhost.html
deleted file mode 100644
index 01641547..00000000
--- a/tooling/talertest/selenium/testhost.html
+++ /dev/null
@@ -1,63 +0,0 @@
-<!doctype html>
-<html>
- <head>
- <title>Browser Test Host</title>
-
- <script src="/testlib/selenium/esprima.js"></script>
- <script src="/testlib/selenium/escodegen.browser.js"></script>
- <script src="/testlib/selenium/instrumenter.js"></script>
-
- <script src="/src/vendor/URI.js"></script>
-
- <!-- for instrumentation to work, we have to use the non-csp version -->
- <script src="/testlib/selenium/system.js"></script>
-
- </head>
- <body>
- <script>
- document.body.appendChild(document.createTextNode(`starting test`));
- document.body.appendChild(document.createElement("br"));
-
- var requestCoverage = false;
-
- let parser = document.createElement('a');
-
- let oldTranslate = System.translate.bind(System);
- System.translate = (load) => {
- let srcP = oldTranslate(load);
- if (!requestCoverage) {
- return srcP;
- }
-
- parser.href = load.name;
- let modName = parser.pathname.substring(1);
-
- if (/.*\/?taler-emscripten-lib.js/.test(load.name)) {
- // don't instrument emscripten
- document.body.appendChild(document.createTextNode(`not instrumenting
${modName}`));
- document.body.appendChild(document.createElement("br"));
- return srcP;
- }
-
- let inst = new Instrumenter();
- document.body.appendChild(document.createTextNode(`instrumenting
${modName}`));
- document.body.appendChild(document.createElement("br"));
-
- return Promise.resolve(srcP).then((src) => {
- return inst.instrumentSync(src, modName);
- });
- }
-
- System.config({
- baseURL: "/",
- defaultJSExtensions: true,
- meta: {
- "src/emscripten/taler-emscripten-lib": {
- format: "global",
- exports: "Module",
- },
- },
- });
- </script>
- </body>
-</html>
diff --git a/tooling/talertest/talertest.d.ts b/tooling/talertest/talertest.d.ts
deleted file mode 100644
index 599b8b60..00000000
--- a/tooling/talertest/talertest.d.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-/**
- *
- * @author Florian Dold
- */
-export declare type TestFn = (t: TestLib) => void | Promise<void>;
-export interface TestLib {
- pass(msg?: string): void;
- fail(msg?: string): void;
- assert(v: any, msg?: string): void;
- assertEqualsStrict(v1: any, v2: any, msg?: string): void;
-}
-/**
- * Register a test case.
- */
-export declare function test(name: string, testFn: TestFn): void;
-/**
- * Run all registered test case, producing a TAP stream.
- */
-export declare function run(statusCallback?: (m: string) => void):
Promise<void>;
diff --git a/tooling/talertest/talertest.js b/tooling/talertest/talertest.js
deleted file mode 100644
index 9f7d63a0..00000000
--- a/tooling/talertest/talertest.js
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 Inria
-
- TALER is free software; you can redistribute it and/or modify it under the
- terms of the GNU General Public License as published by the Free Software
- Foundation; either version 3, or (at your option) any later version.
-
- TALER is distributed in the hope that it will be useful, but WITHOUT ANY
- WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
- A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License along with
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-"use strict";
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P,
generator) {
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch
(e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); }
catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : new
P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-let tests = [];
-let testRunner;
-/**
- * Register a test case.
- */
-function test(name, testFn) {
- tests.push({ name, testFn });
-}
-exports.test = test;
-/**
- * Run all registered test case, producing a TAP stream.
- */
-function run(statusCallback) {
- return __awaiter(this, void 0, void 0, function* () {
- console.log(`1..${tests.length}`);
- for (let i in tests) {
- let t = tests[i];
- let passed = false;
- let lastMsg = undefined;
- let p = new Promise((resolve, reject) => {
- let pass = (msg) => {
- if (passed) {
- let e = Error("test passed twice");
- reject(e);
- throw e;
- }
- passed = true;
- lastMsg = msg;
- resolve();
- };
- let fail = (msg) => {
- lastMsg = msg;
- let e = Error("test failed");
- reject(e);
- throw e;
- };
- let assert = (v, msg) => {
- if (!v) {
- lastMsg = msg;
- reject(Error("test failed"));
- return;
- }
- };
- let assertEqualsStrict = (v1, v2, msg) => {
- if (v1 !== v2) {
- console.log(`# expected: ${v1}`);
- console.log(`# actual: ${v2}`);
- lastMsg = msg;
- let e = Error("test failed");
- reject(e);
- throw e;
- }
- };
- // Test might return a promise. If so, wait for it.
- let r = t.testFn({ pass, fail, assert, assertEqualsStrict });
- if (r) {
- r.then(() => pass(), (e) => fail(e.toString()));
- }
- });
- console.log(`# ${t.name}`);
- statusCallback && statusCallback(`starting test ${t.name}`);
- if (!lastMsg) {
- lastMsg = "-";
- }
- try {
- yield p;
- if (!passed) {
- throw Error("test did not call 'pass'");
- }
- console.log(`ok ${Number(i) + 1} ${lastMsg || "-"}`);
- statusCallback && statusCallback(`finished test ${t.name}`);
- }
- catch (e) {
- try {
- console.error(e.stack);
- }
- catch (e2) {
- console.error(e);
- }
- console.log(`not ok ${Number(i) + 1} ${lastMsg || "-"}`);
- statusCallback && statusCallback(`failed test ${t.name}`);
- }
- }
- });
-}
-exports.run = run;
diff --git a/tooling/talertest/talertest.ts b/tooling/talertest/talertest.ts
deleted file mode 100644
index 5e561981..00000000
--- a/tooling/talertest/talertest.ts
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- This file is part of TALER
- (C) 2016 Inria
-
- TALER is free software; you can redistribute it and/or modify it under the
- terms of the GNU General Public License as published by the Free Software
- Foundation; either version 3, or (at your option) any later version.
-
- TALER is distributed in the hope that it will be useful, but WITHOUT ANY
- WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
- A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License along with
- TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
- */
-
-/**
- *
- * @author Florian Dold
- */
-
-export type TestFn = (t: TestLib) => void | Promise<void>;
-
-interface Test {
- name: string;
- testFn: TestFn;
-}
-
-export interface TestLib {
- pass(msg?: string): void;
- fail(msg?: string): void;
- assert(v: any, msg?: string): void;
- assertEqualsStrict(v1: any, v2: any, msg?: string): void;
-}
-
-let tests: Test[] = [];
-let testRunner: any;
-
-
-/**
- * Register a test case.
- */
-export function test(name: string, testFn: TestFn) {
- tests.push({name, testFn});
-}
-
-
-/**
- * Run all registered test case, producing a TAP stream.
- */
-export async function run(statusCallback?: (m: string) => void) {
- console.log(`1..${tests.length}`);
- for (let i in tests) {
- let t = tests[i];
- let passed = false;
- let lastMsg: string|undefined = undefined;
- let p = new Promise((resolve, reject) => {
- let pass = (msg?: string) => {
- if (passed) {
- let e = Error("test passed twice");
- reject(e);
- throw e;
- }
- passed = true;
- lastMsg = msg;
- resolve();
- };
- let fail = (msg?: string) => {
- lastMsg = msg;
- let e = Error("test failed");
- reject(e);
- throw e;
- };
- let assert = (v: any, msg?: string) => {
- if (!v) {
- lastMsg = msg;
- reject(Error("test failed"));
- return;
- }
- };
- let assertEqualsStrict = (v1: any, v2: any, msg?: string) => {
- if (v1 !== v2) {
- console.log(`# expected: ${v1}`);
- console.log(`# actual: ${v2}`);
- lastMsg = msg;
- let e = Error("test failed");
- reject(e);
- throw e;
- }
- };
- // Test might return a promise. If so, wait for it.
- let r = t.testFn({pass,fail, assert, assertEqualsStrict});
- if (r) {
- r.then(() => pass(), (e) => fail(e.toString()));
- }
- });
-
- console.log(`# ${t.name}`);
- statusCallback && statusCallback(`starting test ${t.name}`);
-
- if (!lastMsg) {
- lastMsg = "-";
- }
-
- try {
- await p;
- if (!passed) {
- throw Error("test did not call 'pass'");
- }
- console.log(`ok ${Number(i) + 1} ${lastMsg || "-"}`);
- statusCallback && statusCallback(`finished test ${t.name}`);
- } catch (e) {
- try {
- console.error(e.stack);
- } catch (e2) {
- console.error(e);
- }
- console.log(`not ok ${Number(i) + 1} ${lastMsg || "-"}`);
- statusCallback && statusCallback(`failed test ${t.name}`);
- }
- }
-}
diff --git a/tooling/talertest/tsconfig.json b/tooling/talertest/tsconfig.json
deleted file mode 100644
index 1f668701..00000000
--- a/tooling/talertest/tsconfig.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "compilerOptions": {
- "target": "es6",
- "module": "commonjs",
- "lib": [
- "ES6",
- "DOM"
- ],
- "noImplicitReturns": true,
- "noFallthroughCasesInSwitch": true,
- "strictNullChecks": true,
- "noImplicitAny": true,
- "declaration": true,
- "alwaysStrict": true
- },
- "files": [
- "talertest.ts"
- ]
-}
diff --git a/tooling/talertest/yarn.lock b/tooling/talertest/yarn.lock
deleted file mode 100644
index 0be90c94..00000000
--- a/tooling/talertest/yarn.lock
+++ /dev/null
@@ -1,7 +0,0 @@
-# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
-# yarn lockfile v1
-
-
address@hidden:
- version "2.2.2"
- resolved
"https://registry.yarnpkg.com/typescript/-/typescript-2.2.2.tgz#606022508479b55ffa368b58fee963a03dfd7b0c"
--
To stop receiving notification emails like this one, please contact
address@hidden
[Prev in Thread] |
Current Thread |
[Next in Thread] |
- [GNUnet-SVN] [taler-wallet-webex] branch master updated: convert tests to ava tests,
gnunet <=