1
0
Fork 0
BangleApps/js/espruinotools.js

33209 lines
1.3 MiB
JavaScript
Raw Normal View History

2020-04-27 15:12:13 +00:00
// EspruinoTools (https://github.com/espruino/EspruinoTools)
if (typeof $ === "undefined") {
var jqReady = [];
var jqShim = {
ready : function(cb) { jqReady.push(cb); },
css : function() {},
html : function() {},
width : function() {},
height : function() {},
addClass : function() {},
removeClass : function() {},
appendTo : function() { return jqShim; },
show : function() {},
hide : function() {},
};
var $ = function() { return jqShim; };
}
/**
Copyright 2014 Gordon Williams (gw@pur3.co.uk)
This Source Code is subject to the terms of the Mozilla Public
License, v2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
------------------------------------------------------------------
Initialisation code
------------------------------------------------------------------
**/
"use strict";
var Espruino;
(function() {
/** List of processors. These are functions that are called one
* after the other with the data received from the last one.
*
* Common processors are:
*
* sending - sending code to Espruino (no data)
* transformForEspruino - transform code ready to be sent to Espruino
* transformModuleForEspruino({code,name})
* - transform module code before it's sent to Espruino with Modules.addCached (we only do this if we don't think it's been minified before)
* connected - connected to Espruino (no data)
* disconnected - disconnected from Espruino (no data)
* environmentVar - Board's process.env loaded (object to be saved into Espruino.Env.environmentData)
* boardJSONLoaded - Board's JSON was loaded into environmentVar
* getModule - Called with data={moduleName:"foo", moduleCode:undefined} - moduleCode should be filled in if the module can be found
* getURL - Called with data={url:"http://....", data:undefined) - data should be filled in if the URL is handled (See Espruino.Core.Utils.getURL to use this)
* terminalClear - terminal has been cleared
* terminalPrompt - we've received a '>' character (eg, `>` or `debug>`). The argument is the current line's contents.
* terminalNewLine - When we get a new line on the terminal, this gets called with the last line's contents
* debugMode - called with true or false when debug mode is entered or left
* editorHover - called with { node : htmlNode, showTooltip : function(htmlNode) } when something is hovered over
* notification - called with { mdg, type:"success","error"/"warning"/"info" }
**/
var processors = {};
function init() {
Espruino.Core.Config.loadConfiguration(function() {
// Initialise all modules
function initModule(modName, mod) {
console.log("Initialising "+modName);
if (mod.init !== undefined)
mod.init();
}
var module;
for (module in Espruino.Core) initModule(module, Espruino.Core[module]);
for (module in Espruino.Plugins) initModule(module, Espruino.Plugins[module]);
callProcessor("initialised", undefined, function() {
// We need the delay because of background.js's url_handler...
setTimeout(function() {
Espruino.initialised = true;
}, 1000);
});
});
}
// workaround for broken chrome on Mac
if (navigator.userAgent.indexOf("Mac OS X")>=0 &&
navigator.userAgent.indexOf("Chrome/33.0.1750")>=0) {
$(document).ready(function() { window.setTimeout(init,100); });
} else {
$(document).ready(init);
}
/** Add a processor function of type function(data,callback) */
function addProcessor(eventType, processor) {
if (processors[eventType]===undefined)
processors[eventType] = [];
processors[eventType].push(processor);
}
/** Call a processor function */
function callProcessor(eventType, data, callback) {
var p = processors[eventType];
// no processors
if (p===undefined || p.length==0) {
if (callback!==undefined) callback(data);
return;
}
// now go through all processors
var n = 0;
var cbCalled = false;
var cb = function(inData) {
if (cbCalled) throw new Error("Internal error in "+eventType+" processor. Callback is called TWICE.");
cbCalled = true;
if (n < p.length) {
cbCalled = false;
p[n++](inData, cb);
} else {
if (callback!==undefined) callback(inData);
}
};
cb(data);
}
// -----------------------------------
Espruino = {
Core : { },
Plugins : { },
addProcessor : addProcessor,
callProcessor : callProcessor,
initialised : false,
init : init, // just in case we need to initialise this by hand
};
return Espruino;
})();
Espruino.Core.Notifications = {
success : function(e) { console.log(e); },
error : function(e) { console.error(e); },
warning : function(e) { console.warn(e); },
info : function(e) { console.log(e); },
};
Espruino.Core.Status = {
setStatus : function(e,len) { console.log(e); },
hasProgress : function() { return false; },
incrementProgress : function(amt) {}
};
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.acorn = {})));
}(this, (function (exports) { 'use strict';
// Reserved word lists for various dialects of the language
var reservedWords = {
3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
5: "class enum extends super const export import",
6: "enum",
strict: "implements interface let package private protected public static yield",
strictBind: "eval arguments"
};
// And the keywords
var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
var keywords = {
5: ecma5AndLessKeywords,
6: ecma5AndLessKeywords + " const class extends export import super"
};
var keywordRelationalOperator = /^in(stanceof)?$/;
// ## Character categories
// Big ugly regular expressions that match characters in the
// whitespace, identifier, and identifier-start categories. These
// are only applied when a character is found to actually have a
// code point above 128.
// Generated by `bin/generate-identifier-regex.js`.
var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fd5\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ae\ua7b0-\ua7b7\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab65\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\u
var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d4-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d01-\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1cf8\u1cf9\u1dc0-\u1df5\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
// These are a run-length and offset encoded representation of the
// >0xffff code points that are a valid part of identifiers. The
// offset starts at 0x10000, and each pair of numbers represents an
// offset to the next range, and then a size of the range. They were
// generated by bin/generate-identifier-regex.js
// eslint-disable-next-line comma-spacing
var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,17,26,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,785,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,25,391,63,32,0,449,56,264,8,2,36,18,0,50,29,881,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,65,0,32,6124,20,754,9486,1,3071,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,60,67,1213,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,10591,541];
// eslint-disable-next-line comma-spacing
var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,10,2,4,9,83,11,7,0,161,11,6,9,7,3,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,87,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,423,9,838,7,2,7,17,9,57,21,2,13,19882,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239];
// This has a complexity linear to the value of the code. The
// assumption is that looking up astral identifier characters is
// rare.
function isInAstralSet(code, set) {
var pos = 0x10000;
for (var i = 0; i < set.length; i += 2) {
pos += set[i];
if (pos > code) { return false }
pos += set[i + 1];
if (pos >= code) { return true }
}
}
// Test whether a given character code starts an identifier.
function isIdentifierStart(code, astral) {
if (code < 65) { return code === 36 }
if (code < 91) { return true }
if (code < 97) { return code === 95 }
if (code < 123) { return true }
if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
if (astral === false) { return false }
return isInAstralSet(code, astralIdentifierStartCodes)
}
// Test whether a given character is part of an identifier.
function isIdentifierChar(code, astral) {
if (code < 48) { return code === 36 }
if (code < 58) { return true }
if (code < 65) { return false }
if (code < 91) { return true }
if (code < 97) { return code === 95 }
if (code < 123) { return true }
if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
if (astral === false) { return false }
return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
}
// ## Token types
// The assignment of fine-grained, information-carrying type objects
// allows the tokenizer to store the information it has about a
// token in a way that is very cheap for the parser to look up.
// All token type variables start with an underscore, to make them
// easy to recognize.
// The `beforeExpr` property is used to disambiguate between regular
// expressions and divisions. It is set on all token types that can
// be followed by an expression (thus, a slash after them would be a
// regular expression).
//
// The `startsExpr` property is used to check if the token ends a
// `yield` expression. It is set on all token types that either can
// directly start an expression (like a quotation mark) or can
// continue an expression (like the body of a string).
//
// `isLoop` marks a keyword as starting a loop, which is important
// to know when parsing a label, in order to allow or disallow
// continue jumps to that label.
var TokenType = function TokenType(label, conf) {
if ( conf === void 0 ) conf = {};
this.label = label;
this.keyword = conf.keyword;
this.beforeExpr = !!conf.beforeExpr;
this.startsExpr = !!conf.startsExpr;
this.isLoop = !!conf.isLoop;
this.isAssign = !!conf.isAssign;
this.prefix = !!conf.prefix;
this.postfix = !!conf.postfix;
this.binop = conf.binop || null;
this.updateContext = null;
};
function binop(name, prec) {
return new TokenType(name, {beforeExpr: true, binop: prec})
}
var beforeExpr = {beforeExpr: true};
var startsExpr = {startsExpr: true};
// Map keyword names to token types.
var keywords$1 = {};
// Succinct definitions of keyword token types
function kw(name, options) {
if ( options === void 0 ) options = {};
options.keyword = name;
return keywords$1[name] = new TokenType(name, options)
}
var types = {
num: new TokenType("num", startsExpr),
regexp: new TokenType("regexp", startsExpr),
string: new TokenType("string", startsExpr),
name: new TokenType("name", startsExpr),
eof: new TokenType("eof"),
// Punctuation token types.
bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
bracketR: new TokenType("]"),
braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
braceR: new TokenType("}"),
parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
parenR: new TokenType(")"),
comma: new TokenType(",", beforeExpr),
semi: new TokenType(";", beforeExpr),
colon: new TokenType(":", beforeExpr),
dot: new TokenType("."),
question: new TokenType("?", beforeExpr),
arrow: new TokenType("=>", beforeExpr),
template: new TokenType("template"),
invalidTemplate: new TokenType("invalidTemplate"),
ellipsis: new TokenType("...", beforeExpr),
backQuote: new TokenType("`", startsExpr),
dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
// Operators. These carry several kinds of properties to help the
// parser use them properly (the presence of these properties is
// what categorizes them as operators).
//
// `binop`, when present, specifies that this operator is a binary
// operator, and will refer to its precedence.
//
// `prefix` and `postfix` mark the operator as a prefix or postfix
// unary operator.
//
// `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
// binary operators with a very low precedence, that should result
// in AssignmentExpression nodes.
eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
logicalOR: binop("||", 1),
logicalAND: binop("&&", 2),
bitwiseOR: binop("|", 3),
bitwiseXOR: binop("^", 4),
bitwiseAND: binop("&", 5),
equality: binop("==/!=/===/!==", 6),
relational: binop("</>/<=/>=", 7),
bitShift: binop("<</>>/>>>", 8),
plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
modulo: binop("%", 10),
star: binop("*", 10),
slash: binop("/", 10),
starstar: new TokenType("**", {beforeExpr: true}),
// Keyword token types.
_break: kw("break"),
_case: kw("case", beforeExpr),
_catch: kw("catch"),
_continue: kw("continue"),
_debugger: kw("debugger"),
_default: kw("default", beforeExpr),
_do: kw("do", {isLoop: true, beforeExpr: true}),
_else: kw("else", beforeExpr),
_finally: kw("finally"),
_for: kw("for", {isLoop: true}),
_function: kw("function", startsExpr),
_if: kw("if"),
_return: kw("return", beforeExpr),
_switch: kw("switch"),
_throw: kw("throw", beforeExpr),
_try: kw("try"),
_var: kw("var"),
_const: kw("const"),
_while: kw("while", {isLoop: true}),
_with: kw("with"),
_new: kw("new", {beforeExpr: true, startsExpr: true}),
_this: kw("this", startsExpr),
_super: kw("super", startsExpr),
_class: kw("class", startsExpr),
_extends: kw("extends", beforeExpr),
_export: kw("export"),
_import: kw("import"),
_null: kw("null", startsExpr),
_true: kw("true", startsExpr),
_false: kw("false", startsExpr),
_in: kw("in", {beforeExpr: true, binop: 7}),
_instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
_typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
_void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
_delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
};
// Matches a whole line break (where CRLF is considered a single
// line break). Used to count lines.
var lineBreak = /\r\n?|\n|\u2028|\u2029/;
var lineBreakG = new RegExp(lineBreak.source, "g");
function isNewLine(code) {
return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
}
var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
var ref = Object.prototype;
var hasOwnProperty = ref.hasOwnProperty;
var toString = ref.toString;
// Checks if an object has a property.
function has(obj, propName) {
return hasOwnProperty.call(obj, propName)
}
var isArray = Array.isArray || (function (obj) { return (
toString.call(obj) === "[object Array]"
); });
// These are used when `options.locations` is on, for the
// `startLoc` and `endLoc` properties.
var Position = function Position(line, col) {
this.line = line;
this.column = col;
};
Position.prototype.offset = function offset (n) {
return new Position(this.line, this.column + n)
};
var SourceLocation = function SourceLocation(p, start, end) {
this.start = start;
this.end = end;
if (p.sourceFile !== null) { this.source = p.sourceFile; }
};
// The `getLineInfo` function is mostly useful when the
// `locations` option is off (for performance reasons) and you
// want to find the line/column position for a given character
// offset. `input` should be the code string that the offset refers
// into.
function getLineInfo(input, offset) {
for (var line = 1, cur = 0;;) {
lineBreakG.lastIndex = cur;
var match = lineBreakG.exec(input);
if (match && match.index < offset) {
++line;
cur = match.index + match[0].length;
} else {
return new Position(line, offset - cur)
}
}
}
// A second optional argument can be given to further configure
// the parser process. These options are recognized:
var defaultOptions = {
// `ecmaVersion` indicates the ECMAScript version to parse. Must
// be either 3, 5, 6 (2015), 7 (2016), or 8 (2017). This influences support
// for strict mode, the set of reserved words, and support for
// new syntax features. The default is 7.
ecmaVersion: 7,
// `sourceType` indicates the mode the code should be parsed in.
// Can be either `"script"` or `"module"`. This influences global
// strict mode and parsing of `import` and `export` declarations.
sourceType: "script",
// `onInsertedSemicolon` can be a callback that will be called
// when a semicolon is automatically inserted. It will be passed
// th position of the comma as an offset, and if `locations` is
// enabled, it is given the location as a `{line, column}` object
// as second argument.
onInsertedSemicolon: null,
// `onTrailingComma` is similar to `onInsertedSemicolon`, but for
// trailing commas.
onTrailingComma: null,
// By default, reserved words are only enforced if ecmaVersion >= 5.
// Set `allowReserved` to a boolean value to explicitly turn this on
// an off. When this option has the value "never", reserved words
// and keywords can also not be used as property names.
allowReserved: null,
// When enabled, a return at the top level is not considered an
// error.
allowReturnOutsideFunction: false,
// When enabled, import/export statements are not constrained to
// appearing at the top of the program.
allowImportExportEverywhere: false,
// When enabled, hashbang directive in the beginning of file
// is allowed and treated as a line comment.
allowHashBang: false,
// When `locations` is on, `loc` properties holding objects with
// `start` and `end` properties in `{line, column}` form (with
// line being 1-based and column 0-based) will be attached to the
// nodes.
locations: false,
// A function can be passed as `onToken` option, which will
// cause Acorn to call that function with object in the same
// format as tokens returned from `tokenizer().getToken()`. Note
// that you are not allowed to call the parser from the
// callback—that will corrupt its internal state.
onToken: null,
// A function can be passed as `onComment` option, which will
// cause Acorn to call that function with `(block, text, start,
// end)` parameters whenever a comment is skipped. `block` is a
// boolean indicating whether this is a block (`/* */`) comment,
// `text` is the content of the comment, and `start` and `end` are
// character offsets that denote the start and end of the comment.
// When the `locations` option is on, two more parameters are
// passed, the full `{line, column}` locations of the start and
// end of the comments. Note that you are not allowed to call the
// parser from the callback—that will corrupt its internal state.
onComment: null,
// Nodes have their start and end characters offsets recorded in
// `start` and `end` properties (directly on the node, rather than
// the `loc` object, which holds line/column data. To also add a
// [semi-standardized][range] `range` property holding a `[start,
// end]` array with the same numbers, set the `ranges` option to
// `true`.
//
// [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
ranges: false,
// It is possible to parse multiple files into a single AST by
// passing the tree produced by parsing the first file as
// `program` option in subsequent parses. This will add the
// toplevel forms of the parsed file to the `Program` (top) node
// of an existing parse tree.
program: null,
// When `locations` is on, you can pass this to record the source
// file in every node's `loc` object.
sourceFile: null,
// This value, if given, is stored in every node, whether
// `locations` is on or off.
directSourceFile: null,
// When enabled, parenthesized expressions are represented by
// (non-standard) ParenthesizedExpression nodes
preserveParens: false,
plugins: {}
};
// Interpret and default an options object
function getOptions(opts) {
var options = {};
for (var opt in defaultOptions)
{ options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }
if (options.ecmaVersion >= 2015)
{ options.ecmaVersion -= 2009; }
if (options.allowReserved == null)
{ options.allowReserved = options.ecmaVersion < 5; }
if (isArray(options.onToken)) {
var tokens = options.onToken;
options.onToken = function (token) { return tokens.push(token); };
}
if (isArray(options.onComment))
{ options.onComment = pushComment(options, options.onComment); }
return options
}
function pushComment(options, array) {
return function(block, text, start, end, startLoc, endLoc) {
var comment = {
type: block ? "Block" : "Line",
value: text,
start: start,
end: end
};
if (options.locations)
{ comment.loc = new SourceLocation(this, startLoc, endLoc); }
if (options.ranges)
{ comment.range = [start, end]; }
array.push(comment);
}
}
// Registered plugins
var plugins = {};
function keywordRegexp(words) {
return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
}
var Parser = function Parser(options, input, startPos) {
this.options = options = getOptions(options);
this.sourceFile = options.sourceFile;
this.keywords = keywordRegexp(keywords[options.ecmaVersion >= 6 ? 6 : 5]);
var reserved = "";
if (!options.allowReserved) {
for (var v = options.ecmaVersion;; v--)
{ if (reserved = reservedWords[v]) { break } }
if (options.sourceType == "module") { reserved += " await"; }
}
this.reservedWords = keywordRegexp(reserved);
var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
this.reservedWordsStrict = keywordRegexp(reservedStrict);
this.reservedWordsStrictBind = keywordRegexp(reservedStrict + " " + reservedWords.strictBind);
this.input = String(input);
// Used to signal to callers of `readWord1` whether the word
// contained any escape sequences. This is needed because words with
// escape sequences must not be interpreted as keywords.
this.containsEsc = false;
// Load plugins
this.loadPlugins(options.plugins);
// Set up token state
// The current position of the tokenizer in the input.
if (startPos) {
this.pos = startPos;
this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
} else {
this.pos = this.lineStart = 0;
this.curLine = 1;
}
// Properties of the current token:
// Its type
this.type = types.eof;
// For tokens that include more information than their type, the value
this.value = null;
// Its start and end offset
this.start = this.end = this.pos;
// And, if locations are used, the {line, column} object
// corresponding to those offsets
this.startLoc = this.endLoc = this.curPosition();
// Position information for the previous token
this.lastTokEndLoc = this.lastTokStartLoc = null;
this.lastTokStart = this.lastTokEnd = this.pos;
// The context stack is used to superficially track syntactic
// context to predict whether a regular expression is allowed in a
// given position.
this.context = this.initialContext();
this.exprAllowed = true;
// Figure out if it's a module code.
this.inModule = options.sourceType === "module";
this.strict = this.inModule || this.strictDirective(this.pos);
// Used to signify the start of a potential arrow function
this.potentialArrowAt = -1;
// Flags to track whether we are in a function, a generator, an async function.
this.inFunction = this.inGenerator = this.inAsync = false;
// Positions to delayed-check that yield/await does not exist in default parameters.
this.yieldPos = this.awaitPos = 0;
// Labels in scope.
this.labels = [];
// If enabled, skip leading hashbang line.
if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
{ this.skipLineComment(2); }
// Scope tracking for duplicate variable names (see scope.js)
this.scopeStack = [];
this.enterFunctionScope();
};
// DEPRECATED Kept for backwards compatibility until 3.0 in case a plugin uses them
Parser.prototype.isKeyword = function isKeyword (word) { return this.keywords.test(word) };
Parser.prototype.isReservedWord = function isReservedWord (word) { return this.reservedWords.test(word) };
Parser.prototype.extend = function extend (name, f) {
this[name] = f(this[name]);
};
Parser.prototype.loadPlugins = function loadPlugins (pluginConfigs) {
var this$1 = this;
for (var name in pluginConfigs) {
var plugin = plugins[name];
if (!plugin) { throw new Error("Plugin '" + name + "' not found") }
plugin(this$1, pluginConfigs[name]);
}
};
Parser.prototype.parse = function parse () {
var node = this.options.program || this.startNode();
this.nextToken();
return this.parseTopLevel(node)
};
var pp = Parser.prototype;
// ## Parser utilities
var literal = /^(?:'((?:\\.|[^'])*?)'|"((?:\\.|[^"])*?)"|;)/;
pp.strictDirective = function(start) {
var this$1 = this;
for (;;) {
skipWhiteSpace.lastIndex = start;
start += skipWhiteSpace.exec(this$1.input)[0].length;
var match = literal.exec(this$1.input.slice(start));
if (!match) { return false }
if ((match[1] || match[2]) == "use strict") { return true }
start += match[0].length;
}
};
// Predicate that tests whether the next token is of the given
// type, and if yes, consumes it as a side effect.
pp.eat = function(type) {
if (this.type === type) {
this.next();
return true
} else {
return false
}
};
// Tests whether parsed token is a contextual keyword.
pp.isContextual = function(name) {
return this.type === types.name && this.value === name && !this.containsEsc
};
// Consumes contextual keyword if possible.
pp.eatContextual = function(name) {
if (!this.isContextual(name)) { return false }
this.next();
return true
};
// Asserts that following token is given contextual keyword.
pp.expectContextual = function(name) {
if (!this.eatContextual(name)) { this.unexpected(); }
};
// Test whether a semicolon can be inserted at the current position.
pp.canInsertSemicolon = function() {
return this.type === types.eof ||
this.type === types.braceR ||
lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
};
pp.insertSemicolon = function() {
if (this.canInsertSemicolon()) {
if (this.options.onInsertedSemicolon)
{ this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
return true
}
};
// Consume a semicolon, or, failing that, see if we are allowed to
// pretend that there is a semicolon at this position.
pp.semicolon = function() {
if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }
};
pp.afterTrailingComma = function(tokType, notNext) {
if (this.type == tokType) {
if (this.options.onTrailingComma)
{ this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
if (!notNext)
{ this.next(); }
return true
}
};
// Expect a token of a given type. If found, consume it, otherwise,
// raise an unexpected token error.
pp.expect = function(type) {
this.eat(type) || this.unexpected();
};
// Raise an unexpected token error.
pp.unexpected = function(pos) {
this.raise(pos != null ? pos : this.start, "Unexpected token");
};
function DestructuringErrors() {
this.shorthandAssign =
this.trailingComma =
this.parenthesizedAssign =
this.parenthesizedBind =
this.doubleProto =
-1;
}
pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
if (!refDestructuringErrors) { return }
if (refDestructuringErrors.trailingComma > -1)
{ this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
};
pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
if (!refDestructuringErrors) { return false }
var shorthandAssign = refDestructuringErrors.shorthandAssign;
var doubleProto = refDestructuringErrors.doubleProto;
if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
if (shorthandAssign >= 0)
{ this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
if (doubleProto >= 0)
{ this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
};
pp.checkYieldAwaitInDefaultParams = function() {
if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
{ this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
if (this.awaitPos)
{ this.raise(this.awaitPos, "Await expression cannot be a default value"); }
};
pp.isSimpleAssignTarget = function(expr) {
if (expr.type === "ParenthesizedExpression")
{ return this.isSimpleAssignTarget(expr.expression) }
return expr.type === "Identifier" || expr.type === "MemberExpression"
};
var pp$1 = Parser.prototype;
// ### Statement parsing
// Parse a program. Initializes the parser, reads any number of
// statements, and wraps them in a Program node. Optionally takes a
// `program` argument. If present, the statements will be appended
// to its body instead of creating a new node.
pp$1.parseTopLevel = function(node) {
var this$1 = this;
var exports = {};
if (!node.body) { node.body = []; }
while (this.type !== types.eof) {
var stmt = this$1.parseStatement(true, true, exports);
node.body.push(stmt);
}
this.adaptDirectivePrologue(node.body);
this.next();
if (this.options.ecmaVersion >= 6) {
node.sourceType = this.options.sourceType;
}
return this.finishNode(node, "Program")
};
var loopLabel = {kind: "loop"};
var switchLabel = {kind: "switch"};
pp$1.isLet = function() {
if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
skipWhiteSpace.lastIndex = this.pos;
var skip = skipWhiteSpace.exec(this.input);
var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
if (nextCh === 91 || nextCh == 123) { return true } // '{' and '['
if (isIdentifierStart(nextCh, true)) {
var pos = next + 1;
while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; }
var ident = this.input.slice(next, pos);
if (!keywordRelationalOperator.test(ident)) { return true }
}
return false
};
// check 'async [no LineTerminator here] function'
// - 'async /*foo*/ function' is OK.
// - 'async /*\n*/ function' is invalid.
pp$1.isAsyncFunction = function() {
if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
{ return false }
skipWhiteSpace.lastIndex = this.pos;
var skip = skipWhiteSpace.exec(this.input);
var next = this.pos + skip[0].length;
return !lineBreak.test(this.input.slice(this.pos, next)) &&
this.input.slice(next, next + 8) === "function" &&
(next + 8 == this.input.length || !isIdentifierChar(this.input.charAt(next + 8)))
};
// Parse a single statement.
//
// If expecting a statement and finding a slash operator, parse a
// regular expression literal. This is to handle cases like
// `if (foo) /blah/.exec(foo)`, where looking at the previous token
// does not help.
pp$1.parseStatement = function(declaration, topLevel, exports) {
var starttype = this.type, node = this.startNode(), kind;
if (this.isLet()) {
starttype = types._var;
kind = "let";
}
// Most types of statements are recognized by the keyword they
// start with. Many are trivial to parse, some require a bit of
// complexity.
switch (starttype) {
case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
case types._debugger: return this.parseDebuggerStatement(node)
case types._do: return this.parseDoStatement(node)
case types._for: return this.parseForStatement(node)
case types._function:
if (!declaration && this.options.ecmaVersion >= 6) { this.unexpected(); }
return this.parseFunctionStatement(node, false)
case types._class:
if (!declaration) { this.unexpected(); }
return this.parseClass(node, true)
case types._if: return this.parseIfStatement(node)
case types._return: return this.parseReturnStatement(node)
case types._switch: return this.parseSwitchStatement(node)
case types._throw: return this.parseThrowStatement(node)
case types._try: return this.parseTryStatement(node)
case types._const: case types._var:
kind = kind || this.value;
if (!declaration && kind != "var") { this.unexpected(); }
return this.parseVarStatement(node, kind)
case types._while: return this.parseWhileStatement(node)
case types._with: return this.parseWithStatement(node)
case types.braceL: return this.parseBlock()
case types.semi: return this.parseEmptyStatement(node)
case types._export:
case types._import:
if (!this.options.allowImportExportEverywhere) {
if (!topLevel)
{ this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
if (!this.inModule)
{ this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
}
return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports)
// If the statement does not start with a statement keyword or a
// brace, it's an ExpressionStatement or LabeledStatement. We
// simply start parsing an expression, and afterwards, if the
// next token is a colon and the expression was a simple
// Identifier node, we switch to interpreting it as a label.
default:
if (this.isAsyncFunction()) {
if (!declaration) { this.unexpected(); }
this.next();
return this.parseFunctionStatement(node, true)
}
var maybeName = this.value, expr = this.parseExpression();
if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon))
{ return this.parseLabeledStatement(node, maybeName, expr) }
else { return this.parseExpressionStatement(node, expr) }
}
};
pp$1.parseBreakContinueStatement = function(node, keyword) {
var this$1 = this;
var isBreak = keyword == "break";
this.next();
if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }
else if (this.type !== types.name) { this.unexpected(); }
else {
node.label = this.parseIdent();
this.semicolon();
}
// Verify that there is an actual destination to break or
// continue to.
var i = 0;
for (; i < this.labels.length; ++i) {
var lab = this$1.labels[i];
if (node.label == null || lab.name === node.label.name) {
if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
if (node.label && isBreak) { break }
}
}
if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
};
pp$1.parseDebuggerStatement = function(node) {
this.next();
this.semicolon();
return this.finishNode(node, "DebuggerStatement")
};
pp$1.parseDoStatement = function(node) {
this.next();
this.labels.push(loopLabel);
node.body = this.parseStatement(false);
this.labels.pop();
this.expect(types._while);
node.test = this.parseParenExpression();
if (this.options.ecmaVersion >= 6)
{ this.eat(types.semi); }
else
{ this.semicolon(); }
return this.finishNode(node, "DoWhileStatement")
};
// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
// loop is non-trivial. Basically, we have to parse the init `var`
// statement or expression, disallowing the `in` operator (see
// the second parameter to `parseExpression`), and then check
// whether the next token is `in` or `of`. When there is no init
// part (semicolon immediately after the opening parenthesis), it
// is a regular `for` loop.
pp$1.parseForStatement = function(node) {
this.next();
var awaitAt = (this.options.ecmaVersion >= 9 && this.inAsync && this.eatContextual("await")) ? this.lastTokStart : -1;
this.labels.push(loopLabel);
this.enterLexicalScope();
this.expect(types.parenL);
if (this.type === types.semi) {
if (awaitAt > -1) { this.unexpected(awaitAt); }
return this.parseFor(node, null)
}
var isLet = this.isLet();
if (this.type === types._var || this.type === types._const || isLet) {
var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
this.next();
this.parseVar(init$1, true, kind);
this.finishNode(init$1, "VariableDeclaration");
if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1 &&
!(kind !== "var" && init$1.declarations[0].init)) {
if (this.options.ecmaVersion >= 9) {
if (this.type === types._in) {
if (awaitAt > -1) { this.unexpected(awaitAt); }
} else { node.await = awaitAt > -1; }
}
return this.parseForIn(node, init$1)
}
if (awaitAt > -1) { this.unexpected(awaitAt); }
return this.parseFor(node, init$1)
}
var refDestructuringErrors = new DestructuringErrors;
var init = this.parseExpression(true, refDestructuringErrors);
if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
if (this.options.ecmaVersion >= 9) {
if (this.type === types._in) {
if (awaitAt > -1) { this.unexpected(awaitAt); }
} else { node.await = awaitAt > -1; }
}
this.toAssignable(init, false, refDestructuringErrors);
this.checkLVal(init);
return this.parseForIn(node, init)
} else {
this.checkExpressionErrors(refDestructuringErrors, true);
}
if (awaitAt > -1) { this.unexpected(awaitAt); }
return this.parseFor(node, init)
};
pp$1.parseFunctionStatement = function(node, isAsync) {
this.next();
return this.parseFunction(node, true, false, isAsync)
};
pp$1.parseIfStatement = function(node) {
this.next();
node.test = this.parseParenExpression();
// allow function declarations in branches, but only in non-strict mode
node.consequent = this.parseStatement(!this.strict && this.type == types._function);
node.alternate = this.eat(types._else) ? this.parseStatement(!this.strict && this.type == types._function) : null;
return this.finishNode(node, "IfStatement")
};
pp$1.parseReturnStatement = function(node) {
if (!this.inFunction && !this.options.allowReturnOutsideFunction)
{ this.raise(this.start, "'return' outside of function"); }
this.next();
// In `return` (and `break`/`continue`), the keywords with
// optional arguments, we eagerly look for a semicolon or the
// possibility to insert one.
if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; }
else { node.argument = this.parseExpression(); this.semicolon(); }
return this.finishNode(node, "ReturnStatement")
};
pp$1.parseSwitchStatement = function(node) {
var this$1 = this;
this.next();
node.discriminant = this.parseParenExpression();
node.cases = [];
this.expect(types.braceL);
this.labels.push(switchLabel);
this.enterLexicalScope();
// Statements under must be grouped (by label) in SwitchCase
// nodes. `cur` is used to keep the node that we are currently
// adding statements to.
var cur;
for (var sawDefault = false; this.type != types.braceR;) {
if (this$1.type === types._case || this$1.type === types._default) {
var isCase = this$1.type === types._case;
if (cur) { this$1.finishNode(cur, "SwitchCase"); }
node.cases.push(cur = this$1.startNode());
cur.consequent = [];
this$1.next();
if (isCase) {
cur.test = this$1.parseExpression();
} else {
if (sawDefault) { this$1.raiseRecoverable(this$1.lastTokStart, "Multiple default clauses"); }
sawDefault = true;
cur.test = null;
}
this$1.expect(types.colon);
} else {
if (!cur) { this$1.unexpected(); }
cur.consequent.push(this$1.parseStatement(true));
}
}
this.exitLexicalScope();
if (cur) { this.finishNode(cur, "SwitchCase"); }
this.next(); // Closing brace
this.labels.pop();
return this.finishNode(node, "SwitchStatement")
};
pp$1.parseThrowStatement = function(node) {
this.next();
if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
{ this.raise(this.lastTokEnd, "Illegal newline after throw"); }
node.argument = this.parseExpression();
this.semicolon();
return this.finishNode(node, "ThrowStatement")
};
// Reused empty array added for node fields that are always empty.
var empty = [];
pp$1.parseTryStatement = function(node) {
this.next();
node.block = this.parseBlock();
node.handler = null;
if (this.type === types._catch) {
var clause = this.startNode();
this.next();
this.expect(types.parenL);
clause.param = this.parseBindingAtom();
this.enterLexicalScope();
this.checkLVal(clause.param, "let");
this.expect(types.parenR);
clause.body = this.parseBlock(false);
this.exitLexicalScope();
node.handler = this.finishNode(clause, "CatchClause");
}
node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
if (!node.handler && !node.finalizer)
{ this.raise(node.start, "Missing catch or finally clause"); }
return this.finishNode(node, "TryStatement")
};
pp$1.parseVarStatement = function(node, kind) {
this.next();
this.parseVar(node, false, kind);
this.semicolon();
return this.finishNode(node, "VariableDeclaration")
};
pp$1.parseWhileStatement = function(node) {
this.next();
node.test = this.parseParenExpression();
this.labels.push(loopLabel);
node.body = this.parseStatement(false);
this.labels.pop();
return this.finishNode(node, "WhileStatement")
};
pp$1.parseWithStatement = function(node) {
if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
this.next();
node.object = this.parseParenExpression();
node.body = this.parseStatement(false);
return this.finishNode(node, "WithStatement")
};
pp$1.parseEmptyStatement = function(node) {
this.next();
return this.finishNode(node, "EmptyStatement")
};
pp$1.parseLabeledStatement = function(node, maybeName, expr) {
var this$1 = this;
for (var i$1 = 0, list = this$1.labels; i$1 < list.length; i$1 += 1)
{
var label = list[i$1];
if (label.name === maybeName)
{ this$1.raise(expr.start, "Label '" + maybeName + "' is already declared");
} }
var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null;
for (var i = this.labels.length - 1; i >= 0; i--) {
var label$1 = this$1.labels[i];
if (label$1.statementStart == node.start) {
// Update information about previous labels on this node
label$1.statementStart = this$1.start;
label$1.kind = kind;
} else { break }
}
this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
node.body = this.parseStatement(true);
if (node.body.type == "ClassDeclaration" ||
node.body.type == "VariableDeclaration" && node.body.kind != "var" ||
node.body.type == "FunctionDeclaration" && (this.strict || node.body.generator))
{ this.raiseRecoverable(node.body.start, "Invalid labeled declaration"); }
this.labels.pop();
node.label = expr;
return this.finishNode(node, "LabeledStatement")
};
pp$1.parseExpressionStatement = function(node, expr) {
node.expression = expr;
this.semicolon();
return this.finishNode(node, "ExpressionStatement")
};
// Parse a semicolon-enclosed block of statements, handling `"use
// strict"` declarations when `allowStrict` is true (used for
// function bodies).
pp$1.parseBlock = function(createNewLexicalScope) {
var this$1 = this;
if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
var node = this.startNode();
node.body = [];
this.expect(types.braceL);
if (createNewLexicalScope) {
this.enterLexicalScope();
}
while (!this.eat(types.braceR)) {
var stmt = this$1.parseStatement(true);
node.body.push(stmt);
}
if (createNewLexicalScope) {
this.exitLexicalScope();
}
return this.finishNode(node, "BlockStatement")
};
// Parse a regular `for` loop. The disambiguation code in
// `parseStatement` will already have parsed the init statement or
// expression.
pp$1.parseFor = function(node, init) {
node.init = init;
this.expect(types.semi);
node.test = this.type === types.semi ? null : this.parseExpression();
this.expect(types.semi);
node.update = this.type === types.parenR ? null : this.parseExpression();
this.expect(types.parenR);
this.exitLexicalScope();
node.body = this.parseStatement(false);
this.labels.pop();
return this.finishNode(node, "ForStatement")
};
// Parse a `for`/`in` and `for`/`of` loop, which are almost
// same from parser's perspective.
pp$1.parseForIn = function(node, init) {
var type = this.type === types._in ? "ForInStatement" : "ForOfStatement";
this.next();
if (type == "ForInStatement") {
if (init.type === "AssignmentPattern" ||
(init.type === "VariableDeclaration" && init.declarations[0].init != null &&
(this.strict || init.declarations[0].id.type !== "Identifier")))
{ this.raise(init.start, "Invalid assignment in for-in loop head"); }
}
node.left = init;
node.right = type == "ForInStatement" ? this.parseExpression() : this.parseMaybeAssign();
this.expect(types.parenR);
this.exitLexicalScope();
node.body = this.parseStatement(false);
this.labels.pop();
return this.finishNode(node, type)
};
// Parse a list of variable declarations.
pp$1.parseVar = function(node, isFor, kind) {
var this$1 = this;
node.declarations = [];
node.kind = kind;
for (;;) {
var decl = this$1.startNode();
this$1.parseVarId(decl, kind);
if (this$1.eat(types.eq)) {
decl.init = this$1.parseMaybeAssign(isFor);
} else if (kind === "const" && !(this$1.type === types._in || (this$1.options.ecmaVersion >= 6 && this$1.isContextual("of")))) {
this$1.unexpected();
} else if (decl.id.type != "Identifier" && !(isFor && (this$1.type === types._in || this$1.isContextual("of")))) {
this$1.raise(this$1.lastTokEnd, "Complex binding patterns require an initialization value");
} else {
decl.init = null;
}
node.declarations.push(this$1.finishNode(decl, "VariableDeclarator"));
if (!this$1.eat(types.comma)) { break }
}
return node
};
pp$1.parseVarId = function(decl, kind) {
decl.id = this.parseBindingAtom(kind);
this.checkLVal(decl.id, kind, false);
};
// Parse a function declaration or literal (depending on the
// `isStatement` parameter).
pp$1.parseFunction = function(node, isStatement, allowExpressionBody, isAsync) {
this.initFunction(node);
if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync)
{ node.generator = this.eat(types.star); }
if (this.options.ecmaVersion >= 8)
{ node.async = !!isAsync; }
if (isStatement) {
node.id = isStatement === "nullableID" && this.type != types.name ? null : this.parseIdent();
if (node.id) {
this.checkLVal(node.id, "var");
}
}
var oldInGen = this.inGenerator, oldInAsync = this.inAsync,
oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction;
this.inGenerator = node.generator;
this.inAsync = node.async;
this.yieldPos = 0;
this.awaitPos = 0;
this.inFunction = true;
this.enterFunctionScope();
if (!isStatement)
{ node.id = this.type == types.name ? this.parseIdent() : null; }
this.parseFunctionParams(node);
this.parseFunctionBody(node, allowExpressionBody);
this.inGenerator = oldInGen;
this.inAsync = oldInAsync;
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
this.inFunction = oldInFunc;
return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression")
};
pp$1.parseFunctionParams = function(node) {
this.expect(types.parenL);
node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
this.checkYieldAwaitInDefaultParams();
};
// Parse a class declaration or literal (depending on the
// `isStatement` parameter).
pp$1.parseClass = function(node, isStatement) {
var this$1 = this;
this.next();
this.parseClassId(node, isStatement);
this.parseClassSuper(node);
var classBody = this.startNode();
var hadConstructor = false;
classBody.body = [];
this.expect(types.braceL);
while (!this.eat(types.braceR)) {
var member = this$1.parseClassMember(classBody);
if (member && member.type === "MethodDefinition" && member.kind === "constructor") {
if (hadConstructor) { this$1.raise(member.start, "Duplicate constructor in the same class"); }
hadConstructor = true;
}
}
node.body = this.finishNode(classBody, "ClassBody");
return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
};
pp$1.parseClassMember = function(classBody) {
var this$1 = this;
if (this.eat(types.semi)) { return null }
var method = this.startNode();
var tryContextual = function (k, noLineBreak) {
if ( noLineBreak === void 0 ) noLineBreak = false;
var start = this$1.start, startLoc = this$1.startLoc;
if (!this$1.eatContextual(k)) { return false }
if (this$1.type !== types.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) { return true }
if (method.key) { this$1.unexpected(); }
method.computed = false;
method.key = this$1.startNodeAt(start, startLoc);
method.key.name = k;
this$1.finishNode(method.key, "Identifier");
return false
};
method.kind = "method";
method.static = tryContextual("static");
var isGenerator = this.eat(types.star);
var isAsync = false;
if (!isGenerator) {
if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) {
isAsync = true;
isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
} else if (tryContextual("get")) {
method.kind = "get";
} else if (tryContextual("set")) {
method.kind = "set";
}
}
if (!method.key) { this.parsePropertyName(method); }
var key = method.key;
if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" ||
key.type === "Literal" && key.value === "constructor")) {
if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier"); }
if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
method.kind = "constructor";
} else if (method.static && key.type === "Identifier" && key.name === "prototype") {
this.raise(key.start, "Classes may not have a static property named prototype");
}
this.parseClassMethod(classBody, method, isGenerator, isAsync);
if (method.kind === "get" && method.value.params.length !== 0)
{ this.raiseRecoverable(method.value.start, "getter should have no params"); }
if (method.kind === "set" && method.value.params.length !== 1)
{ this.raiseRecoverable(method.value.start, "setter should have exactly one param"); }
if (method.kind === "set" && method.value.params[0].type === "RestElement")
{ this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); }
return method
};
pp$1.parseClassMethod = function(classBody, method, isGenerator, isAsync) {
method.value = this.parseMethod(isGenerator, isAsync);
classBody.body.push(this.finishNode(method, "MethodDefinition"));
};
pp$1.parseClassId = function(node, isStatement) {
node.id = this.type === types.name ? this.parseIdent() : isStatement === true ? this.unexpected() : null;
};
pp$1.parseClassSuper = function(node) {
node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
};
// Parses module export declaration.
pp$1.parseExport = function(node, exports) {
var this$1 = this;
this.next();
// export * from '...'
if (this.eat(types.star)) {
this.expectContextual("from");
if (this.type !== types.string) { this.unexpected(); }
node.source = this.parseExprAtom();
this.semicolon();
return this.finishNode(node, "ExportAllDeclaration")
}
if (this.eat(types._default)) { // export default ...
this.checkExport(exports, "default", this.lastTokStart);
var isAsync;
if (this.type === types._function || (isAsync = this.isAsyncFunction())) {
var fNode = this.startNode();
this.next();
if (isAsync) { this.next(); }
node.declaration = this.parseFunction(fNode, "nullableID", false, isAsync);
} else if (this.type === types._class) {
var cNode = this.startNode();
node.declaration = this.parseClass(cNode, "nullableID");
} else {
node.declaration = this.parseMaybeAssign();
this.semicolon();
}
return this.finishNode(node, "ExportDefaultDeclaration")
}
// export var|const|let|function|class ...
if (this.shouldParseExportStatement()) {
node.declaration = this.parseStatement(true);
if (node.declaration.type === "VariableDeclaration")
{ this.checkVariableExport(exports, node.declaration.declarations); }
else
{ this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
node.specifiers = [];
node.source = null;
} else { // export { x, y as z } [from '...']
node.declaration = null;
node.specifiers = this.parseExportSpecifiers(exports);
if (this.eatContextual("from")) {
if (this.type !== types.string) { this.unexpected(); }
node.source = this.parseExprAtom();
} else {
// check for keywords used as local names
for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
var spec = list[i];
this$1.checkUnreserved(spec.local);
}
node.source = null;
}
this.semicolon();
}
return this.finishNode(node, "ExportNamedDeclaration")
};
pp$1.checkExport = function(exports, name, pos) {
if (!exports) { return }
if (has(exports, name))
{ this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
exports[name] = true;
};
pp$1.checkPatternExport = function(exports, pat) {
var this$1 = this;
var type = pat.type;
if (type == "Identifier")
{ this.checkExport(exports, pat.name, pat.start); }
else if (type == "ObjectPattern")
{ for (var i = 0, list = pat.properties; i < list.length; i += 1)
{
var prop = list[i];
this$1.checkPatternExport(exports, prop);
} }
else if (type == "ArrayPattern")
{ for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
var elt = list$1[i$1];
if (elt) { this$1.checkPatternExport(exports, elt); }
} }
else if (type == "Property")
{ this.checkPatternExport(exports, pat.value); }
else if (type == "AssignmentPattern")
{ this.checkPatternExport(exports, pat.left); }
else if (type == "RestElement")
{ this.checkPatternExport(exports, pat.argument); }
else if (type == "ParenthesizedExpression")
{ this.checkPatternExport(exports, pat.expression); }
};
pp$1.checkVariableExport = function(exports, decls) {
var this$1 = this;
if (!exports) { return }
for (var i = 0, list = decls; i < list.length; i += 1)
{
var decl = list[i];
this$1.checkPatternExport(exports, decl.id);
}
};
pp$1.shouldParseExportStatement = function() {
return this.type.keyword === "var" ||
this.type.keyword === "const" ||
this.type.keyword === "class" ||
this.type.keyword === "function" ||
this.isLet() ||
this.isAsyncFunction()
};
// Parses a comma-separated list of module exports.
pp$1.parseExportSpecifiers = function(exports) {
var this$1 = this;
var nodes = [], first = true;
// export { x, y as z } [from '...']
this.expect(types.braceL);
while (!this.eat(types.braceR)) {
if (!first) {
this$1.expect(types.comma);
if (this$1.afterTrailingComma(types.braceR)) { break }
} else { first = false; }
var node = this$1.startNode();
node.local = this$1.parseIdent(true);
node.exported = this$1.eatContextual("as") ? this$1.parseIdent(true) : node.local;
this$1.checkExport(exports, node.exported.name, node.exported.start);
nodes.push(this$1.finishNode(node, "ExportSpecifier"));
}
return nodes
};
// Parses import declaration.
pp$1.parseImport = function(node) {
this.next();
// import '...'
if (this.type === types.string) {
node.specifiers = empty;
node.source = this.parseExprAtom();
} else {
node.specifiers = this.parseImportSpecifiers();
this.expectContextual("from");
node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
}
this.semicolon();
return this.finishNode(node, "ImportDeclaration")
};
// Parses a comma-separated list of module imports.
pp$1.parseImportSpecifiers = function() {
var this$1 = this;
var nodes = [], first = true;
if (this.type === types.name) {
// import defaultObj, { x, y as z } from '...'
var node = this.startNode();
node.local = this.parseIdent();
this.checkLVal(node.local, "let");
nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
if (!this.eat(types.comma)) { return nodes }
}
if (this.type === types.star) {
var node$1 = this.startNode();
this.next();
this.expectContextual("as");
node$1.local = this.parseIdent();
this.checkLVal(node$1.local, "let");
nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
return nodes
}
this.expect(types.braceL);
while (!this.eat(types.braceR)) {
if (!first) {
this$1.expect(types.comma);
if (this$1.afterTrailingComma(types.braceR)) { break }
} else { first = false; }
var node$2 = this$1.startNode();
node$2.imported = this$1.parseIdent(true);
if (this$1.eatContextual("as")) {
node$2.local = this$1.parseIdent();
} else {
this$1.checkUnreserved(node$2.imported);
node$2.local = node$2.imported;
}
this$1.checkLVal(node$2.local, "let");
nodes.push(this$1.finishNode(node$2, "ImportSpecifier"));
}
return nodes
};
// Set `ExpressionStatement#directive` property for directive prologues.
pp$1.adaptDirectivePrologue = function(statements) {
for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
statements[i].directive = statements[i].expression.raw.slice(1, -1);
}
};
pp$1.isDirectiveCandidate = function(statement) {
return (
statement.type === "ExpressionStatement" &&
statement.expression.type === "Literal" &&
typeof statement.expression.value === "string" &&
// Reject parenthesized strings.
(this.input[statement.start] === "\"" || this.input[statement.start] === "'")
)
};
var pp$2 = Parser.prototype;
// Convert existing expression atom to assignable pattern
// if possible.
pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) {
var this$1 = this;
if (this.options.ecmaVersion >= 6 && node) {
switch (node.type) {
case "Identifier":
if (this.inAsync && node.name === "await")
{ this.raise(node.start, "Can not use 'await' as identifier inside an async function"); }
break
case "ObjectPattern":
case "ArrayPattern":
case "RestElement":
break
case "ObjectExpression":
node.type = "ObjectPattern";
if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
for (var i = 0, list = node.properties; i < list.length; i += 1) {
var prop = list[i];
this$1.toAssignable(prop, isBinding);
// Early error:
// AssignmentRestProperty[Yield, Await] :
// `...` DestructuringAssignmentTarget[Yield, Await]
//
// It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
if (
prop.type === "RestElement" &&
(prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
) {
this$1.raise(prop.argument.start, "Unexpected token");
}
}
break
case "Property":
// AssignmentProperty has type == "Property"
if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
this.toAssignable(node.value, isBinding);
break
case "ArrayExpression":
node.type = "ArrayPattern";
if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
this.toAssignableList(node.elements, isBinding);
break
case "SpreadElement":
node.type = "RestElement";
this.toAssignable(node.argument, isBinding);
if (node.argument.type === "AssignmentPattern")
{ this.raise(node.argument.start, "Rest elements cannot have a default value"); }
break
case "AssignmentExpression":
if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
node.type = "AssignmentPattern";
delete node.operator;
this.toAssignable(node.left, isBinding);
// falls through to AssignmentPattern
case "AssignmentPattern":
break
case "ParenthesizedExpression":
this.toAssignable(node.expression, isBinding);
break
case "MemberExpression":
if (!isBinding) { break }
default:
this.raise(node.start, "Assigning to rvalue");
}
} else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
return node
};
// Convert list of expression atoms to binding list.
pp$2.toAssignableList = function(exprList, isBinding) {
var this$1 = this;
var end = exprList.length;
for (var i = 0; i < end; i++) {
var elt = exprList[i];
if (elt) { this$1.toAssignable(elt, isBinding); }
}
if (end) {
var last = exprList[end - 1];
if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
{ this.unexpected(last.argument.start); }
}
return exprList
};
// Parses spread element.
pp$2.parseSpread = function(refDestructuringErrors) {
var node = this.startNode();
this.next();
node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
return this.finishNode(node, "SpreadElement")
};
pp$2.parseRestBinding = function() {
var node = this.startNode();
this.next();
// RestElement inside of a function parameter must be an identifier
if (this.options.ecmaVersion === 6 && this.type !== types.name)
{ this.unexpected(); }
node.argument = this.parseBindingAtom();
return this.finishNode(node, "RestElement")
};
// Parses lvalue (assignable) atom.
pp$2.parseBindingAtom = function() {
if (this.options.ecmaVersion >= 6) {
switch (this.type) {
case types.bracketL:
var node = this.startNode();
this.next();
node.elements = this.parseBindingList(types.bracketR, true, true);
return this.finishNode(node, "ArrayPattern")
case types.braceL:
return this.parseObj(true)
}
}
return this.parseIdent()
};
pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
var this$1 = this;
var elts = [], first = true;
while (!this.eat(close)) {
if (first) { first = false; }
else { this$1.expect(types.comma); }
if (allowEmpty && this$1.type === types.comma) {
elts.push(null);
} else if (allowTrailingComma && this$1.afterTrailingComma(close)) {
break
} else if (this$1.type === types.ellipsis) {
var rest = this$1.parseRestBinding();
this$1.parseBindingListItem(rest);
elts.push(rest);
if (this$1.type === types.comma) { this$1.raise(this$1.start, "Comma is not permitted after the rest element"); }
this$1.expect(close);
break
} else {
var elem = this$1.parseMaybeDefault(this$1.start, this$1.startLoc);
this$1.parseBindingListItem(elem);
elts.push(elem);
}
}
return elts
};
pp$2.parseBindingListItem = function(param) {
return param
};
// Parses assignment pattern around given atom if possible.
pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
left = left || this.parseBindingAtom();
if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left }
var node = this.startNodeAt(startPos, startLoc);
node.left = left;
node.right = this.parseMaybeAssign();
return this.finishNode(node, "AssignmentPattern")
};
// Verify that a node is an lval — something that can be assigned
// to.
// bindingType can be either:
// 'var' indicating that the lval creates a 'var' binding
// 'let' indicating that the lval creates a lexical ('let' or 'const') binding
// 'none' indicating that the binding should be checked for illegal identifiers, but not for duplicate references
pp$2.checkLVal = function(expr, bindingType, checkClashes) {
var this$1 = this;
switch (expr.type) {
case "Identifier":
if (this.strict && this.reservedWordsStrictBind.test(expr.name))
{ this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
if (checkClashes) {
if (has(checkClashes, expr.name))
{ this.raiseRecoverable(expr.start, "Argument name clash"); }
checkClashes[expr.name] = true;
}
if (bindingType && bindingType !== "none") {
if (
bindingType === "var" && !this.canDeclareVarName(expr.name) ||
bindingType !== "var" && !this.canDeclareLexicalName(expr.name)
) {
this.raiseRecoverable(expr.start, ("Identifier '" + (expr.name) + "' has already been declared"));
}
if (bindingType === "var") {
this.declareVarName(expr.name);
} else {
this.declareLexicalName(expr.name);
}
}
break
case "MemberExpression":
if (bindingType) { this.raiseRecoverable(expr.start, "Binding member expression"); }
break
case "ObjectPattern":
for (var i = 0, list = expr.properties; i < list.length; i += 1)
{
var prop = list[i];
this$1.checkLVal(prop, bindingType, checkClashes);
}
break
case "Property":
// AssignmentProperty has type == "Property"
this.checkLVal(expr.value, bindingType, checkClashes);
break
case "ArrayPattern":
for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
var elem = list$1[i$1];
if (elem) { this$1.checkLVal(elem, bindingType, checkClashes); }
}
break
case "AssignmentPattern":
this.checkLVal(expr.left, bindingType, checkClashes);
break
case "RestElement":
this.checkLVal(expr.argument, bindingType, checkClashes);
break
case "ParenthesizedExpression":
this.checkLVal(expr.expression, bindingType, checkClashes);
break
default:
this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue");
}
};
// A recursive descent parser operates by defining functions for all
// syntactic elements, and recursively calling those, each function
// advancing the input stream and returning an AST node. Precedence
// of constructs (for example, the fact that `!x[1]` means `!(x[1])`
// instead of `(!x)[1]` is handled by the fact that the parser
// function that parses unary prefix operators is called first, and
// in turn calls the function that parses `[]` subscripts — that
// way, it'll receive the node for `x[1]` already parsed, and wraps
// *that* in the unary operator node.
//
// Acorn uses an [operator precedence parser][opp] to handle binary
// operator precedence, because it is much more compact than using
// the technique outlined above, which uses different, nesting
// functions to specify precedence, for all of the ten binary
// precedence levels that JavaScript defines.
//
// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
var pp$3 = Parser.prototype;
// Check if property name clashes with already added.
// Object/class getters and setters are not allowed to clash —
// either with each other or with an init property — and in
// strict mode, init properties are also not allowed to be repeated.
pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) {
if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
{ return }
if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
{ return }
var key = prop.key;
var name;
switch (key.type) {
case "Identifier": name = key.name; break
case "Literal": name = String(key.value); break
default: return
}
var kind = prop.kind;
if (this.options.ecmaVersion >= 6) {
if (name === "__proto__" && kind === "init") {
if (propHash.proto) {
if (refDestructuringErrors && refDestructuringErrors.doubleProto < 0) { refDestructuringErrors.doubleProto = key.start; }
// Backwards-compat kludge. Can be removed in version 6.0
else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); }
}
propHash.proto = true;
}
return
}
name = "$" + name;
var other = propHash[name];
if (other) {
var redefinition;
if (kind === "init") {
redefinition = this.strict && other.init || other.get || other.set;
} else {
redefinition = other.init || other[kind];
}
if (redefinition)
{ this.raiseRecoverable(key.start, "Redefinition of property"); }
} else {
other = propHash[name] = {
init: false,
get: false,
set: false
};
}
other[kind] = true;
};
// ### Expression parsing
// These nest, from the most general expression type at the top to
// 'atomic', nondivisible expression types at the bottom. Most of
// the functions will simply let the function(s) below them parse,
// and, *if* the syntactic construct they handle is present, wrap
// the AST node that the inner parser gave them in another node.
// Parse a full expression. The optional arguments are used to
// forbid the `in` operator (in for loops initalization expressions)
// and provide reference for storing '=' operator inside shorthand
// property assignment in contexts where both object expression
// and object pattern might appear (so it's possible to raise
// delayed syntax error at correct position).
pp$3.parseExpression = function(noIn, refDestructuringErrors) {
var this$1 = this;
var startPos = this.start, startLoc = this.startLoc;
var expr = this.parseMaybeAssign(noIn, refDestructuringErrors);
if (this.type === types.comma) {
var node = this.startNodeAt(startPos, startLoc);
node.expressions = [expr];
while (this.eat(types.comma)) { node.expressions.push(this$1.parseMaybeAssign(noIn, refDestructuringErrors)); }
return this.finishNode(node, "SequenceExpression")
}
return expr
};
// Parse an assignment expression. This includes applications of
// operators like `+=`.
pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {
if (this.inGenerator && this.isContextual("yield")) { return this.parseYield() }
var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;
if (refDestructuringErrors) {
oldParenAssign = refDestructuringErrors.parenthesizedAssign;
oldTrailingComma = refDestructuringErrors.trailingComma;
refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
} else {
refDestructuringErrors = new DestructuringErrors;
ownDestructuringErrors = true;
}
var startPos = this.start, startLoc = this.startLoc;
if (this.type == types.parenL || this.type == types.name)
{ this.potentialArrowAt = this.start; }
var left = this.parseMaybeConditional(noIn, refDestructuringErrors);
if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
if (this.type.isAssign) {
var node = this.startNodeAt(startPos, startLoc);
node.operator = this.value;
node.left = this.type === types.eq ? this.toAssignable(left, false, refDestructuringErrors) : left;
if (!ownDestructuringErrors) { DestructuringErrors.call(refDestructuringErrors); }
refDestructuringErrors.shorthandAssign = -1; // reset because shorthand default was used correctly
this.checkLVal(left);
this.next();
node.right = this.parseMaybeAssign(noIn);
return this.finishNode(node, "AssignmentExpression")
} else {
if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
}
if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
return left
};
// Parse a ternary conditional (`?:`) operator.
pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc;
var expr = this.parseExprOps(noIn, refDestructuringErrors);
if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
if (this.eat(types.question)) {
var node = this.startNodeAt(startPos, startLoc);
node.test = expr;
node.consequent = this.parseMaybeAssign();
this.expect(types.colon);
node.alternate = this.parseMaybeAssign(noIn);
return this.finishNode(node, "ConditionalExpression")
}
return expr
};
// Start the precedence parser.
pp$3.parseExprOps = function(noIn, refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc;
var expr = this.parseMaybeUnary(refDestructuringErrors, false);
if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
return expr.start == startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn)
};
// Parse binary operators with the operator precedence parsing
// algorithm. `left` is the left-hand side of the operator.
// `minPrec` provides context that allows the function to stop and
// defer further parser to one of its callers when it encounters an
// operator that has a lower precedence than the set it is parsing.
pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
var prec = this.type.binop;
if (prec != null && (!noIn || this.type !== types._in)) {
if (prec > minPrec) {
var logical = this.type === types.logicalOR || this.type === types.logicalAND;
var op = this.value;
this.next();
var startPos = this.start, startLoc = this.startLoc;
var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn);
var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical);
return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn)
}
}
return left
};
pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
var node = this.startNodeAt(startPos, startLoc);
node.left = left;
node.operator = op;
node.right = right;
return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
};
// Parse unary operators, both prefix and postfix.
pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {
var this$1 = this;
var startPos = this.start, startLoc = this.startLoc, expr;
if (this.inAsync && this.isContextual("await")) {
expr = this.parseAwait();
sawUnary = true;
} else if (this.type.prefix) {
var node = this.startNode(), update = this.type === types.incDec;
node.operator = this.value;
node.prefix = true;
this.next();
node.argument = this.parseMaybeUnary(null, true);
this.checkExpressionErrors(refDestructuringErrors, true);
if (update) { this.checkLVal(node.argument); }
else if (this.strict && node.operator === "delete" &&
node.argument.type === "Identifier")
{ this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
else { sawUnary = true; }
expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
} else {
expr = this.parseExprSubscripts(refDestructuringErrors);
if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
while (this.type.postfix && !this.canInsertSemicolon()) {
var node$1 = this$1.startNodeAt(startPos, startLoc);
node$1.operator = this$1.value;
node$1.prefix = false;
node$1.argument = expr;
this$1.checkLVal(expr);
this$1.next();
expr = this$1.finishNode(node$1, "UpdateExpression");
}
}
if (!sawUnary && this.eat(types.starstar))
{ return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) }
else
{ return expr }
};
// Parse call, dot, and `[]`-subscript expressions.
pp$3.parseExprSubscripts = function(refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc;
var expr = this.parseExprAtom(refDestructuringErrors);
var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")";
if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) { return expr }
var result = this.parseSubscripts(expr, startPos, startLoc);
if (refDestructuringErrors && result.type === "MemberExpression") {
if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
}
return result
};
pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
var this$1 = this;
var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
this.lastTokEnd == base.end && !this.canInsertSemicolon() && this.input.slice(base.start, base.end) === "async";
for (var computed = (void 0);;) {
if ((computed = this$1.eat(types.bracketL)) || this$1.eat(types.dot)) {
var node = this$1.startNodeAt(startPos, startLoc);
node.object = base;
node.property = computed ? this$1.parseExpression() : this$1.parseIdent(true);
node.computed = !!computed;
if (computed) { this$1.expect(types.bracketR); }
base = this$1.finishNode(node, "MemberExpression");
} else if (!noCalls && this$1.eat(types.parenL)) {
var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this$1.yieldPos, oldAwaitPos = this$1.awaitPos;
this$1.yieldPos = 0;
this$1.awaitPos = 0;
var exprList = this$1.parseExprList(types.parenR, this$1.options.ecmaVersion >= 8, false, refDestructuringErrors);
if (maybeAsyncArrow && !this$1.canInsertSemicolon() && this$1.eat(types.arrow)) {
this$1.checkPatternErrors(refDestructuringErrors, false);
this$1.checkYieldAwaitInDefaultParams();
this$1.yieldPos = oldYieldPos;
this$1.awaitPos = oldAwaitPos;
return this$1.parseArrowExpression(this$1.startNodeAt(startPos, startLoc), exprList, true)
}
this$1.checkExpressionErrors(refDestructuringErrors, true);
this$1.yieldPos = oldYieldPos || this$1.yieldPos;
this$1.awaitPos = oldAwaitPos || this$1.awaitPos;
var node$1 = this$1.startNodeAt(startPos, startLoc);
node$1.callee = base;
node$1.arguments = exprList;
base = this$1.finishNode(node$1, "CallExpression");
} else if (this$1.type === types.backQuote) {
var node$2 = this$1.startNodeAt(startPos, startLoc);
node$2.tag = base;
node$2.quasi = this$1.parseTemplate({isTagged: true});
base = this$1.finishNode(node$2, "TaggedTemplateExpression");
} else {
return base
}
}
};
// Parse an atomic expression — either a single token that is an
// expression, an expression started by a keyword like `function` or
// `new`, or an expression wrapped in punctuation like `()`, `[]`,
// or `{}`.
pp$3.parseExprAtom = function(refDestructuringErrors) {
var node, canBeArrow = this.potentialArrowAt == this.start;
switch (this.type) {
case types._super:
if (!this.inFunction)
{ this.raise(this.start, "'super' outside of function or class"); }
node = this.startNode();
this.next();
// The `super` keyword can appear at below:
// SuperProperty:
// super [ Expression ]
// super . IdentifierName
// SuperCall:
// super Arguments
if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL)
{ this.unexpected(); }
return this.finishNode(node, "Super")
case types._this:
node = this.startNode();
this.next();
return this.finishNode(node, "ThisExpression")
case types.name:
var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
var id = this.parseIdent(this.type !== types.name);
if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function))
{ return this.parseFunction(this.startNodeAt(startPos, startLoc), false, false, true) }
if (canBeArrow && !this.canInsertSemicolon()) {
if (this.eat(types.arrow))
{ return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) }
if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc) {
id = this.parseIdent();
if (this.canInsertSemicolon() || !this.eat(types.arrow))
{ this.unexpected(); }
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
}
}
return id
case types.regexp:
var value = this.value;
node = this.parseLiteral(value.value);
node.regex = {pattern: value.pattern, flags: value.flags};
return node
case types.num: case types.string:
return this.parseLiteral(this.value)
case types._null: case types._true: case types._false:
node = this.startNode();
node.value = this.type === types._null ? null : this.type === types._true;
node.raw = this.type.keyword;
this.next();
return this.finishNode(node, "Literal")
case types.parenL:
var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
if (refDestructuringErrors) {
if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
{ refDestructuringErrors.parenthesizedAssign = start; }
if (refDestructuringErrors.parenthesizedBind < 0)
{ refDestructuringErrors.parenthesizedBind = start; }
}
return expr
case types.bracketL:
node = this.startNode();
this.next();
node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors);
return this.finishNode(node, "ArrayExpression")
case types.braceL:
return this.parseObj(false, refDestructuringErrors)
case types._function:
node = this.startNode();
this.next();
return this.parseFunction(node, false)
case types._class:
return this.parseClass(this.startNode(), false)
case types._new:
return this.parseNew()
case types.backQuote:
return this.parseTemplate()
default:
this.unexpected();
}
};
pp$3.parseLiteral = function(value) {
var node = this.startNode();
node.value = value;
node.raw = this.input.slice(this.start, this.end);
this.next();
return this.finishNode(node, "Literal")
};
pp$3.parseParenExpression = function() {
this.expect(types.parenL);
var val = this.parseExpression();
this.expect(types.parenR);
return val
};
pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
var this$1 = this;
var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
if (this.options.ecmaVersion >= 6) {
this.next();
var innerStartPos = this.start, innerStartLoc = this.startLoc;
var exprList = [], first = true, lastIsComma = false;
var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
this.yieldPos = 0;
this.awaitPos = 0;
while (this.type !== types.parenR) {
first ? first = false : this$1.expect(types.comma);
if (allowTrailingComma && this$1.afterTrailingComma(types.parenR, true)) {
lastIsComma = true;
break
} else if (this$1.type === types.ellipsis) {
spreadStart = this$1.start;
exprList.push(this$1.parseParenItem(this$1.parseRestBinding()));
if (this$1.type === types.comma) { this$1.raise(this$1.start, "Comma is not permitted after the rest element"); }
break
} else {
exprList.push(this$1.parseMaybeAssign(false, refDestructuringErrors, this$1.parseParenItem));
}
}
var innerEndPos = this.start, innerEndLoc = this.startLoc;
this.expect(types.parenR);
if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
this.checkPatternErrors(refDestructuringErrors, false);
this.checkYieldAwaitInDefaultParams();
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
return this.parseParenArrowList(startPos, startLoc, exprList)
}
if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
if (spreadStart) { this.unexpected(spreadStart); }
this.checkExpressionErrors(refDestructuringErrors, true);
this.yieldPos = oldYieldPos || this.yieldPos;
this.awaitPos = oldAwaitPos || this.awaitPos;
if (exprList.length > 1) {
val = this.startNodeAt(innerStartPos, innerStartLoc);
val.expressions = exprList;
this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
} else {
val = exprList[0];
}
} else {
val = this.parseParenExpression();
}
if (this.options.preserveParens) {
var par = this.startNodeAt(startPos, startLoc);
par.expression = val;
return this.finishNode(par, "ParenthesizedExpression")
} else {
return val
}
};
pp$3.parseParenItem = function(item) {
return item
};
pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
};
// New's precedence is slightly tricky. It must allow its argument to
// be a `[]` or dot subscript expression, but not a call — at least,
// not without wrapping it in parentheses. Thus, it uses the noCalls
// argument to parseSubscripts to prevent it from consuming the
// argument list.
var empty$1 = [];
pp$3.parseNew = function() {
var node = this.startNode();
var meta = this.parseIdent(true);
if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {
node.meta = meta;
var containsEsc = this.containsEsc;
node.property = this.parseIdent(true);
if (node.property.name !== "target" || containsEsc)
{ this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target"); }
if (!this.inFunction)
{ this.raiseRecoverable(node.start, "new.target can only be used in functions"); }
return this.finishNode(node, "MetaProperty")
}
var startPos = this.start, startLoc = this.startLoc;
node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); }
else { node.arguments = empty$1; }
return this.finishNode(node, "NewExpression")
};
// Parse template expression.
pp$3.parseTemplateElement = function(ref) {
var isTagged = ref.isTagged;
var elem = this.startNode();
if (this.type === types.invalidTemplate) {
if (!isTagged) {
this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
}
elem.value = {
raw: this.value,
cooked: null
};
} else {
elem.value = {
raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
cooked: this.value
};
}
this.next();
elem.tail = this.type === types.backQuote;
return this.finishNode(elem, "TemplateElement")
};
pp$3.parseTemplate = function(ref) {
var this$1 = this;
if ( ref === void 0 ) ref = {};
var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
var node = this.startNode();
this.next();
node.expressions = [];
var curElt = this.parseTemplateElement({isTagged: isTagged});
node.quasis = [curElt];
while (!curElt.tail) {
this$1.expect(types.dollarBraceL);
node.expressions.push(this$1.parseExpression());
this$1.expect(types.braceR);
node.quasis.push(curElt = this$1.parseTemplateElement({isTagged: isTagged}));
}
this.next();
return this.finishNode(node, "TemplateLiteral")
};
pp$3.isAsyncProp = function(prop) {
return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
(this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) &&
!lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
};
// Parse an object literal or binding pattern.
pp$3.parseObj = function(isPattern, refDestructuringErrors) {
var this$1 = this;
var node = this.startNode(), first = true, propHash = {};
node.properties = [];
this.next();
while (!this.eat(types.braceR)) {
if (!first) {
this$1.expect(types.comma);
if (this$1.afterTrailingComma(types.braceR)) { break }
} else { first = false; }
var prop = this$1.parseProperty(isPattern, refDestructuringErrors);
if (!isPattern) { this$1.checkPropClash(prop, propHash, refDestructuringErrors); }
node.properties.push(prop);
}
return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
};
pp$3.parseProperty = function(isPattern, refDestructuringErrors) {
var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) {
if (isPattern) {
prop.argument = this.parseIdent(false);
if (this.type === types.comma) {
this.raise(this.start, "Comma is not permitted after the rest element");
}
return this.finishNode(prop, "RestElement")
}
// To disallow parenthesized identifier via `this.toAssignable()`.
if (this.type === types.parenL && refDestructuringErrors) {
if (refDestructuringErrors.parenthesizedAssign < 0) {
refDestructuringErrors.parenthesizedAssign = this.start;
}
if (refDestructuringErrors.parenthesizedBind < 0) {
refDestructuringErrors.parenthesizedBind = this.start;
}
}
// Parse argument.
prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
// To disallow trailing comma via `this.toAssignable()`.
if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
refDestructuringErrors.trailingComma = this.start;
}
// Finish
return this.finishNode(prop, "SpreadElement")
}
if (this.options.ecmaVersion >= 6) {
prop.method = false;
prop.shorthand = false;
if (isPattern || refDestructuringErrors) {
startPos = this.start;
startLoc = this.startLoc;
}
if (!isPattern)
{ isGenerator = this.eat(types.star); }
}
var containsEsc = this.containsEsc;
this.parsePropertyName(prop);
if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
isAsync = true;
isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
this.parsePropertyName(prop, refDestructuringErrors);
} else {
isAsync = false;
}
this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
return this.finishNode(prop, "Property")
};
pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
if ((isGenerator || isAsync) && this.type === types.colon)
{ this.unexpected(); }
if (this.eat(types.colon)) {
prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
prop.kind = "init";
} else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) {
if (isPattern) { this.unexpected(); }
prop.kind = "init";
prop.method = true;
prop.value = this.parseMethod(isGenerator, isAsync);
} else if (!isPattern && !containsEsc &&
this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
(prop.key.name === "get" || prop.key.name === "set") &&
(this.type != types.comma && this.type != types.braceR)) {
if (isGenerator || isAsync) { this.unexpected(); }
prop.kind = prop.key.name;
this.parsePropertyName(prop);
prop.value = this.parseMethod(false);
var paramCount = prop.kind === "get" ? 0 : 1;
if (prop.value.params.length !== paramCount) {
var start = prop.value.start;
if (prop.kind === "get")
{ this.raiseRecoverable(start, "getter should have no params"); }
else
{ this.raiseRecoverable(start, "setter should have exactly one param"); }
} else {
if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
{ this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
}
} else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
this.checkUnreserved(prop.key);
prop.kind = "init";
if (isPattern) {
prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
} else if (this.type === types.eq && refDestructuringErrors) {
if (refDestructuringErrors.shorthandAssign < 0)
{ refDestructuringErrors.shorthandAssign = this.start; }
prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
} else {
prop.value = prop.key;
}
prop.shorthand = true;
} else { this.unexpected(); }
};
pp$3.parsePropertyName = function(prop) {
if (this.options.ecmaVersion >= 6) {
if (this.eat(types.bracketL)) {
prop.computed = true;
prop.key = this.parseMaybeAssign();
this.expect(types.bracketR);
return prop.key
} else {
prop.computed = false;
}
}
return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(true)
};
// Initialize empty function node.
pp$3.initFunction = function(node) {
node.id = null;
if (this.options.ecmaVersion >= 6) {
node.generator = false;
node.expression = false;
}
if (this.options.ecmaVersion >= 8)
{ node.async = false; }
};
// Parse object or class method.
pp$3.parseMethod = function(isGenerator, isAsync) {
var node = this.startNode(), oldInGen = this.inGenerator, oldInAsync = this.inAsync,
oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction;
this.initFunction(node);
if (this.options.ecmaVersion >= 6)
{ node.generator = isGenerator; }
if (this.options.ecmaVersion >= 8)
{ node.async = !!isAsync; }
this.inGenerator = node.generator;
this.inAsync = node.async;
this.yieldPos = 0;
this.awaitPos = 0;
this.inFunction = true;
this.enterFunctionScope();
this.expect(types.parenL);
node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
this.checkYieldAwaitInDefaultParams();
this.parseFunctionBody(node, false);
this.inGenerator = oldInGen;
this.inAsync = oldInAsync;
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
this.inFunction = oldInFunc;
return this.finishNode(node, "FunctionExpression")
};
// Parse arrow function expression with given parameters.
pp$3.parseArrowExpression = function(node, params, isAsync) {
var oldInGen = this.inGenerator, oldInAsync = this.inAsync,
oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction;
this.enterFunctionScope();
this.initFunction(node);
if (this.options.ecmaVersion >= 8)
{ node.async = !!isAsync; }
this.inGenerator = false;
this.inAsync = node.async;
this.yieldPos = 0;
this.awaitPos = 0;
this.inFunction = true;
node.params = this.toAssignableList(params, true);
this.parseFunctionBody(node, true);
this.inGenerator = oldInGen;
this.inAsync = oldInAsync;
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
this.inFunction = oldInFunc;
return this.finishNode(node, "ArrowFunctionExpression")
};
// Parse function body and check parameters.
pp$3.parseFunctionBody = function(node, isArrowFunction) {
var isExpression = isArrowFunction && this.type !== types.braceL;
var oldStrict = this.strict, useStrict = false;
if (isExpression) {
node.body = this.parseMaybeAssign();
node.expression = true;
this.checkParams(node, false);
} else {
var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
if (!oldStrict || nonSimple) {
useStrict = this.strictDirective(this.end);
// If this is a strict mode function, verify that argument names
// are not repeated, and it does not try to bind the words `eval`
// or `arguments`.
if (useStrict && nonSimple)
{ this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
}
// Start a new scope with regard to labels and the `inFunction`
// flag (restore them to their old value afterwards).
var oldLabels = this.labels;
this.labels = [];
if (useStrict) { this.strict = true; }
// Add the params to varDeclaredNames to ensure that an error is thrown
// if a let/const declaration in the function clashes with one of the params.
this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && this.isSimpleParamList(node.params));
node.body = this.parseBlock(false);
node.expression = false;
this.adaptDirectivePrologue(node.body.body);
this.labels = oldLabels;
}
this.exitFunctionScope();
if (this.strict && node.id) {
// Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
this.checkLVal(node.id, "none");
}
this.strict = oldStrict;
};
pp$3.isSimpleParamList = function(params) {
for (var i = 0, list = params; i < list.length; i += 1)
{
var param = list[i];
if (param.type !== "Identifier") { return false
} }
return true
};
// Checks function params for various disallowed patterns such as using "eval"
// or "arguments" and duplicate parameters.
pp$3.checkParams = function(node, allowDuplicates) {
var this$1 = this;
var nameHash = {};
for (var i = 0, list = node.params; i < list.length; i += 1)
{
var param = list[i];
this$1.checkLVal(param, "var", allowDuplicates ? null : nameHash);
}
};
// Parses a comma-separated list of expressions, and returns them as
// an array. `close` is the token type that ends the list, and
// `allowEmpty` can be turned on to allow subsequent commas with
// nothing in between them to be parsed as `null` (which is needed
// for array literals).
pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
var this$1 = this;
var elts = [], first = true;
while (!this.eat(close)) {
if (!first) {
this$1.expect(types.comma);
if (allowTrailingComma && this$1.afterTrailingComma(close)) { break }
} else { first = false; }
var elt = (void 0);
if (allowEmpty && this$1.type === types.comma)
{ elt = null; }
else if (this$1.type === types.ellipsis) {
elt = this$1.parseSpread(refDestructuringErrors);
if (refDestructuringErrors && this$1.type === types.comma && refDestructuringErrors.trailingComma < 0)
{ refDestructuringErrors.trailingComma = this$1.start; }
} else {
elt = this$1.parseMaybeAssign(false, refDestructuringErrors);
}
elts.push(elt);
}
return elts
};
pp$3.checkUnreserved = function(ref) {
var start = ref.start;
var end = ref.end;
var name = ref.name;
if (this.inGenerator && name === "yield")
{ this.raiseRecoverable(start, "Can not use 'yield' as identifier inside a generator"); }
if (this.inAsync && name === "await")
{ this.raiseRecoverable(start, "Can not use 'await' as identifier inside an async function"); }
if (this.isKeyword(name))
{ this.raise(start, ("Unexpected keyword '" + name + "'")); }
if (this.options.ecmaVersion < 6 &&
this.input.slice(start, end).indexOf("\\") != -1) { return }
var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
if (re.test(name)) {
if (!this.inAsync && name === "await")
{ this.raiseRecoverable(start, "Can not use keyword 'await' outside an async function"); }
this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
}
};
// Parse the next token as an identifier. If `liberal` is true (used
// when parsing properties), it will also convert keywords into
// identifiers.
pp$3.parseIdent = function(liberal, isBinding) {
var node = this.startNode();
if (liberal && this.options.allowReserved == "never") { liberal = false; }
if (this.type === types.name) {
node.name = this.value;
} else if (this.type.keyword) {
node.name = this.type.keyword;
// To fix https://github.com/acornjs/acorn/issues/575
// `class` and `function` keywords push new context into this.context.
// But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
// If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
if ((node.name === "class" || node.name === "function") &&
(this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
this.context.pop();
}
} else {
this.unexpected();
}
this.next();
this.finishNode(node, "Identifier");
if (!liberal) { this.checkUnreserved(node); }
return node
};
// Parses yield expression inside generator.
pp$3.parseYield = function() {
if (!this.yieldPos) { this.yieldPos = this.start; }
var node = this.startNode();
this.next();
if (this.type == types.semi || this.canInsertSemicolon() || (this.type != types.star && !this.type.startsExpr)) {
node.delegate = false;
node.argument = null;
} else {
node.delegate = this.eat(types.star);
node.argument = this.parseMaybeAssign();
}
return this.finishNode(node, "YieldExpression")
};
pp$3.parseAwait = function() {
if (!this.awaitPos) { this.awaitPos = this.start; }
var node = this.startNode();
this.next();
node.argument = this.parseMaybeUnary(null, true);
return this.finishNode(node, "AwaitExpression")
};
var pp$4 = Parser.prototype;
// This function is used to raise exceptions on parse errors. It
// takes an offset integer (into the current `input`) to indicate
// the location of the error, attaches the position to the end
// of the error message, and then raises a `SyntaxError` with that
// message.
pp$4.raise = function(pos, message) {
var loc = getLineInfo(this.input, pos);
message += " (" + loc.line + ":" + loc.column + ")";
var err = new SyntaxError(message);
err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
throw err
};
pp$4.raiseRecoverable = pp$4.raise;
pp$4.curPosition = function() {
if (this.options.locations) {
return new Position(this.curLine, this.pos - this.lineStart)
}
};
var pp$5 = Parser.prototype;
// Object.assign polyfill
var assign = Object.assign || function(target) {
var sources = [], len = arguments.length - 1;
while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ];
for (var i = 0, list = sources; i < list.length; i += 1) {
var source = list[i];
for (var key in source) {
if (has(source, key)) {
target[key] = source[key];
}
}
}
return target
};
// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
pp$5.enterFunctionScope = function() {
// var: a hash of var-declared names in the current lexical scope
// lexical: a hash of lexically-declared names in the current lexical scope
// childVar: a hash of var-declared names in all child lexical scopes of the current lexical scope (within the current function scope)
// parentLexical: a hash of lexically-declared names in all parent lexical scopes of the current lexical scope (within the current function scope)
this.scopeStack.push({var: {}, lexical: {}, childVar: {}, parentLexical: {}});
};
pp$5.exitFunctionScope = function() {
this.scopeStack.pop();
};
pp$5.enterLexicalScope = function() {
var parentScope = this.scopeStack[this.scopeStack.length - 1];
var childScope = {var: {}, lexical: {}, childVar: {}, parentLexical: {}};
this.scopeStack.push(childScope);
assign(childScope.parentLexical, parentScope.lexical, parentScope.parentLexical);
};
pp$5.exitLexicalScope = function() {
var childScope = this.scopeStack.pop();
var parentScope = this.scopeStack[this.scopeStack.length - 1];
assign(parentScope.childVar, childScope.var, childScope.childVar);
};
/**
* A name can be declared with `var` if there are no variables with the same name declared with `let`/`const`
* in the current lexical scope or any of the parent lexical scopes in this function.
*/
pp$5.canDeclareVarName = function(name) {
var currentScope = this.scopeStack[this.scopeStack.length - 1];
return !has(currentScope.lexical, name) && !has(currentScope.parentLexical, name)
};
/**
* A name can be declared with `let`/`const` if there are no variables with the same name declared with `let`/`const`
* in the current scope, and there are no variables with the same name declared with `var` in the current scope or in
* any child lexical scopes in this function.
*/
pp$5.canDeclareLexicalName = function(name) {
var currentScope = this.scopeStack[this.scopeStack.length - 1];
return !has(currentScope.lexical, name) && !has(currentScope.var, name) && !has(currentScope.childVar, name)
};
pp$5.declareVarName = function(name) {
this.scopeStack[this.scopeStack.length - 1].var[name] = true;
};
pp$5.declareLexicalName = function(name) {
this.scopeStack[this.scopeStack.length - 1].lexical[name] = true;
};
var Node = function Node(parser, pos, loc) {
this.type = "";
this.start = pos;
this.end = 0;
if (parser.options.locations)
{ this.loc = new SourceLocation(parser, loc); }
if (parser.options.directSourceFile)
{ this.sourceFile = parser.options.directSourceFile; }
if (parser.options.ranges)
{ this.range = [pos, 0]; }
};
// Start an AST node, attaching a start offset.
var pp$6 = Parser.prototype;
pp$6.startNode = function() {
return new Node(this, this.start, this.startLoc)
};
pp$6.startNodeAt = function(pos, loc) {
return new Node(this, pos, loc)
};
// Finish an AST node, adding `type` and `end` properties.
function finishNodeAt(node, type, pos, loc) {
node.type = type;
node.end = pos;
if (this.options.locations)
{ node.loc.end = loc; }
if (this.options.ranges)
{ node.range[1] = pos; }
return node
}
pp$6.finishNode = function(node, type) {
return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
};
// Finish node at given position
pp$6.finishNodeAt = function(node, type, pos, loc) {
return finishNodeAt.call(this, node, type, pos, loc)
};
// The algorithm used to determine whether a regexp can appear at a
// given point in the program is loosely based on sweet.js' approach.
// See https://github.com/mozilla/sweet.js/wiki/design
var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
this.token = token;
this.isExpr = !!isExpr;
this.preserveSpace = !!preserveSpace;
this.override = override;
this.generator = !!generator;
};
var types$1 = {
b_stat: new TokContext("{", false),
b_expr: new TokContext("{", true),
b_tmpl: new TokContext("${", false),
p_stat: new TokContext("(", false),
p_expr: new TokContext("(", true),
q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
f_stat: new TokContext("function", false),
f_expr: new TokContext("function", true),
f_expr_gen: new TokContext("function", true, false, null, true),
f_gen: new TokContext("function", false, false, null, true)
};
var pp$7 = Parser.prototype;
pp$7.initialContext = function() {
return [types$1.b_stat]
};
pp$7.braceIsBlock = function(prevType) {
var parent = this.curContext();
if (parent === types$1.f_expr || parent === types$1.f_stat)
{ return true }
if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr))
{ return !parent.isExpr }
// The check for `tt.name && exprAllowed` detects whether we are
// after a `yield` or `of` construct. See the `updateContext` for
// `tt.name`.
if (prevType === types._return || prevType == types.name && this.exprAllowed)
{ return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType == types.arrow)
{ return true }
if (prevType == types.braceL)
{ return parent === types$1.b_stat }
if (prevType == types._var || prevType == types.name)
{ return false }
return !this.exprAllowed
};
pp$7.inGeneratorContext = function() {
var this$1 = this;
for (var i = this.context.length - 1; i >= 1; i--) {
var context = this$1.context[i];
if (context.token === "function")
{ return context.generator }
}
return false
};
pp$7.updateContext = function(prevType) {
var update, type = this.type;
if (type.keyword && prevType == types.dot)
{ this.exprAllowed = false; }
else if (update = type.updateContext)
{ update.call(this, prevType); }
else
{ this.exprAllowed = type.beforeExpr; }
};
// Token-specific context update code
types.parenR.updateContext = types.braceR.updateContext = function() {
if (this.context.length == 1) {
this.exprAllowed = true;
return
}
var out = this.context.pop();
if (out === types$1.b_stat && this.curContext().token === "function") {
out = this.context.pop();
}
this.exprAllowed = !out.isExpr;
};
types.braceL.updateContext = function(prevType) {
this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
this.exprAllowed = true;
};
types.dollarBraceL.updateContext = function() {
this.context.push(types$1.b_tmpl);
this.exprAllowed = true;
};
types.parenL.updateContext = function(prevType) {
var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);
this.exprAllowed = true;
};
types.incDec.updateContext = function() {
// tokExprAllowed stays unchanged
};
types._function.updateContext = types._class.updateContext = function(prevType) {
if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else &&
!((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat))
{ this.context.push(types$1.f_expr); }
else
{ this.context.push(types$1.f_stat); }
this.exprAllowed = false;
};
types.backQuote.updateContext = function() {
if (this.curContext() === types$1.q_tmpl)
{ this.context.pop(); }
else
{ this.context.push(types$1.q_tmpl); }
this.exprAllowed = false;
};
types.star.updateContext = function(prevType) {
if (prevType == types._function) {
var index = this.context.length - 1;
if (this.context[index] === types$1.f_expr)
{ this.context[index] = types$1.f_expr_gen; }
else
{ this.context[index] = types$1.f_gen; }
}
this.exprAllowed = true;
};
types.name.updateContext = function(prevType) {
var allowed = false;
if (this.options.ecmaVersion >= 6) {
if (this.value == "of" && !this.exprAllowed ||
this.value == "yield" && this.inGeneratorContext())
{ allowed = true; }
}
this.exprAllowed = allowed;
};
// Object type used to represent tokens. Note that normally, tokens
// simply exist as properties on the parser object. This is only
// used for the onToken callback and the external tokenizer.
var Token = function Token(p) {
this.type = p.type;
this.value = p.value;
this.start = p.start;
this.end = p.end;
if (p.options.locations)
{ this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
if (p.options.ranges)
{ this.range = [p.start, p.end]; }
};
// ## Tokenizer
var pp$8 = Parser.prototype;
// Are we running under Rhino?
var isRhino = typeof Packages == "object" && Object.prototype.toString.call(Packages) == "[object JavaPackage]";
// Move to the next token
pp$8.next = function() {
if (this.options.onToken)
{ this.options.onToken(new Token(this)); }
this.lastTokEnd = this.end;
this.lastTokStart = this.start;
this.lastTokEndLoc = this.endLoc;
this.lastTokStartLoc = this.startLoc;
this.nextToken();
};
pp$8.getToken = function() {
this.next();
return new Token(this)
};
// If we're in an ES6 environment, make parsers iterable
if (typeof Symbol !== "undefined")
{ pp$8[Symbol.iterator] = function() {
var this$1 = this;
return {
next: function () {
var token = this$1.getToken();
return {
done: token.type === types.eof,
value: token
}
}
}
}; }
// Toggle strict mode. Re-reads the next number or string to please
// pedantic tests (`"use strict"; 010;` should fail).
pp$8.curContext = function() {
return this.context[this.context.length - 1]
};
// Read a single token, updating the parser object's token-related
// properties.
pp$8.nextToken = function() {
var curContext = this.curContext();
if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
this.start = this.pos;
if (this.options.locations) { this.startLoc = this.curPosition(); }
if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
if (curContext.override) { return curContext.override(this) }
else { this.readToken(this.fullCharCodeAtPos()); }
};
pp$8.readToken = function(code) {
// Identifier or keyword. '\uXXXX' sequences are allowed in
// identifiers, so '\' also dispatches to that.
if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
{ return this.readWord() }
return this.getTokenFromCode(code)
};
pp$8.fullCharCodeAtPos = function() {
var code = this.input.charCodeAt(this.pos);
if (code <= 0xd7ff || code >= 0xe000) { return code }
var next = this.input.charCodeAt(this.pos + 1);
return (code << 10) + next - 0x35fdc00
};
pp$8.skipBlockComment = function() {
var this$1 = this;
var startLoc = this.options.onComment && this.curPosition();
var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
this.pos = end + 2;
if (this.options.locations) {
lineBreakG.lastIndex = start;
var match;
while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
++this$1.curLine;
this$1.lineStart = match.index + match[0].length;
}
}
if (this.options.onComment)
{ this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
startLoc, this.curPosition()); }
};
pp$8.skipLineComment = function(startSkip) {
var this$1 = this;
var start = this.pos;
var startLoc = this.options.onComment && this.curPosition();
var ch = this.input.charCodeAt(this.pos += startSkip);
while (this.pos < this.input.length && !isNewLine(ch)) {
ch = this$1.input.charCodeAt(++this$1.pos);
}
if (this.options.onComment)
{ this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
startLoc, this.curPosition()); }
};
// Called at the start of the parse and after every token. Skips
// whitespace and comments, and.
pp$8.skipSpace = function() {
var this$1 = this;
loop: while (this.pos < this.input.length) {
var ch = this$1.input.charCodeAt(this$1.pos);
switch (ch) {
case 32: case 160: // ' '
++this$1.pos;
break
case 13:
if (this$1.input.charCodeAt(this$1.pos + 1) === 10) {
++this$1.pos;
}
case 10: case 8232: case 8233:
++this$1.pos;
if (this$1.options.locations) {
++this$1.curLine;
this$1.lineStart = this$1.pos;
}
break
case 47: // '/'
switch (this$1.input.charCodeAt(this$1.pos + 1)) {
case 42: // '*'
this$1.skipBlockComment();
break
case 47:
this$1.skipLineComment(2);
break
default:
break loop
}
break
default:
if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
++this$1.pos;
} else {
break loop
}
}
}
};
// Called at the end of every token. Sets `end`, `val`, and
// maintains `context` and `exprAllowed`, and skips the space after
// the token, so that the next one's `start` will point at the
// right position.
pp$8.finishToken = function(type, val) {
this.end = this.pos;
if (this.options.locations) { this.endLoc = this.curPosition(); }
var prevType = this.type;
this.type = type;
this.value = val;
this.updateContext(prevType);
};
// ### Token reading
// This is the function that is called to fetch the next token. It
// is somewhat obscure, because it works in character codes rather
// than characters, and because operator parsing has been inlined
// into it.
//
// All in the name of speed.
//
pp$8.readToken_dot = function() {
var next = this.input.charCodeAt(this.pos + 1);
if (next >= 48 && next <= 57) { return this.readNumber(true) }
var next2 = this.input.charCodeAt(this.pos + 2);
if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
this.pos += 3;
return this.finishToken(types.ellipsis)
} else {
++this.pos;
return this.finishToken(types.dot)
}
};
pp$8.readToken_slash = function() { // '/'
var next = this.input.charCodeAt(this.pos + 1);
if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
if (next === 61) { return this.finishOp(types.assign, 2) }
return this.finishOp(types.slash, 1)
};
pp$8.readToken_mult_modulo_exp = function(code) { // '%*'
var next = this.input.charCodeAt(this.pos + 1);
var size = 1;
var tokentype = code === 42 ? types.star : types.modulo;
// exponentiation operator ** and **=
if (this.options.ecmaVersion >= 7 && code == 42 && next === 42) {
++size;
tokentype = types.starstar;
next = this.input.charCodeAt(this.pos + 2);
}
if (next === 61) { return this.finishOp(types.assign, size + 1) }
return this.finishOp(tokentype, size)
};
pp$8.readToken_pipe_amp = function(code) { // '|&'
var next = this.input.charCodeAt(this.pos + 1);
if (next === code) { return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2) }
if (next === 61) { return this.finishOp(types.assign, 2) }
return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1)
};
pp$8.readToken_caret = function() { // '^'
var next = this.input.charCodeAt(this.pos + 1);
if (next === 61) { return this.finishOp(types.assign, 2) }
return this.finishOp(types.bitwiseXOR, 1)
};
pp$8.readToken_plus_min = function(code) { // '+-'
var next = this.input.charCodeAt(this.pos + 1);
if (next === code) {
if (next == 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) == 62 &&
(this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
// A `-->` line comment
this.skipLineComment(3);
this.skipSpace();
return this.nextToken()
}
return this.finishOp(types.incDec, 2)
}
if (next === 61) { return this.finishOp(types.assign, 2) }
return this.finishOp(types.plusMin, 1)
};
pp$8.readToken_lt_gt = function(code) { // '<>'
var next = this.input.charCodeAt(this.pos + 1);
var size = 1;
if (next === code) {
size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) }
return this.finishOp(types.bitShift, size)
}
if (next == 33 && code == 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) == 45 &&
this.input.charCodeAt(this.pos + 3) == 45) {
// `<!--`, an XML-style comment that should be interpreted as a line comment
this.skipLineComment(4);
this.skipSpace();
return this.nextToken()
}
if (next === 61) { size = 2; }
return this.finishOp(types.relational, size)
};
pp$8.readToken_eq_excl = function(code) { // '=!'
var next = this.input.charCodeAt(this.pos + 1);
if (next === 61) { return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
this.pos += 2;
return this.finishToken(types.arrow)
}
return this.finishOp(code === 61 ? types.eq : types.prefix, 1)
};
pp$8.getTokenFromCode = function(code) {
switch (code) {
// The interpretation of a dot depends on whether it is followed
// by a digit or another two dots.
case 46: // '.'
return this.readToken_dot()
// Punctuation tokens.
case 40: ++this.pos; return this.finishToken(types.parenL)
case 41: ++this.pos; return this.finishToken(types.parenR)
case 59: ++this.pos; return this.finishToken(types.semi)
case 44: ++this.pos; return this.finishToken(types.comma)
case 91: ++this.pos; return this.finishToken(types.bracketL)
case 93: ++this.pos; return this.finishToken(types.bracketR)
case 123: ++this.pos; return this.finishToken(types.braceL)
case 125: ++this.pos; return this.finishToken(types.braceR)
case 58: ++this.pos; return this.finishToken(types.colon)
case 63: ++this.pos; return this.finishToken(types.question)
case 96: // '`'
if (this.options.ecmaVersion < 6) { break }
++this.pos;
return this.finishToken(types.backQuote)
case 48: // '0'
var next = this.input.charCodeAt(this.pos + 1);
if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
if (this.options.ecmaVersion >= 6) {
if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
}
// Anything else beginning with a digit is an integer, octal
// number, or float.
case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
return this.readNumber(false)
// Quotes produce strings.
case 34: case 39: // '"', "'"
return this.readString(code)
// Operators are parsed inline in tiny state machines. '=' (61) is
// often referred to. `finishOp` simply skips the amount of
// characters it is given as second argument, and returns a token
// of the type given by its first argument.
case 47: // '/'
return this.readToken_slash()
case 37: case 42: // '%*'
return this.readToken_mult_modulo_exp(code)
case 124: case 38: // '|&'
return this.readToken_pipe_amp(code)
case 94: // '^'
return this.readToken_caret()
case 43: case 45: // '+-'
return this.readToken_plus_min(code)
case 60: case 62: // '<>'
return this.readToken_lt_gt(code)
case 61: case 33: // '=!'
return this.readToken_eq_excl(code)
case 126: // '~'
return this.finishOp(types.prefix, 1)
}
this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
};
pp$8.finishOp = function(type, size) {
var str = this.input.slice(this.pos, this.pos + size);
this.pos += size;
return this.finishToken(type, str)
};
// Parse a regular expression. Some context-awareness is necessary,
// since a '/' inside a '[]' set does not end the expression.
function tryCreateRegexp(src, flags, throwErrorAt, parser) {
try {
return new RegExp(src, flags)
} catch (e) {
if (throwErrorAt !== undefined) {
if (e instanceof SyntaxError) { parser.raise(throwErrorAt, "Error parsing regular expression: " + e.message); }
throw e
}
}
}
var regexpUnicodeSupport = !!tryCreateRegexp("\uffff", "u");
pp$8.readRegexp = function() {
var this$1 = this;
var escaped, inClass, start = this.pos;
for (;;) {
if (this$1.pos >= this$1.input.length) { this$1.raise(start, "Unterminated regular expression"); }
var ch = this$1.input.charAt(this$1.pos);
if (lineBreak.test(ch)) { this$1.raise(start, "Unterminated regular expression"); }
if (!escaped) {
if (ch === "[") { inClass = true; }
else if (ch === "]" && inClass) { inClass = false; }
else if (ch === "/" && !inClass) { break }
escaped = ch === "\\";
} else { escaped = false; }
++this$1.pos;
}
var content = this.input.slice(start, this.pos);
++this.pos;
var flagsStart = this.pos;
var mods = this.readWord1();
if (this.containsEsc) { this.unexpected(flagsStart); }
var tmp = content, tmpFlags = "";
if (mods) {
var validFlags = "gim";
if (this.options.ecmaVersion >= 6) { validFlags += "uy"; }
if (this.options.ecmaVersion >= 9) { validFlags += "s"; }
for (var i = 0; i < mods.length; i++) {
var mod = mods.charAt(i);
if (validFlags.indexOf(mod) == -1) { this$1.raise(start, "Invalid regular expression flag"); }
if (mods.indexOf(mod, i + 1) > -1) { this$1.raise(start, "Duplicate regular expression flag"); }
}
if (mods.indexOf("u") >= 0) {
if (regexpUnicodeSupport) {
tmpFlags = "u";
} else {
// Replace each astral symbol and every Unicode escape sequence that
// possibly represents an astral symbol or a paired surrogate with a
// single ASCII symbol to avoid throwing on regular expressions that
// are only valid in combination with the `/u` flag.
// Note: replacing with the ASCII symbol `x` might cause false
// negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
// perfectly valid pattern that is equivalent to `[a-b]`, but it would
// be replaced by `[x-b]` which throws an error.
tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}/g, function (_match, code, offset) {
code = Number("0x" + code);
if (code > 0x10FFFF) { this$1.raise(start + offset + 3, "Code point out of bounds"); }
return "x"
});
tmp = tmp.replace(/\\u([a-fA-F0-9]{4})|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "x");
tmpFlags = tmpFlags.replace("u", "");
}
}
}
// Detect invalid regular expressions.
var value = null;
// Rhino's regular expression parser is flaky and throws uncatchable exceptions,
// so don't do detection if we are running under Rhino
if (!isRhino) {
tryCreateRegexp(tmp, tmpFlags, start, this);
// Get a regular expression object for this pattern-flag pair, or `null` in
// case the current environment doesn't support the flags it uses.
value = tryCreateRegexp(content, mods);
}
return this.finishToken(types.regexp, {pattern: content, flags: mods, value: value})
};
// Read an integer in the given radix. Return null if zero digits
// were read, the integer value otherwise. When `len` is given, this
// will return `null` unless the integer has exactly `len` digits.
pp$8.readInt = function(radix, len) {
var this$1 = this;
var start = this.pos, total = 0;
for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) {
var code = this$1.input.charCodeAt(this$1.pos), val = (void 0);
if (code >= 97) { val = code - 97 + 10; } // a
else if (code >= 65) { val = code - 65 + 10; } // A
else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
else { val = Infinity; }
if (val >= radix) { break }
++this$1.pos;
total = total * radix + val;
}
if (this.pos === start || len != null && this.pos - start !== len) { return null }
return total
};
pp$8.readRadixNumber = function(radix) {
this.pos += 2; // 0x
var val = this.readInt(radix);
if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
return this.finishToken(types.num, val)
};
// Read an integer, octal integer, or floating-point number.
pp$8.readNumber = function(startsWithDot) {
var start = this.pos;
if (!startsWithDot && this.readInt(10) === null) { this.raise(start, "Invalid number"); }
var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
if (octal && this.strict) { this.raise(start, "Invalid number"); }
if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
var next = this.input.charCodeAt(this.pos);
if (next === 46 && !octal) { // '.'
++this.pos;
this.readInt(10);
next = this.input.charCodeAt(this.pos);
}
if ((next === 69 || next === 101) && !octal) { // 'eE'
next = this.input.charCodeAt(++this.pos);
if (next === 43 || next === 45) { ++this.pos; } // '+-'
if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
}
if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
var str = this.input.slice(start, this.pos);
var val = octal ? parseInt(str, 8) : parseFloat(str);
return this.finishToken(types.num, val)
};
// Read a string value, interpreting backslash-escapes.
pp$8.readCodePoint = function() {
var ch = this.input.charCodeAt(this.pos), code;
if (ch === 123) { // '{'
if (this.options.ecmaVersion < 6) { this.unexpected(); }
var codePos = ++this.pos;
code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
++this.pos;
if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
} else {
code = this.readHexChar(4);
}
return code
};
function codePointToString(code) {
// UTF-16 Decoding
if (code <= 0xFFFF) { return String.fromCharCode(code) }
code -= 0x10000;
return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
}
pp$8.readString = function(quote) {
var this$1 = this;
var out = "", chunkStart = ++this.pos;
for (;;) {
if (this$1.pos >= this$1.input.length) { this$1.raise(this$1.start, "Unterminated string constant"); }
var ch = this$1.input.charCodeAt(this$1.pos);
if (ch === quote) { break }
if (ch === 92) { // '\'
out += this$1.input.slice(chunkStart, this$1.pos);
out += this$1.readEscapedChar(false);
chunkStart = this$1.pos;
} else {
if (isNewLine(ch)) { this$1.raise(this$1.start, "Unterminated string constant"); }
++this$1.pos;
}
}
out += this.input.slice(chunkStart, this.pos++);
return this.finishToken(types.string, out)
};
// Reads template string tokens.
var INVALID_TEMPLATE_ESCAPE_ERROR = {};
pp$8.tryReadTemplateToken = function() {
this.inTemplateElement = true;
try {
this.readTmplToken();
} catch (err) {
if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
this.readInvalidTemplateToken();
} else {
throw err
}
}
this.inTemplateElement = false;
};
pp$8.invalidStringToken = function(position, message) {
if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
throw INVALID_TEMPLATE_ESCAPE_ERROR
} else {
this.raise(position, message);
}
};
pp$8.readTmplToken = function() {
var this$1 = this;
var out = "", chunkStart = this.pos;
for (;;) {
if (this$1.pos >= this$1.input.length) { this$1.raise(this$1.start, "Unterminated template"); }
var ch = this$1.input.charCodeAt(this$1.pos);
if (ch === 96 || ch === 36 && this$1.input.charCodeAt(this$1.pos + 1) === 123) { // '`', '${'
if (this$1.pos === this$1.start && (this$1.type === types.template || this$1.type === types.invalidTemplate)) {
if (ch === 36) {
this$1.pos += 2;
return this$1.finishToken(types.dollarBraceL)
} else {
++this$1.pos;
return this$1.finishToken(types.backQuote)
}
}
out += this$1.input.slice(chunkStart, this$1.pos);
return this$1.finishToken(types.template, out)
}
if (ch === 92) { // '\'
out += this$1.input.slice(chunkStart, this$1.pos);
out += this$1.readEscapedChar(true);
chunkStart = this$1.pos;
} else if (isNewLine(ch)) {
out += this$1.input.slice(chunkStart, this$1.pos);
++this$1.pos;
switch (ch) {
case 13:
if (this$1.input.charCodeAt(this$1.pos) === 10) { ++this$1.pos; }
case 10:
out += "\n";
break
default:
out += String.fromCharCode(ch);
break
}
if (this$1.options.locations) {
++this$1.curLine;
this$1.lineStart = this$1.pos;
}
chunkStart = this$1.pos;
} else {
++this$1.pos;
}
}
};
// Reads a template token to search for the end, without validating any escape sequences
pp$8.readInvalidTemplateToken = function() {
var this$1 = this;
for (; this.pos < this.input.length; this.pos++) {
switch (this$1.input[this$1.pos]) {
case "\\":
++this$1.pos;
break
case "$":
if (this$1.input[this$1.pos + 1] !== "{") {
break
}
// falls through
case "`":
return this$1.finishToken(types.invalidTemplate, this$1.input.slice(this$1.start, this$1.pos))
// no default
}
}
this.raise(this.start, "Unterminated template");
};
// Used to read escaped characters
pp$8.readEscapedChar = function(inTemplate) {
var ch = this.input.charCodeAt(++this.pos);
++this.pos;
switch (ch) {
case 110: return "\n" // 'n' -> '\n'
case 114: return "\r" // 'r' -> '\r'
case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
case 117: return codePointToString(this.readCodePoint()) // 'u'
case 116: return "\t" // 't' -> '\t'
case 98: return "\b" // 'b' -> '\b'
case 118: return "\u000b" // 'v' -> '\u000b'
case 102: return "\f" // 'f' -> '\f'
case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
case 10: // ' \n'
if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
return ""
default:
if (ch >= 48 && ch <= 55) {
var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
var octal = parseInt(octalStr, 8);
if (octal > 255) {
octalStr = octalStr.slice(0, -1);
octal = parseInt(octalStr, 8);
}
this.pos += octalStr.length - 1;
ch = this.input.charCodeAt(this.pos);
if ((octalStr !== "0" || ch == 56 || ch == 57) && (this.strict || inTemplate)) {
this.invalidStringToken(this.pos - 1 - octalStr.length, "Octal literal in strict mode");
}
return String.fromCharCode(octal)
}
return String.fromCharCode(ch)
}
};
// Used to read character escape sequences ('\x', '\u', '\U').
pp$8.readHexChar = function(len) {
var codePos = this.pos;
var n = this.readInt(16, len);
if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
return n
};
// Read an identifier, and return it as a string. Sets `this.containsEsc`
// to whether the word contained a '\u' escape.
//
// Incrementally adds only escaped chars, adding other chunks as-is
// as a micro-optimization.
pp$8.readWord1 = function() {
var this$1 = this;
this.containsEsc = false;
var word = "", first = true, chunkStart = this.pos;
var astral = this.options.ecmaVersion >= 6;
while (this.pos < this.input.length) {
var ch = this$1.fullCharCodeAtPos();
if (isIdentifierChar(ch, astral)) {
this$1.pos += ch <= 0xffff ? 1 : 2;
} else if (ch === 92) { // "\"
this$1.containsEsc = true;
word += this$1.input.slice(chunkStart, this$1.pos);
var escStart = this$1.pos;
if (this$1.input.charCodeAt(++this$1.pos) != 117) // "u"
{ this$1.invalidStringToken(this$1.pos, "Expecting Unicode escape sequence \\uXXXX"); }
++this$1.pos;
var esc = this$1.readCodePoint();
if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
{ this$1.invalidStringToken(escStart, "Invalid Unicode escape"); }
word += codePointToString(esc);
chunkStart = this$1.pos;
} else {
break
}
first = false;
}
return word + this.input.slice(chunkStart, this.pos)
};
// Read an identifier or keyword token. Will check for reserved
// words when necessary.
pp$8.readWord = function() {
var word = this.readWord1();
var type = types.name;
if (this.keywords.test(word)) {
if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword " + word); }
type = keywords$1[word];
}
return this.finishToken(type, word)
};
// Acorn is a tiny, fast JavaScript parser written in JavaScript.
//
// Acorn was written by Marijn Haverbeke, Ingvar Stepanyan, and
// various contributors and released under an MIT license.
//
// Git repositories for Acorn are available at
//
// http://marijnhaverbeke.nl/git/acorn
// https://github.com/acornjs/acorn.git
//
// Please use the [github bug tracker][ghbt] to report issues.
//
// [ghbt]: https://github.com/acornjs/acorn/issues
//
// This file defines the main parser interface. The library also comes
// with a [error-tolerant parser][dammit] and an
// [abstract syntax tree walker][walk], defined in other files.
//
// [dammit]: acorn_loose.js
// [walk]: util/walk.js
var version = "5.4.1";
// The main exported interface (under `self.acorn` when in the
// browser) is a `parse` function that takes a code string and
// returns an abstract syntax tree as specified by [Mozilla parser
// API][api].
//
// [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
function parse(input, options) {
return new Parser(options, input).parse()
}
// This function tries to parse a single expression at a given
// offset in a string. Useful for parsing mixed-language formats
// that embed JavaScript expressions.
function parseExpressionAt(input, pos, options) {
var p = new Parser(options, input, pos);
p.nextToken();
return p.parseExpression()
}
// Acorn is organized as a tokenizer and a recursive-descent parser.
// The `tokenizer` export provides an interface to the tokenizer.
function tokenizer(input, options) {
return new Parser(options, input)
}
// This is a terrible kludge to support the existing, pre-ES6
// interface where the loose parser module retroactively adds exports
// to this module.
// eslint-disable-line camelcase
function addLooseExports(parse, Parser$$1, plugins$$1) {
exports.parse_dammit = parse; // eslint-disable-line camelcase
exports.LooseParser = Parser$$1;
exports.pluginsLoose = plugins$$1;
}
exports.version = version;
exports.parse = parse;
exports.parseExpressionAt = parseExpressionAt;
exports.tokenizer = tokenizer;
exports.addLooseExports = addLooseExports;
exports.Parser = Parser;
exports.plugins = plugins;
exports.defaultOptions = defaultOptions;
exports.Position = Position;
exports.SourceLocation = SourceLocation;
exports.getLineInfo = getLineInfo;
exports.Node = Node;
exports.TokenType = TokenType;
exports.tokTypes = types;
exports.keywordTypes = keywords$1;
exports.TokContext = TokContext;
exports.tokContexts = types$1;
exports.isIdentifierChar = isIdentifierChar;
exports.isIdentifierStart = isIdentifierStart;
exports.Token = Token;
exports.isNewLine = isNewLine;
exports.lineBreak = lineBreak;
exports.lineBreakG = lineBreakG;
exports.nonASCIIwhitespace = nonASCIIwhitespace;
Object.defineProperty(exports, '__esModule', { value: true });
})));
/**
Copyright 2014 Gordon Williams (gw@pur3.co.uk)
This Source Code is subject to the terms of the Mozilla Public
License, v2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
------------------------------------------------------------------
Utilities
------------------------------------------------------------------
**/
"use strict";
(function(){
function init() {
}
function isWindows() {
return (typeof navigator!="undefined") && navigator.userAgent.indexOf("Windows")>=0;
}
function isAppleDevice() {
return (typeof navigator!="undefined") && (typeof window!="undefined") && /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
}
function getChromeVersion(){
return parseInt(window.navigator.appVersion.match(/Chrome\/(.*?) /)[1].split(".")[0]);
}
function isNWApp() {
return (typeof require === "function") && (typeof require('nw.gui') !== "undefined");
}
function isChromeWebApp() {
return ((typeof chrome === "object") && chrome.app && chrome.app.window);
}
function isProgressiveWebApp() {
return !isNWApp() && !isChromeWebApp() && window && window.matchMedia && window.matchMedia('(display-mode: standalone)').matches;
}
function hasNativeTitleBar() {
return !isNWApp() && !isChromeWebApp();
}
function escapeHTML(text, escapeSpaces)
{
escapeSpaces = typeof escapeSpaces !== 'undefined' ? escapeSpaces : true;
var chr = { '"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;', ' ' : (escapeSpaces ? '&nbsp;' : ' ') };
return text.toString().replace(/[\"&<> ]/g, function (a) { return chr[a]; });
}
/* Google Docs, forums, etc tend to break code by replacing characters with
fancy unicode versions. Un-break the code by undoing these changes */
function fixBrokenCode(text)
{
// make sure we ignore `&shy;` - which gets inserted
// by the forum's code formatter
text = text.replace(/\u00AD/g,'');
// replace quotes that get auto-replaced by Google Docs and other editors
text = text.replace(/[\u201c\u201d]/g,'"');
text = text.replace(/[\u2018\u2019]/g,'\'');
return text;
}
function getSubString(str, from, len) {
if (len == undefined) {
return str.substr(from, len);
} else {
var s = str.substr(from, len);
while (s.length < len) s+=" ";
return s;
}
};
/** Get a Lexer to parse JavaScript - this is really very nasty right now and it doesn't lex even remotely properly.
* It'll return {type:"type", str:"chars that were parsed", value:"string", startIdx: Index in string of the start, endIdx: Index in string of the end}, until EOF when it returns undefined */
function getLexer(str) {
// Nasty lexer - no comments/etc
var chAlpha="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_$";
var chNum="0123456789";
var chAlphaNum = chAlpha+chNum;
var chWhiteSpace=" \t\n\r";
var chQuotes = "\"'`";
var ch;
var idx = 0;
var lineNumber = 1;
var nextCh = function() {
ch = str[idx++];
if (ch=="\n") lineNumber++;
};
nextCh();
var isIn = function(s,c) { return s.indexOf(c)>=0; } ;
var nextToken = function() {
while (isIn(chWhiteSpace,ch)) {
nextCh();
}
if (ch==undefined) return undefined;
if (ch=="/") {
nextCh();
if (ch=="/") {
// single line comment
while (ch!==undefined && ch!="\n") nextCh();
return nextToken();
} else if (ch=="*") {
nextCh();
var last = ch;
nextCh();
// multiline comment
while (ch!==undefined && !(last=="*" && ch=="/")) {
last = ch;
nextCh();
}
nextCh();
return nextToken();
}
return {type:"CHAR", str:"/", value:"/", startIdx:idx-2, endIdx:idx-1, lineNumber:lineNumber};
}
var s = "";
var type, value;
var startIdx = idx-1;
if (isIn(chAlpha,ch)) { // ID
type = "ID";
do {
s+=ch;
nextCh();
} while (isIn(chAlphaNum,ch));
} else if (isIn(chNum,ch)) { // NUMBER
type = "NUMBER";
do {
s+=ch;
nextCh();
} while (isIn(chNum,ch) || ch==".")
} else if (isIn(chQuotes,ch)) { // STRING
type = "STRING";
var q = ch;
value = "";
s+=ch;
nextCh();
while (ch!==undefined && ch!=q) {
s+=ch;
if (ch=="\\") {
nextCh();
s+=ch;
// FIXME: handle hex/etc correctly here
}
value += ch;
nextCh();
};
if (ch!==undefined) s+=ch;
nextCh();
} else {
type = "CHAR";
s+=ch;
nextCh();
}
if (value===undefined) value=s;
return {type:type, str:s, value:value, startIdx:startIdx, endIdx:idx-1, lineNumber:lineNumber};
};
return {
next : nextToken
};
};
/** Count brackets in a string - will be 0 if all are closed */
function countBrackets(str) {
var lex = getLexer(str);
var brackets = 0;
var tok = lex.next();
while (tok!==undefined) {
if (tok.str=="(" || tok.str=="{" || tok.str=="[") brackets++;
if (tok.str==")" || tok.str=="}" || tok.str=="]") brackets--;
tok = lex.next();
}
return brackets;
}
/** Try and get a prompt from Espruino - if we don't see one, issue Ctrl-C
* and hope it comes back. Calls callback with first argument true if it
had to Ctrl-C out */
function getEspruinoPrompt(callback) {
if (Espruino.Core.Terminal!==undefined &&
Espruino.Core.Terminal.getTerminalLine()==">") {
console.log("Found a prompt... great!");
return callback();
}
var receivedData = "";
var prevReader = Espruino.Core.Serial.startListening(function (readData) {
var bufView = new Uint8Array(readData);
for(var i = 0; i < bufView.length; i++) {
receivedData += String.fromCharCode(bufView[i]);
}
if (receivedData[receivedData.length-1] == ">") {
if (receivedData.substr(-6)=="debug>") {
console.log("Got debug> - sending Ctrl-C to break out and we'll be good");
Espruino.Core.Serial.write('\x03');
} else {
if (receivedData == "\r\n=undefined\r\n>")
receivedData=""; // this was just what we expected - so ignore it
console.log("Received a prompt after sending newline... good!");
clearTimeout(timeout);
nextStep();
}
}
});
// timeout in case something goes wrong...
var hadToBreak = false;
var timeout = setTimeout(function() {
console.log("Got "+JSON.stringify(receivedData));
// if we haven't had the prompt displayed for us, Ctrl-C to break out of what we had
console.log("No Prompt found, got "+JSON.stringify(receivedData[receivedData.length-1])+" - issuing Ctrl-C to try and break out");
Espruino.Core.Serial.write('\x03');
hadToBreak = true;
timeout = setTimeout(function() {
console.log("Still no prompt - issuing another Ctrl-C");
Espruino.Core.Serial.write('\x03');
nextStep();
},500);
},500);
// when we're done...
var nextStep = function() {
// send data to console anyway...
if(prevReader) prevReader(receivedData);
receivedData = "";
// start the previous reader listening again
Espruino.Core.Serial.startListening(prevReader);
// call our callback
if (callback) callback(hadToBreak);
};
// send a newline, and we hope we'll see '=undefined\r\n>'
Espruino.Core.Serial.write('\n');
};
/** Return the value of executing an expression on the board. If
If exprPrintsResult=false/undefined the actual value returned by the expression is returned.
If exprPrintsResult=true, whatever expression prints to the console is returned */
function executeExpression(expressionToExecute, callback, exprPrintsResult) {
var receivedData = "";
var hadDataSinceTimeout = false;
var allDataSent = false;
var progress = 100;
function incrementProgress() {
if (progress==100) {
Espruino.Core.Status.setStatus("Receiving...",100);
progress=0;
} else {
progress++;
Espruino.Core.Status.incrementProgress(1);
}
}
function getProcessInfo(expressionToExecute, callback) {
var prevReader = Espruino.Core.Serial.startListening(function (readData) {
var bufView = new Uint8Array(readData);
for(var i = 0; i < bufView.length; i++) {
receivedData += String.fromCharCode(bufView[i]);
}
if(allDataSent) incrementProgress();
// check if we got what we wanted
var startProcess = receivedData.indexOf("< <<");
var endProcess = receivedData.indexOf(">> >", startProcess);
if(startProcess >= 0 && endProcess > 0){
// All good - get the data!
var result = receivedData.substring(startProcess + 4,endProcess);
console.log("Got "+JSON.stringify(receivedData));
// strip out the text we found
receivedData = receivedData.substr(0,startProcess) + receivedData.substr(endProcess+4);
// Now stop time timeout
if (timeout) clearInterval(timeout);
timeout = "cancelled";
// Do the next stuff
nextStep(result);
} else if (startProcess >= 0) {
// we got some data - so keep waiting...
hadDataSinceTimeout = true;
}
});
// when we're done...
var nextStep = function(result) {
Espruino.Core.Status.setStatus("");
// start the previous reader listing again
Espruino.Core.Serial.startListening(prevReader);
// forward the original text to the previous reader
if(prevReader) prevReader(receivedData);
// run the callback
callback(result);
};
var timeout = undefined;
// Don't Ctrl-C, as we've already got ourselves a prompt with Espruino.Core.Utils.getEspruinoPrompt
var cmd;
if (exprPrintsResult)
cmd = '\x10print("<","<<");'+expressionToExecute+';print(">>",">")\n';
else
cmd = '\x10print("<","<<",JSON.stringify('+expressionToExecute+'),">>",">")\n';
Espruino.Core.Serial.write(cmd,
undefined, function() {
allDataSent = true;
// now it's sent, wait for data
var maxTimeout = 30; // seconds - how long we wait if we're getting data
var minTimeout = 2; // seconds - how long we wait if we're not getting data
var pollInterval = 500; // milliseconds
var timeoutSeconds = 0;
if (timeout != "cancelled") {
timeout = setInterval(function onTimeout(){
incrementProgress();
timeoutSeconds += pollInterval/1000;
// if we're still getting data, keep waiting for up to 10 secs
if (hadDataSinceTimeout && timeoutSeconds<maxTimeout) {
hadDataSinceTimeout = false;
} else if (timeoutSeconds > minTimeout) {
// No data yet...
// OR we keep getting data for > maxTimeout seconds
clearInterval(timeout);
console.warn("No result found for "+JSON.stringify(expressionToExecute)+" - just got "+JSON.stringify(receivedData));
nextStep(undefined);
}
}, pollInterval);
}
});
}
if(Espruino.Core.Serial.isConnected()){
Espruino.Core.Utils.getEspruinoPrompt(function() {
getProcessInfo(expressionToExecute, callback);
});
} else {
console.error("executeExpression called when not connected!");
callback(undefined);
}
};
function versionToFloat(version) {
return parseFloat(version.trim().replace("v","."));
};
/// Gets a URL, and returns callback(data) or callback(undefined) on error
function getURL(url, callback) {
Espruino.callProcessor("getURL", { url : url, data : undefined }, function(result) {
if (result.data!==undefined) {
callback(result.data);
} else {
var resultUrl = result.url ? result.url : url;
if (typeof process === 'undefined') {
// Web browser
var xhr = new XMLHttpRequest();
xhr.responseType = "text";
xhr.addEventListener("load", function () {
if (xhr.status === 200) {
callback(xhr.response.toString());
} else {
console.error("getURL("+JSON.stringify(url)+") error : HTTP "+xhr.status);
callback(undefined);
}
});
xhr.addEventListener("error", function (e) {
console.error("getURL("+JSON.stringify(url)+") error "+e);
callback(undefined);
});
xhr.open("GET", url, true);
xhr.send(null);
} else {
// Node.js
if (resultUrl.substr(0,4)=="http") {
var m = resultUrl[4]=="s"?"https":"http";
var http_options = Espruino.Config.MODULE_PROXY_ENABLED ? {
host: Espruino.Config.MODULE_PROXY_URL,
port: Espruino.Config.MODULE_PROXY_PORT,
path: resultUrl,
} : resultUrl;
require(m).get(http_options, function(res) {
if (res.statusCode != 200) {
console.log("Espruino.Core.Utils.getURL: got HTTP status code "+res.statusCode+" for "+url);
return callback(undefined);
}
var data = "";
res.on("data", function(d) { data += d; });
res.on("end", function() {
callback(data);
});
}).on('error', function(err) {
console.error("getURL("+JSON.stringify(url)+") error : "+err);
callback(undefined);
});
} else {
require("fs").readFile(resultUrl, function(err, d) {
if (err) {
console.error(err);
callback(undefined);
} else
callback(d.toString());
});
}
}
}
});
}
/// Gets a URL as a Binary file, returning callback(err, ArrayBuffer)
var getBinaryURL = function(url, callback) {
console.log("Downloading "+url);
Espruino.Core.Status.setStatus("Downloading binary...");
var xhr = new XMLHttpRequest();
xhr.responseType = "arraybuffer";
xhr.addEventListener("load", function () {
if (xhr.status === 200) {
Espruino.Core.Status.setStatus("Done.");
var data = xhr.response;
callback(undefined,data);
} else
callback("Error downloading file - HTTP "+xhr.status);
});
xhr.addEventListener("error", function () {
callback("Error downloading file");
});
xhr.open("GET", url, true);
xhr.send(null);
};
/// Gets a URL as JSON, and returns callback(data) or callback(undefined) on error
function getJSONURL(url, callback) {
getURL(url, function(d) {
if (!d) return callback(d);
var j;
try { j=JSON.parse(d); } catch (e) { console.error("Unable to parse JSON",d); }
callback(j);
});
}
function isURL(text) {
return (new RegExp( '(http|https)://' )).test(text);
}
/* Are we served from a secure location so we're
forced to use a secure get? */
function needsHTTPS() {
if (typeof window==="undefined" || !window.location) return false;
return window.location.protocol=="https:";
}
/* Open a file load dialog.
options = {
id : ID is to ensure that subsequent calls with the same ID remember the last used directory.
type :
type=="text" => (default) Callback is called with a string
type=="arraybuffer" => Callback is called with an arraybuffer
mimeType : (optional) comma-separated list of accepted mime types for files or extensions (eg. ".js,application/javascript")
callback(contents, mimeType, fileName)
*/
function fileOpenDialog(options, callback) {
options = options||{};
options.type = options.type||"text";
options.id = options.id||"default";
var loaderId = options.id+"FileLoader";
var fileLoader = document.getElementById(loaderId);
if (!fileLoader) {
fileLoader = document.createElement("input");
fileLoader.setAttribute("id", loaderId);
fileLoader.setAttribute("type", "file");
fileLoader.setAttribute("style", "z-index:-2000;position:absolute;top:0px;left:0px;");
if (options.mimeType)
fileLoader.setAttribute("accept",options.mimeType);
fileLoader.addEventListener('click', function(e) {
e.target.value = ''; // handle repeated upload of the same file
});
fileLoader.addEventListener('change', function(e) {
if (!fileLoader.callback) return;
var files = e.target.files;
var file = files[0];
var reader = new FileReader();
reader.onload = function(e) {
/* Doing reader.readAsText(file) interprets the file as UTF8
which we don't want. */
var result;
if (options.type=="text") {
var a = new Uint8Array(e.target.result);
result = "";
for (var i=0;i<a.length;i++)
result += String.fromCharCode(a[i]);
} else
result = e.target.result;
fileLoader.callback(result, file.type, file.name);
fileLoader.callback = undefined;
};
if (options.type=="text" || options.type=="arraybuffer") reader.readAsArrayBuffer(file);
else throw new Error("fileOpenDialog: unknown type "+options.type);
}, false);
document.body.appendChild(fileLoader);
}
fileLoader.callback = callback;
fileLoader.click();
}
// Save a file with a save file dialog
function fileSaveDialog(data, filename) {
function errorHandler() {
Espruino.Core.Notifications.error("Error Saving", true);
}
if (chrome.fileSystem) {
// Chrome Web App / NW.js
chrome.fileSystem.chooseEntry({type: 'saveFile', suggestedName:filename}, function(writableFileEntry) {
if (!writableFileEntry) return; // cancelled
writableFileEntry.createWriter(function(writer) {
var blob = new Blob([data],{ type: "text/plain"} );
writer.onerror = errorHandler;
// when truncation has finished, write
writer.onwriteend = function(e) {
writer.onwriteend = function(e) {
console.log('FileWriter: complete');
};
console.log('FileWriter: writing');
writer.write(blob);
};
// truncate
console.log('FileWriter: truncating');
writer.truncate(blob.size);
}, errorHandler);
});
} else {
var a = document.createElement("a"),
file = new Blob([data], {type: "text/plain"});
var url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
};
/** Bluetooth device names that we KNOW run Espruino */
function recognisedBluetoothDevices() {
return [
"Puck.js", "Pixl.js", "MDBT42Q", "Espruino", "Badge", "Thingy", "RuuviTag", "iTracker", "Smartibot", "Bangle.js",
];
}
/** If we can't find service info, add devices
based only on their name */
function isRecognisedBluetoothDevice(name) {
if (!name) return false;
var devs = recognisedBluetoothDevices();
for (var i=0;i<devs.length;i++)
if (name.substr(0, devs[i].length) == devs[i])
return true;
return false;
}
function getVersion(callback) {
var xmlhttp = new XMLHttpRequest();
var path = (window.location.pathname.indexOf("relay")>=0)?"../":"";
xmlhttp.open('GET', path+'manifest.json');
xmlhttp.onload = function (e) {
var manifest = JSON.parse(xmlhttp.responseText);
callback(manifest.version);
};
xmlhttp.send(null);
}
function getVersionInfo(callback) {
getVersion(function(version) {
var platform = "Web App";
if (isNWApp())
platform = "NW.js Native App";
if (isChromeWebApp())
platform = "Chrome App";
callback(platform+", v"+version);
});
}
// Converts a string to an ArrayBuffer
function stringToArrayBuffer(str) {
var buf=new Uint8Array(str.length);
for (var i=0; i<str.length; i++) {
var ch = str.charCodeAt(i);
if (ch>=256) {
console.warn("stringToArrayBuffer got non-8 bit character - code "+ch);
ch = "?".charCodeAt(0);
}
buf[i] = ch;
}
return buf.buffer;
};
// Converts a string to a Buffer
function stringToBuffer(str) {
var buf = Buffer.alloc(str.length);
for (var i = 0; i < buf.length; i++) {
buf.writeUInt8(str.charCodeAt(i), i);
}
return buf;
};
// Converts a DataView to an ArrayBuffer
function dataViewToArrayBuffer(str) {
var bufView = new Uint8Array(dv.byteLength);
for (var i = 0; i < bufView.length; i++) {
bufView[i] = dv.getUint8(i);
}
return bufView.buffer;
};
// Converts an ArrayBuffer to a string
function arrayBufferToString(str) {
return String.fromCharCode.apply(null, new Uint8Array(buf));
};
/* Parses a JSON string into JS, taking into account some of the issues
with Espruino's JSON from 2v04 and before */
function parseJSONish(str) {
var lex = getLexer(str);
var tok = lex.next();
var final = "";
while (tok!==undefined) {
var s = tok.str;
if (tok.type=="STRING") {
s = s.replace(/\\([0-9])/g,"\\u000$1");
s = s.replace(/\\x(..)/g,"\\u00$1");
}
final += s;
tok = lex.next();
}
return JSON.parse(final);
};
// Does the given string contain only ASCII characters?
function isASCII(str) {
for (var i=0;i<str.length;i++) {
var c = str.charCodeAt(i);
if ((c<32 || c>126) &&
(c!=10) && (c!=13) && (c!=9)) return false;
}
return true;
}
// btoa that works on utf8
function btoa(input) {
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var out = "";
var i=0;
while (i<input.length) {
var octet_a = 0|input.charCodeAt(i++);
var octet_b = 0;
var octet_c = 0;
var padding = 0;
if (i<input.length) {
octet_b = 0|input.charCodeAt(i++);
if (i<input.length) {
octet_c = 0|input.charCodeAt(i++);
padding = 0;
} else
padding = 1;
} else
padding = 2;
var triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
out += b64[(triple >> 18) & 63] +
b64[(triple >> 12) & 63] +
((padding>1)?'=':b64[(triple >> 6) & 63]) +
((padding>0)?'=':b64[triple & 63]);
}
return out;
}
Espruino.Core.Utils = {
init : init,
isWindows : isWindows,
isAppleDevice : isAppleDevice,
getChromeVersion : getChromeVersion,
isNWApp : isNWApp,
isChromeWebApp : isChromeWebApp,
isProgressiveWebApp : isProgressiveWebApp,
hasNativeTitleBar : hasNativeTitleBar,
escapeHTML : escapeHTML,
fixBrokenCode : fixBrokenCode,
getSubString : getSubString,
getLexer : getLexer,
countBrackets : countBrackets,
getEspruinoPrompt : getEspruinoPrompt,
executeExpression : function(expr,callback) { executeExpression(expr,callback,false); },
executeStatement : function(statement,callback) { executeExpression(statement,callback,true); },
versionToFloat : versionToFloat,
getURL : getURL,
getBinaryURL : getBinaryURL,
getJSONURL : getJSONURL,
isURL : isURL,
needsHTTPS : needsHTTPS,
fileOpenDialog : fileOpenDialog,
fileSaveDialog : fileSaveDialog,
recognisedBluetoothDevices : recognisedBluetoothDevices,
isRecognisedBluetoothDevice : isRecognisedBluetoothDevice,
getVersion : getVersion,
getVersionInfo : getVersionInfo,
stringToArrayBuffer : stringToArrayBuffer,
stringToBuffer : stringToBuffer,
dataViewToArrayBuffer : dataViewToArrayBuffer,
arrayBufferToString : arrayBufferToString,
parseJSONish : parseJSONish,
isASCII : isASCII,
btoa : btoa
};
}());
/**
Copyright 2014 Gordon Williams (gw@pur3.co.uk)
This Source Code is subject to the terms of the Mozilla Public
License, v2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
------------------------------------------------------------------
Central place to store and retrieve Options
To use this, on your plugin's `init` function, do something like the
following:
Espruino.Core.Config.add("MAX_FOOBARS", {
section : "Communications", // Heading this will come under in the config screen
name : "Foobars", // Nice name
description : "How many foobars?", // More detail about this
type : "int"/"boolean"/"string"/{ value1:niceName, value2:niceName },
defaultValue : 20,
onChange : function(newValue) { ... }
});
* onChange will be called whenever the value changes from the default
(including when it is loaded)
Then use:
Espruino.Config.MAX_FOOBARS in your code
------------------------------------------------------------------
**/
"use strict";
(function() {
/** See addSection and getSections */
var builtinSections = {};
function _get(callback) {
if (typeof chrome !== 'undefined' && chrome.storage) {
chrome.storage.sync.get( "CONFIGS", function (data) {
var value = data["CONFIGS"];
console.log("GET chrome.storage.sync = "+JSON.stringify(value));
callback(value);
});
} else if (typeof document != "undefined") {
var data = {};
var cookie = document.cookie;
if (cookie!==undefined && cookie.indexOf("CONFIG=")>=0) {
cookie = cookie.substring(cookie.indexOf("CONFIG=")+7);
cookie = cookie.substring(0,cookie.indexOf(";"));
try {
var json = atob(cookie);
data = JSON.parse(json);
} catch (e) {
console.log("Got ", e, " while reading info");
}
}
callback(data);
} else {
callback({});
}
}
function _set(data) {
if (typeof chrome !== 'undefined' && chrome.storage) {
console.log("SET chrome.storage.sync = "+JSON.stringify(data));
chrome.storage.sync.set({ CONFIGS : data });
} else if (typeof document != "undefined") {
document.cookie = "CONFIG="+btoa(JSON.stringify(data));
}
}
function loadConfiguration(callback) {
_get(function (value) {
for (var key in value) {
if (key=="set") continue;
Espruino.Config[key] = value[key];
if (Espruino.Core.Config.data[key] !== undefined &&
Espruino.Core.Config.data[key].onChange !== undefined)
Espruino.Core.Config.data[key].onChange(value[key]);
}
if (callback!==undefined)
callback();
});
}
function init() {
addSection("General", { sortOrder:100, description: "General Web IDE Settings" });
addSection("Communications", { sortOrder:200, description: "Settings for communicating with the Espruino Board" });
addSection("Board", { sortOrder:300, description: "Settings for the Espruino Board itself" });
}
function add(name, options) {
Espruino.Core.Config.data[name] = options;
if (Espruino.Config[name] === undefined)
Espruino.Config[name] = options.defaultValue;
}
/** Add a section (or information on the page).
* options = {
* sortOrder : int, // a number used for sorting
* description : "",
* getHTML : function(callback(html)) // optional
* };
*/
function addSection(name, options) {
options.name = name;
builtinSections[name] = options;
}
/** Get an object containing the information on a section used in configs */
function getSection(name) {
if (builtinSections[name]!==undefined)
return builtinSections[name];
// not found - but we warned about this in getSections
return {
name : name
};
}
/** Get an object containing information on all 'sections' used in all the configs */
function getSections() {
var sections = [];
// add sections we know about
for (var name in builtinSections)
sections.push(builtinSections[name]);
// add other sections
for (var i in Espruino.Core.Config.data) {
var c = Espruino.Core.Config.data[i];
var found = false;
for (var s in sections)
if (sections[s].name == c.section)
found = true;
if (!found) {
console.warn("Section named "+c.section+" was not added with Config.addSection");
sections[c.section] = {
name : c.section,
sortOrder : 0
};
}
}
// Now sort by sortOrder
sections.sort(function (a,b) { return a.sortOrder - b.sortOrder; });
return sections;
}
Espruino.Config = {};
Espruino.Config.set = function (key, value) {
if (Espruino.Config[key] != value) {
Espruino.Config[key] = value;
// Do the callback
if (Espruino.Core.Config.data[key] !== undefined &&
Espruino.Core.Config.data[key].onChange !== undefined)
Espruino.Core.Config.data[key].onChange(value);
// Save to synchronized storage...
var data = {};
for (var key in Espruino.Config)
if (key != "set")
data[key] = Espruino.Config[key];
_set(data);
}
};
function clearAll() { // clear all settings
_set({});
for (var name in Espruino.Core.Config.data) {
var options = Espruino.Core.Config.data[name];
Espruino.Config[name] = options.defaultValue;
}
}
Espruino.Core.Config = {
loadConfiguration : loadConfiguration, // special - called before init
init : init,
add : add,
data : {},
addSection : addSection,
getSection : getSection,
getSections : getSections,
clearAll : clearAll, // clear all settings
};
})();
/*
Gordon Williams (gw@pur3.co.uk)
Common entrypoint for all communications from the IDE. This handles
all serial_*.js connection types and passes calls to the correct one.
To add a new serial device, you must add an object to
Espruino.Core.Serial.devices:
Espruino.Core.Serial.devices.push({
"name" : "Test", // Name, when initialising
"init" : function() // Gets called at startup
"getPorts": function(callback) // calls 'callback' with an array of ports:
callback([{path:"TEST", // path passed to 'open' (and displayed to user)
description:"test", // description displayed to user
type:"test", // bluetooth|usb|socket - used to show icon in UI
// autoconnect : true // automatically conect to this (without the connect menu)
}], true); // instantPorts - will getPorts return all the ports on the first call, or does it need multiple calls (eg. Bluetooth)
"open": function(path, openCallback, receiveCallback, disconnectCallback),
"write": function(dataAsString, callbackWhenWritten)
"close": function(),
"maxWriteLength": 20, // optional - the maximum amount of characters that should be given to 'write' at a time
});
*/
(function() {
// List of ports and the devices they map to
var portToDevice = undefined;
// The current connected device (from Espruino.Core.Serial.devices)
var currentDevice = undefined;
// called when data received
var readListener = undefined;
// are we sending binary data? If so, don't automatically insert breaks for stuff like Ctrl-C
var sendingBinary = false;
// For throttled write
var slowWrite = true;
var writeData = [];
var writeTimeout = undefined;
/// flow control XOFF received - we shouldn't send anything
var flowControlXOFF = false;
function init() {
Espruino.Core.Config.add("BAUD_RATE", {
section : "Communications",
name : "Baud Rate",
description : "When connecting over serial, this is the baud rate that is used. 9600 is the default for Espruino",
type : {9600:9600,14400:14400,19200:19200,28800:28800,38400:38400,57600:57600,115200:115200},
defaultValue : 9600,
});
Espruino.Core.Config.add("SERIAL_IGNORE", {
section : "Communications",
name : "Ignore Serial Ports",
description : "A '|' separated list of serial port paths to ignore, eg `/dev/ttyS*|/dev/*.SOC`",
type : "string",
defaultValue : "/dev/ttyS*|/dev/*.SOC|/dev/*.MALS"
});
Espruino.Core.Config.add("SERIAL_FLOW_CONTROL", {
section : "Communications",
name : "Software Flow Control",
description : "Respond to XON/XOFF flow control characters to throttle data uploads. By default Espruino sends XON/XOFF for USB and Bluetooth (on 2v05+).",
type : "boolean",
defaultValue : true
});
var devices = Espruino.Core.Serial.devices;
for (var i=0;i<devices.length;i++) {
console.log(" - Initialising Serial "+devices[i].name);
if (devices[i].init)
devices[i].init();
}
}
var startListening=function(callback) {
var oldListener = readListener;
readListener = callback;
return oldListener;
};
/* Calls 'callback(port_list, shouldCallAgain)'
'shouldCallAgain==true' means that more devices
may appear later on (eg Bluetooth LE).*/
var getPorts=function(callback) {
var ports = [];
var newPortToDevice = [];
// get all devices
var responses = 0;
var devices = Espruino.Core.Serial.devices;
if (!devices || devices.length==0) {
portToDevice = newPortToDevice;
return callback(ports, false);
}
var shouldCallAgain = false;
devices.forEach(function (device) {
//console.log("getPorts -->",device.name);
device.getPorts(function(devicePorts, instantPorts) {
//console.log("getPorts <--",device.name);
if (instantPorts===false) shouldCallAgain = true;
if (devicePorts) {
devicePorts.forEach(function(port) {
var ignored = false;
if (Espruino.Config.SERIAL_IGNORE)
Espruino.Config.SERIAL_IGNORE.split("|").forEach(function(wildcard) {
var regexp = "^"+wildcard.replace(/\./g,"\\.").replace(/\*/g,".*")+"$";
if (port.path.match(new RegExp(regexp)))
ignored = true;
});
if (!ignored) {
if (port.usb && port.usb[0]==0x0483 && port.usb[1]==0x5740)
port.description = "Espruino board";
ports.push(port);
newPortToDevice[port.path] = device;
}
});
}
responses++;
if (responses == devices.length) {
portToDevice = newPortToDevice;
ports.sort(function(a,b) {
if (a.unimportant && !b.unimportant) return 1;
if (b.unimportant && !a.unimportant) return -1;
return 0;
});
callback(ports, shouldCallAgain);
}
});
});
};
var openSerial=function(serialPort, connectCallback, disconnectCallback) {
return openSerialInternal(serialPort, connectCallback, disconnectCallback, 2);
}
var openSerialInternal=function(serialPort, connectCallback, disconnectCallback, attempts) {
/* If openSerial is called, we need to have called getPorts first
in order to figure out which one of the serial_ implementations
we must call into. */
if (portToDevice === undefined) {
portToDevice = []; // stop recursive calls if something errors
return getPorts(function() {
openSerialInternal(serialPort, connectCallback, disconnectCallback, attempts);
});
}
if (!(serialPort in portToDevice)) {
if (serialPort.toLowerCase() in portToDevice) {
serialPort = serialPort.toLowerCase();
} else {
if (attempts>0) {
console.log("Port "+JSON.stringify(serialPort)+" not found - checking ports again ("+attempts+" attempts left)");
return getPorts(function() {
openSerialInternal(serialPort, connectCallback, disconnectCallback, attempts-1);
});
} else {
console.error("Port "+JSON.stringify(serialPort)+" not found");
return connectCallback(undefined);
}
}
}
connectionInfo = undefined;
flowControlXOFF = false;
currentDevice = portToDevice[serialPort];
currentDevice.open(serialPort, function(cInfo) { // CONNECT
if (!cInfo) {
// Espruino.Core.Notifications.error("Unable to connect");
console.error("Unable to open device (connectionInfo="+cInfo+")");
connectCallback(undefined);
} else {
connectionInfo = cInfo;
connectedPort = serialPort;
console.log("Connected", cInfo);
var portInfo = { port:serialPort };
if (connectionInfo.portName)
portInfo.portName = connectionInfo.portName;
Espruino.callProcessor("connected", portInfo, function() {
connectCallback(cInfo);
});
}
}, function(data) { // RECEIEVE DATA
if (!(data instanceof ArrayBuffer)) console.warn("Serial port implementation is not returning ArrayBuffers");
if (Espruino.Config.SERIAL_FLOW_CONTROL) {
var u = new Uint8Array(data);
for (var i=0;i<u.length;i++) {
if (u[i]==17) { // XON
console.log("XON received => resume upload");
flowControlXOFF = false;
}
if (u[i]==19) { // XOFF
console.log("XOFF received => pause upload");
flowControlXOFF = true;
}
}
}
if (readListener) readListener(data);
}, function() { // DISCONNECT
currentDevice = undefined;
if (!connectionInfo) {
// we got a disconnect when we hadn't connected...
// Just call connectCallback(undefined), don't bother sending disconnect
connectCallback(undefined);
return;
}
connectionInfo = undefined;
if (writeTimeout!==undefined)
clearTimeout(writeTimeout);
writeTimeout = undefined;
writeData = [];
sendingBinary = false;
flowControlXOFF = false;
Espruino.callProcessor("disconnected", undefined, function() {
disconnectCallback();
});
});
};
var str2ab=function(str) {
var buf=new ArrayBuffer(str.length);
var bufView=new Uint8Array(buf);
for (var i=0; i<str.length; i++) {
var ch = str.charCodeAt(i);
if (ch>=256) {
console.warn("Attempted to send non-8 bit character - code "+ch);
ch = "?".charCodeAt(0);
}
bufView[i] = ch;
}
return buf;
};
var closeSerial=function() {
if (currentDevice) {
currentDevice.close();
currentDevice = undefined;
} else
console.error("Close called, but serial port not open");
};
var isConnected = function() {
return currentDevice!==undefined;
};
var writeSerialWorker = function(isStarting) {
writeTimeout = undefined; // we've been called
// check flow control
if (flowControlXOFF) {
/* flow control was enabled - bit hacky (we could use a callback)
but safe - just check again in a bit to see if we should send */
writeTimeout = setTimeout(function() {
writeSerialWorker();
}, 50);
return;
}
// if we disconnected while sending, empty queue
if (currentDevice === undefined) {
if (writeData[0].callback)
writeData[0].callback();
writeData.shift();
if (writeData.length) setTimeout(function() {
writeSerialWorker(false);
}, 1);
return;
}
if (writeData[0].data === "") {
if (writeData[0].showStatus)
Espruino.Core.Status.setStatus("Sent");
if (writeData[0].callback)
writeData[0].callback();
writeData.shift(); // remove this empty first element
if (!writeData.length) return; // anything left to do?
isStarting = true;
}
if (isStarting) {
var blockSize = 512;
if (currentDevice.maxWriteLength)
blockSize = currentDevice.maxWriteLength;
/* if we're throttling our writes we want to send small
* blocks of data at once. We still limit the size of
* sent blocks to 512 because on Mac we seem to lose
* data otherwise (not on any other platforms!) */
if (slowWrite) blockSize=19;
writeData[0].blockSize = blockSize;
writeData[0].showStatus &= writeData[0].data.length>writeData[0].blockSize;
if (writeData[0].showStatus) {
Espruino.Core.Status.setStatus("Sending...", writeData[0].data.length);
console.log("---> "+JSON.stringify(writeData[0].data));
}
}
// Initial split use previous, or don't
var d = undefined;
var split = writeData[0].nextSplit || { start:0, end:writeData[0].data.length, delay:0 };
// if we get something like Ctrl-C or `reset`, wait a bit for it to complete
if (!sendingBinary) {
function findSplitIdx(prev, substr, delay, reason) {
var match = writeData[0].data.match(substr);
// not found
if (match===null) return prev;
// or previous find was earlier in str
var end = match.index + match[0].length;
if (end > prev.end) return prev;
// found, and earlier
prev.start = match.index;
prev.end = end;
prev.delay = delay;
prev.match = match[0];
prev.reason = reason;
return prev;
}
split = findSplitIdx(split, /\x03/, 250, "Ctrl-C"); // Ctrl-C
split = findSplitIdx(split, /reset\(\);\n/, 250, "reset()"); // Reset
split = findSplitIdx(split, /load\(\);\n/, 250, "load()"); // Load
split = findSplitIdx(split, /Modules.addCached\("[^\n]*"\);\n/, 250, "Modules.addCached"); // Adding a module
split = findSplitIdx(split, /\x10require\("Storage"\).write\([^\n]*\);\n/, 500, "Storage.write"); // Write chunk of data
}
// Otherwise split based on block size
if (!split.match || split.end >= writeData[0].blockSize) {
if (split.match) writeData[0].nextSplit = split;
split = { start:0, end:writeData[0].blockSize, delay:0 };
}
if (split.match) console.log("Splitting for "+split.reason+", delay "+split.delay);
// Only send some of the data
if (writeData[0].data.length>split.end) {
if (slowWrite && split.delay==0) split.delay=50;
d = writeData[0].data.substr(0,split.end);
writeData[0].data = writeData[0].data.substr(split.end);
if (writeData[0].nextSplit) {
writeData[0].nextSplit.start -= split.end;
writeData[0].nextSplit.end -= split.end;
if (writeData[0].nextSplit.end<=0)
writeData[0].nextSplit = undefined;
}
} else {
d = writeData[0].data;
writeData[0].data = "";
writeData[0].nextSplit = undefined;
}
// update status
if (writeData[0].showStatus)
Espruino.Core.Status.incrementProgress(d.length);
// actually write data
//console.log("Sending block "+JSON.stringify(d)+", wait "+split.delay+"ms");
currentDevice.write(d, function() {
// Once written, start timeout
writeTimeout = setTimeout(function() {
writeSerialWorker();
}, split.delay);
});
}
// Throttled serial write
var writeSerial = function(data, showStatus, callback) {
if (showStatus===undefined) showStatus=true;
/* Queue our data to write. If there was previous data and no callback to
invoke on this data or the previous then just append data. This would happen
if typing in the terminal for example. */
if (!callback && writeData.length && !writeData[writeData.length-1].callback) {
writeData[writeData.length-1].data += data;
} else {
writeData.push({data:data,callback:callback,showStatus:showStatus});
/* if this is our first data, start sending now. Otherwise we're already
busy sending and will pull data off writeData when ready */
if (writeData.length==1)
writeSerialWorker(true);
}
};
// ----------------------------------------------------------
Espruino.Core.Serial = {
"devices" : [], // List of devices that can provide a serial API
"init" : init,
"getPorts": getPorts,
"open": openSerial,
"isConnected": isConnected,
"startListening": startListening,
"write": writeSerial,
"close": closeSerial,
"isSlowWrite": function() { return slowWrite; },
"setSlowWrite": function(isOn, force) {
if ((!force) && Espruino.Config.SERIAL_THROTTLE_SEND) {
console.log("ForceThrottle option is set - set Slow Write = true");
isOn = true;
} else
console.log("Set Slow Write = "+isOn);
slowWrite = isOn;
},
"setBinary": function(isOn) {
sendingBinary = isOn;
}
};
})();
/**
Copyright 2014 Gordon Williams (gw@pur3.co.uk)
This Source Code is subject to the terms of the Mozilla Public
License, v2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
------------------------------------------------------------------
The plugin that actually writes code out to Espruino
------------------------------------------------------------------
**/
"use strict";
(function(){
function init() {
Espruino.Core.Config.add("RESET_BEFORE_SEND", {
section : "Communications",
name : "Reset before Send",
description : "Reset Espruino before sending code from the editor pane?",
type : "boolean",
defaultValue : true
});
Espruino.Core.Config.add("STORE_LINE_NUMBERS", {
section : "Communications",
name : "Store line numbers",
description : "Should Espruino store line numbers for each function? This uses one extra variable per function, but allows you to get source code debugging in the Web IDE",
type : "boolean",
defaultValue : true
});
}
function writeToEspruino(code, callback) {
/* hack around non-K&R code formatting that would have
broken Espruino CLI's bracket counting */
code = reformatCode(code);
if (code === undefined) return; // it should already have errored
// We want to make sure we've got a prompt before sending. If not,
// this will issue a Ctrl+C
Espruino.Core.Utils.getEspruinoPrompt(function() {
// Make sure code ends in 2 newlines
while (code[code.length-2]!="\n" || code[code.length-1]!="\n")
code += "\n";
// If we're supposed to reset Espruino before sending...
if (Espruino.Config.RESET_BEFORE_SEND) {
code = "\x10reset();\n"+code;
}
//console.log("Sending... "+data);
Espruino.Core.Serial.write(code, true, function() {
// give 5 seconds for sending with save and 2 seconds without save
var count = Espruino.Config.SAVE_ON_SEND ? 50 : 20;
setTimeout(function cb() {
if (Espruino.Core.Terminal!==undefined &&
Espruino.Core.Terminal.getTerminalLine()!=">") {
count--;
if (count>0) {
setTimeout(cb, 100);
} else {
Espruino.Core.Notifications.error("Prompt not detected - upload failed. Trying to recover...");
Espruino.Core.Serial.write("\x03\x03echo(1)\n", false, callback);
}
} else {
if (callback) callback();
}
}, 100);
});
});
};
/// Parse and fix issues like `if (false)\n foo` in the root scope
function reformatCode(code) {
var APPLY_LINE_NUMBERS = false;
var lineNumberOffset = 0;
var ENV = Espruino.Core.Env.getData();
if (ENV && ENV.VERSION_MAJOR && ENV.VERSION_MINOR) {
if (ENV.VERSION_MAJOR>1 ||
ENV.VERSION_MINOR>=81.086) {
if (Espruino.Config.STORE_LINE_NUMBERS)
APPLY_LINE_NUMBERS = true;
}
}
// Turn cr/lf into just lf (eg. windows -> unix)
code = code.replace(/\r\n/g,"\n");
// First off, try and fix funky characters
for (var i=0;i<code.length;i++) {
var ch = code.charCodeAt(i);
if ((ch<32 || ch>255) && ch!=9/*Tab*/ && ch!=10/*LF*/ && ch!=13/*CR*/) {
console.warn("Funky character code "+ch+" at position "+i+". Replacing with ?");
code = code.substr(0,i)+"?"+code.substr(i+1);
}
}
/* Search for lines added to the start of the code by the module handler.
Ideally there would be a better way of doing this so line numbers stayed correct,
but this hack works for now. Fixes EspruinoWebIDE#140 */
if (APPLY_LINE_NUMBERS) {
var l = code.split("\n");
var i = 0;
while (l[i] && (l[i].substr(0,8)=="Modules." ||
l[i].substr(0,8)=="setTime(")) i++;
lineNumberOffset = -i;
}
var resultCode = "\x10"; // 0x10 = echo off for line
/** we're looking for:
* `a = \n b`
* `for (.....) \n X`
* `if (.....) \n X`
* `if (.....) { } \n else foo`
* `while (.....) \n X`
* `do \n X`
* `function (.....) \n X`
* `function N(.....) \n X`
* `var a \n , b` `var a = 0 \n, b`
* `var a, \n b` `var a = 0, \n b`
* `a \n . b`
* `foo() \n . b`
* `try { } \n catch \n () \n {}`
*
* These are divided into two groups - where there are brackets
* after the keyword (statementBeforeBrackets) and where there aren't
* (statement)
*
* We fix them by replacing \n with what you get when you press
* Alt+Enter (Ctrl + LF). This tells Espruino that it's a newline
* but NOT to execute.
*/
var lex = Espruino.Core.Utils.getLexer(code);
var brackets = 0;
var curlyBrackets = 0;
var statementBeforeBrackets = false;
var statement = false;
var varDeclaration = false;
var lastIdx = 0;
var lastTok = {str:""};
var tok = lex.next();
while (tok!==undefined) {
var previousString = code.substring(lastIdx, tok.startIdx);
var tokenString = code.substring(tok.startIdx, tok.endIdx);
//console.log("prev "+JSON.stringify(previousString)+" next "+tokenString);
/* Inserting Alt-Enter newline, which adds newline without trying
to execute */
if (brackets>0 || // we have brackets - sending the alt-enter special newline means Espruino doesn't have to do a search itself - faster.
statement || // statement was before brackets - expecting something else
statementBeforeBrackets || // we have an 'if'/etc
varDeclaration || // variable declaration then newline
tok.str=="," || // comma on newline - there was probably something before
tok.str=="." || // dot on newline - there was probably something before
tok.str=="+" || tok.str=="-" || // +/- on newline - there was probably something before
tok.str=="=" || // equals on newline - there was probably something before
tok.str=="else" || // else on newline
lastTok.str=="else" || // else befgore newline
tok.str=="catch" || // catch on newline - part of try..catch
lastTok.str=="catch"
) {
//console.log("Possible"+JSON.stringify(previousString));
previousString = previousString.replace(/\n/g, "\x1B\x0A");
}
var previousBrackets = brackets;
if (tok.str=="(" || tok.str=="{" || tok.str=="[") brackets++;
if (tok.str=="{") curlyBrackets++;
if (tok.str==")" || tok.str=="}" || tok.str=="]") brackets--;
if (tok.str=="}") curlyBrackets--;
if (brackets==0) {
if (tok.str=="for" || tok.str=="if" || tok.str=="while" || tok.str=="function" || tok.str=="throw") {
statementBeforeBrackets = true;
varDeclaration = false;
} else if (tok.str=="var") {
varDeclaration = true;
} else if (tok.type=="ID" && lastTok.str=="function") {
statementBeforeBrackets = true;
} else if (tok.str=="try" || tok.str=="catch") {
statementBeforeBrackets = true;
} else if (tok.str==")" && statementBeforeBrackets) {
statementBeforeBrackets = false;
statement = true;
} else if (["=","^","&&","||","+","+=","-","-=","*","*=","/","/=","%","%=","&","&=","|","|="].indexOf(tok.str)>=0) {
statement = true;
} else {
if (tok.str==";") varDeclaration = false;
statement = false;
statementBeforeBrackets = false;
}
}
/* If we're at root scope and had whitespace/comments between code,
remove it all and replace it with a single newline and a
0x10 (echo off for line) character. However DON'T do this if we had
an alt-enter in the line, as it was there to stop us executing
prematurely */
if (previousBrackets==0 &&
previousString.indexOf("\n")>=0 &&
previousString.indexOf("\x1B\x0A")<0) {
previousString = "\n\x10";
// Apply line numbers to each new line sent, to aid debugger
if (APPLY_LINE_NUMBERS && tok.lineNumber && (tok.lineNumber+lineNumberOffset)>0) {
// Esc [ 1234 d
// This is the 'set line number' command that we're abusing :)
previousString += "\x1B\x5B"+(tok.lineNumber+lineNumberOffset)+"d";
}
}
// add our stuff back together
resultCode += previousString+tokenString;
// next
lastIdx = tok.endIdx;
lastTok = tok;
tok = lex.next();
}
//console.log(resultCode);
if (brackets>0) {
Espruino.Core.Notifications.error("You have more open brackets than close brackets. Please see the hints in the Editor window.");
return undefined;
}
if (brackets<0) {
Espruino.Core.Notifications.error("You have more close brackets than open brackets. Please see the hints in the Editor window.");
return undefined;
}
return resultCode;
};
Espruino.Core.CodeWriter = {
init : init,
writeToEspruino : writeToEspruino,
};
}());
/**
Copyright 2014 Gordon Williams (gw@pur3.co.uk)
This Source Code is subject to the terms of the Mozilla Public
License, v2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
------------------------------------------------------------------
Automatically load any referenced modules
------------------------------------------------------------------
**/
"use strict";
(function(){
function init() {
Espruino.Core.Config.add("MODULE_URL", {
section : "Communications",
name : "Module URL",
description : "Where to search online for modules when `require()` is used",
type : "string",
defaultValue : "https://www.espruino.com/modules"
});
Espruino.Core.Config.add("MODULE_EXTENSIONS", {
section : "Communications",
name : "Module Extensions",
description : "The file extensions to use for each module. These are checked in order and the first that exists is used. One or more file extensions (including the dot) separated by `|`",
type : "string",
defaultValue : ".min.js|.js"
});
Espruino.Core.Config.add("MODULE_AS_FUNCTION", {
section : "Communications",
name : "Modules uploaded as functions",
description : "Espruino 1v90 and later ONLY. Upload modules as Functions, allowing any functions inside them to be loaded directly from flash when 'Save on Send' is enabled.",
type : "boolean",
defaultValue : true
});
Espruino.Core.Config.add("MODULE_PROXY_ENABLED", {
section : "Communications",
name : "Enable Proxy",
description : "Enable Proxy for loading the modules when `require()` is used (only in native IDE)",
type : "boolean",
defaultValue : false
});
Espruino.Core.Config.add("MODULE_PROXY_URL", {
section : "Communications",
name : "Proxy URL",
description : "Proxy URL for loading the modules when `require()` is used (only in native IDE)",
type : "string",
defaultValue : ""
});
Espruino.Core.Config.add("MODULE_PROXY_PORT", {
section : "Communications",
name : "Proxy Port",
description : "Proxy Port for loading the modules when `require()` is used (only in native IDE)",
type : "string",
defaultValue : ""
});
// When code is sent to Espruino, search it for modules and add extra code required to load them
Espruino.addProcessor("transformForEspruino", function(code, callback) {
loadModules(code, callback);
});
// Append the 'getModule' processor as the last (plugins get initialized after Espruino.Core modules)
Espruino.Plugins.CoreModules = {
init: function() {
Espruino.addProcessor("getModule", function(data, callback) {
if (data.moduleCode!==undefined) { // already provided be previous getModule processor
return callback(data);
}
fetchGetModule(data, callback);
});
}
};
}
function isBuiltIn(module) {
var d = Espruino.Core.Env.getData();
// If we got data from the device itself, use that as the
// definitive answer
if ("string" == typeof d.MODULES)
return d.MODULES.split(",").indexOf(module)>=0;
// Otherwise try and figure it out from JSON
if ("info" in d &&
"builtin_modules" in d.info &&
d.info.builtin_modules.indexOf(module)>=0)
return true;
// Otherwise assume we don't have it
return false;
}
/** Find any instances of require(...) in the code string and return a list */
var getModulesRequired = function(code) {
var modules = [];
var lex = Espruino.Core.Utils.getLexer(code);
var tok = lex.next();
var state = 0;
while (tok!==undefined) {
if (state==0 && tok.str=="require") {
state=1;
} else if (state==1 && tok.str=="(") {
state=2;
} else if (state==2 && (tok.type=="STRING")) {
state=0;
var module = tok.value;
if (!isBuiltIn(module) && modules.indexOf(module)<0)
modules.push(module);
} else
state = 0;
tok = lex.next();
}
return modules;
};
/** Download modules from MODULE_URL/.. */
function fetchGetModule(data, callback) {
var fullModuleName = data.moduleName;
// try and load the module the old way...
console.log("loadModule("+fullModuleName+")");
var urls = []; // Array of where to look for this module
var modName; // Simple name of the module
if(Espruino.Core.Utils.isURL(fullModuleName)) {
modName = fullModuleName.substr(fullModuleName.lastIndexOf("/") + 1).split(".")[0];
urls = [ fullModuleName ];
} else {
modName = fullModuleName;
Espruino.Config.MODULE_URL.split("|").forEach(function (url) {
url = url.trim();
if (url.length!=0)
Espruino.Config.MODULE_EXTENSIONS.split("|").forEach(function (extension) {
urls.push(url + "/" + fullModuleName + extension);
})
});
};
// Recursively go through all the urls
(function download(urls) {
if (urls.length==0) {
return callback(data);
}
var dlUrl = urls[0];
Espruino.Core.Utils.getURL(dlUrl, function (code) {
if (code!==undefined) {
// we got it!
data.moduleCode = code;
data.isMinified = dlUrl.substr(-7)==".min.js";
return callback(data);
} else {
// else try next
download(urls.slice(1));
}
});
})(urls);
}
/** Called from loadModule when a module is loaded. Parse it for other modules it might use
* and resolve dfd after all submodules have been loaded */
function moduleLoaded(resolve, requires, modName, data, loadedModuleData, alreadyMinified){
// Check for any modules used from this module that we don't already have
var newRequires = getModulesRequired(data);
console.log(" - "+modName+" requires "+JSON.stringify(newRequires));
// if we need new modules, set them to load and get their promises
var newPromises = [];
for (var i in newRequires) {
if (requires.indexOf(newRequires[i])<0) {
console.log(" Queueing "+newRequires[i]);
requires.push(newRequires[i]);
newPromises.push(loadModule(requires, newRequires[i], loadedModuleData));
} else {
console.log(" Already loading "+newRequires[i]);
}
}
var loadProcessedModule = function (module) {
// if we needed to load something, wait until it's loaded before resolving this
Promise.all(newPromises).then(function(){
// add the module to end of our array
if (Espruino.Config.MODULE_AS_FUNCTION)
loadedModuleData.push("Modules.addCached(" + JSON.stringify(module.name) + ",function(){" + module.code + "});");
else
loadedModuleData.push("Modules.addCached(" + JSON.stringify(module.name) + "," + JSON.stringify(module.code) + ");");
// We're done
resolve();
});
}
if (alreadyMinified)
loadProcessedModule({code:data,name:modName});
else
Espruino.callProcessor("transformModuleForEspruino", {code:data,name:modName}, loadProcessedModule);
}
/** Given a module name (which could be a URL), try and find it. Return
* a deferred thingybob which signals when we're done. */
function loadModule(requires, fullModuleName, loadedModuleData) {
return new Promise(function(resolve, reject) {
// First off, try and find this module using callProcessor
Espruino.callProcessor("getModule",
{ moduleName:fullModuleName, moduleCode:undefined, isMinified:false },
function(data) {
if (data.moduleCode===undefined) {
Espruino.Core.Notifications.warning("Module "+fullModuleName+" not found");
return resolve();
}
// great! it found something. Use it.
moduleLoaded(resolve, requires, fullModuleName, data.moduleCode, loadedModuleData, data.isMinified);
});
});
}
/** Finds instances of 'require' and then ensures that
those modules are loaded into the module cache beforehand
(by inserting the relevant 'addCached' commands into 'code' */
function loadModules(code, callback){
var loadedModuleData = [];
var requires = getModulesRequired(code);
if (requires.length == 0) {
// no modules needed - just return
callback(code);
} else {
Espruino.Core.Status.setStatus("Loading modules");
// Kick off the module loading (each returns a promise)
var promises = requires.map(function (moduleName) {
return loadModule(requires, moduleName, loadedModuleData);
});
// When all promises are complete
Promise.all(promises).then(function(){
callback(loadedModuleData.join("\n") + "\n" + code);
});
}
};
Espruino.Core.Modules = {
init : init
};
}());
/**
Copyright 2014 Gordon Williams (gw@pur3.co.uk)
This Source Code is subject to the terms of the Mozilla Public
License, v2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
------------------------------------------------------------------
Board Environment variables (process.env) - queried when board connects
------------------------------------------------------------------
**/
"use strict";
(function(){
var environmentData = {};
var boardData = {};
function init() {
Espruino.Core.Config.add("ENV_ON_CONNECT", {
section : "Communications",
name : "Request board details on connect",
description : 'Just after the board is connected, should we query `process.env` to find out which board we\'re connected to? '+
'This enables the Web IDE\'s code completion, compiler features, and firmware update notice.',
type : "boolean",
defaultValue : true,
});
Espruino.addProcessor("connected", function(data, callback) {
// Give us some time for any stored data to come in
setTimeout(queryBoardProcess, 200, data, callback);
});
}
function queryBoardProcess(data, callback) {
if ((!Espruino.Config.ENV_ON_CONNECT) ||
(Espruino.Core.MenuFlasher && Espruino.Core.MenuFlasher.isFlashing())) {
return callback(data);
}
Espruino.Core.Utils.executeExpression("process.env", function(result) {
var json = {};
if (result!==undefined) {
try {
json = JSON.parse(result);
} catch (e) {
console.log("JSON parse failed - " + e + " in " + JSON.stringify(result));
}
}
if (Object.keys(json).length==0) {
Espruino.Core.Notifications.error("Unable to retrieve board information.\nConnection Error?");
// make sure we don't remember a previous board's info
json = {
VERSION : undefined,
BOARD : undefined,
MODULES : undefined,
EXPTR : undefined
};
} else {
if (json.BOARD && json.VERSION)
Espruino.Core.Notifications.info("Found " +json.BOARD+", "+json.VERSION);
}
// now process the enviroment variables
for (var k in json) {
boardData[k] = json[k];
environmentData[k] = json[k];
}
if (environmentData.VERSION) {
var v = environmentData.VERSION;
var vIdx = v.indexOf("v");
if (vIdx>=0) {
environmentData.VERSION_MAJOR = parseInt(v.substr(0,vIdx));
var minor = v.substr(vIdx+1);
var dot = minor.indexOf(".");
if (dot>=0)
environmentData.VERSION_MINOR = parseInt(minor.substr(0,dot)) + parseInt(minor.substr(dot+1))*0.001;
else
environmentData.VERSION_MINOR = parseFloat(minor);
}
}
Espruino.callProcessor("environmentVar", environmentData, function(envData) {
environmentData = envData;
callback(data);
});
});
}
/** Get all data merged in from the board */
function getData() {
return environmentData;
}
/** Get just the board's environment data */
function getBoardData() {
return boardData;
}
/** Get a list of boards that we know about */
function getBoardList(callback) {
var jsonDir = Espruino.Config.BOARD_JSON_URL;
// ensure jsonDir ends with slash
if (jsonDir.indexOf('/', jsonDir.length - 1) === -1) {
jsonDir += '/';
}
Espruino.Core.Utils.getJSONURL(jsonDir + "boards.json", function(boards){
// now load all the individual JSON files
var promises = [];
for (var boardId in boards) {
promises.push((function() {
var id = boardId;
return new Promise(function(resolve, reject) {
Espruino.Core.Utils.getJSONURL(jsonDir + boards[boardId].json, function (data) {
boards[id]["json"] = data;
resolve();
});
});
})());
}
// When all are loaded, load the callback
Promise.all(promises).then(function() {
callback(boards);
});
});
}
Espruino.Core.Env = {
init : init,
getData : getData,
getBoardData : getBoardData,
getBoardList : getBoardList,
};
}());
/**
Copyright 2014 Gordon Williams (gw@pur3.co.uk)
This Source Code is subject to the terms of the Mozilla Public
License, v2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
------------------------------------------------------------------
Try and get any URLS that are from GitHub
------------------------------------------------------------------
**/
"use strict";
(function(){
function init() {
Espruino.addProcessor("getURL", getGitHub);
}
function getGitHub(data, callback) {
var match = data.url.match(/^https?:\/\/github.com\/([^\/]+)\/([^\/]+)\/blob\/([^\/]+)\/(.*)$/);
if (match) {
var git = {
owner : match[1],
repo : match[2],
branch : match[3],
path : match[4]
};
var url = "https://raw.githubusercontent.com/"+git.owner+"/"+git.repo+"/"+git.branch+"/"+git.path;
console.log("Found GitHub", JSON.stringify(git));
callback({url: url});
} else
callback(data); // no match - continue as normal
}
Espruino.Plugins.GetGitHub = {
init : init,
};
}());
/*! https://mths.be/utf8js v2.0.0 by @mathias */
;(function(root) {
// Detect free variables `exports`
var freeExports = typeof exports == 'object' && exports;
// Detect free variable `module`
var freeModule = typeof module == 'object' && module &&
module.exports == freeExports && module;
// Detect free variable `global`, from Node.js or Browserified code,
// and use it as `root`
var freeGlobal = typeof global == 'object' && global;
if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
root = freeGlobal;
}
/*--------------------------------------------------------------------------*/
var stringFromCharCode = String.fromCharCode;
// Taken from https://mths.be/punycode
function ucs2decode(string) {
var output = [];
var counter = 0;
var length = string.length;
var value;
var extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
// Taken from https://mths.be/punycode
function ucs2encode(array) {
var length = array.length;
var index = -1;
var value;
var output = '';
while (++index < length) {
value = array[index];
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
}
return output;
}
function checkScalarValue(codePoint) {
if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
throw Error(
'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
' is not a scalar value'
);
}
}
/*--------------------------------------------------------------------------*/
function createByte(codePoint, shift) {
return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
}
function encodeCodePoint(codePoint) {
if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
return stringFromCharCode(codePoint);
}
var symbol = '';
if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
}
else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
checkScalarValue(codePoint);
symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
symbol += createByte(codePoint, 6);
}
else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
symbol += createByte(codePoint, 12);
symbol += createByte(codePoint, 6);
}
symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
return symbol;
}
function utf8encode(string) {
var codePoints = ucs2decode(string);
var length = codePoints.length;
var index = -1;
var codePoint;
var byteString = '';
while (++index < length) {
codePoint = codePoints[index];
byteString += encodeCodePoint(codePoint);
}
return byteString;
}
/*--------------------------------------------------------------------------*/
function readContinuationByte() {
if (byteIndex >= byteCount) {
throw Error('Invalid byte index');
}
var continuationByte = byteArray[byteIndex] & 0xFF;
byteIndex++;
if ((continuationByte & 0xC0) == 0x80) {
return continuationByte & 0x3F;
}
// If we end up here, its not a continuation byte
throw Error('Invalid continuation byte');
}
function decodeSymbol() {
var byte1;
var byte2;
var byte3;
var byte4;
var codePoint;
if (byteIndex > byteCount) {
throw Error('Invalid byte index');
}
if (byteIndex == byteCount) {
return false;
}
// Read first byte
byte1 = byteArray[byteIndex] & 0xFF;
byteIndex++;
// 1-byte sequence (no continuation bytes)
if ((byte1 & 0x80) == 0) {
return byte1;
}
// 2-byte sequence
if ((byte1 & 0xE0) == 0xC0) {
var byte2 = readContinuationByte();
codePoint = ((byte1 & 0x1F) << 6) | byte2;
if (codePoint >= 0x80) {
return codePoint;
} else {
throw Error('Invalid continuation byte');
}
}
// 3-byte sequence (may include unpaired surrogates)
if ((byte1 & 0xF0) == 0xE0) {
byte2 = readContinuationByte();
byte3 = readContinuationByte();
codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
if (codePoint >= 0x0800) {
checkScalarValue(codePoint);
return codePoint;
} else {
throw Error('Invalid continuation byte');
}
}
// 4-byte sequence
if ((byte1 & 0xF8) == 0xF0) {
byte2 = readContinuationByte();
byte3 = readContinuationByte();
byte4 = readContinuationByte();
codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
(byte3 << 0x06) | byte4;
if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
return codePoint;
}
}
throw Error('Invalid UTF-8 detected');
}
var byteArray;
var byteCount;
var byteIndex;
function utf8decode(byteString) {
byteArray = ucs2decode(byteString);
byteCount = byteArray.length;
byteIndex = 0;
var codePoints = [];
var tmp;
while ((tmp = decodeSymbol()) !== false) {
codePoints.push(tmp);
}
return ucs2encode(codePoints);
}
/*--------------------------------------------------------------------------*/
var utf8 = {
'version': '2.0.0',
'encode': utf8encode,
'decode': utf8decode
};
// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if (
typeof define == 'function' &&
typeof define.amd == 'object' &&
define.amd
) {
define(function() {
return utf8;
});
} else if (freeExports && !freeExports.nodeType) {
if (freeModule) { // in Node.js or RingoJS v0.8.0+
freeModule.exports = utf8;
} else { // in Narwhal or RingoJS v0.7.0-
var object = {};
var hasOwnProperty = object.hasOwnProperty;
for (var key in utf8) {
hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
}
}
} else { // in Rhino or a web browser
root.utf8 = utf8;
}
}(this));
/**
Copyright 2015 Gordon Williams (gw@pur3.co.uk),
Victor Nakoryakov (victor@amperka.ru)
This Source Code is subject to the terms of the Mozilla Public
License, v2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
------------------------------------------------------------------
Escape non-ASCII characters into \xHH UTF-8 sequences before send
------------------------------------------------------------------
**/
"use strict";
(function(){
// Node.js doesn't have utf8 installed
var utf8lib;
if ("undefined"==typeof utf8) {
if ("undefined"!=typeof require) {
console.log("Loading UTF8 with require");
utf8lib = require('utf8');
} else {
console.log("WARNING: Loading placeholder UTF8");
utf8lib = { encode : function(c){return c} };
}
} else {
console.log("UTF8 Library loaded successfully");
utf8lib = utf8;
}
function init() {
Espruino.addProcessor("transformForEspruino", function(code, callback) {
escapeUnicode(code, callback);
});
}
function escapeUnicode(code, callback) {
// Only correct unicode inside strings
var newCode = "";
var lex = Espruino.Core.Utils.getLexer(code);
var lastIdx = 0;
var tok = lex.next();
while (tok!==undefined) {
var previousString = code.substring(lastIdx, tok.startIdx);
var tokenString = code.substring(tok.startIdx, tok.endIdx);
if (tok.type=="STRING") {
var newTokenString = "";
for (var i=0;i<tokenString.length;i++) {
var ch = tokenString.charCodeAt(i);
if (ch >= 255)
newTokenString += escapeChar(tokenString[i]);
else
newTokenString += tokenString[i];
}
tokenString = newTokenString;
}
newCode += previousString+tokenString;
// next
lastIdx = tok.endIdx;
tok = lex.next();
}
newCode += code.substring(lastIdx);
callback(newCode);
}
function escapeChar(c) {
// encode char into UTF-8 sequence in form of \xHH codes
var result = '';
utf8lib.encode(c).split('').forEach(function(c) {
var code = c.charCodeAt(0) & 0xFF;
result += "\\x";
if (code < 0x10) result += '0';
result += code.toString(16).toUpperCase();
});
return result;
}
Espruino.Plugins.Unicode = {
init : init,
};
}());
(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__) {
"use strict";
/*
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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
var comment_handler_1 = __webpack_require__(1);
var jsx_parser_1 = __webpack_require__(3);
var parser_1 = __webpack_require__(8);
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.1';
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
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";
Object.defineProperty(exports, "__esModule", { value: true });
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";
/* istanbul ignore next */
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var character_1 = __webpack_require__(4);
var JSXNode = __webpack_require__(5);
var jsx_syntax_1 = __webpack_require__(6);
var Node = __webpack_require__(7);
var parser_1 = __webpack_require__(8);
var token_1 = __webpack_require__(13);
var xhtml_entities_1 = __webpack_require__(14);
token_1.TokenName[100 /* Identifier */] = 'JSXIdentifier';
token_1.TokenName[101 /* 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;
/* istanbul ignore next */
default:
break;
}
return qualifiedName;
}
var JSXParser = (function (_super) {
__extends(JSXParser, _super);
function JSXParser(code, options, delegate) {
return _super.call(this, code, options, delegate) || this;
}
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.line;
this.scanner.lineStart = this.startMarker.index - this.startMarker.column;
};
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 (quote) {
var result = '&';
var valid = true;
var terminated = false;
var numeric = false;
var hex = false;
while (!this.scanner.eof() && valid && !terminated) {
var ch = this.scanner.source[this.scanner.index];
if (ch === quote) {
break;
}
terminated = (ch === ';');
result += ch;
++this.scanner.index;
if (!terminated) {
switch (result.length) {
case 2:
// e.g. '&#123;'
numeric = (ch === '#');
break;
case 3:
if (numeric) {
// e.g. '&#x41;'
hex = (ch === 'x');
valid = hex || character_1.Character.isDecimalDigit(ch.charCodeAt(0));
numeric = numeric && !hex;
}
break;
default:
valid = valid && !(numeric && !character_1.Character.isDecimalDigit(ch.charCodeAt(0)));
valid = valid && !(hex && !character_1.Character.isHexDigit(ch.charCodeAt(0)));
break;
}
}
}
if (valid && terminated && result.length > 2) {
// e.g. '&#x41;' becomes just '#x41'
var str = result.substr(1, result.length - 2);
if (numeric && str.length > 1) {
result = String.fromCharCode(parseInt(str.substr(1), 10));
}
else if (hex && str.length > 2) {
result = String.fromCharCode(parseInt('0' + str.substr(1), 16));
}
else if (!numeric && !hex && xhtml_entities_1.XHTMLEntities[str]) {
result = xhtml_entities_1.XHTMLEntities[str];
}
}
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: 7 /* 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(quote);
}
else {
str += ch;
}
}
return {
type: 8 /* 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: 7 /* Punctuator */,
value: value,
lineNumber: this.scanner.lineNumber,
lineStart: this.scanner.lineStart,
start: start,
end: this.scanner.index
};
}
// `
if (cp === 96) {
// Only placeholder, since it will be rescanned as a real assignment expression.
return {
type: 10 /* Template */,
value: '',
lineNumber: this.scanner.lineNumber,
lineStart: this.scanner.lineStart,
start: this.scanner.index,
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: 100 /* Identifier */,
value: id,
lineNumber: this.scanner.lineNumber,
lineStart: this.scanner.lineStart,
start: start,
end: this.scanner.index
};
}
return this.scanner.lex();
};
JSXParser.prototype.nextJSXToken = function () {
this.collectComments();
this.startMarker.index = this.scanner.index;
this.startMarker.line = this.scanner.lineNumber;
this.startMarker.column = this.scanner.index - this.scanner.lineStart;
var token = this.lexJSX();
this.lastMarker.index = this.scanner.index;
this.lastMarker.line = this.scanner.lineNumber;
this.lastMarker.column = this.scanner.index - 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.line = this.scanner.lineNumber;
this.startMarker.column = this.scanner.index - 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.line = this.scanner.lineNumber;
this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
var token = {
type: 101 /* 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 state = this.scanner.saveState();
this.scanner.scanComments();
var next = this.lexJSX();
this.scanner.restoreState(state);
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 !== 7 /* 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 === 7 /* Punctuator */ && next.value === value;
};
JSXParser.prototype.parseJSXIdentifier = function () {
var node = this.createJSXNode();
var token = this.nextJSXToken();
if (token.type !== 100 /* 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 !== 8 /* 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.line = this.scanner.lineNumber;
this.lastMarker.column = this.scanner.index - 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;
};
JSXParser.prototype.isStartOfExpression = function () {
return _super.prototype.isStartOfExpression.call(this) || this.match('<');
};
return JSXParser;
}(parser_1.Parser));
exports.JSXParser = JSXParser;
/***/ },
/* 4 */
/***/ function(module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// 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\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\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\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u
};
exports.Character = {
/* tslint:disable:no-bitwise */
fromCodePoint: function (cp) {
return (cp < 0x10000) ? String.fromCharCode(cp) :
String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) +
String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023));
},
// https://tc39.github.io/ecma262/#sec-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);
},
// https://tc39.github.io/ecma262/#sec-line-terminators
isLineTerminator: function (cp) {
return (cp === 0x0A) || (cp === 0x0D) || (cp === 0x2028) || (cp === 0x2029);
},
// https://tc39.github.io/ecma262/#sec-names-and-keywords
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)));
},
// https://tc39.github.io/ecma262/#sec-literals-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
}
};
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var jsx_syntax_1 = __webpack_require__(6);
/* tslint:disable:max-classes-per-file */
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;
/***/ },
/* 6 */
/***/ function(module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.JSXSyntax = {
JSXAttribute: 'JSXAttribute',
JSXClosingElement: 'JSXClosingElement',
JSXElement: 'JSXElement',
JSXEmptyExpression: 'JSXEmptyExpression',
JSXExpressionContainer: 'JSXExpressionContainer',
JSXIdentifier: 'JSXIdentifier',
JSXMemberExpression: 'JSXMemberExpression',
JSXNamespacedName: 'JSXNamespacedName',
JSXOpeningElement: 'JSXOpeningElement',
JSXSpreadAttribute: 'JSXSpreadAttribute',
JSXText: 'JSXText'
};
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var syntax_1 = __webpack_require__(2);
/* tslint:disable:max-classes-per-file */
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, pattern, flags) {
this.type = syntax_1.Syntax.Literal;
this.value = value;
this.raw = raw;
this.regex = { pattern: pattern, flags: flags };
}
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;
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var assert_1 = __webpack_require__(9);
var error_handler_1 = __webpack_require__(10);
var messages_1 = __webpack_require__(11);
var Node = __webpack_require__(7);
var scanner_1 = __webpack_require__(12);
var syntax_1 = __webpack_require__(2);
var token_1 = __webpack_require__(13);
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 = {
type: 2 /* EOF */,
value: '',
lineNumber: this.scanner.lineNumber,
lineStart: 0,
start: 0,
end: 0
};
this.hasLineTerminator = false;
this.context = {
isModule: false,
await: false,
allowIn: true,
allowStrictDirective: true,
allowYield: true,
firstCoverInitializedNameError: null,
isAssignmentTarget: false,
isBindingElement: false,
inFunctionBody: false,
inIteration: false,
inSwitch: false,
labelSet: {},
strict: false
};
this.tokens = [];
this.startMarker = {
index: 0,
line: this.scanner.lineNumber,
column: 0
};
this.lastMarker = {
index: 0,
line: this.scanner.lineNumber,
column: 0
};
this.nextToken();
this.lastMarker = {
index: this.scanner.index,
line: this.scanner.lineNumber,
column: this.scanner.index - 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.line;
var column = this.lastMarker.column + 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.column + 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 === 2 /* EOF */) ? messages_1.Messages.UnexpectedEOS :
(token.type === 3 /* Identifier */) ? messages_1.Messages.UnexpectedIdentifier :
(token.type === 6 /* NumericLiteral */) ? messages_1.Messages.UnexpectedNumber :
(token.type === 8 /* StringLiteral */) ? messages_1.Messages.UnexpectedString :
(token.type === 10 /* Template */) ? messages_1.Messages.UnexpectedTemplate :
messages_1.Messages.UnexpectedToken;
if (token.type === 4 /* 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.value;
}
else {
value = 'ILLEGAL';
}
msg = msg.replace('%0', value);
if (token && typeof token.lineNumber === 'number') {
var index = token.start;
var line = token.lineNumber;
var lastMarkerLineStart = this.lastMarker.index - this.lastMarker.column;
var column = token.start - lastMarkerLineStart + 1;
return this.errorHandler.createError(index, line, column, msg);
}
else {
var index = this.lastMarker.index;
var line = this.lastMarker.line;
var column = this.lastMarker.column + 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 = {
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.line,
column: this.startMarker.column
},
end: {
line: this.scanner.lineNumber,
column: this.scanner.index - this.scanner.lineStart
}
};
}
if (token.type === 9 /* RegularExpression */) {
var pattern = token.pattern;
var flags = token.flags;
t.regex = { pattern: pattern, flags: flags };
}
return t;
};
Parser.prototype.nextToken = function () {
var token = this.lookahead;
this.lastMarker.index = this.scanner.index;
this.lastMarker.line = this.scanner.lineNumber;
this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
this.collectComments();
if (this.scanner.index !== this.startMarker.index) {
this.startMarker.index = this.scanner.index;
this.startMarker.line = this.scanner.lineNumber;
this.startMarker.column = this.scanner.index - this.scanner.lineStart;
}
var next = this.scanner.lex();
this.hasLineTerminator = (token.lineNumber !== next.lineNumber);
if (next && this.context.strict && next.type === 3 /* Identifier */) {
if (this.scanner.isStrictModeReservedWord(next.value)) {
next.type = 4 /* Keyword */;
}
}
this.lookahead = next;
if (this.config.tokens && next.type !== 2 /* 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.line,
column: this.startMarker.column
};
};
Parser.prototype.startNode = function (token, lastLineStart) {
if (lastLineStart === void 0) { lastLineStart = 0; }
var column = token.start - token.lineStart;
var line = token.lineNumber;
if (column < 0) {
column += lastLineStart;
line--;
}
return {
index: token.start,
line: line,
column: column
};
};
Parser.prototype.finalize = function (marker, node) {
if (this.config.range) {
node.range = [marker.index, this.lastMarker.index];
}
if (this.config.loc) {
node.loc = {
start: {
line: marker.line,
column: marker.column,
},
end: {
line: this.lastMarker.line,
column: this.lastMarker.column
}
};
if (this.config.source) {
node.loc.source = this.config.source;
}
}
if (this.delegate) {
var metadata = {
start: {
line: marker.line,
column: marker.column,
offset: marker.index
},
end: {
line: this.lastMarker.line,
column: this.lastMarker.column,
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 !== 7 /* 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 === 7 /* Punctuator */ && token.value === ',') {
this.nextToken();
}
else if (token.type === 7 /* 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 !== 4 /* 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 === 7 /* Punctuator */ && this.lookahead.value === value;
};
// Return true if the next token matches the specified keyword
Parser.prototype.matchKeyword = function (keyword) {
return this.lookahead.type === 4 /* 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 === 3 /* Identifier */ && this.lookahead.value === keyword;
};
// Return true if the next token is an assignment operator
Parser.prototype.matchAssign = function () {
if (this.lookahead.type !== 7 /* 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 !== 2 /* EOF */ && !this.match('}')) {
this.throwUnexpectedToken(this.lookahead);
}
this.lastMarker.index = this.startMarker.index;
this.lastMarker.line = this.startMarker.line;
this.lastMarker.column = this.startMarker.column;
}
};
// https://tc39.github.io/ecma262/#sec-primary-expression
Parser.prototype.parsePrimaryExpression = function () {
var node = this.createNode();
var expr;
var token, raw;
switch (this.lookahead.type) {
case 3 /* 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 6 /* NumericLiteral */:
case 8 /* 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 1 /* BooleanLiteral */:
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
token = this.nextToken();
raw = this.getTokenRaw(token);
expr = this.finalize(node, new Node.Literal(token.value === 'true', raw));
break;
case 5 /* NullLiteral */:
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
token = this.nextToken();
raw = this.getTokenRaw(token);
expr = this.finalize(node, new Node.Literal(null, raw));
break;
case 10 /* Template */:
expr = this.parseTemplateLiteral();
break;
case 7 /* Punctuator */:
switch (this.lookahead.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.regex, raw, token.pattern, token.flags));
break;
default:
expr = this.throwUnexpectedToken(this.nextToken());
}
break;
case 4 /* 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;
};
// https://tc39.github.io/ecma262/#sec-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));
};
// https://tc39.github.io/ecma262/#sec-object-initializer
Parser.prototype.parsePropertyMethod = function (params) {
this.context.isAssignmentTarget = false;
this.context.isBindingElement = false;
var previousStrict = this.context.strict;
var previousAllowStrictDirective = this.context.allowStrictDirective;
this.context.allowStrictDirective = params.simple;
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;
this.context.allowStrictDirective = previousAllowStrictDirective;
return body;
};
Parser.prototype.parsePropertyMethodFunction = function () {
var isGenerator = false;
var node = this.createNode();
var previousAllowYield = this.context.allowYield;
this.context.allowYield = true;
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 8 /* StringLiteral */:
case 6 /* 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 3 /* Identifier */:
case 1 /* BooleanLiteral */:
case 5 /* NullLiteral */:
case 4 /* Keyword */:
key = this.finalize(node, new Node.Identifier(token.value));
break;
case 7 /* 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 === 3 /* Identifier */) {
var id = token.value;
this.nextToken();
computed = this.match('[');
isAsync = !this.hasLineTerminator && (id === 'async') &&
!this.match(':') && !this.match('(') && !this.match('*') && !this.match(',');
key = isAsync ? this.parseObjectPropertyKey() : 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 === 3 /* 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 === 3 /* Identifier */ && !isAsync && token.value === 'set' && lookaheadPropertyKey) {
kind = 'set';
computed = this.match('[');
key = this.parseObjectPropertyKey();
value = this.parseSetterMethod();
}
else if (token.type === 7 /* 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(':') && !isAsync) {
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 === 3 /* 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));
};
// https://tc39.github.io/ecma262/#sec-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 raw = token.value;
var cooked = token.cooked;
return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail));
};
Parser.prototype.parseTemplateElement = function () {
if (this.lookahead.type !== 10 /* Template */) {
this.throwUnexpectedToken();
}
var node = this.createNode();
var token = this.nextToken();
var raw = token.value;
var cooked = token.cooked;
return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, 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));
};
// https://tc39.github.io/ecma262/#sec-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.lookahead.type !== 2 /* EOF */) {
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 parameters = (expr.type === syntax_1.Syntax.SequenceExpression ? expr.expressions : [expr]);
expr = {
type: ArrowParameterPlaceHolder,
params: parameters,
async: false
};
}
}
this.context.isBindingElement = false;
}
}
}
return expr;
};
// https://tc39.github.io/ecma262/#sec-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 === 3 /* Identifier */ ||
token.type === 4 /* Keyword */ ||
token.type === 1 /* BooleanLiteral */ ||
token.type === 5 /* 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 === 3 /* 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('=>')) {
for (var i = 0; i < args.length; ++i) {
this.reinterpretExpressionAsPattern(args[i]);
}
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 === 10 /* 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 === 10 /* Template */ && this.lookahead.head) {
var quasi = this.parseTemplateLiteral();
expr = this.finalize(node, new Node.TaggedTemplateExpression(expr, quasi));
}
else {
break;
}
}
return expr;
};
// https://tc39.github.io/ecma262/#sec-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 === 7 /* 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;
};
// https://tc39.github.io/ecma262/#sec-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;
};
// https://tc39.github.io/ecma262/#sec-exp-operator
// https://tc39.github.io/ecma262/#sec-multiplicative-operators
// https://tc39.github.io/ecma262/#sec-additive-operators
// https://tc39.github.io/ecma262/#sec-bitwise-shift-operators
// https://tc39.github.io/ecma262/#sec-relational-operators
// https://tc39.github.io/ecma262/#sec-equality-operators
// https://tc39.github.io/ecma262/#sec-binary-bitwise-operators
// https://tc39.github.io/ecma262/#sec-binary-logical-operators
Parser.prototype.binaryPrecedence = function (token) {
var op = token.value;
var precedence;
if (token.type === 7 /* Punctuator */) {
precedence = this.operatorPrecedence[op] || 0;
}
else if (token.type === 4 /* 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();
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.value, right];
var precedences = [prec];
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 <= precedences[precedences.length - 1])) {
right = stack.pop();
var operator = stack.pop();
precedences.pop();
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.
stack.push(this.nextToken().value);
precedences.push(prec);
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];
var lastMarker = markers.pop();
while (i > 1) {
var marker = markers.pop();
var lastLineStart = lastMarker && lastMarker.lineStart;
var node = this.startNode(marker, lastLineStart);
var operator = stack[i - 1];
expr = this.finalize(node, new Node.BinaryExpression(operator, stack[i - 2], expr));
i -= 2;
lastMarker = marker;
}
}
return expr;
};
// https://tc39.github.io/ecma262/#sec-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;
};
// https://tc39.github.io/ecma262/#sec-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;
}
options.simple = options.simple && (param instanceof Node.Identifier);
};
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 = {
simple: true,
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 {
simple: options.simple,
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 === 3 /* Identifier */ && (token.lineNumber === this.lookahead.lineNumber) && token.value === 'async') {
if (this.lookahead.type === 3 /* Identifier */ || this.matchKeyword('yield')) {
var arg = this.parsePrimaryExpression();
this.reinterpretExpressionAsPattern(arg);
expr = {
type: ArrowParameterPlaceHolder,
params: [arg],
async: true
};
}
}
if (expr.type === ArrowParameterPlaceHolder || this.match('=>')) {
// https://tc39.github.io/ecma262/#sec-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 previousAllowStrictDirective = this.context.allowStrictDirective;
this.context.allowStrictDirective = list.simple;
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 = void 0;
if (this.match('{')) {
var previousAllowIn = this.context.allowIn;
this.context.allowIn = true;
body = this.parseFunctionSourceElements();
this.context.allowIn = previousAllowIn;
}
else {
body = 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.allowStrictDirective = previousAllowStrictDirective;
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 operator = token.value;
var right = this.isolateCoverGrammar(this.parseAssignmentExpression);
expr = this.finalize(this.startNode(startToken), new Node.AssignmentExpression(operator, expr, right));
this.context.firstCoverInitializedNameError = null;
}
}
}
return expr;
};
// https://tc39.github.io/ecma262/#sec-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.lookahead.type !== 2 /* EOF */) {
if (!this.match(',')) {
break;
}
this.nextToken();
expressions.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
}
expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions));
}
return expr;
};
// https://tc39.github.io/ecma262/#sec-block
Parser.prototype.parseStatementListItem = function () {
var statement;
this.context.isAssignmentTarget = true;
this.context.isBindingElement = true;
if (this.lookahead.type === 4 /* 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));
};
// https://tc39.github.io/ecma262/#sec-let-and-const-declarations
Parser.prototype.parseLexicalBinding = function (kind, options) {
var node = this.createNode();
var params = [];
var id = this.parsePattern(params, kind);
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 state = this.scanner.saveState();
this.scanner.scanComments();
var next = this.scanner.lex();
this.scanner.restoreState(state);
return (next.type === 3 /* Identifier */) ||
(next.type === 7 /* Punctuator */ && next.value === '[') ||
(next.type === 7 /* Punctuator */ && next.value === '{') ||
(next.type === 4 /* Keyword */ && next.value === 'let') ||
(next.type === 4 /* 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));
};
// https://tc39.github.io/ecma262/#sec-destructuring-binding-patterns
Parser.prototype.parseBindingRestElement = function (params, kind) {
var node = this.createNode();
this.expect('...');
var arg = this.parsePattern(params, 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 === 3 /* 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;
};
// https://tc39.github.io/ecma262/#sec-variable-statement
Parser.prototype.parseVariableIdentifier = function (kind) {
var node = this.createNode();
var token = this.nextToken();
if (token.type === 4 /* Keyword */ && token.value === 'yield') {
if (this.context.strict) {
this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
}
else if (!this.context.allowYield) {
this.throwUnexpectedToken(token);
}
}
else if (token.type !== 3 /* Identifier */) {
if (this.context.strict && token.type === 4 /* 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 === 3 /* 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');
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'));
};
// https://tc39.github.io/ecma262/#sec-empty-statement
Parser.prototype.parseEmptyStatement = function () {
var node = this.createNode();
this.expect(';');
return this.finalize(node, new Node.EmptyStatement());
};
// https://tc39.github.io/ecma262/#sec-expression-statement
Parser.prototype.parseExpressionStatement = function () {
var node = this.createNode();
var expr = this.parseExpression();
this.consumeSemicolon();
return this.finalize(node, new Node.ExpressionStatement(expr));
};
// https://tc39.github.io/ecma262/#sec-if-statement
Parser.prototype.parseIfClause = function () {
if (this.context.strict && this.matchKeyword('function')) {
this.tolerateError(messages_1.Messages.StrictFunction);
}
return this.parseStatement();
};
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.parseIfClause();
if (this.matchKeyword('else')) {
this.nextToken();
alternate = this.parseIfClause();
}
}
return this.finalize(node, new Node.IfStatement(test, consequent, alternate));
};
// https://tc39.github.io/ecma262/#sec-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();
if (!this.match(')') && this.config.tolerant) {
this.tolerateUnexpectedToken(this.nextToken());
}
else {
this.expect(')');
if (this.match(';')) {
this.nextToken();
}
}
return this.finalize(node, new Node.DoWhileStatement(body, test));
};
// https://tc39.github.io/ecma262/#sec-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));
};
// https://tc39.github.io/ecma262/#sec-for-statement
// https://tc39.github.io/ecma262/#sec-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));
};
// https://tc39.github.io/ecma262/#sec-continue-statement
Parser.prototype.parseContinueStatement = function () {
var node = this.createNode();
this.expectKeyword('continue');
var label = null;
if (this.lookahead.type === 3 /* 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));
};
// https://tc39.github.io/ecma262/#sec-break-statement
Parser.prototype.parseBreakStatement = function () {
var node = this.createNode();
this.expectKeyword('break');
var label = null;
if (this.lookahead.type === 3 /* 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));
};
// https://tc39.github.io/ecma262/#sec-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 !== 2 /* EOF */) ||
this.lookahead.type === 8 /* StringLiteral */ ||
this.lookahead.type === 10 /* Template */;
var argument = hasArgument ? this.parseExpression() : null;
this.consumeSemicolon();
return this.finalize(node, new Node.ReturnStatement(argument));
};
// https://tc39.github.io/ecma262/#sec-with-statement
Parser.prototype.parseWithStatement = function () {
if (this.context.strict) {
this.tolerateError(messages_1.Messages.StrictModeWith);
}
var node = this.createNode();
var body;
this.expectKeyword('with');
this.expect('(');
var object = this.parseExpression();
if (!this.match(')') && this.config.tolerant) {
this.tolerateUnexpectedToken(this.nextToken());
body = this.finalize(this.createNode(), new Node.EmptyStatement());
}
else {
this.expect(')');
body = this.parseStatement();
}
return this.finalize(node, new Node.WithStatement(object, body));
};
// https://tc39.github.io/ecma262/#sec-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));
};
// https://tc39.github.io/ecma262/#sec-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 body = void 0;
if (this.matchKeyword('class')) {
this.tolerateUnexpectedToken(this.lookahead);
body = this.parseClassDeclaration();
}
else if (this.matchKeyword('function')) {
var token = this.lookahead;
var declaration = this.parseFunctionDeclaration();
if (this.context.strict) {
this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunction);
}
else if (declaration.generator) {
this.tolerateUnexpectedToken(token, messages_1.Messages.GeneratorInLegacyContext);
}
body = declaration;
}
else {
body = this.parseStatement();
}
delete this.context.labelSet[key];
statement = new Node.LabeledStatement(id, body);
}
else {
this.consumeSemicolon();
statement = new Node.ExpressionStatement(expr);
}
return this.finalize(node, statement);
};
// https://tc39.github.io/ecma262/#sec-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));
};
// https://tc39.github.io/ecma262/#sec-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));
};
// https://tc39.github.io/ecma262/#sec-debugger-statement
Parser.prototype.parseDebuggerStatement = function () {
var node = this.createNode();
this.expectKeyword('debugger');
this.consumeSemicolon();
return this.finalize(node, new Node.DebuggerStatement());
};
// https://tc39.github.io/ecma262/#sec-ecmascript-language-statements-and-declarations
Parser.prototype.parseStatement = function () {
var statement;
switch (this.lookahead.type) {
case 1 /* BooleanLiteral */:
case 5 /* NullLiteral */:
case 6 /* NumericLiteral */:
case 8 /* StringLiteral */:
case 10 /* Template */:
case 9 /* RegularExpression */:
statement = this.parseExpressionStatement();
break;
case 7 /* 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 3 /* Identifier */:
statement = this.matchAsyncFunction() ? this.parseFunctionDeclaration() : this.parseLabelledStatement();
break;
case 4 /* 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;
};
// https://tc39.github.io/ecma262/#sec-function-definitions
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.lookahead.type !== 2 /* EOF */) {
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.expect('...');
var arg = this.parsePattern(params);
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(arg));
};
Parser.prototype.parseFormalParameter = function (options) {
var params = [];
var param = this.match('...') ? this.parseRestElement(params) : this.parsePatternWithDefault(params);
for (var i = 0; i < params.length; i++) {
this.validateParam(options, params[i], params[i].value);
}
options.simple = options.simple && (param instanceof Node.Identifier);
options.params.push(param);
};
Parser.prototype.parseFormalParameters = function (firstRestricted) {
var options;
options = {
simple: true,
params: [],
firstRestricted: firstRestricted
};
this.expect('(');
if (!this.match(')')) {
options.paramSet = {};
while (this.lookahead.type !== 2 /* EOF */) {
this.parseFormalParameter(options);
if (this.match(')')) {
break;
}
this.expect(',');
if (this.match(')')) {
break;
}
}
}
this.expect(')');
return {
simple: options.simple,
params: options.params,
stricted: options.stricted,
firstRestricted: options.firstRestricted,
message: options.message
};
};
Parser.prototype.matchAsyncFunction = function () {
var match = this.matchContextualKeyword('async');
if (match) {
var state = this.scanner.saveState();
this.scanner.scanComments();
var next = this.scanner.lex();
this.scanner.restoreState(state);
match = (state.lineNumber === next.lineNumber) && (next.type === 4 /* 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 previousAllowStrictDirective = this.context.allowStrictDirective;
this.context.allowStrictDirective = formalParameters.simple;
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.allowStrictDirective = previousAllowStrictDirective;
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 previousAllowStrictDirective = this.context.allowStrictDirective;
this.context.allowStrictDirective = formalParameters.simple;
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.allowStrictDirective = previousAllowStrictDirective;
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));
};
// https://tc39.github.io/ecma262/#sec-directive-prologues-and-the-use-strict-directive
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 !== 8 /* 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);
}
if (!this.context.allowStrictDirective) {
this.tolerateUnexpectedToken(token, messages_1.Messages.IllegalLanguageModeDirective);
}
}
else {
if (!firstRestricted && token.octal) {
firstRestricted = token;
}
}
}
return body;
};
// https://tc39.github.io/ecma262/#sec-method-definitions
Parser.prototype.qualifiedPropertyName = function (token) {
switch (token.type) {
case 3 /* Identifier */:
case 8 /* StringLiteral */:
case 1 /* BooleanLiteral */:
case 5 /* NullLiteral */:
case 6 /* NumericLiteral */:
case 4 /* Keyword */:
return true;
case 7 /* Punctuator */:
return token.value === '[';
default:
break;
}
return false;
};
Parser.prototype.parseGetterMethod = function () {
var node = this.createNode();
var isGenerator = false;
var previousAllowYield = this.context.allowYield;
this.context.allowYield = !isGenerator;
var formalParameters = this.parseFormalParameters();
if (formalParameters.params.length > 0) {
this.tolerateError(messages_1.Messages.BadGetterArity);
}
var method = this.parsePropertyMethod(formalParameters);
this.context.allowYield = previousAllowYield;
return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator));
};
Parser.prototype.parseSetterMethod = function () {
var node = this.createNode();
var isGenerator = false;
var previousAllowYield = this.context.allowYield;
this.context.allowYield = !isGenerator;
var formalParameters = this.parseFormalParameters();
if (formalParameters.params.length !== 1) {
this.tolerateError(messages_1.Messages.BadSetterArity);
}
else if (formalParameters.params[0] instanceof Node.RestElement) {
this.tolerateError(messages_1.Messages.BadSetterRestParameter);
}
var method = this.parsePropertyMethod(formalParameters);
this.context.allowYield = previousAllowYield;
return this.finalize(node, new Node.FunctionExpression(null, formalParameters.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));
};
// https://tc39.github.io/ecma262/#sec-generator-function-definitions
Parser.prototype.isStartOfExpression = function () {
var start = true;
var value = this.lookahead.value;
switch (this.lookahead.type) {
case 7 /* Punctuator */:
start = (value === '[') || (value === '(') || (value === '{') ||
(value === '+') || (value === '-') ||
(value === '!') || (value === '~') ||
(value === '++') || (value === '--') ||
(value === '/') || (value === '/='); // regular expression literal
break;
case 4 /* Keyword */:
start = (value === 'class') || (value === 'delete') ||
(value === 'function') || (value === 'let') || (value === 'new') ||
(value === 'super') || (value === 'this') || (value === 'typeof') ||
(value === 'void') || (value === 'yield');
break;
default:
break;
}
return start;
};
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.isStartOfExpression()) {
argument = this.parseAssignmentExpression();
}
this.context.allowYield = previousAllowYield;
}
return this.finalize(node, new Node.YieldExpression(argument, delegate));
};
// https://tc39.github.io/ecma262/#sec-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();
}
}
if ((token.type === 3 /* Identifier */) && !this.hasLineTerminator && (token.value === 'async')) {
var punctuator = this.lookahead.value;
if (punctuator !== ':' && punctuator !== '(' && punctuator !== '*') {
isAsync = true;
token = this.lookahead;
key = this.parseObjectPropertyKey();
if (token.type === 3 /* Identifier */ && token.value === 'constructor') {
this.tolerateUnexpectedToken(token, messages_1.Messages.ConstructorIsAsync);
}
}
}
}
var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead);
if (token.type === 3 /* 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 === 7 /* 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 !== 3 /* 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 === 3 /* 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));
};
// https://tc39.github.io/ecma262/#sec-scripts
// https://tc39.github.io/ecma262/#sec-modules
Parser.prototype.parseModule = function () {
this.context.strict = true;
this.context.isModule = true;
this.scanner.isModule = true;
var node = this.createNode();
var body = this.parseDirectivePrologues();
while (this.lookahead.type !== 2 /* EOF */) {
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.lookahead.type !== 2 /* EOF */) {
body.push(this.parseStatementListItem());
}
return this.finalize(node, new Node.Script(body));
};
// https://tc39.github.io/ecma262/#sec-imports
Parser.prototype.parseModuleSpecifier = function () {
var node = this.createNode();
if (this.lookahead.type !== 8 /* 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 === 3 /* 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 === 8 /* 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));
};
// https://tc39.github.io/ecma262/#sec-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('async')) {
// export default async function f () {}
// export default async function () {}
// export default async x => x
var declaration = this.matchAsyncFunction() ? this.parseFunctionDeclaration(true) : this.parseAssignmentExpression();
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 === 4 /* 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;
/***/ },
/* 9 */
/***/ function(module, exports) {
"use strict";
// 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.
Object.defineProperty(exports, "__esModule", { value: true });
function assert(condition, message) {
/* istanbul ignore if */
if (!condition) {
throw new Error('ASSERT: ' + message);
}
}
exports.assert = assert;
/***/ },
/* 10 */
/***/ function(module, exports) {
"use strict";
/* tslint:disable:max-classes-per-file */
Object.defineProperty(exports, "__esModule", { value: true });
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 });
}
}
/* 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;
/***/ },
/* 11 */
/***/ function(module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// Error messages should be identical to V8.
exports.Messages = {
BadGetterArity: 'Getter must not have any formal parameters',
BadSetterArity: 'Setter must have exactly one formal parameter',
BadSetterRestParameter: 'Setter function argument must not be a rest parameter',
ConstructorIsAsync: 'Class constructor may not be an async method',
ConstructorSpecialMethod: 'Class constructor may not be an accessor',
DeclarationMissingInitializer: 'Missing initializer in %0 declaration',
DefaultRestParameter: 'Unexpected token =',
DuplicateBinding: 'Duplicate binding %0',
DuplicateConstructor: 'A class may only have one constructor',
DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals',
ForInOfLoopInitializer: '%0 loop variable declaration may not have an initializer',
GeneratorInLegacyContext: 'Generator declarations are not allowed in legacy contexts',
IllegalBreak: 'Illegal break statement',
IllegalContinue: 'Illegal continue statement',
IllegalExportDeclaration: 'Unexpected token',
IllegalImportDeclaration: 'Unexpected token',
IllegalLanguageModeDirective: 'Illegal \'use strict\' directive in function with non-simple parameter list',
IllegalReturn: 'Illegal return statement',
InvalidEscapedReservedWord: 'Keyword must not contain escaped characters',
InvalidHexEscapeSequence: 'Invalid hexadecimal escape sequence',
InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
InvalidLHSInForIn: 'Invalid left-hand side in for-in',
InvalidLHSInForLoop: 'Invalid left-hand side in for-loop',
InvalidModuleSpecifier: 'Unexpected token',
InvalidRegExp: 'Invalid regular expression',
LetInLexicalBinding: 'let is disallowed as a lexically bound name',
MissingFromClause: 'Unexpected token',
MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
NewlineAfterThrow: 'Illegal newline after throw',
NoAsAfterImportNamespace: 'Unexpected token',
NoCatchOrFinally: 'Missing catch or finally after try',
ParameterAfterRestParameter: 'Rest parameter must be last formal parameter',
Redeclaration: '%0 \'%1\' has already been declared',
StaticPrototype: 'Classes may not have static property named prototype',
StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
StrictDelete: 'Delete of an unqualified identifier in strict mode.',
StrictFunction: 'In strict mode code, functions can only be declared at top level or inside a block',
StrictFunctionName: 'Function name may not be eval or arguments 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',
StrictModeWith: 'Strict mode code may not include a with statement',
StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
StrictReservedWord: 'Use of future reserved word in strict mode',
StrictVarName: 'Variable name may not be eval or arguments in strict mode',
TemplateOctalLiteral: 'Octal literals are not allowed in template strings.',
UnexpectedEOS: 'Unexpected end of input',
UnexpectedIdentifier: 'Unexpected identifier',
UnexpectedNumber: 'Unexpected number',
UnexpectedReserved: 'Unexpected reserved word',
UnexpectedString: 'Unexpected string',
UnexpectedTemplate: 'Unexpected quasi %0',
UnexpectedToken: 'Unexpected token %0',
UnexpectedTokenIllegal: 'Unexpected token ILLEGAL',
UnknownLabel: 'Undefined label \'%0\'',
UnterminatedRegExp: 'Invalid regular expression: missing /'
};
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var assert_1 = __webpack_require__(9);
var character_1 = __webpack_require__(4);
var messages_1 = __webpack_require__(11);
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.isModule = false;
this.length = code.length;
this.index = 0;
this.lineNumber = (code.length > 0) ? 1 : 0;
this.lineStart = 0;
this.curlyStack = [];
}
Scanner.prototype.saveState = function () {
return {
index: this.index,
lineNumber: this.lineNumber,
lineStart: this.lineStart
};
};
Scanner.prototype.restoreState = function (state) {
this.index = state.index;
this.lineNumber = state.lineNumber;
this.lineStart = state.lineStart;
};
Scanner.prototype.eof = function () {
return this.index >= this.length;
};
Scanner.prototype.throwUnexpectedToken = function (message) {
if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; }
return this.errorHandler.throwError(this.index, this.lineNumber, this.index - this.lineStart + 1, message);
};
Scanner.prototype.tolerateUnexpectedToken = function (message) {
if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; }
this.errorHandler.tolerateError(this.index, this.lineNumber, this.index - this.lineStart + 1, message);
};
// https://tc39.github.io/ecma262/#sec-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 && !this.isModule) {
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;
};
// https://tc39.github.io/ecma262/#sec-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';
};
// https://tc39.github.io/ecma262/#sec-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 null;
}
}
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');
if (ch === null || ch === '\\' || !character_1.Character.isIdentifierStart(ch.charCodeAt(0))) {
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');
if (ch === null || ch === '\\' || !character_1.Character.isIdentifierPart(ch.charCodeAt(0))) {
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
};
};
// https://tc39.github.io/ecma262/#sec-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 = 3 /* Identifier */;
}
else if (this.isKeyword(id)) {
type = 4 /* Keyword */;
}
else if (id === 'null') {
type = 5 /* NullLiteral */;
}
else if (id === 'true' || id === 'false') {
type = 1 /* BooleanLiteral */;
}
else {
type = 3 /* Identifier */;
}
if (type !== 3 /* Identifier */ && (start + id.length !== this.index)) {
var restore = this.index;
this.index = start;
this.tolerateUnexpectedToken(messages_1.Messages.InvalidEscapedReservedWord);
this.index = restore;
}
return {
type: type,
value: id,
lineNumber: this.lineNumber,
lineStart: this.lineStart,
start: start,
end: this.index
};
};
// https://tc39.github.io/ecma262/#sec-punctuators
Scanner.prototype.scanPunctuator = function () {
var start = 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 === start) {
this.throwUnexpectedToken();
}
return {
type: 7 /* Punctuator */,
value: str,
lineNumber: this.lineNumber,
lineStart: this.lineStart,
start: start,
end: this.index
};
};
// https://tc39.github.io/ecma262/#sec-literals-numeric-literals
Scanner.prototype.scanHexLiteral = function (start) {
var num = '';
while (!this.eof()) {
if (!character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
break;
}
num += this.source[this.index++];
}
if (num.length === 0) {
this.throwUnexpectedToken();
}
if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
this.throwUnexpectedToken();
}
return {
type: 6 /* NumericLiteral */,
value: parseInt('0x' + num, 16),
lineNumber: this.lineNumber,
lineStart: this.lineStart,
start: start,
end: this.index
};
};
Scanner.prototype.scanBinaryLiteral = function (start) {
var num = '';
var ch;
while (!this.eof()) {
ch = this.source[this.index];
if (ch !== '0' && ch !== '1') {
break;
}
num += this.source[this.index++];
}
if (num.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: 6 /* NumericLiteral */,
value: parseInt(num, 2),
lineNumber: this.lineNumber,
lineStart: this.lineStart,
start: start,
end: this.index
};
};
Scanner.prototype.scanOctalLiteral = function (prefix, start) {
var num = '';
var octal = false;
if (character_1.Character.isOctalDigit(prefix.charCodeAt(0))) {
octal = true;
num = '0' + this.source[this.index++];
}
else {
++this.index;
}
while (!this.eof()) {
if (!character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
break;
}
num += this.source[this.index++];
}
if (!octal && num.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: 6 /* NumericLiteral */,
value: parseInt(num, 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 num = '';
if (ch !== '.') {
num = 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 (num === '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))) {
num += this.source[this.index++];
}
ch = this.source[this.index];
}
if (ch === '.') {
num += this.source[this.index++];
while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
num += this.source[this.index++];
}
ch = this.source[this.index];
}
if (ch === 'e' || ch === 'E') {
num += this.source[this.index++];
ch = this.source[this.index];
if (ch === '+' || ch === '-') {
num += this.source[this.index++];
}
if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
num += this.source[this.index++];
}
}
else {
this.throwUnexpectedToken();
}
}
if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
this.throwUnexpectedToken();
}
return {
type: 6 /* NumericLiteral */,
value: parseFloat(num),
lineNumber: this.lineNumber,
lineStart: this.lineStart,
start: start,
end: this.index
};
};
// https://tc39.github.io/ecma262/#sec-literals-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':
if (this.source[this.index] === '{') {
++this.index;
str += this.scanUnicodeCodePointEscape();
}
else {
var unescaped_1 = this.scanHexEscape(ch);
if (unescaped_1 === null) {
this.throwUnexpectedToken();
}
str += unescaped_1;
}
break;
case 'x':
var unescaped = this.scanHexEscape(ch);
if (unescaped === null) {
this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence);
}
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: 8 /* StringLiteral */,
value: str,
octal: octal,
lineNumber: this.lineNumber,
lineStart: this.lineStart,
start: start,
end: this.index
};
};
// https://tc39.github.io/ecma262/#sec-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':
if (this.source[this.index] === '{') {
++this.index;
cooked += this.scanUnicodeCodePointEscape();
}
else {
var restore = this.index;
var unescaped_2 = this.scanHexEscape(ch);
if (unescaped_2 !== null) {
cooked += unescaped_2;
}
else {
this.index = restore;
cooked += ch;
}
}
break;
case 'x':
var unescaped = this.scanHexEscape(ch);
if (unescaped === null) {
this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence);
}
cooked += unescaped;
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: 10 /* Template */,
value: this.source.slice(start + 1, this.index - rawOffset),
cooked: cooked,
head: head,
tail: tail,
lineNumber: this.lineNumber,
lineStart: this.lineStart,
start: start,
end: this.index
};
};
// https://tc39.github.io/ecma262/#sec-literals-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++];
// https://tc39.github.io/ecma262/#sec-literals-regular-expression-literals
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.
return str.substr(1, str.length - 2);
};
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;
var char = this.scanHexEscape('u');
if (char !== null) {
flags += char;
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 flags;
};
Scanner.prototype.scanRegExp = function () {
var start = this.index;
var pattern = this.scanRegExpBody();
var flags = this.scanRegExpFlags();
var value = this.testRegExp(pattern, flags);
return {
type: 9 /* RegularExpression */,
value: '',
pattern: pattern,
flags: flags,
regex: value,
lineNumber: this.lineNumber,
lineStart: this.lineStart,
start: start,
end: this.index
};
};
Scanner.prototype.lex = function () {
if (this.eof()) {
return {
type: 2 /* EOF */,
value: '',
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;
/***/ },
/* 13 */
/***/ function(module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TokenName = {};
exports.TokenName[1 /* BooleanLiteral */] = 'Boolean';
exports.TokenName[2 /* EOF */] = '<end>';
exports.TokenName[3 /* Identifier */] = 'Identifier';
exports.TokenName[4 /* Keyword */] = 'Keyword';
exports.TokenName[5 /* NullLiteral */] = 'Null';
exports.TokenName[6 /* NumericLiteral */] = 'Numeric';
exports.TokenName[7 /* Punctuator */] = 'Punctuator';
exports.TokenName[8 /* StringLiteral */] = 'String';
exports.TokenName[9 /* RegularExpression */] = 'RegularExpression';
exports.TokenName[10 /* Template */] = 'Template';
/***/ },
/* 14 */
/***/ function(module, exports) {
"use strict";
// Generated by generate-xhtml-entities.js. DO NOT MODIFY!
Object.defineProperty(exports, "__esModule", { value: true });
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'
};
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var error_handler_1 = __webpack_require__(10);
var scanner_1 = __webpack_require__(12);
var token_1 = __webpack_require__(13);
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 keyword = this.values[this.paren - 1];
regex = (keyword === 'if' || keyword === 'while' || keyword === 'for' || keyword === '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 = this.values[this.curly - 4];
regex = check ? !this.beforeFunctionExpression(check) : false;
}
else if (this.values[this.curly - 4] === 'function') {
// Named function, e.g. function f(){} /42/
var check = this.values[this.curly - 5];
regex = check ? !this.beforeFunctionExpression(check) : true;
}
break;
default:
break;
}
return regex;
};
Reader.prototype.push = function (token) {
if (token.type === 7 /* Punctuator */ || token.type === 4 /* 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 value = this.scanner.source.slice(e.slice[0], e.slice[1]);
var 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 startRegex = (this.scanner.source[this.scanner.index] === '/') && this.reader.isRegexStart();
var token = startRegex ? this.scanner.scanRegExp() : this.scanner.lex();
this.reader.push(token);
var 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.type === 9 /* RegularExpression */) {
var pattern = token.pattern;
var flags = token.flags;
entry.regex = { pattern: pattern, flags: flags };
}
this.buffer.push(entry);
}
}
return this.buffer.shift();
};
return Tokenizer;
}());
exports.Tokenizer = Tokenizer;
/***/ }
/******/ ])
});
;(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, estraverse, common;
Name = 'annotate-directive';
estraverse = require('estraverse');
common = require('./common');
Syntax = common.Syntax;
function isDirective(stmt) {
var expr;
if (stmt.type === Syntax.ExpressionStatement) {
expr = stmt.expression;
if (expr.type === Syntax.Literal && typeof expr.value === 'string') {
return true;
}
}
return false;
}
function escapeAllowedCharacter(ch, next) {
var code = ch.charCodeAt(0), hex = code.toString(16), result = '\\';
switch (ch) {
case '\b':
result += 'b';
break;
case '\f':
result += 'f';
break;
case '\t':
result += 't';
break;
default:
if (code > 0xff) {
result += 'u' + '0000'.slice(hex.length) + hex;
} else if (ch === '\u0000' && '0123456789'.indexOf(next) < 0) {
result += '0';
} else if (ch === '\v') {
result += 'v';
} else {
result += 'x' + '00'.slice(hex.length) + hex;
}
break;
}
return result;
}
function escapeDisallowedCharacter(ch) {
var result = '\\';
switch (ch) {
case '\\':
result += '\\';
break;
case '\n':
result += 'n';
break;
case '\r':
result += 'r';
break;
case '\u2028':
result += 'u2028';
break;
case '\u2029':
result += 'u2029';
break;
default:
throw new Error('Incorrectly classified character');
}
return result;
}
function escapeString(str) {
var result = '', i, len, ch;
if (typeof str[0] === 'undefined') {
str = common.stringToArray(str);
}
for (i = 0, len = str.length; i < len; i += 1) {
ch = str[i];
if (ch === '\'') {
result += '\\\'';
continue;
} else if ('\\\n\r\u2028\u2029'.indexOf(ch) >= 0) {
result += escapeDisallowedCharacter(ch);
continue;
} else if (!(ch >= ' ' && ch <= '~')) {
result += escapeAllowedCharacter(ch, str[i + 1]);
continue;
}
result += ch;
}
return result;
}
function annotateDirective(tree, options) {
var result;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
estraverse.traverse(result, {
enter: function enter(node, parent) {
var stmt, i, iz;
if (!(node.type === Syntax.Program ||
(node.type === Syntax.BlockStatement && (parent.type === Syntax.FunctionExpression || parent.type === Syntax.FunctionDeclaration)))) {
return;
}
for (i = 0, iz = node.body.length; i < iz; ++i) {
stmt = node.body[i];
if (isDirective(stmt)) {
stmt.type = Syntax.DirectiveStatement;
if (stmt.expression.raw) {
stmt.directive = stmt.expression.raw.substring(1, stmt.expression.raw.length - 1);
stmt.value = stmt.expression.value;
stmt.raw = stmt.expression.raw;
} else {
stmt.directive = escapeString(stmt.expression.value);
stmt.value = stmt.expression.value;
stmt.raw = '\'' + stmt.directive + '\'';
}
delete stmt.expression;
} else {
return;
}
}
}
});
return result;
}
annotateDirective.passName = Name;
module.exports = annotateDirective;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"./common":2,"estraverse":129}],2:[function(require,module,exports){
/*!
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
(function () {
'use strict';
var Syntax,
isArray,
arrayFrom,
arrayOf,
has,
sameValue,
estraverse,
escope,
esutils;
estraverse = require('estraverse');
escope = require('escope');
esutils = require('esutils');
isArray = require('isarray');
Syntax = estraverse.Syntax;
function isObject(obj) {
return typeof obj === 'object' && obj !== null;
}
has = (function () {
var method = {}.hasOwnProperty;
return function has(obj, prop) {
return method.call(obj, prop);
};
}());
// ES6 Array.from
arrayFrom = (function () {
var slice = Array.prototype.slice;
return function arrayFrom(array) {
return slice.call(array);
};
}());
// ES6 Array.of
arrayOf = (function () {
var slice = Array.prototype.slice;
return function arrayOf() {
return slice.call(arguments);
};
}());
function arrayLast(array) {
return array[array.length - 1];
}
function arrayEmpty(array) {
return array.length === 0;
}
function stringRepeat(str, num) {
var result = '';
for (num |= 0; num > 0; num >>>= 1, str += str) {
if (num & 1) {
result += str;
}
}
return result;
}
// see http://wiki.ecmascript.org/doku.php?id=harmony:egal
// ECMA262 SameValue algorithm
if (Object.is) {
sameValue = Object.is;
} else {
sameValue = function sameValue(x, y) {
if (x === y) {
// 0 === -0, but they are not identical
return x !== 0 || 1 / x === 1 / y;
}
// NaN !== NaN, but they are identical.
// NaNs are the only non-reflexive value, i.e., if x !== x,
// then x is a NaN.
// isNaN is broken: it converts its argument to number, so
// isNaN("foo") => true
return x !== x && y !== y;
};
}
function deepCopy(obj) {
function deepCopyInternal(obj, result) {
var key, val;
for (key in obj) {
if (key.lastIndexOf('__', 0) === 0) {
continue;
}
if (obj.hasOwnProperty(key)) {
val = obj[key];
if (typeof val === 'object' && val !== null) {
if (val instanceof RegExp) {
val = new RegExp(val);
} else {
val = deepCopyInternal(val, isArray(val) ? [] : {});
}
}
result[key] = val;
}
}
return result;
}
return deepCopyInternal(obj, isArray(obj) ? [] : {});
}
function assert(cond, text) {
if (!cond) {
throw new Error(text);
}
}
function unreachable() {
throw new Error('Unreachable point. logically broken.');
}
function isIdentifier(name) {
// fallback for ES3
if (esutils.keyword.isKeywordES5(name, true) || esutils.keyword.isRestrictedWord(name)) {
return false;
}
return esutils.keyword.isIdentifierNameES5(name);
}
function mayBeCompletionValue(node, ancestors) {
var i, ancestor;
if (node.type !== Syntax.ExpressionStatement) {
return true;
}
for (i = ancestors.length - 1; i >= 0; --i, node = ancestor) {
ancestor = ancestors[i];
switch (ancestor.type) {
case Syntax.FunctionExpression:
case Syntax.FunctionDeclaration:
return false;
case Syntax.BlockStatement:
case Syntax.Program:
if (arrayLast(ancestor.body) !== node) {
return false;
}
break;
case Syntax.SwitchCase:
if (arrayLast(ancestor.consequent) !== node) {
return false;
}
break;
}
}
return true;
}
function moveLocation(from, to) {
if (from.loc == null) {
return to;
}
to.loc = deepCopy(from.loc);
return to;
}
function deleteLocation(node) {
if (node.hasOwnProperty('loc')) {
return delete node.loc;
}
return false;
}
function convertToEmptyStatement(node) {
var i, iz, keys;
keys = estraverse.VisitorKeys[node.type];
for (i = 0, iz = keys.length; i < iz; ++i) {
delete node[keys[i]];
}
node.type = Syntax.EmptyStatement;
return node;
}
function isNegative(value) {
return value === value && (value < 0 || (value === 0 && 1 / value < 0));
}
function isFunctionBody(node, parent) {
return node.type === Syntax.BlockStatement && (parent.type === Syntax.FunctionDeclaration || parent.type === Syntax.FunctionExpression);
}
function isNumberLiteral(node) {
return node.type === Syntax.Literal && typeof node.value === 'number';
}
function isOptimizedArgument(argument) {
return isNumberLiteral(argument) && String(argument.value).length === 1;
}
function generateNegativeNode(value, node) {
var result;
result = {
type: Syntax.UnaryExpression,
operator: '-',
argument: {
type: Syntax.Literal,
value: -value
}
};
return (node) ? moveLocation(node, result) : result;
}
function isNegativeNode(node) {
return node.type === Syntax.UnaryExpression && node.operator === '-' && isNumberLiteral(node.argument);
}
function generateUndefined(node) {
var result = {
type: Syntax.UnaryExpression,
operator: 'void',
argument: {
type: Syntax.Literal,
value: 0
}
};
return (node) ? moveLocation(node, result) : result;
}
function isUndefined(node) {
return node.type === Syntax.UnaryExpression && node.operator === 'void' && isOptimizedArgument(node.argument);
}
function generateNaN(node) {
var result = {
type: Syntax.BinaryExpression,
operator: '/',
left: {
type: Syntax.Literal,
value: 0
},
right: {
type: Syntax.Literal,
value: 0
}
};
return (node) ? moveLocation(node, result) : result;
}
function isNaNNode(node) {
if (node.type === Syntax.BinaryExpression) {
if (isOptimizedArgument(node.left) && isOptimizedArgument(node.right)) {
return node.left.value === 0 && node.right.value === 0;
}
}
return false;
}
function generateFromValue(value) {
if (typeof value === 'number') {
if (isNaN(value)) {
return generateNaN();
}
if (isNegative(value)) {
return generateNegativeNode(value);
}
}
if (value === undefined) {
return generateUndefined();
}
return {
type: Syntax.Literal,
value: value
};
}
function isReference(node) {
var type = node.type;
return type === Syntax.Identifier || type === Syntax.MemberExpression;
}
// @param last last element of SequenceExpression
// @param parent parent element of SequenceExpression
// @param scope scope
function canExtractSequence(last, parent, scope) {
var ref;
if (parent.type === Syntax.CallExpression) {
if (last.type === Syntax.Identifier) {
if (last.name === 'eval') {
// This becomes direct call to eval.
return false;
}
ref = scope.resolve(last);
return ref && ref.isStatic();
}
return last.type !== Syntax.MemberExpression;
} else if (parent.type === Syntax.UnaryExpression) {
if (parent.operator === 'delete') {
return !isReference(last);
} else if (parent.operator === 'typeof') {
if (last.type === Syntax.Identifier) {
ref = scope.resolve(last);
return ref && ref.isStatic();
}
}
} else if (parent.type === Syntax.UpdateExpression) {
return !isReference(last);
}
return true;
}
function isFunctionNode(node) {
return node.type === Syntax.Program ||
node.type === Syntax.FunctionDeclaration ||
node.type === Syntax.FunctionExpression ||
node.type === Syntax.ArrowFunctionExpression;
}
function delegateVariableDeclarations(stmt, func) {
var decls, target;
decls = [];
estraverse.traverse(stmt, {
enter: function (node) {
var i, iz, decl;
if (node.type === Syntax.VariableDeclaration) {
if (node.kind === 'let' || node.kind === 'const') {
return;
}
for (i = 0, iz = node.declarations.length; i < iz; ++i) {
decl = node.declarations[i];
delete decl.init;
decls.push(decl);
}
return this.skip();
} else if (isFunctionNode(node)) {
return this.skip();
}
}
});
if (!decls.length) {
return null;
}
target = null;
estraverse.traverse(func.body, {
enter: function (node, parent) {
if (node === stmt) {
return this.skip();
}
if (isFunctionNode(node)) {
return this.skip();
}
if (node.type === Syntax.VariableDeclaration && node.kind === 'var') {
// list is not allowed
if (parent.type !== Syntax.ForInStatement) {
target = node;
return this['break']();
}
}
}
});
if (target) {
target.declarations = target.declarations.concat(decls);
return null;
} else {
return {
type: Syntax.VariableDeclaration,
kind: 'var',
declarations: decls
};
}
}
function isScopedDeclaration(node) {
if (node.type === Syntax.VariableDeclaration && (node.kind === 'let' || node.kind === 'const')) {
return true;
} else if (node.type === Syntax.FunctionDeclaration) {
return true;
}
return false;
}
exports.deepCopy = deepCopy;
exports.stringRepeat = stringRepeat;
exports.sameValue = sameValue;
exports.Array = {
from: arrayFrom,
of: arrayOf,
last: arrayLast,
empty: arrayEmpty
};
exports.Object = {
isObject: isObject,
has: has
};
exports.Syntax = Syntax;
exports.assert = assert;
exports.unreachable = unreachable;
exports.isIdentifier = isIdentifier;
exports.moveLocation = moveLocation;
exports.deleteLocation = deleteLocation;
exports.convertToEmptyStatement = convertToEmptyStatement;
exports.mayBeCompletionValue = mayBeCompletionValue;
exports.isNegative = isNegative;
exports.isFunctionNode = isFunctionNode;
exports.isFunctionBody = isFunctionBody;
exports.SpecialNode = {
generateNegative: generateNegativeNode,
isNegative: isNegativeNode,
generateUndefined: generateUndefined,
isUndefined: isUndefined,
generateNaN: generateNaN,
isNaN: isNaNNode,
isReference: isReference,
canExtractSequence: canExtractSequence,
generateFromValue: generateFromValue
};
exports.delegateVariableDeclarations = delegateVariableDeclarations;
exports.isScopedDeclaration = isScopedDeclaration;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"escope":115,"estraverse":129,"esutils":134,"isarray":139}],3:[function(require,module,exports){
/*!
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global exports:true*/
(function () {
'use strict';
var camelCase,
esshorten,
estraverse,
esutils,
isArray,
common,
Options,
Syntax,
Pass,
annotateDirective;
camelCase = require('camel-case');
esshorten = require('esshorten2');
estraverse = require('estraverse');
esutils = require('esutils');
isArray = require('isarray');
common = require('./common');
Options = require('./options');
Pass = require('./pass');
annotateDirective = require('./annotate-directive');
Syntax = common.Syntax;
// recover some broken AST
function recover(tree, useDirectiveStatement) {
estraverse.traverse(tree, {
leave: function leave(node) {
if (esutils.ast.isProblematicIfStatement(node)) {
node.consequent = {
type: Syntax.BlockStatement,
body: [ node.consequent ]
};
}
if (!useDirectiveStatement && node.type === Syntax.DirectiveStatement) {
node.type = Syntax.ExpressionStatement;
node.expression = common.moveLocation(node, {
type: Syntax.Literal,
value: node.value,
raw: node.raw
});
delete node.directive;
delete node.value;
delete node.raw;
}
}
});
return tree;
}
function iteration(tree, p, options) {
var i, iz, pass, res, changed, statuses, passes, result;
function addPass(pass) {
var name, camelCaseName;
if (typeof pass !== 'function') {
// automatic lookup pass (esmangle pass format)
name = Object.keys(pass)[0];
pass = pass[name];
}
if (pass.hasOwnProperty('passName')) {
name = pass.passName;
} else {
name = pass.name;
}
camelCaseName = camelCase(name);
if (typeof options.data.passes === 'undefined' ||
options.data.passes[camelCaseName]) {
passes.push(pass);
statuses.push(true);
}
}
function fillStatuses(bool) {
var i, iz;
for (i = 0, iz = statuses.length; i < iz; ++i) {
statuses[i] = bool;
}
}
result = (options.get('destructive')) ? tree : common.deepCopy(tree);
statuses = [];
passes = [];
for (i = 0, iz = p.length; i < iz; ++i) {
addPass(p[i]);
}
do {
changed = false;
for (i = 0, iz = passes.length; i < iz; ++i) {
pass = passes[i];
if (statuses[i]) {
res = pass(result, options);
if (res.modified) {
changed = true;
fillStatuses(true);
} else {
statuses[i] = false;
}
result = res.result;
}
}
} while (changed);
return result;
}
function optimize(tree, pipeline, options) {
var i, iz, j, jz, section, pass, passName;
options = new Options(options);
tree = annotateDirective(tree, new Options({ destructive: options.data.destructive }));
if (null == pipeline) {
pipeline = Pass.__defaultPipeline;
}
for (i = 0, iz = pipeline.length; i < iz; ++i) {
section = pipeline[i];
// simple iterative pass
if (isArray(section)) {
tree = iteration(tree, section, options);
} else if (section.once) {
pass = section.pass;
for (j = 0, jz = pass.length; j < jz; ++j) {
passName = camelCase(pass[j].passName);
if (typeof options.data.passes === 'undefined' ||
options.data.passes[passName]) {
tree = pass[j](tree, options).result;
}
}
}
}
return recover(tree, options.get('directive'));
}
exports.version = require('../package.json').version;
exports.mangle = esshorten.mangle;
exports.optimize = optimize;
exports.pass = Pass;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../package.json":159,"./annotate-directive":1,"./common":2,"./options":6,"./pass":7,"camel-case":44,"esshorten2":125,"estraverse":129,"esutils":134,"isarray":139}],4:[function(require,module,exports){
/*
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jshint eqeqeq:false*/
(function () {
'use strict';
var Syntax, common;
common = require('./common');
Syntax = common.Syntax;
// constant
function isConstant(node, allowRegExp) {
if (node.type === Syntax.Literal) {
if (typeof node.value === 'object' && node.value !== null) {
// This is RegExp
return allowRegExp;
}
return true;
}
if (node.type === Syntax.UnaryExpression) {
if (node.operator === 'void' || node.operator === 'delete' || node.operator === '!') {
return isConstant(node.argument, true);
}
return isConstant(node.argument, false);
}
if (node.type === Syntax.BinaryExpression) {
if (node.operator === 'in' || node.operator === 'instanceof') {
return false;
}
return isConstant(node.left, false) && isConstant(node.right, false);
}
if (node.type === Syntax.LogicalExpression) {
return isConstant(node.left, true) && isConstant(node.right, true);
}
return false;
}
function getConstant(node) {
if (node.type === Syntax.Literal) {
return node.value;
}
if (node.type === Syntax.UnaryExpression) {
return doUnary(node.operator, getConstant(node.argument));
}
if (node.type === Syntax.BinaryExpression) {
return doBinary(node.operator, getConstant(node.left), getConstant(node.right));
}
if (node.type === Syntax.LogicalExpression) {
return doLogical(node.operator, getConstant(node.left), getConstant(node.right));
}
common.unreachable();
}
function doLogical(operator, left, right) {
if (operator === '||') {
return left || right;
}
if (operator === '&&') {
return left && right;
}
common.unreachable();
}
function doUnary(operator, argument) {
switch (operator) {
case '+':
return +argument;
case '-':
return -argument;
case '~':
return ~argument;
case '!':
return !argument;
case 'delete':
// do delete on constant value (not considering identifier in this tree based constant folding)
return true;
case 'void':
return undefined;
case 'typeof':
return typeof argument;
}
common.unreachable();
}
function doBinary(operator, left, right) {
switch (operator) {
case '|':
return left | right;
case '^':
return left ^ right;
case '&':
return left & right;
case '==':
return left == right;
case '!=':
return left != right;
case '===':
return left === right;
case '!==':
return left !== right;
case '<':
return left < right;
case '>':
return left > right;
case '<=':
return left <= right;
case '>=':
return left >= right;
// case 'in':
// return left in right;
// case 'instanceof':
// return left instanceof right;
case '<<':
return left << right;
case '>>':
return left >> right;
case '>>>':
return left >>> right;
case '+':
return left + right;
case '-':
return left - right;
case '*':
return left * right;
case '/':
return left / right;
case '%':
return left % right;
}
common.unreachable();
}
exports.constant = {
doBinary: doBinary,
doUnary: doUnary,
doLogical: doLogical,
evaluate: getConstant,
isConstant: isConstant
};
// has side effect
function hasSideEffect(expr, scope) {
function visit(expr) {
var i, iz, ref;
switch (expr.type) {
case Syntax.AssignmentExpression:
return true;
case Syntax.ArrayExpression:
for (i = 0, iz = expr.elements.length; i < iz; ++i) {
if (expr.elements[i] !== null && visit(expr.elements[i])) {
return true;
}
}
return false;
case Syntax.BinaryExpression:
return !isConstant(expr);
case Syntax.CallExpression:
return true;
case Syntax.ConditionalExpression:
return visit(expr.test) || visit(expr.consequent) || visit(expr.alternate);
case Syntax.FunctionExpression:
return false;
case Syntax.Identifier:
ref = scope.resolve(expr);
if (ref && ref.isStatic()) {
return false;
}
return true;
case Syntax.Literal:
return false;
case Syntax.LogicalExpression:
return visit(expr.left) || visit(expr.right);
case Syntax.MemberExpression:
return true;
case Syntax.NewExpression:
return true;
case Syntax.ObjectExpression:
for (i = 0, iz = expr.properties.length; i < iz; ++i) {
if (visit(expr.properties[i])) {
return true;
}
}
return false;
case Syntax.Property:
return visit(expr.value);
case Syntax.SequenceExpression:
for (i = 0, iz = expr.expressions.length; i < iz; ++i) {
if (visit(expr.expressions[i])) {
return true;
}
}
return false;
case Syntax.ThisExpression:
return false;
case Syntax.UnaryExpression:
if (expr.operator === 'void' || expr.operator === 'delete' || expr.operator === 'typeof' || expr.operator === '!') {
return visit(expr.argument);
}
return !isConstant(expr);
case Syntax.UpdateExpression:
return true;
}
return true;
}
return visit(expr);
}
exports.hasSideEffect = hasSideEffect;
// boolean decision
// @return {boolean|null} when indeterminate value comes, returns null
function booleanCondition(expr) {
var ret;
switch (expr.type) {
case Syntax.AssignmentExpression:
return booleanCondition(expr.right);
case Syntax.ArrayExpression:
return true;
case Syntax.BinaryExpression:
if (isConstant(expr)) {
return !!getConstant(expr);
}
return null;
case Syntax.CallExpression:
return null;
case Syntax.ConditionalExpression:
ret = booleanCondition(expr.test);
if (ret === true) {
return booleanCondition(expr.consequent);
}
if (ret === false) {
return booleanCondition(expr.alternate);
}
ret = booleanCondition(expr.consequent);
if (ret === booleanCondition(expr.alternate)) {
return ret;
}
return null;
case Syntax.FunctionExpression:
return true;
case Syntax.Identifier:
return null;
case Syntax.Literal:
return !!getConstant(expr);
case Syntax.LogicalExpression:
if (expr.operator === '&&') {
ret = booleanCondition(expr.left);
if (ret === null) {
return null;
}
if (!ret) {
return false;
}
return booleanCondition(expr.right);
} else {
ret = booleanCondition(expr.left);
if (ret === null) {
return null;
}
if (ret) {
return true;
}
return booleanCondition(expr.right);
}
return null;
case Syntax.MemberExpression:
return null;
case Syntax.NewExpression:
// always return object
return true;
case Syntax.ObjectExpression:
return true;
case Syntax.Property:
common.unreachable();
return null;
case Syntax.SequenceExpression:
return booleanCondition(common.Array.last(expr.expressions));
case Syntax.ThisExpression:
// in strict mode, this may be null / undefined
return null;
case Syntax.UnaryExpression:
if (expr.operator === 'void') {
return false;
}
if (expr.operator === 'typeof') {
return true;
}
if (expr.operator === '!') {
ret = booleanCondition(expr.argument);
if (ret === null) {
return null;
}
return !ret;
}
if (isConstant(expr)) {
return !!getConstant(expr);
}
return null;
case Syntax.UpdateExpression:
return null;
}
return null;
}
exports.booleanCondition = booleanCondition;
}());
},{"./common":2}],5:[function(require,module,exports){
(function (global){
/*
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*global module:true*/
(function () {
'use strict';
var Map;
if (typeof global.Map !== 'undefined') {
// ES6 Map
Map = global.Map;
} else {
Map = function Map() {
this.__data = {};
};
Map.prototype.get = function MapGet(key) {
key = '$' + key;
if (this.__data.hasOwnProperty(key)) {
return this.__data[key];
}
};
Map.prototype.has = function MapHas(key) {
key = '$' + key;
return this.__data.hasOwnProperty(key);
};
Map.prototype.set = function MapSet(key, val) {
key = '$' + key;
this.__data[key] = val;
};
Map.prototype['delete'] = function MapDelete(key) {
key = '$' + key;
return delete this.__data[key];
};
Map.prototype.clear = function MapClear() {
this.__data = {};
};
Map.prototype.forEach = function MapForEach(callback, thisArg) {
var real, key;
for (real in this.__data) {
if (this.__data.hasOwnProperty(real)) {
key = real.substring(1);
callback.call(thisArg, this.__data[real], key, this);
}
}
};
Map.prototype.keys = function MapKeys() {
var real, result;
result = [];
for (real in this.__data) {
if (this.__data.hasOwnProperty(real)) {
result.push(real.substring(1));
}
}
return result;
};
Map.prototype.values = function MapValues() {
var real, result;
result = [];
for (real in this.__data) {
if (this.__data.hasOwnProperty(real)) {
result.push(this.__data[real]);
}
}
return result;
};
Map.prototype.items = function MapItems() {
var real, result;
result = [];
for (real in this.__data) {
if (this.__data.hasOwnProperty(real)) {
result.push([real.substring(1), this.__data[real]]);
}
}
return result;
};
}
module.exports = Map;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],6:[function(require,module,exports){
/*
Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
(function () {
'use strict';
var common;
common = require('./common');
function extend(result, update) {
var prop, lhs, rhs;
for (prop in update) {
if (!common.Object.has(update, prop)) {
continue;
}
if (prop in result) {
lhs = result[prop];
rhs = update[prop];
if (common.Object.isObject(rhs) && common.Object.isObject(lhs)) {
result[prop] = extend(lhs, rhs);
} else {
result[prop] = update[prop];
}
} else {
result[prop] = update[prop];
}
}
return result;
}
function Options(override) {
var defaults = {
destructive: true,
preserveCompletionValue: false,
legacy: true,
topLevelContext: 'global', // Specifies 'global', 'module', 'function' etc.
inStrictCode: false // Top level is strict or not
};
if (override == null) {
this.data = defaults;
return;
}
this.data = extend(defaults, override);
}
// options.get(name, {
// pathName: pathName
// });
Options.prototype.get = function get(name, details) {
var local;
if (details != null) {
if (common.Object.has(details, 'pathName')) {
local = this.data[details.pathName];
if (local != null && common.Object.has(local, name)) {
return local[name];
}
}
}
return this.data[name];
};
module.exports = Options;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"./common":2}],7:[function(require,module,exports){
/*
Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global exports:true*/
(function () {
'use strict';
var query, Registry, pass, post, common;
common = require('./common');
query = require('./query');
Registry = {};
Registry.__direct = {};
// initialization
function initialize(kind, passes) {
var i, iz, pass;
Registry[kind] = {};
for (i = 0, iz = passes.length; i < iz; ++i) {
pass = passes[i];
common.assert(Registry[kind][pass.passName] == null, 'don\'t create duplicate pass names');
Registry[kind][pass.passName] = pass;
}
common.assert(Registry.__direct[pass.passName] == null, 'don\'t create duplicate pass names');
Registry.__direct[pass.passName] = pass;
}
pass = [
require('./pass/hoist-variable-to-arguments'),
require('./pass/transform-dynamic-to-static-property-access'),
require('./pass/transform-dynamic-to-static-property-definition'),
require('./pass/transform-immediate-function-call'),
require('./pass/transform-logical-association'),
require('./pass/reordering-function-declarations'),
require('./pass/remove-unused-label'),
require('./pass/remove-empty-statement'),
require('./pass/remove-wasted-blocks'),
require('./pass/transform-to-compound-assignment'),
require('./pass/transform-to-sequence-expression'),
require('./pass/transform-branch-to-expression'),
require('./pass/transform-typeof-undefined'),
require('./pass/reduce-sequence-expression'),
require('./pass/reduce-branch-jump'),
require('./pass/reduce-multiple-if-statements'),
require('./pass/dead-code-elimination'),
require('./pass/remove-side-effect-free-expressions'),
require('./pass/remove-context-sensitive-expressions'),
require('./pass/tree-based-constant-folding'),
require('./pass/concatenate-variable-definition'),
require('./pass/drop-variable-definition'),
require('./pass/remove-unreachable-branch'),
require('./pass/eliminate-duplicate-function-declarations'),
require('./pass/typeof-prefix-comparison'),
require('./pass/top-level-variable-declaration-to-assignment'),
];
post = [
require('./post/transform-static-to-dynamic-property-access'),
require('./post/transform-infinity'),
require('./post/rewrite-boolean'),
require('./post/rewrite-conditional-expression'),
require('./post/omit-parens-in-void-context-iife')
];
initialize('pass', pass);
initialize('post', post);
function passRequire(name) {
if (common.Object.has(Registry.__direct, name)) {
return Registry.__direct[name];
}
return query.get(Registry, name.split('/'));
}
exports.require = passRequire;
exports.Registry = Registry;
// CAUTION:(Constellation)
// This API would be changed
exports.__defaultPipeline = [
pass,
{
once: true,
pass: post
}
];
}());
},{"./common":2,"./pass/concatenate-variable-definition":8,"./pass/dead-code-elimination":9,"./pass/drop-variable-definition":10,"./pass/eliminate-duplicate-function-declarations":11,"./pass/hoist-variable-to-arguments":12,"./pass/reduce-branch-jump":13,"./pass/reduce-multiple-if-statements":14,"./pass/reduce-sequence-expression":15,"./pass/remove-context-sensitive-expressions":16,"./pass/remove-empty-statement":17,"./pass/remove-side-effect-free-expressions":18,"./pass/remove-unreachable-branch":19,"./pass/remove-unused-label":20,"./pass/remove-wasted-blocks":21,"./pass/reordering-function-declarations":22,"./pass/top-level-variable-declaration-to-assignment":23,"./pass/transform-branch-to-expression":24,"./pass/transform-dynamic-to-static-property-access":25,"./pass/transform-dynamic-to-static-property-definition":26,"./pass/transform-immediate-function-call":27,"./pass/transform-logical-association":28,"./pass/transform-to-compound-assignment":29,"./pass/transform-to-sequence-expression":30,"./pass/transform-typeof-undefined":31,"./pass/tree-based-constant-folding":32,"./pass/typeof-prefix-comparison":33,"./post/omit-parens-in-void-context-iife":34,"./post/rewrite-boolean":35,"./post/rewrite-conditional-expression":36,"./post/transform-infinity":37,"./post/transform-static-to-dynamic-property-access":38,"./query":39}],8:[function(require,module,exports){
/*
Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, estraverse, common, modified;
Name = 'concatenate-variable-definition';
estraverse = require('estraverse');
common = require('../common');
Syntax = common.Syntax;
function concatenateVariableDefinition(tree, options) {
var result;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
modified = false;
estraverse.traverse(result, {
leave: function leave(node) {
var i, iz, j, jz, stmt, decl, target, body;
if (node.type !== Syntax.BlockStatement && node.type !== Syntax.Program) {
return;
}
// concat sequencial variable definition to one
target = null;
body = [];
for (i = 0, iz = node.body.length; i < iz; ++i) {
stmt = node.body[i];
if (stmt.type === Syntax.VariableDeclaration && stmt.kind === 'var') {
if (!target) {
target = stmt;
body.push(stmt);
continue;
}
modified = true;
for (j = 0, jz = stmt.declarations.length; j < jz; ++j) {
decl = stmt.declarations[j];
target.declarations.push(decl);
}
} else {
target = null;
body.push(stmt);
}
}
node.body = body;
}
});
return {
result: result,
modified: modified
};
}
concatenateVariableDefinition.passName = Name;
module.exports = concatenateVariableDefinition;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"estraverse":129}],9:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name,
Syntax,
estraverse,
common,
status,
modified;
Name = 'dead-code-elimination';
estraverse = require('estraverse');
common = require('../common');
Syntax = common.Syntax;
function JumpTarget(node, status, type) {
this.node = node;
this.type = type;
this.labels = status.labels || [];
status.labels = null;
}
JumpTarget.NAMED_ONLY = 0; // (00)2
JumpTarget.ITERATION = 2; // (10)2
JumpTarget.SWITCH = 3; // (11)2
JumpTarget.prototype.isIteration = function isIteration() {
return this.type === JumpTarget.ITERATION;
};
JumpTarget.prototype.isAnonymous = function isAnonymous() {
return this.type & 2;
};
JumpTarget.prototype.contains = function contains(label) {
return this.labels.indexOf(label) !== -1;
};
function Jumps() {
this.targets = [];
}
Jumps.prototype.lookupContinuableTarget = function lookupContinuableTarget(label) {
var i, target;
for (i = this.targets.length - 1; i >= 0; --i) {
target = this.targets[i];
if (target.isIteration() && (!label || target.contains(label.name))) {
return target.node;
}
}
common.unreachable();
};
Jumps.prototype.lookupBreakableTarget = function lookupBreakableTarget(label) {
var i, target;
for (i = this.targets.length - 1; i >= 0; --i) {
target = this.targets[i];
if (label) {
if (target.contains(label.name)) {
return target.node;
}
} else {
if (target.isAnonymous()) {
return target.node;
}
}
}
common.unreachable();
};
Jumps.prototype.push = function push(target) {
this.targets.push(target);
};
Jumps.prototype.pop = function pop() {
this.targets.pop();
};
// Status implementation
//
// This is based on Constellation/iv lv5 railgun compiler continuation_status.h
function Status(upper) {
this.current = [];
this.upper = upper;
this.jumps = new Jumps();
this.labels = null;
this.next();
}
Status.NEXT = {};
Status.prototype.insert = function insert(stmt) {
this.current.push(stmt);
};
Status.prototype.erase = function erase(stmt) {
var index = this.current.indexOf(stmt);
if (index === -1) {
return false;
}
this.current.splice(index, 1);
return true;
};
Status.prototype.kill = function kill() {
return this.erase(Status.NEXT);
};
Status.prototype.has = function has(stmt) {
return this.current.indexOf(stmt) !== -1;
};
Status.prototype.jumpTo = function jumpTo(stmt) {
this.kill();
this.insert(stmt);
};
Status.prototype.resolveJump = function resolveJump(stmt) {
var index = this.current.indexOf(stmt);
if (index !== -1) {
this.current.splice(index, 1);
this.insert(Status.NEXT);
}
};
Status.prototype.clear = function clear() {
this.current.length = 0;
};
Status.prototype.next = function next() {
this.insert(Status.NEXT);
};
Status.prototype.isDead = function isDead() {
return !this.has(Status.NEXT);
};
Status.prototype.revive = function revive() {
if (this.isDead()) {
this.next();
return true;
}
return false;
};
Status.prototype.register = function register(node) {
if (!this.labels) {
this.labels = [];
}
this.labels.push(node.label.name);
};
Status.prototype.unregister = function unregister() {
this.labels = null;
};
Status.isRequired = function isRequired(node) {
var type = node.type;
common.assert(node, 'should be node');
return type === Syntax.Program ||
type === Syntax.FunctionExpression ||
type === Syntax.FunctionDeclaration ||
type === Syntax.ArrowFunctionExpression;
};
function Context(node) {
node.__$context = this;
this.node = node;
}
Context.prototype.detach = function detach() {
delete this.node.__$context;
};
Context.lookup = function lookup(node) {
return node.__$context;
};
function getForwardLastNode(node) {
while (true) {
switch (node.type) {
case Syntax.IfStatement:
if (node.alternate) {
return null;
}
node = node.consequent;
continue;
case Syntax.WithStatement:
case Syntax.LabeledStatement:
node = node.body;
continue;
case Syntax.BlockStatement:
if (node.body.length) {
node = common.Array.last(node.body);
continue;
}
break;
}
return node;
}
}
function visitLoopBody(loop, body) {
var jump, last;
last = getForwardLastNode(body);
if (last) {
if (last.type === Syntax.ContinueStatement) {
jump = status.jumps.lookupContinuableTarget(last.label);
if (jump === loop) {
// this continue is dead code
modified = true;
common.convertToEmptyStatement(last);
}
}
}
return visit(body);
}
function visit(target) {
var live = false;
if (!target) {
return !status.isDead();
}
function eliminate(node, array) {
var i, iz, stmt, ret, info, result;
result = [];
for (i = 0, iz = array.length; i < iz; ++i) {
stmt = array[i];
if (stmt.type === Syntax.IfStatement) {
info = new Context(stmt);
ret = visit(stmt);
info.detach();
} else {
ret = visit(stmt);
}
if (ret) {
live |= 1;
result.push(stmt);
// we transform
// if (cond) {
// #1
// return;
// } else
// #2;
// #3
// to
// if (cond) {
// #1
// return;
// }
// #2
// #3
//
// and
//
// if (cond)
// #1;
// else {
// #2
// return;
// }
// #3
// to
// if (!cond) {
// #2
// return;
// }
// #1
// #3
if (stmt.type === Syntax.IfStatement && stmt.alternate) {
if ((!info.consequent || !info.alternate) && info.consequent !== info.alternate) {
modified = true;
if (info.consequent) {
stmt.test = common.moveLocation(stmt.test, {
type: Syntax.UnaryExpression,
operator: '!',
argument: stmt.test
});
result.push(stmt.consequent);
stmt.consequent = stmt.alternate;
stmt.alternate = null;
} else { // info.alternate
result.push(stmt.alternate);
stmt.alternate = null;
}
}
}
} else {
// deleted
modified = true;
}
}
return result;
}
estraverse.traverse(target, {
enter: function enter(node) {
var i, iz, stmt, consequent, alternate, ctx, hasDefaultClause, handlers;
if (Status.isRequired(node)) {
status = new Status(status);
}
live |= !status.isDead();
switch (node.type) {
case Syntax.Program:
node.body = eliminate(node, node.body);
return this.skip();
case Syntax.BlockStatement:
status.jumps.push(new JumpTarget(node, status, JumpTarget.NAMED_ONLY));
node.body = eliminate(node, node.body);
status.jumps.pop();
status.resolveJump(node);
return this.skip();
case Syntax.BreakStatement:
// like
// label: break label;
// we treat as like empty statement
if (node.label && status.labels && status.labels.indexOf(node.label)) {
// change this statement to empty statement
modified = true;
common.convertToEmptyStatement(node);
} else {
status.jumpTo(status.jumps.lookupBreakableTarget(node.label));
}
return this.skip();
case Syntax.CatchClause:
live |= visit(node.body);
return this.skip();
case Syntax.ContinueStatement:
status.jumpTo(status.jumps.lookupContinuableTarget(node.label));
return this.skip();
case Syntax.DoWhileStatement:
status.jumps.push(new JumpTarget(node, status, JumpTarget.ITERATION));
live |= visitLoopBody(node, node.body);
status.jumps.pop();
live |= visit(node.test);
status.resolveJump(node);
status.revive();
return this.skip();
case Syntax.DebuggerStatement:
return this.skip();
case Syntax.EmptyStatement:
return this.skip();
case Syntax.ExpressionStatement:
break;
case Syntax.ForStatement:
live |= visit(node.init);
live |= visit(node.test);
status.jumps.push(new JumpTarget(node, status, JumpTarget.ITERATION));
live |= visitLoopBody(node, node.body);
status.jumps.pop();
live |= visit(node.update);
status.resolveJump(node);
status.revive();
return this.skip();
case Syntax.ForInStatement:
live |= visit(node.left);
live |= visit(node.right);
status.jumps.push(new JumpTarget(node, status, JumpTarget.ITERATION));
live |= visitLoopBody(node, node.body);
status.jumps.pop();
status.resolveJump(node);
status.revive();
return this.skip();
case Syntax.IfStatement:
live |= visit(node.test);
live |= visit(node.consequent);
if (!node.alternate) {
status.revive();
return this.skip();
}
consequent = !status.isDead();
if (!status.revive()) {
status.insert(node);
}
live |= visit(node.alternate);
alternate = !status.isDead();
if (status.erase(node)) {
status.revive();
}
if ((ctx = Context.lookup(node))) {
ctx.consequent = consequent;
ctx.alternate = alternate;
}
return this.skip();
case Syntax.LabeledStatement:
status.register(node);
break;
case Syntax.ReturnStatement:
live |= visit(node.argument);
status.kill();
return this.skip();
case Syntax.SwitchStatement:
visit(node.discriminant);
status.jumps.push(new JumpTarget(node, status, JumpTarget.SWITCH));
for (i = 0, iz = node.cases.length; i < iz; ++i) {
stmt = node.cases[i];
live |= visit(stmt);
if (!stmt.test) {
hasDefaultClause = true;
}
if (status.isDead() && (i + 1) < iz) {
status.next();
}
}
status.jumps.pop();
status.resolveJump(node);
if (status.isDead() && !hasDefaultClause) {
status.next();
}
return this.skip();
case Syntax.SwitchCase:
if (node.test) {
live |= visit(node.test);
}
node.consequent = eliminate(node, node.consequent);
return this.skip();
case Syntax.ThrowStatement:
live |= visit(node.argument);
status.kill();
return this.skip();
case Syntax.TryStatement:
live |= visit(node.block);
// NOTE: TryStatement interface changed from {handlers: [CatchClause]} to {handler: CatchClause}; we support both
handlers = node.handlers || (node.handler ? [node.handler] : []);
if (handlers && handlers.length) {
if (!status.revive()) {
status.insert(node);
}
handlers = eliminate(node, handlers);
node.handler = handlers.shift();
delete node.handlers;
if (status.erase(node)) {
status.revive();
}
}
if (node.finalizer) {
if (!status.revive()) {
status.insert(node);
}
live |= visit(node.finalizer);
if (!status.erase(node)) {
status.kill();
}
}
return this.skip();
case Syntax.WhileStatement:
live |= visit(node.test);
status.jumps.push(new JumpTarget(node, status, JumpTarget.ITERATION));
live |= visitLoopBody(node, node.body);
status.jumps.pop();
status.resolveJump(node);
status.revive();
return this.skip();
case Syntax.WithStatement:
break;
case Syntax.VariableDeclaration:
case Syntax.FunctionDeclaration:
live = true;
break;
}
},
leave: function leave(node) {
if (Status.isRequired(node)) {
status = status.upper;
return;
}
if (node.type === Syntax.LabeledStatement) {
status.unregister();
}
}
});
return live;
}
// This is iv / lv5 / railgun bytecode compiler dead code elimination algorithm
function deadCodeElimination(tree, options) {
var result;
result = (options.get('destructive', { pathName: Name })) ? tree : common.deepCopy(tree);
status = null;
modified = false;
visit(result);
common.assert(status === null, 'status should be null');
return {
result: result,
modified: modified
};
}
deadCodeElimination.passName = Name;
module.exports = deadCodeElimination;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"estraverse":129}],10:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, common, modified, estraverse, escope, evaluator;
Name = 'drop-variable-definition';
estraverse = require('estraverse');
escope = require('escope');
common = require('../common');
evaluator = require('../evaluator');
Syntax = common.Syntax;
function getCandidates(scope) {
var i, iz, j, jz, identifiers, slots, v;
if (!scope.candidates) {
slots = [];
identifiers = [];
for (i = 0, iz = scope.variables.length; i < iz; ++i) {
v = scope.variables[i];
for (j = 0, jz = v.identifiers.length; j < jz; ++j) {
identifiers.push(v.identifiers[j]);
slots.push(v);
}
}
scope.candidates = {
slots: slots,
identifiers: identifiers
};
}
return scope.candidates;
}
function isRemovableDefinition(slot) {
var i, iz, ref, parent;
if (slot.identifiers.length !== 1) {
return false;
}
if (slot.references.length === 0) {
return true;
}
for (i = 0, iz = slot.references.length; i < iz; ++i) {
ref = slot.references[i];
if (ref.isRead()) {
return false;
}
if (ref.isWrite()) {
if (!ref.writeExpr) {
return false;
}
parent = ref.writeExpr.__$parent$__;
if (!parent) {
return false;
}
if (parent.type !== Syntax.AssignmentExpression &&
parent.type !== Syntax.VariableDeclarator) {
return false;
}
if (evaluator.hasSideEffect(ref.writeExpr, ref.from)) {
return false;
}
}
}
return true;
}
function overrideExpression(from, to) {
var key;
for (key in from) {
delete from[key];
}
for (key in to) {
from[key] = to[key];
}
return from;
}
function removeDefinition(node, index, slot) {
var i, iz, ref, parent;
// remove from declaration list
node.declarations.splice(index, 1);
for (i = 0, iz = slot.references.length; i < iz; ++i) {
ref = slot.references[i];
common.assert(!ref.isRead());
if (ref.isWrite()) {
parent = ref.writeExpr.__$parent$__;
if (parent.type === Syntax.AssignmentExpression) {
overrideExpression(ref.writeExpr.__$parent$__, ref.writeExpr);
}
}
}
}
function attachParent(tree) {
return estraverse.traverse(tree, {
enter: function (node, parent) {
node.__$parent$__ = parent;
}
});
}
function removeParent(tree) {
return estraverse.traverse(tree, {
enter: function (node) {
delete node.__$parent$__;
delete node.__$escope$__;
}
});
}
function dropVariableDefinition(tree, options) {
var result, manager, scope;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
modified = false;
scope = null;
manager = escope.analyze(result, { directive: true });
manager.attach();
attachParent(result);
result = estraverse.replace(result, {
enter: function enter(node, parent) {
var i, decl, cand, index, slot, ret;
ret = node;
if (scope) {
if (scope.variableScope.isStatic()) {
cand = getCandidates(scope.variableScope);
// remove unused variable
if (node.type === Syntax.VariableDeclaration && node.kind === 'var') {
i = node.declarations.length;
while (i--) {
decl = node.declarations[i];
index = cand.identifiers.indexOf(decl.id);
if (index !== -1) {
slot = cand.slots[index];
if (isRemovableDefinition(slot)) {
// ok, remove this variable
modified = true;
removeDefinition(node, i, slot);
continue;
}
}
}
if (node.declarations.length === 0) {
if (parent.type === Syntax.ForStatement) {
ret = null;
} else {
ret = common.moveLocation(node, {
type: Syntax.EmptyStatement
});
}
}
}
// remove unused function declaration
if (node.type === Syntax.FunctionDeclaration) {
index = cand.identifiers.indexOf(node.id);
if (index !== -1) {
slot = cand.slots[index];
if (slot.identifiers.length === 1 && slot.references.length === 0) {
// ok, remove this function declaration
modified = true;
ret = common.moveLocation(node, {
type: Syntax.EmptyStatement
});
return ret;
}
}
}
}
}
scope = manager.acquire(node) || scope;
return ret;
},
leave: function leave(node) {
scope = manager.release(node) || scope;
}
});
manager.detach();
removeParent(result);
return {
result: result,
modified: modified
};
}
dropVariableDefinition.passName = Name;
module.exports = dropVariableDefinition;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"../evaluator":4,"escope":115,"estraverse":129}],11:[function(require,module,exports){
/*
Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, Map, common, estraverse, modified;
Name = 'eliminate-duplicate-function-declarations';
estraverse = require('estraverse');
common = require('../common');
Map = require ('../map');
Syntax = common.Syntax;
function unique(map, root) {
return estraverse.replace(root, {
enter: function (node) {
var name, info;
if (node.type === Syntax.FunctionDeclaration) {
name = node.id.name;
info = map.get(name);
--info.count;
if (info.count !== 0) {
// Duplicate function declaration.
modified = true;
return common.moveLocation(node, { type: Syntax.EmptyStatement });
}
}
if (node !== root && node.type === Syntax.BlockStatement) {
return this.skip();
}
}
});
}
function uniqueInGlobal(map, root) {
return estraverse.replace(root, {
enter: function (node) {
var name, info, first;
if (node.type === Syntax.FunctionDeclaration) {
name = node.id.name;
info = map.get(name);
first = info.count === info.declarations.length;
--info.count;
if (info.declarations.length > 1) {
if (first) {
// replace the first declaration with the last declaration
modified = true;
return common.Array.last(info.declarations);
} else {
modified = true;
return common.moveLocation(node, { type: Syntax.EmptyStatement });
}
}
}
if (node !== root && node.type === Syntax.BlockStatement) {
return this.skip();
}
}
});
}
function main(tree, options) {
var result, stack, functionDepth, globalBlockFound;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
modified = false;
functionDepth = 0;
globalBlockFound = false;
stack = [ new Map() ];
result = estraverse.replace(result, {
enter: function enter(node) {
var map, name, info;
if (node.type === Syntax.FunctionDeclaration) {
name = node.id.name;
map = common.Array.last(stack);
if (map.has(name)) {
info = map.get(name);
info.declarations.push(node);
++info.count;
} else {
info = {
declarations: [ node ],
count: 1
};
map.set(name, info);
}
}
// To support Block scoped FunctionDeclaration (ES6)
// Syntax.FunctionExpression and Syntax.FunctionDeclaration also hold block.
if (node.type === Syntax.BlockStatement) {
stack.push(new Map());
}
if (node.type === Syntax.FunctionDeclaration || node.type === Syntax.FunctionExpression) {
++functionDepth;
}
},
leave: function leave(node) {
var map, ret;
if (node.type === Syntax.BlockStatement) {
map = stack.pop();
if (functionDepth === 0) {
if (map.keys().length !== 0) {
globalBlockFound = true;
}
} else {
ret = unique(map, node);
}
}
if (node.type === Syntax.FunctionDeclaration || node.type === Syntax.FunctionExpression) {
--functionDepth;
}
return ret;
}
});
// If we had global block that contains function declaration, we
// suppress this optimization on global code.
common.assert(stack.length === 1, 'global map remains');
if (!globalBlockFound) {
result = uniqueInGlobal(stack[0], result);
}
return {
result: result,
modified: modified
};
}
main.passName = Name;
module.exports = main;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"../map":5,"estraverse":129}],12:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, common, estraverse, escope, modified;
Name = 'hoist-variable-to-arguments';
escope = require('escope');
estraverse = require('estraverse');
common = require('../common');
Syntax = common.Syntax;
function hoist(callee) {
function hoisting(ident) {
var hoisted, i, iz;
hoisted = false;
for (i = 0, iz = callee.params.length; i < iz; ++i) {
if (ident.name === callee.params[i].name) {
// already hoisted name
hoisted = true;
break;
}
}
if (!hoisted) {
callee.params.push(ident);
}
}
callee.body = estraverse.replace(callee.body, {
enter: function (node, parent) {
var i, iz, expressions, declaration, forstmt, expr;
if (node.type === Syntax.FunctionExpression || node.type === Syntax.FunctionDeclaration) {
this.skip();
return;
}
if (node.type === Syntax.VariableDeclaration && node.kind === 'var') {
// We should consider following pattern
//
// for (var i = 0;;);
// or
// for (var i in []);
// specialize pass for `for-in`
if (parent.type === Syntax.ForInStatement) {
common.assert(node.declarations.length === 1, 'for-in declaration length should be 1');
declaration = node.declarations[0];
// not optimize
// for (var i = 1 in []);
if (declaration.init) {
return;
}
// TODO(Constellation)
// in the future, destructuring pattern may come
if (declaration.id.type !== Syntax.Identifier) {
return;
}
hoisting(declaration.id);
modified = true;
return declaration.id;
}
forstmt = parent.type === Syntax.ForStatement;
expressions = [];
for (i = 0, iz = node.declarations.length; i < iz; ++i) {
declaration = node.declarations[i];
// TODO(Constellation)
// in the future, destructuring pattern may come
if (declaration.id.type !== Syntax.Identifier) {
return;
}
hoisting(declaration.id);
if (declaration.init) {
expressions.push(common.moveLocation(declaration, {
type: Syntax.AssignmentExpression,
operator: '=',
left: declaration.id,
right: declaration.init
}));
}
}
modified = true;
if (expressions.length === 0) {
if (forstmt) {
return null;
}
return common.moveLocation(node, {
type: Syntax.EmptyStatement
});
}
if (expressions.length === 1) {
expr = expressions[0];
} else {
expr = common.moveLocation(node, {
type: Syntax.SequenceExpression,
expressions: expressions
});
}
if (forstmt) {
return expr;
}
return common.moveLocation(node, {
type: Syntax.ExpressionStatement,
expression: expr
});
}
}
});
}
function hoistVariableToArguments(tree, options) {
var result, scope, manager;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
modified = false;
scope = null;
manager = escope.analyze(result, { directive: true });
manager.attach();
estraverse.traverse(result, {
enter: function enter(node) {
var callee;
if (node.type === Syntax.CallExpression || node.type === Syntax.NewExpression) {
callee = node.callee;
if (callee.type === Syntax.FunctionExpression && !callee.id) {
if (callee.params.length === node['arguments'].length) {
scope = manager.acquire(callee);
if (!scope.isArgumentsMaterialized() && (node.type !== Syntax.NewExpression || !scope.isThisMaterialized())) {
// ok, arguments is not used
hoist(callee);
}
}
}
}
}
});
manager.detach();
return {
result: result,
modified: modified
};
}
hoistVariableToArguments.passName = Name;
module.exports = hoistVariableToArguments;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"escope":115,"estraverse":129}],13:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, common, estraverse, modified;
Name = 'reduce-branch-jump';
estraverse = require('estraverse');
common = require('../common');
Syntax = common.Syntax;
function reduceLast(ary, index) {
var node, left;
node = ary[index];
if (node.type === Syntax.IfStatement) {
if (!node.alternate) {
if (node.consequent.type === Syntax.ReturnStatement) {
modified = true;
left = node.consequent.argument;
if (!left) {
ary[index] = common.moveLocation(node, {
type: Syntax.ReturnStatement,
argument: {
type: Syntax.SequenceExpression,
expressions: [
node.test,
common.SpecialNode.generateUndefined()
]
}
});
return true;
}
ary[index] = common.moveLocation(node, {
type: Syntax.ReturnStatement,
argument: {
type: Syntax.ConditionalExpression,
test: node.test,
consequent: left,
alternate: common.SpecialNode.generateUndefined()
}
});
return true;
}
}
}
}
function reduce(ary, index) {
var node, sibling, left, right;
node = ary[index];
sibling = ary[index + 1];
if (node.type === Syntax.IfStatement) {
if (!node.alternate) {
if (node.consequent.type === Syntax.ReturnStatement && sibling.type === Syntax.ReturnStatement) {
// pattern:
// if (cond) return v;
// return v2;
modified = true;
ary.splice(index, 1);
left = node.consequent.argument;
right = sibling.argument;
if (!left && !right) {
ary[index] = common.moveLocation(node, {
type: Syntax.ReturnStatement,
argument: {
type: Syntax.SequenceExpression,
expressions: [
node.test,
common.SpecialNode.generateUndefined()
]
}
});
return true;
}
if (!left) {
left = common.SpecialNode.generateUndefined();
}
if (!right) {
right = common.SpecialNode.generateUndefined();
}
ary[index] = common.moveLocation(node, {
type: Syntax.ReturnStatement,
argument: {
type: Syntax.ConditionalExpression,
test: node.test,
consequent: left,
alternate: right
}
});
return true;
}
}
}
return false;
}
function reduceBranchJump(tree, options) {
var result;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
modified = false;
estraverse.traverse(result, {
leave: function leave(node, parent) {
var i;
switch (node.type) {
case Syntax.BlockStatement:
case Syntax.Program:
i = 0;
while (i < (node.body.length - 1)) {
if (!reduce(node.body, i)) {
++i;
}
}
if (common.isFunctionBody(node, parent)) {
if (node.body.length > 0) {
i = node.body.length - 1;
reduceLast(node.body, i);
}
}
break;
case Syntax.SwitchCase:
i = 0;
while (i < (node.consequent.length - 1)) {
if (!reduce(node.consequent, i)) {
++i;
}
}
break;
}
}
});
return {
result: result,
modified: modified
};
}
reduceBranchJump.passName = Name;
module.exports = reduceBranchJump;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"estraverse":129}],14:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, estraverse, common, modified;
Name = 'reduce-multiple-if-statements';
estraverse = require('estraverse');
common = require('../common');
Syntax = common.Syntax;
function reduceMultipleIfStatements(tree, options) {
var result;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
modified = false;
estraverse.traverse(result, {
leave: function leave(node) {
// reduce
// if (cond) {
// if (cond2) {
// ...
// }
// }
// to
// if (cond && cond2) {
// ...
// }
if (node.type === Syntax.IfStatement && !node.alternate &&
node.consequent.type === Syntax.IfStatement && !node.consequent.alternate) {
modified = true;
node.test = {
type: Syntax.LogicalExpression,
operator: '&&',
left: node.test,
right: node.consequent.test
};
node.consequent = node.consequent.consequent;
}
}
});
return {
result: result,
modified: modified
};
}
reduceMultipleIfStatements.passName = Name;
module.exports = reduceMultipleIfStatements;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"estraverse":129}],15:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, common, evaluator, estraverse, escope, modified;
Name = 'reduce-sequence-expression';
estraverse = require('estraverse');
escope = require('escope');
common = require('../common');
evaluator = require('../evaluator');
Syntax = common.Syntax;
function reduce(node) {
var i, iz, j, jz, expr, result;
result = [];
for (i = 0, iz = node.expressions.length; i < iz; ++i) {
expr = node.expressions[i];
if (expr.type === Syntax.SequenceExpression) {
modified = true;
// delete SequenceExpression location information,
// because information of SequenceExpression is not used effectively in source-map.
common.deleteLocation(node);
for (j = 0, jz = expr.expressions.length; j < jz; ++j) {
result.push(expr.expressions[j]);
}
} else {
result.push(expr);
}
}
node.expressions = result;
}
function isLoadSideEffectFree(node, scope) {
var ref, value;
if (evaluator.constant.isConstant(node)) {
value = evaluator.constant.evaluate(node);
if (value === null || typeof value !== 'object') {
return true;
}
}
if (node.type === Syntax.Identifier) {
ref = scope.resolve(node);
return ref && ref.isStatic();
}
return false;
}
function isStoreSideEffectFree(node, scope) {
if (!evaluator.hasSideEffect(node, scope)) {
return true;
}
if (node.type === Syntax.Identifier) {
return true;
}
if (node.type === Syntax.MemberExpression) {
if (!evaluator.hasSideEffect(node.object, scope)) {
// Because of toString operation
if (!node.computed || isLoadSideEffectFree(node.property, scope)) {
return true;
}
}
return false;
}
return false;
}
function reduceSequenceExpression(tree, options) {
var result, scope, manager;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
modified = false;
scope = null;
manager = escope.analyze(result, { directive: true });
manager.attach();
result = estraverse.replace(result, {
enter: function enter(node) {
scope = manager.acquire(node) || scope;
},
leave: function leave(node) {
var result, last;
switch (node.type) {
case Syntax.SequenceExpression:
reduce(node);
break;
case Syntax.ConditionalExpression:
if (node.test.type === Syntax.SequenceExpression) {
modified = true;
result = node.test;
node.test = common.Array.last(result.expressions);
result.expressions[result.expressions.length - 1] = node;
}
break;
case Syntax.LogicalExpression:
if (node.left.type === Syntax.SequenceExpression) {
modified = true;
result = node.left;
node.left = common.Array.last(result.expressions);
result.expressions[result.expressions.length - 1] = node;
}
break;
case Syntax.BinaryExpression:
if (node.left.type === Syntax.SequenceExpression) {
modified = true;
result = node.left;
node.left = common.Array.last(result.expressions);
result.expressions[result.expressions.length - 1] = node;
} else if (node.right.type === Syntax.SequenceExpression && !evaluator.hasSideEffect(node.left, scope)) {
modified = true;
result = node.right;
node.right = common.Array.last(result.expressions);
result.expressions[result.expressions.length - 1] = node;
}
break;
case Syntax.UpdateExpression:
case Syntax.UnaryExpression:
if (node.argument.type === Syntax.SequenceExpression) {
// Don't transform
// typeof (0, ident)
// to
// 0, typeof ident
//
// delete (0, 1, t.t)
// to
// delete t.t
last = common.Array.last(node.argument.expressions);
if (!common.SpecialNode.canExtractSequence(last, node, scope)) {
break;
}
modified = true;
result = node.argument;
node.argument = common.Array.last(result.expressions);
result.expressions[result.expressions.length - 1] = node;
}
break;
case Syntax.AssignmentExpression:
if (node.operator === '=' && node.right.type === Syntax.SequenceExpression && isStoreSideEffectFree(node.left, scope)) {
modified = true;
result = node.right;
node.right = common.Array.last(result.expressions);
result.expressions[result.expressions.length - 1] = node;
}
break;
}
scope = manager.release(node) || scope;
return result;
}
});
manager.detach();
return {
result: result,
modified: modified
};
}
reduceSequenceExpression.passName = Name;
module.exports = reduceSequenceExpression;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"../evaluator":4,"escope":115,"estraverse":129}],16:[function(require,module,exports){
/*
Copyright (C) 2012 Mihai Bazon <mihai.bazon@gmail.com>
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, common, evaluator, escope, estraverse, modified;
Name = 'remove-context-sensitive-expressions';
estraverse = require('estraverse');
escope = require('escope');
common = require('../common');
evaluator = require('../evaluator');
Syntax = common.Syntax;
function Transformer(trans, booleanFunction, voidFunction, scope) {
this.transform = trans;
this.booleanFunction = booleanFunction;
this.voidFunction = voidFunction;
this.scope = scope;
}
Transformer.prototype.booleanTransformation = function (expr) {
var consequent;
do {
if (expr.type === Syntax.UnaryExpression) {
if (expr.operator === '!' &&
expr.argument.type === Syntax.UnaryExpression && expr.argument.operator === '!') {
modified = true;
expr = expr.argument.argument;
continue;
}
} else if (expr.type === Syntax.LogicalExpression) {
if (expr.left.type === Syntax.UnaryExpression && expr.left.operator === '!' &&
expr.right.type === Syntax.UnaryExpression && expr.right.operator === '!') {
// !cond && !ok() => !(cond || ok())
// this introduces more optimizations
modified = true;
expr.left = expr.left.argument;
expr.right = expr.right.argument;
expr.operator = (expr.operator === '||') ? '&&' : '||';
expr = common.moveLocation(expr, {
type: Syntax.UnaryExpression,
operator: '!',
argument: expr
});
continue;
}
} else if (expr.type === Syntax.ConditionalExpression) {
if (expr.test.type === Syntax.UnaryExpression && expr.test.operator === '!') {
modified = true;
expr.test = expr.test.argument;
consequent = expr.consequent;
expr.consequent = expr.alternate;
expr.alternate = consequent;
}
}
break;
} while (true);
return expr;
};
Transformer.prototype.voidTransformation = function (expr) {
var leftHasSideEffect, rightHasSideEffect;
do {
expr = this.booleanTransformation(expr);
if (expr.type === Syntax.UnaryExpression) {
if (expr.operator === '!' || expr.operator === 'void') {
modified = true;
expr = expr.argument;
continue;
}
} else if (expr.type === Syntax.LogicalExpression) {
if (expr.left.type === Syntax.UnaryExpression && expr.left.operator === '!') {
// !cond && ok() => cond || ok()
modified = true;
expr.left = expr.left.argument;
expr.operator = (expr.operator === '||') ? '&&' : '||';
}
} else if (expr.type === Syntax.ConditionalExpression) {
// a?0:1 => a
// a?0:b => a||b
// a?b:0 => a&&b
leftHasSideEffect = evaluator.hasSideEffect(expr.consequent, this.scope);
rightHasSideEffect = evaluator.hasSideEffect(expr.alternate, this.scope);
if (!leftHasSideEffect && !rightHasSideEffect) {
modified = true;
expr = expr.test;
} else if (!leftHasSideEffect) {
modified = true;
expr = common.moveLocation(expr, {
type: Syntax.LogicalExpression,
operator: '||',
left: expr.test,
right: expr.alternate
});
} else if (!rightHasSideEffect) {
modified = true;
expr = common.moveLocation(expr, {
type: Syntax.LogicalExpression,
operator: '&&',
left: expr.test,
right: expr.consequent
});
}
}
break;
} while (true);
return expr;
};
Transformer.prototype.apply = function (expr) {
var prev;
do {
prev = expr;
expr = this.transform(expr);
if (prev !== expr) {
continue;
}
if (expr.type === Syntax.LogicalExpression) {
expr.left = this.booleanFunction(expr.left, this.scope);
expr.right = this.voidFunction(expr.right, this.scope);
} else if (expr.type === Syntax.ConditionalExpression) {
expr.consequent = this.voidFunction(expr.consequent, this.scope);
expr.alternate = this.voidFunction(expr.alternate, this.scope);
} else if (expr.type === Syntax.SequenceExpression) {
expr.expressions[expr.expressions.length - 1] = this.voidFunction(common.Array.last(expr.expressions), this.scope);
}
break;
} while (true);
return expr;
};
function voidContext(expr, scope) {
var trans = new Transformer(Transformer.prototype.voidTransformation, booleanContext, voidContext, scope);
return trans.apply(expr);
}
function booleanContext(expr, scope) {
var trans = new Transformer(Transformer.prototype.booleanTransformation, booleanContext, booleanContext, scope);
return trans.apply(expr);
}
function removeContextSensitiveExpressions(tree, options) {
var result, stackCount, preserveCompletionValue, scope, manager;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
modified = false;
stackCount = 0;
preserveCompletionValue = options.get('preserveCompletionValue', { pathName: Name });
scope = null;
manager = escope.analyze(result, { directive: true });
manager.attach();
result = estraverse.replace(result, {
enter: function enter(node) {
var i, iz;
scope = manager.acquire(node) || scope;
if (node.type === Syntax.FunctionExpression || node.type === Syntax.FunctionDeclaration) {
++stackCount;
}
switch (node.type) {
case Syntax.AssignmentExpression:
break;
case Syntax.ArrayExpression:
break;
case Syntax.BlockStatement:
break;
case Syntax.BinaryExpression:
break;
case Syntax.BreakStatement:
break;
case Syntax.CallExpression:
break;
case Syntax.CatchClause:
break;
case Syntax.ConditionalExpression:
node.test = booleanContext(node.test, scope);
break;
case Syntax.ContinueStatement:
break;
case Syntax.DoWhileStatement:
node.test = booleanContext(node.test, scope);
break;
case Syntax.DebuggerStatement:
break;
case Syntax.EmptyStatement:
break;
case Syntax.ExpressionStatement:
if (!preserveCompletionValue || stackCount !== 0) {
// not global context
node.expression = voidContext(node.expression, scope);
}
break;
case Syntax.FunctionExpression:
break;
case Syntax.ForInStatement:
break;
case Syntax.FunctionDeclaration:
break;
case Syntax.ForStatement:
if (node.init && node.init.type !== Syntax.VariableDeclaration) {
node.init = voidContext(node.init, scope);
}
if (node.test) {
node.test = booleanContext(node.test, scope);
}
if (node.update) {
node.update = voidContext(node.update, scope);
}
break;
case Syntax.Identifier:
break;
case Syntax.IfStatement:
node.test = booleanContext(node.test, scope);
break;
case Syntax.Literal:
break;
case Syntax.LabeledStatement:
break;
case Syntax.LogicalExpression:
break;
case Syntax.MemberExpression:
break;
case Syntax.NewExpression:
break;
case Syntax.ObjectExpression:
break;
case Syntax.Program:
break;
case Syntax.Property:
break;
case Syntax.ReturnStatement:
break;
case Syntax.SequenceExpression:
for (i = 0, iz = node.expressions.length - 1; i < iz; ++i) {
node.expressions[i] = voidContext(node.expressions[i], scope);
}
break;
case Syntax.SwitchStatement:
break;
case Syntax.SwitchCase:
break;
case Syntax.ThisExpression:
break;
case Syntax.ThrowStatement:
break;
case Syntax.TryStatement:
break;
case Syntax.UnaryExpression:
if (node.operator === '!') {
node.argument = booleanContext(node.argument, scope);
} else if (node.operator === 'void') {
node.argument = voidContext(node.argument, scope);
}
break;
case Syntax.UpdateExpression:
break;
case Syntax.VariableDeclaration:
break;
case Syntax.VariableDeclarator:
break;
case Syntax.WhileStatement:
node.test = booleanContext(node.test, scope);
break;
case Syntax.WithStatement:
break;
}
},
leave: function leave(node) {
scope = manager.release(node) || scope;
if (node.type === Syntax.FunctionExpression || node.type === Syntax.FunctionDeclaration) {
--stackCount;
}
}
});
manager.detach();
return {
result: result,
modified: modified
};
}
removeContextSensitiveExpressions.passName = Name;
module.exports = removeContextSensitiveExpressions;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"../evaluator":4,"escope":115,"estraverse":129}],17:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, estraverse, common, modified;
Name = 'remove-empty-statement';
estraverse = require('estraverse');
common = require('../common');
Syntax = common.Syntax;
function remove(array) {
var i, iz, node, result;
result = [];
for (i = 0, iz = array.length; i < iz; ++i) {
node = array[i];
if (node.type === Syntax.EmptyStatement) {
modified = true;
} else {
result.push(node);
}
}
return result;
}
function removeAlternate(node) {
if (node.alternate) {
if (node.alternate.type === Syntax.EmptyStatement) {
modified = true;
node.alternate = null;
} else if (node.consequent.type === Syntax.EmptyStatement) {
modified = true;
node.consequent = node.alternate;
node.alternate = null;
node.test = common.moveLocation(node.test, {
type: Syntax.UnaryExpression,
operator: '!',
argument: node.test
});
}
}
}
function removeEmptyStatement(tree, options) {
var result;
modified = false;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
estraverse.traverse(result, {
enter: function enter(node) {
var clause;
switch (node.type) {
case Syntax.BlockStatement:
case Syntax.Program:
node.body = remove(node.body);
break;
case Syntax.SwitchCase:
node.consequent = remove(node.consequent);
break;
case Syntax.IfStatement:
removeAlternate(node);
break;
// drop unused default block
case Syntax.SwitchStatement:
if (node.cases.length) {
clause = common.Array.last(node.cases);
if (!clause.test && common.Array.empty(clause.consequent)) {
// this is wasted default case
modified = true;
node.cases.pop();
}
}
}
}
});
return {
result: result,
modified: modified
};
}
removeEmptyStatement.passName = Name;
module.exports = removeEmptyStatement;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"estraverse":129}],18:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, common, estraverse, escope, evaluator, modified;
Name = 'remove-side-effect-free-expressions';
estraverse = require('estraverse');
escope = require('escope');
common = require('../common');
evaluator = require('../evaluator');
Syntax = common.Syntax;
function reduce(node, scope, parent, isResultNeeded) {
var i, iz, expr, result, prev;
common.assert(node.expressions.length > 1, 'expressions should be more than one');
result = [];
for (i = 0, iz = node.expressions.length; i < iz; ++i) {
prev = expr;
expr = node.expressions[i];
if (((i + 1) !== iz) || !isResultNeeded) {
if (!evaluator.hasSideEffect(expr, scope)) {
continue;
}
}
result.push(expr);
}
if (!isResultNeeded && result.length === 0) {
modified = true;
return expr;
}
common.assert(result.length > 0, 'result should be more than zero');
// not changed
do {
if (iz === result.length) {
return node;
}
if (result.length === 1) {
if (!common.SpecialNode.canExtractSequence(result[0], parent, scope)) {
result.unshift(prev);
continue;
}
modified = true;
return result[0];
}
modified = true;
node.expressions = result;
return node;
} while (true);
}
function removeSideEffectFreeExpressions(tree, options) {
var result, scope, manager, preserveCompletionValue;
function isResultNeeded(parent, scope) {
if (parent.type === Syntax.ExpressionStatement && (!preserveCompletionValue || scope.type !== 'global')) {
return false;
}
return true;
}
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
preserveCompletionValue = options.get('preserveCompletionValue', { pathName: Name });
modified = false;
scope = null;
manager = escope.analyze(result, { directive: true });
manager.attach();
result = estraverse.replace(result, {
enter: function enter(node, parent) {
var res, unary, trans;
res = node;
scope = manager.acquire(node) || scope;
if (res.type === Syntax.SequenceExpression) {
res = reduce(res, scope, parent, isResultNeeded(parent, scope));
}
if (res.type === Syntax.SequenceExpression) {
common.assert(res.expressions.length > 1, 'sequences\' length should be more than 1');
unary = common.Array.last(res.expressions);
if (unary.type === Syntax.UnaryExpression && unary.operator === 'void' && !evaluator.hasSideEffect(unary.argument, scope)) {
// (x, void sideEffectFree) => (void x)
modified = true;
res.expressions.pop();
trans = common.moveLocation(unary, {
type: Syntax.UnaryExpression,
operator: 'void',
argument: common.Array.last(res.expressions)
});
if (res.expressions.length === 1) {
res = trans;
} else {
res.expressions[res.expressions.length - 1] = trans;
}
}
}
// Because eval code should return last evaluated value in
// ExpressionStatement, we should not remove.
if (!isResultNeeded(res, scope)) {
if (!evaluator.hasSideEffect(res.expression, scope)) {
modified = true;
res = common.moveLocation(res, {
type: Syntax.EmptyStatement
});
}
}
return res;
},
leave: function leave(node) {
scope = manager.release(node) || scope;
}
});
manager.detach();
return {
result: result,
modified: modified
};
}
removeSideEffectFreeExpressions.passName = Name;
module.exports = removeSideEffectFreeExpressions;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"../evaluator":4,"escope":115,"estraverse":129}],19:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, common, estraverse, escope, evaluator, modified;
Name = 'remove-unreachable-branch';
estraverse = require('estraverse');
escope = require('escope');
common = require('../common');
evaluator = require('../evaluator');
Syntax = common.Syntax;
function handleIfStatement(func, node) {
var test, body, decl;
test = evaluator.booleanCondition(node.test);
if (!node.alternate) {
if (typeof test === 'boolean') {
modified = true;
body = [];
if (test) {
body.push(common.moveLocation(node.test, {
type: Syntax.ExpressionStatement,
expression: node.test
}), node.consequent);
return {
type: Syntax.BlockStatement,
body: body
};
} else {
decl = common.delegateVariableDeclarations(node.consequent, func);
if (decl) {
body.push(decl);
}
body.push(common.moveLocation(node.test, {
type: Syntax.ExpressionStatement,
expression: node.test
}));
return {
type: Syntax.BlockStatement,
body: body
};
}
}
} else {
if (typeof test === 'boolean') {
modified = true;
body = [];
if (test) {
decl = common.delegateVariableDeclarations(node.alternate, func);
if (decl) {
body.push(decl);
}
body.push(common.moveLocation(node.test, {
type: Syntax.ExpressionStatement,
expression: node.test
}), node.consequent);
return {
type: Syntax.BlockStatement,
body: body
};
} else {
decl = common.delegateVariableDeclarations(node.consequent, func);
if (decl) {
body.push(decl);
}
body.push(common.moveLocation(node.test, {
type: Syntax.ExpressionStatement,
expression: node.test
}), node.alternate);
return {
type: Syntax.BlockStatement,
body: body
};
}
}
}
}
function handleLogicalExpression(func, node) {
var test;
test = evaluator.booleanCondition(node.left);
if (typeof test === 'boolean') {
modified = true;
if (test) {
if (node.operator === '&&') {
return common.moveLocation(node, {
type: Syntax.SequenceExpression,
expressions: [ node.left, node.right ]
});
} else {
return node.left;
}
} else {
if (node.operator === '&&') {
return node.left;
} else {
return common.moveLocation(node, {
type: Syntax.SequenceExpression,
expressions: [ node.left, node.right ]
});
}
}
}
}
function handleConditionalExpression(func, node) {
var test;
test = evaluator.booleanCondition(node.test);
if (typeof test === 'boolean') {
modified = true;
if (test) {
return common.moveLocation(node, {
type: Syntax.SequenceExpression,
expressions: [ node.test, node.consequent ]
});
} else {
return common.moveLocation(node, {
type: Syntax.SequenceExpression,
expressions: [ node.test, node.alternate ]
});
}
}
}
function handleForOrWhileStatement(func, node) {
var test = node.test;
if (test) {
test = evaluator.booleanCondition(test);
if (typeof test === 'boolean') {
if (!test) {
modified = true;
return {
type: Syntax.EmptyStatement
};
}
}
}
}
function handleDoWhileStatement(func, node) {
var test = node.test;
if (test) {
test = evaluator.booleanCondition(test);
if (typeof test === 'boolean') {
if (!test) {
modified = true;
return node.body;
}
}
}
}
function removeUnreachableBranch(tree, options) {
var result, stack;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
modified = false;
stack = [];
result = estraverse.replace(result, {
enter: function enter(node) {
var func;
if (common.isFunctionNode(node)) {
stack.push(node);
return;
}
func = common.Array.last(stack);
switch (node.type) {
case Syntax.IfStatement:
return handleIfStatement(func, node);
case Syntax.LogicalExpression:
return handleLogicalExpression(func, node);
case Syntax.ConditionalExpression:
return handleConditionalExpression(func, node);
case Syntax.WhileStatement:
case Syntax.ForStatement:
return handleForOrWhileStatement(func, node);
case Syntax.DoWhileStatement:
return handleDoWhileStatement(func, node);
}
},
leave: function leave(node) {
if (common.isFunctionNode(node)) {
stack.pop();
}
}
});
return {
result: result,
modified: modified
};
}
removeUnreachableBranch.passName = Name;
module.exports = removeUnreachableBranch;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"../evaluator":4,"escope":115,"estraverse":129}],20:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, Map, common, estraverse, scope, modified;
Name = 'remove-unused-label';
estraverse = require('estraverse');
common = require('../common');
Map = require('../map');
Syntax = common.Syntax;
function Scope(upper) {
this.set = new Map();
this.unused = [];
this.upper = upper;
}
Scope.prototype.register = function register(node) {
var name;
common.assert(node.type === Syntax.LabeledStatement);
name = node.label.name;
common.assert(!this.set.has(name), 'duplicate label is found');
this.set.set(name, {
used: false,
stmt: node
});
};
Scope.prototype.unregister = function unregister(node) {
var name, ref;
if (node.type === Syntax.LabeledStatement) {
name = node.label.name;
ref = this.set.get(name);
this.set['delete'](name);
if (!ref.used) {
modified = true;
return node.body;
}
}
return node;
};
Scope.prototype.resolve = function resolve(node) {
var name;
if (node.label) {
name = node.label.name;
common.assert(this.set.has(name), 'unresolved label');
this.set.get(name).used = true;
}
};
Scope.prototype.close = function close() {
return this.upper;
};
function removeUnusedLabel(tree, options) {
var result;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
scope = null;
modified = false;
result = estraverse.replace(result, {
enter: function enter(node) {
switch (node.type) {
case Syntax.Program:
case Syntax.FunctionDeclaration:
case Syntax.FunctionExpression:
scope = new Scope(scope);
break;
case Syntax.LabeledStatement:
scope.register(node);
break;
case Syntax.BreakStatement:
case Syntax.ContinueStatement:
scope.resolve(node);
break;
}
},
leave: function leave(node) {
var ret;
ret = scope.unregister(node);
if (node.type === Syntax.Program || node.type === Syntax.FunctionDeclaration || node.type === Syntax.FunctionExpression) {
scope = scope.close();
}
return ret;
}
});
return {
result: result,
modified: modified
};
}
removeUnusedLabel.passName = Name;
module.exports = removeUnusedLabel;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"../map":5,"estraverse":129}],21:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, common, estraverse, modified;
Name = 'remove-wasted-blocks';
estraverse = require('estraverse');
common = require('../common');
Syntax = common.Syntax;
function flattenBlockStatement(body) {
var i, iz, j, jz, result, stmt, inner, ok;
result = [];
for (i = 0, iz = body.length; i < iz; ++i) {
stmt = body[i];
if (stmt.type === Syntax.BlockStatement) {
ok = true;
for (j = 0, jz = stmt.body.length; j < jz; ++j) {
inner = stmt.body[j];
if (common.isScopedDeclaration(inner)) {
// we cannot remove this block
ok = false;
}
}
if (ok) {
modified = true;
result = result.concat(stmt.body);
} else {
result.push(stmt);
}
} else {
result.push(stmt);
}
}
return result;
}
function removeWastedBlocks(tree, options) {
var result;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
modified = false;
result = estraverse.replace(result, {
leave: function leave(node, parent) {
var i, iz, stmt;
if (
node.type === Syntax.BlockStatement &&
parent.type === Syntax.ArrowFunctionExpression
) {
if (!node.body.length){
return;
} else if (
node.body[0].type === Syntax.ReturnStatement &&
/Expression$/.test(node.body[0].argument.type) &&
node.body[0].argument && node.body[0].argument.type !== Syntax.ObjectExpression
) {
node.body[0] = node.body[0].argument;
} else {
return;
}
}
// remove nested blocks
if (node.type === Syntax.BlockStatement || node.type === Syntax.Program) {
for (i = 0, iz = node.body.length; i < iz; ++i) {
stmt = node.body[i];
if (stmt.type === Syntax.BlockStatement) {
node.body = flattenBlockStatement(node.body);
break;
}
}
}
// These type needs BlockStatement
if (parent.type === Syntax.FunctionDeclaration || parent.type === Syntax.FunctionExpression || parent.type === Syntax.TryStatement || parent.type === Syntax.CatchClause) {
return;
}
while (node.type === Syntax.BlockStatement && node.body.length === 1 && !common.isScopedDeclaration(node.body[0])) {
modified = true;
node = node.body[0];
}
// empty body
if (node.type === Syntax.BlockStatement && node.body.length === 0) {
modified = true;
return {
type: Syntax.EmptyStatement
};
}
return node;
}
});
return {
result: result,
modified: modified
};
}
removeWastedBlocks.passName = Name;
module.exports = removeWastedBlocks;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"estraverse":129}],22:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, estraverse, common, modified;
Name = 'reordering-function-declarations';
estraverse = require('estraverse');
common = require('../common');
Syntax = common.Syntax;
function reordering(array) {
var i, iz, node, directives, declarations, others;
directives = [];
declarations = [];
others = [];
for (i = 0, iz = array.length; i < iz; ++i) {
node = array[i];
if (node.type === Syntax.FunctionDeclaration) {
if ((declarations.length + directives.length) !== i) {
modified = true;
}
declarations.push(node);
} else if (node.type === Syntax.DirectiveStatement) {
directives.push(node);
} else {
others.push(node);
}
}
return directives.concat(declarations, others);
}
function reorderingFunctionDeclarations(tree, options) {
var result;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
modified = false;
estraverse.traverse(result, {
leave: function leave(node) {
switch (node.type) {
case Syntax.Program:
node.body = reordering(node.body);
break;
case Syntax.FunctionDeclaration:
case Syntax.FunctionExpression:
node.body.body = reordering(node.body.body);
break;
}
}
});
return {
result: result,
modified: modified
};
}
reorderingFunctionDeclarations.passName = Name;
module.exports = reorderingFunctionDeclarations;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"estraverse":129}],23:[function(require,module,exports){
/*
Copyright (C) 2014 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, estraverse, escope, common, modified;
Name = 'top-level-variable-declaration-to-assignment';
estraverse = require('estraverse');
escope = require('escope');
common = require('../common');
Syntax = common.Syntax;
function isStrictProgram(program) {
var i, iz;
if (!program.body.length) {
return false;
}
for (i = 0, iz = program.body.length; i < iz; ++i) {
if (program.body[i].type !== Syntax.DirectiveStatement) {
return false;
}
if (program.body[i].value === 'use strict') {
return true;
}
}
return false;
}
function nothingChanged(result) {
return {
result: result,
modified: false
};
}
function topLevelVariableDeclarationToAssignment(tree, options) {
var result, inNormalTopLevelCode;
modified = false;
if (options.get('topLevelContext', { pathName: Name }) !== 'global') {
return nothingChanged(tree);
}
// If the top level code is strict code, this pass has no effect.
if (options.get('inStrictCode', { pathName: Name })) {
return nothingChanged(tree);
}
inNormalTopLevelCode = false;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
result = estraverse.replace(result, {
enter: function enter(node, parent) {
var i, iz, decl, assigns, declarations, expr;
if (node.type === Syntax.Program) {
if (isStrictProgram(node)) {
return this.break();
}
inNormalTopLevelCode = true;
return;
}
if (!inNormalTopLevelCode) {
return this.break();
}
if (common.isFunctionNode(node) || node.type === Syntax.CatchClause || node.type === Syntax.WithStatement) {
return this.skip();
}
if (node.type !== Syntax.VariableDeclaration) {
return;
}
if (node.kind !== 'var') {
return;
}
// FIXME: We don't support `for (var i = 20; ...) ...` case.
if (parent && parent.type === Syntax.ForStatement || parent.type === Syntax.ForInStatement || parent.type === Syntax.ForOfStatement) {
return;
}
assigns = [];
declarations = [];
for (i = 0, iz = node.declarations.length; i < iz; ++i) {
decl = node.declarations[i];
if (decl.init) {
assigns.push(common.moveLocation(decl, {
type: Syntax.AssignmentExpression,
operator: '=',
left: decl.id,
right: decl.init
}));
} else {
declarations.push(decl);
}
}
if (assigns.length) {
modified = true;
if (assigns.length === 1) {
expr = assigns[0];
} else {
expr = {
type: Syntax.SequenceExpression,
expressions: assigns
};
}
if (declarations.length === 0) {
return {
type: Syntax.ExpressionStatement,
expression: expr
};
}
node.declarations = declarations;
return {
type: Syntax.BlockStatement,
body: [
node,
{
type: Syntax.ExpressionStatement,
expression: expr
}
]
};
}
}
});
return {
result: result,
modified: modified
};
}
topLevelVariableDeclarationToAssignment.passName = Name;
module.exports = topLevelVariableDeclarationToAssignment;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"escope":115,"estraverse":129}],24:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, common, estraverse, modified;
Name = 'transform-branch-to-expression';
estraverse = require('estraverse');
common = require('../common');
Syntax = common.Syntax;
function transformBranchToExpression(tree, options) {
var result, preserveCompletionValue;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
preserveCompletionValue = options.get('preserveCompletionValue', { pathName: Name });
modified = false;
result = estraverse.replace(result, {
leave: function leave(node) {
var consequent, alternate, ancestors;
if (node.type === Syntax.IfStatement) {
ancestors = this.parents();
if (preserveCompletionValue && common.mayBeCompletionValue(node, ancestors)) {
return;
}
if (node.alternate) {
if (node.consequent.type === Syntax.ExpressionStatement && node.alternate.type === Syntax.ExpressionStatement) {
// ok, we can reconstruct this to ConditionalExpression
modified = true;
return common.moveLocation(node, {
type: Syntax.ExpressionStatement,
expression: common.moveLocation(node, {
type: Syntax.ConditionalExpression,
test: node.test,
consequent: node.consequent.expression,
alternate: node.alternate.expression
})
});
}
if (node.consequent.type === Syntax.ReturnStatement && node.alternate.type === Syntax.ReturnStatement) {
// pattern:
// if (cond) return a;
// else return b;
modified = true;
if (!node.consequent.argument && !node.alternate.argument) {
// if (cond) return;
// else return;
return common.moveLocation(node, {
type: Syntax.ReturnStatement,
argument: common.moveLocation(node, {
type: Syntax.SequenceExpression,
expressions: [node.test, common.SpecialNode.generateUndefined() ]
})
});
}
consequent = node.consequent.argument || common.SpecialNode.generateUndefined();
alternate = node.alternate.argument || common.SpecialNode.generateUndefined();
return common.moveLocation(node, {
type: Syntax.ReturnStatement,
argument: common.moveLocation(node, {
type: Syntax.ConditionalExpression,
test: node.test,
consequent: consequent,
alternate: alternate
})
});
}
if (node.consequent.type === Syntax.ThrowStatement && node.alternate.type === Syntax.ThrowStatement) {
// pattern:
// if (cond) throw a;
// else throw b;
modified = true;
return common.moveLocation(node, {
type: Syntax.ThrowStatement,
argument: common.moveLocation(node, {
type: Syntax.ConditionalExpression,
test: node.test,
consequent: node.consequent.argument,
alternate: node.alternate.argument
})
});
}
} else {
if (node.consequent.type === Syntax.ExpressionStatement) {
// ok, we can reconstruct this to LogicalExpression
modified = true;
return common.moveLocation(node, {
type: Syntax.ExpressionStatement,
expression: common.moveLocation(node, {
type: Syntax.LogicalExpression,
operator: '&&',
left: node.test,
right: node.consequent.expression
})
});
} else if (node.consequent.type === Syntax.EmptyStatement) {
// ok, we can reconstruct this to expression statement
modified = true;
return common.moveLocation(node, {
type: Syntax.ExpressionStatement,
expression: node.test
});
}
}
}
}
});
return {
result: result,
modified: modified
};
}
transformBranchToExpression.passName = Name;
module.exports = transformBranchToExpression;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"estraverse":129}],25:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, estraverse, common, modified;
Name = 'transform-dynamic-to-static-property-access';
estraverse = require('estraverse');
common = require('../common');
Syntax = common.Syntax;
function transformDynamicToStaticPropertyAccess(tree, options) {
var result;
modified = false;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
estraverse.traverse(result, {
enter: function enter(node) {
var property;
if (node.type === Syntax.MemberExpression && node.computed) {
property = node.property;
if (property.type === Syntax.Literal && typeof property.value === 'string') {
if (common.isIdentifier(property.value)) {
modified = true;
node.computed = false;
node.property = common.moveLocation(property, {
type: Syntax.Identifier,
name: property.value
});
} else if (property.value === Number(property.value).toString()) {
modified = true;
node.computed = true;
node.property = common.moveLocation(node.property, common.SpecialNode.generateFromValue(Number(node.property.value)));
}
}
}
}
});
return {
result: result,
modified: modified
};
}
transformDynamicToStaticPropertyAccess.passName = Name;
module.exports = transformDynamicToStaticPropertyAccess;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"estraverse":129}],26:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, estraverse, common, modified;
Name = 'transform-dynamic-to-static-property-definition';
estraverse = require('estraverse');
common = require('../common');
Syntax = common.Syntax;
function transformDynamicToStaticPropertyDefinition(tree, options) {
var result;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
modified = false;
estraverse.traverse(result, {
enter: function enter(node) {
var generated;
if (node.type === Syntax.Property) {
if (node.key.type === Syntax.Literal && typeof node.key.value === 'string') {
if (common.isIdentifier(node.key.value)) {
modified = true;
node.key = common.moveLocation(node.key, {
type: Syntax.Identifier,
name: node.key.value
});
} else if (node.key.value === Number(node.key.value).toString()) {
// we should not generate
// var obj = {
// -20: 20
// };
generated = common.SpecialNode.generateFromValue(Number(node.key.value));
if (generated.type === Syntax.Literal) {
modified = true;
node.key = common.moveLocation(node.key, generated);
}
}
}
}
}
});
return {
result: result,
modified: modified
};
}
transformDynamicToStaticPropertyDefinition.passName = Name;
module.exports = transformDynamicToStaticPropertyDefinition;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"estraverse":129}],27:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, common, estraverse, modified;
Name = 'transform-immediate-function-call';
estraverse = require('estraverse');
common = require('../common');
Syntax = common.Syntax;
function isEmptyFunctionCall(call) {
var callee, i, iz, stmt;
if (call.type !== Syntax.CallExpression) {
return false;
}
callee = call.callee;
if (callee.type !== Syntax.FunctionExpression) {
return false;
}
if (callee.body.type !== Syntax.BlockStatement) {
return false;
}
// see side effect
if (callee.body.body.length === 0) {
return true;
}
for (i = 0, iz = callee.body.body.length; i < iz; ++i) {
stmt = callee.body.body[i];
if (stmt.type !== Syntax.FunctionDeclaration) {
return false;
}
}
return true;
}
function callToSequence(call) {
var expressions;
expressions = common.Array.from(call['arguments']);
if (expressions.length === 0) {
return common.SpecialNode.generateUndefined(call);
}
expressions.push(common.SpecialNode.generateUndefined());
return common.moveLocation(call, {
type: Syntax.SequenceExpression,
expressions: expressions
});
}
function transformImmediateFunctionCall(tree, options) {
var result;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
modified = false;
result = estraverse.replace(result, {
leave: function leave(node) {
if (isEmptyFunctionCall(node)) {
modified = true;
return callToSequence(node);
}
}
});
return {
result: result,
modified: modified
};
}
transformImmediateFunctionCall.passName = Name;
module.exports = transformImmediateFunctionCall;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"estraverse":129}],28:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, estraverse, common, modified;
Name = 'transform-logical-association';
estraverse = require('estraverse');
common = require('../common');
Syntax = common.Syntax;
function transformLogicalAssociation(tree, options) {
var result;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
modified = false;
estraverse.traverse(result, {
enter: function enter(node) {
if (node.type === Syntax.LogicalExpression) {
// transform
// a && (b && c) => (a && b) && c
// a || (b || c) => (a || b) || c
if (node.right.type === Syntax.LogicalExpression && node.operator === node.right.operator) {
modified = true;
node.left = {
type: Syntax.LogicalExpression,
operator: node.operator,
left: node.left,
right: node.right.left
};
node.right = node.right.right;
}
}
}
});
return {
result: result,
modified: modified
};
}
transformLogicalAssociation.passName = Name;
module.exports = transformLogicalAssociation;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"estraverse":129}],29:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, common, estraverse, escope, modified;
Name = 'transform-to-compound-assignment';
estraverse = require('estraverse');
escope = require('escope');
common = require('../common');
Syntax = common.Syntax;
function equals(lhs, rhs) {
if (lhs.type !== rhs.type) {
return false;
}
if (lhs.type === Syntax.Identifier) {
return lhs.name === rhs.name;
}
return false;
}
function compound(operator) {
switch (operator) {
case '*':
case '/':
case '%':
case '+':
case '-':
case '<<':
case '>>':
case '>>>':
case '&':
case '^':
case '|':
return operator + '=';
}
return null;
}
function observableCompound(operator) {
switch (operator) {
case '*=':
case '/=':
case '%=':
case '+=':
case '-=':
case '<<=':
case '>>=':
case '>>>=':
case '&=':
case '^=':
case '|=':
return operator;
}
return null;
}
function transformToCompoundAssignment(tree, options) {
var result, scope, manager;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
modified = false;
scope = null;
manager = escope.analyze(result, { directive: true });
manager.attach();
estraverse.traverse(result, {
enter: function enter(node) {
var left, right, operator, ref;
scope = manager.acquire(node) || scope;
if (node.type === Syntax.AssignmentExpression && node.operator === '=') {
left = node.left;
right = node.right;
if (right.type === Syntax.BinaryExpression && equals(right.left, left)) {
operator = compound(right.operator);
if (operator) {
modified = true;
node.operator = operator;
node.right = right.right;
}
} else if (right.type === Syntax.AssignmentExpression && equals(right.left, left)) {
if (observableCompound(right.operator)) {
ref = scope.resolve(node.left);
if (ref.isStatic()) {
modified = true;
node.operator = right.operator;
node.right = right.right;
}
}
}
}
},
leave: function leave(node) {
scope = manager.release(node) || scope;
}
});
manager.detach();
return {
result: result,
modified: modified
};
}
transformToCompoundAssignment.passName = Name;
module.exports = transformToCompoundAssignment;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"escope":115,"estraverse":129}],30:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, common, estraverse, modified;
Name = 'transform-to-sequence-expression';
estraverse = require('estraverse');
common = require('../common');
Syntax = common.Syntax;
function transform(node) {
var i, iz, expressions, stmt, prev, body;
function constructSeq(expressions, stmt) {
var seq;
if (expressions.length !== 1) {
modified = true;
seq = {
type: Syntax.SequenceExpression,
expressions: expressions
};
if (stmt.type === Syntax.ExpressionStatement) {
stmt.expression = seq;
} else {
stmt.argument = seq;
}
}
return stmt;
}
body = [];
expressions = [];
for (i = 0, iz = node.body.length; i < iz; ++i) {
prev = stmt;
stmt = node.body[i];
if (stmt.type === Syntax.ExpressionStatement) {
expressions.push(stmt.expression);
} else if ((stmt.type === Syntax.ReturnStatement && stmt.argument != null) || stmt.type === Syntax.ThrowStatement) {
// Not distinguishing between null or undefined in argument
expressions.push(stmt.argument);
body.push(constructSeq(expressions, stmt));
expressions = [];
} else if (stmt.type === Syntax.ForStatement && (!stmt.init || stmt.init.type !== Syntax.VariableDeclaration)) {
// insert expressions to for (<init>;;);
if (expressions.length) {
modified = true;
if (stmt.init) {
expressions.push(stmt.init);
}
if (expressions.length === 1) {
stmt.init = expressions[0];
} else {
stmt.init = {
type: Syntax.SequenceExpression,
expressions: expressions
};
}
expressions = [];
}
body.push(stmt);
} else if (stmt.type === Syntax.IfStatement) {
if (expressions.length) {
modified = true;
expressions.push(stmt.test);
stmt.test = {
type: Syntax.SequenceExpression,
expressions: expressions
};
expressions = [];
}
body.push(stmt);
} else {
if (expressions.length) {
body.push(constructSeq(expressions, prev));
expressions = [];
}
body.push(stmt);
}
}
if (expressions.length) {
body.push(constructSeq(expressions, stmt));
}
node.body = body;
}
function transformToSequenceExpression(tree, options) {
var result;
modified = false;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
estraverse.traverse(result, {
enter: function enter(node) {
switch (node.type) {
case Syntax.BlockStatement:
case Syntax.Program:
transform(node);
break;
}
}
});
return {
result: result,
modified: modified
};
}
transformToSequenceExpression.passName = Name;
module.exports = transformToSequenceExpression;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"estraverse":129}],31:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, common, escope, estraverse, modified;
Name = 'transform-typeof-undefined';
estraverse = require('estraverse');
escope = require('escope');
common = require('../common');
Syntax = common.Syntax;
function isUndefinedStringLiteral(node) {
return node.type === Syntax.Literal && node.value === 'undefined';
}
function transformTypeofUndefined(tree, options) {
var result, manager, scope;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
modified = false;
scope = null;
manager = escope.analyze(result, { directive: true });
manager.attach();
estraverse.traverse(result, {
enter: function enter(node) {
var target, undef, argument, ref;
scope = manager.acquire(node) || scope;
if (node.type === Syntax.BinaryExpression &&
(node.operator === '===' || node.operator === '!==' || node.operator === '==' || node.operator === '!=')) {
if (isUndefinedStringLiteral(node.left)) {
undef = 'left';
target = 'right';
} else if (isUndefinedStringLiteral(node.right)) {
undef = 'right';
target = 'left';
} else {
return;
}
if (node[target].type === Syntax.UnaryExpression && node[target].operator === 'typeof') {
argument = node[target].argument;
if (argument.type === Syntax.Identifier) {
ref = scope.resolve(argument);
if (!ref || !ref.isStatic() || !ref.resolved) {
// may raise ReferenceError
return;
}
}
modified = true;
node[undef] = common.SpecialNode.generateUndefined();
node[target] = argument;
node.operator = node.operator.charAt(0) === '!' ? '!==' : '===';
}
}
},
leave: function leave(node) {
scope = manager.release(node) || scope;
}
});
manager.detach();
return {
result: result,
modified: modified
};
}
transformTypeofUndefined.passName = Name;
module.exports = transformTypeofUndefined;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"escope":115,"estraverse":129}],32:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, common, evaluator, estraverse, modified;
Name = 'tree-based-constant-folding';
estraverse = require('estraverse');
common = require('../common');
evaluator = require('../evaluator');
Syntax = common.Syntax;
function isModifiedConstant(node) {
// consider
// (undefined) `void 0`
// (negative value) `-1`,
// (NaN) `0/0`
if (common.SpecialNode.isUndefined(node)) {
return false;
}
if (common.SpecialNode.isNegative(node)) {
return false;
}
if (common.SpecialNode.isNaN(node)) {
return false;
}
return evaluator.constant.isConstant(node, false);
}
function isFoldableConditional(node) {
if (node.type !== Syntax.ConditionalExpression) {
return false;
}
return evaluator.constant.isConstant(node.consequent) || evaluator.constant.isConstant(node.alternate);
}
function foldConditional(node) {
var binary, unary, operator, left, right;
switch (node.type) {
case Syntax.BinaryExpression:
if (node.operator === 'in' || node.operator === 'instanceof') {
// cannot fold this
return node;
}
if (evaluator.constant.isConstant(node.left) && isFoldableConditional(node.right)) {
modified = true;
binary = node;
operator = binary.operator;
left = evaluator.constant.evaluate(binary.left);
node = node.right;
if (evaluator.constant.isConstant(node.consequent)) {
node.consequent = common.SpecialNode.generateFromValue(evaluator.constant.doBinary(operator, left, evaluator.constant.evaluate(node.consequent)));
} else {
// cannot fold left
binary.right = node.consequent;
node.consequent = binary;
}
if (evaluator.constant.isConstant(node.alternate)) {
node.alternate = common.SpecialNode.generateFromValue(evaluator.constant.doBinary(operator, left, evaluator.constant.evaluate(node.alternate)));
} else {
// cannot fold right
binary.right = node.alternate;
node.alternate = binary;
}
} else if (evaluator.constant.isConstant(node.right) && isFoldableConditional(node.left)) {
modified = true;
binary = node;
operator = binary.operator;
right = evaluator.constant.evaluate(binary.right);
node = node.left;
if (evaluator.constant.isConstant(node.consequent)) {
node.consequent = common.SpecialNode.generateFromValue(evaluator.constant.doBinary(operator, evaluator.constant.evaluate(node.consequent), right));
} else {
// cannot fold left
binary.left = node.consequent;
node.consequent = binary;
}
if (evaluator.constant.isConstant(node.alternate)) {
node.alternate = common.SpecialNode.generateFromValue(evaluator.constant.doBinary(operator, evaluator.constant.evaluate(node.alternate), right));
} else {
// cannot fold right
binary.left = node.alternate;
node.alternate = binary;
}
}
break;
case Syntax.LogicalExpression:
break;
case Syntax.UnaryExpression:
if (isFoldableConditional(node.argument)) {
modified = true;
unary = node;
operator = unary.operator;
node = unary.argument;
if (evaluator.constant.isConstant(node.consequent)) {
node.consequent = common.SpecialNode.generateFromValue(evaluator.constant.doUnary(operator, evaluator.constant.evaluate(node.consequent)));
} else {
// cannot fold left
unary.argument = node.consequent;
node.consequent = unary;
}
if (evaluator.constant.isConstant(node.alternate)) {
node.alternate = common.SpecialNode.generateFromValue(evaluator.constant.doUnary(operator, evaluator.constant.evaluate(node.alternate)));
} else {
// cannot fold right
unary.argument = node.alternate;
node.alternate = unary;
}
}
break;
}
return node;
}
function treeBasedConstantFolding(tree, options) {
var result;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
modified = false;
result = estraverse.replace(result, {
leave: function leave(node) {
var con, alt;
switch (node.type) {
case Syntax.BinaryExpression:
case Syntax.LogicalExpression:
case Syntax.UnaryExpression:
if (isModifiedConstant(node)) {
modified = true;
return common.moveLocation(node, common.SpecialNode.generateFromValue(evaluator.constant.evaluate(node)));
}
return foldConditional(node);
case Syntax.ConditionalExpression:
if (evaluator.constant.isConstant(node.consequent) && evaluator.constant.isConstant(node.alternate)) {
con = evaluator.constant.evaluate(node.consequent);
alt = evaluator.constant.evaluate(node.alternate);
if (common.sameValue(con, alt)) {
modified = true;
return common.moveLocation(node, {
type: Syntax.SequenceExpression,
expressions: [
node.test,
common.SpecialNode.generateFromValue(con)
]
});
}
}
break;
}
}
});
return {
result: result,
modified: modified
};
}
treeBasedConstantFolding.passName = Name;
module.exports = treeBasedConstantFolding;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"../evaluator":4,"estraverse":129}],33:[function(require,module,exports){
/*
Copyright (C) 2014 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, common, estraverse, modified;
Name = 'typeof-prefix-comparison';
estraverse = require('estraverse');
common = require('../common');
Syntax = common.Syntax;
function isTypeof(node) {
return node.type === 'UnaryExpression' && node.operator === 'typeof';
}
function extractLiteral(node) {
// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-typeof-operator
var index,
literalMap = {
'undefined': 0,
'object': 0,
'boolean': 0,
'number': 0,
'string': 1,
'function': 0,
'symbol': 1 // ES6 Symbol
};
if (node.type !== Syntax.Literal) {
return false;
}
if (typeof node.value !== 'string') {
return false;
}
if (!common.Object.has(literalMap, node.value)) {
return false;
}
index = literalMap[node.value];
return {
value: node.value.charAt(index),
index: index,
};
}
function optimize(parentNode, leftIsTypeof, typeofNode, literalNode, info) {
var wrapped, literal;
wrapped = {
type: 'MemberExpression',
computed: true,
object: typeofNode,
property: {
type: 'Literal',
value: info.index
}
};
literal = common.moveLocation(literalNode, {
type: 'Literal',
value: info.value
});
if (leftIsTypeof) {
parentNode.left = wrapped;
parentNode.right = literal;
} else {
parentNode.right = wrapped;
parentNode.left = literal;
}
if (parentNode.operator === '===' || parentNode.operator === '==') {
parentNode.operator = '==';
} else {
parentNode.operator = '!=';
}
modified = true;
return parentNode;
}
function main(tree, options) {
var result, legacy;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
legacy = options.get('legacy', { pathName: Name });
if (legacy) {
return {
result: result,
modified: false
};
}
modified = false;
result = estraverse.replace(result, {
leave: function leave(node) {
var info;
if (node.type !== Syntax.BinaryExpression) {
return;
}
if (node.operator !== '===' && node.operator !== '==' &&
node.operator !== '!==' && node.operator !== '!=') {
return;
}
if (isTypeof(node.left)) {
info = extractLiteral(node.right);
if (info) {
return optimize(node, true, node.left, node.right, info);
}
} else if (isTypeof(node.right)) {
info = extractLiteral(node.left);
if (info) {
return optimize(node, false, node.right, node.left, info);
}
}
return;
}
});
return {
result: result,
modified: modified
};
}
main.passName = Name;
module.exports = main;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"estraverse":129}],34:[function(require,module,exports){
/*
Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
(function () {
'use strict';
var Name, Syntax, common, estraverse, modified;
Name = 'omit-parens-in-void-context-iife';
estraverse = require('estraverse');
common = require('../common');
Syntax = common.Syntax;
function isIIFE(node) {
var callee;
if (node.type !== Syntax.CallExpression) {
return false;
}
callee = node.callee;
return callee.type === Syntax.FunctionExpression;
}
function main(tree, options) {
var result, stackCount, preserveCompletionValue;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
preserveCompletionValue = options.get('preserveCompletionValue', { pathName: Name });
modified = false;
result = estraverse.replace(result, {
enter: function enter(node, parent) {
var ancestors, target;
if (!isIIFE(node)) {
return;
}
target = parent;
if (target.type === Syntax.ExpressionStatement) {
ancestors = this.parents();
ancestors.pop(); // remove parent: ExpressionStatement
if (preserveCompletionValue && common.mayBeCompletionValue(target, ancestors)) {
return;
}
} else if (target.type === Syntax.SequenceExpression && target.expressions.length >= 2 && target.expressions[0] === node) {
ancestors = this.parents();
ancestors.pop(); // remove parent: SequenceExpression
target = ancestors.pop(); // remove parent: ExpressionStatement
if (target.type !== Syntax.ExpressionStatement) {
return;
}
} else {
return;
}
// transform it
modified = true;
return {
type: Syntax.UnaryExpression,
operator: '!',
argument: node
};
},
leave: function leave(node) {
if (node.type === Syntax.FunctionExpression || node.type === Syntax.FunctionDeclaration) {
--stackCount;
}
}
});
return {
result: result,
modified: modified
};
}
main.passName = Name;
module.exports = main;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"estraverse":129}],35:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, common, estraverse, modified;
Name = 'rewrite-boolean';
estraverse = require('estraverse');
common = require('../common');
Syntax = common.Syntax;
function isBooleanLiteral(node) {
return node.type === Syntax.Literal && typeof node.value === 'boolean';
}
function rewrite(node) {
if (isBooleanLiteral(node)) {
modified = true;
return common.moveLocation(node, {
type: Syntax.UnaryExpression,
operator: '!',
argument: common.moveLocation(node, {
type: Syntax.Literal,
value: +!node.value
})
});
}
if (node.type === Syntax.BinaryExpression && node.operator === '==' || node.operator === '!=') {
if (isBooleanLiteral(node.left)) {
modified = true;
node.left = common.moveLocation(node.left, {
type: Syntax.Literal,
value: +node.left.value
});
return node;
}
if (isBooleanLiteral(node.right)) {
modified = true;
node.right = common.moveLocation(node.right, {
type: Syntax.Literal,
value: +node.right.value
});
return node;
}
}
return node;
}
function rewriteBoolean(tree, options) {
var result;
modified = false;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
result = estraverse.replace(result, {
enter: rewrite
});
return {
result: result,
modified: modified
};
}
rewriteBoolean.passName = Name;
module.exports = rewriteBoolean;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"estraverse":129}],36:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, common, estraverse, modified;
Name = 'rewrite-conditional-expression';
estraverse = require('estraverse');
common = require('../common');
Syntax = common.Syntax;
function rewrite(node) {
var test, consequent, alternate;
test = node.test;
consequent = node.consequent;
alternate = node.alternate;
if (test.type === Syntax.UnaryExpression && test.operator === '!') {
modified = true;
node.consequent = alternate;
node.alternate = consequent;
node.test = test.argument;
}
}
function rewriteConditionalExpression(tree, options) {
var result;
modified = false;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
estraverse.traverse(result, {
enter: function enter(node) {
if (node.type === Syntax.ConditionalExpression) {
rewrite(node);
}
}
});
return {
result: result,
modified: modified
};
}
rewriteConditionalExpression.passName = Name;
module.exports = rewriteConditionalExpression;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"estraverse":129}],37:[function(require,module,exports){
/*
Copyright (C) 2012 Michael Ficarra <esmangle.copyright@michael.ficarra.me>
Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, common, estraverse;
Name = 'transform-infinity';
estraverse = require('estraverse');
common = require('../common');
Syntax = common.Syntax;
function transformInfinity(tree, options) {
var result, modified;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
modified = false;
result = estraverse.replace(result, {
enter: function enter(node) {
if (node.type === Syntax.Literal && typeof node.value === 'number') {
if (node.value === Infinity) {
modified = true;
return common.moveLocation(node, {
type: Syntax.BinaryExpression,
operator: '/',
left: {type: Syntax.Literal, value: 1},
right: {type: Syntax.Literal, value: 0}
});
}
}
}
});
return {
result: result,
modified: modified
};
}
transformInfinity.passName = Name;
module.exports = transformInfinity;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"estraverse":129}],38:[function(require,module,exports){
/*
Copyright (C) 2012 Michael Ficarra <esmangle.copyright@michael.ficarra.me>
Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, common, estraverse;
Name = 'transform-static-to-dynamic-property-access';
estraverse = require('estraverse');
common = require('../common');
Syntax = common.Syntax;
function transformStaticToDynamicPropertyAccess(tree, options) {
var result, modified;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
modified = false;
estraverse.traverse(result, {
enter: function enter(node) {
var property;
if (node.type !== Syntax.MemberExpression || node.computed || node.property.type !== Syntax.Identifier) {
return;
}
property = node.property;
switch (property.name) {
case 'undefined':
modified = true;
node.computed = true;
node.property = common.moveLocation(property, {
type: Syntax.UnaryExpression,
operator: 'void',
argument: {type: Syntax.Literal, value: 0}
});
break;
case 'true':
case 'false':
modified = true;
node.computed = true;
node.property = common.moveLocation(property, {
type: Syntax.Literal,
value: property.name === 'true'
});
break;
case 'Infinity':
modified = true;
node.computed = true;
node.property = common.moveLocation(property, {
type: Syntax.BinaryExpression,
operator: '/',
left: {type: Syntax.Literal, value: 1},
right: {type: Syntax.Literal, value: 0}
});
break;
}
}
});
return {
result: result,
modified: modified
};
}
transformStaticToDynamicPropertyAccess.passName = Name;
module.exports = transformStaticToDynamicPropertyAccess;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../common":2,"estraverse":129}],39:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint bitwise:true */
/*global require:true*/
(function () {
'use strict';
var common;
common = require('./common');
exports.get = function get(root, query) {
var i, iz, name, node;
node = root;
for (i = 0, iz = query.length; i < iz; ++i) {
name = query[i];
node = node[name];
}
return node;
};
exports.set = function set(root, query, value) {
var i, iz, name, node;
common.assert(query.length > 0);
node = root;
for (i = 0, iz = query.length - 1; i < iz; ++i) {
name = query[i];
node = node[name];
}
name = query[i];
node[name] = value;
};
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"./common":2}],40:[function(require,module,exports){
(function (global){
'use strict';
var objectAssign = require('object-assign');
// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
// original notice:
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
function compare(a, b) {
if (a === b) {
return 0;
}
var x = a.length;
var y = b.length;
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i];
y = b[i];
break;
}
}
if (x < y) {
return -1;
}
if (y < x) {
return 1;
}
return 0;
}
function isBuffer(b) {
if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
return global.Buffer.isBuffer(b);
}
return !!(b != null && b._isBuffer);
}
// based on node assert, original notice:
// NB: The URL to the CommonJS spec is kept just for tradition.
// node-assert has evolved a lot since then, both in API and behavior.
// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
//
// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
//
// Originally from narwhal.js (http://narwhaljs.org)
// Copyright (c) 2009 Thomas Robinson <280north.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the 'Software'), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
var util = require('util/');
var hasOwn = Object.prototype.hasOwnProperty;
var pSlice = Array.prototype.slice;
var functionsHaveNames = (function () {
return function foo() {}.name === 'foo';
}());
function pToString (obj) {
return Object.prototype.toString.call(obj);
}
function isView(arrbuf) {
if (isBuffer(arrbuf)) {
return false;
}
if (typeof global.ArrayBuffer !== 'function') {
return false;
}
if (typeof ArrayBuffer.isView === 'function') {
return ArrayBuffer.isView(arrbuf);
}
if (!arrbuf) {
return false;
}
if (arrbuf instanceof DataView) {
return true;
}
if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
return true;
}
return false;
}
// 1. The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.
var assert = module.exports = ok;
// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
// actual: actual,
// expected: expected })
var regex = /\s*function\s+([^\(\s]*)\s*/;
// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
function getName(func) {
if (!util.isFunction(func)) {
return;
}
if (functionsHaveNames) {
return func.name;
}
var str = func.toString();
var match = str.match(regex);
return match && match[1];
}
assert.AssertionError = function AssertionError(options) {
this.name = 'AssertionError';
this.actual = options.actual;
this.expected = options.expected;
this.operator = options.operator;
if (options.message) {
this.message = options.message;
this.generatedMessage = false;
} else {
this.message = getMessage(this);
this.generatedMessage = true;
}
var stackStartFunction = options.stackStartFunction || fail;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, stackStartFunction);
} else {
// non v8 browsers so we can have a stacktrace
var err = new Error();
if (err.stack) {
var out = err.stack;
// try to strip useless frames
var fn_name = getName(stackStartFunction);
var idx = out.indexOf('\n' + fn_name);
if (idx >= 0) {
// once we have located the function frame
// we need to strip out everything before it (and its line)
var next_line = out.indexOf('\n', idx + 1);
out = out.substring(next_line + 1);
}
this.stack = out;
}
}
};
// assert.AssertionError instanceof Error
util.inherits(assert.AssertionError, Error);
function truncate(s, n) {
if (typeof s === 'string') {
return s.length < n ? s : s.slice(0, n);
} else {
return s;
}
}
function inspect(something) {
if (functionsHaveNames || !util.isFunction(something)) {
return util.inspect(something);
}
var rawname = getName(something);
var name = rawname ? ': ' + rawname : '';
return '[Function' + name + ']';
}
function getMessage(self) {
return truncate(inspect(self.actual), 128) + ' ' +
self.operator + ' ' +
truncate(inspect(self.expected), 128);
}
// At present only the three keys mentioned above are used and
// understood by the spec. Implementations or sub modules can pass
// other keys to the AssertionError's constructor - they will be
// ignored.
// 3. All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided. All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.
function fail(actual, expected, message, operator, stackStartFunction) {
throw new assert.AssertionError({
message: message,
actual: actual,
expected: expected,
operator: operator,
stackStartFunction: stackStartFunction
});
}
// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;
// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.
function ok(value, message) {
if (!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;
// 5. The equality assertion tests shallow, coercive equality with
// ==.
// assert.equal(actual, expected, message_opt);
assert.equal = function equal(actual, expected, message) {
if (actual != expected) fail(actual, expected, message, '==', assert.equal);
};
// 6. The non-equality assertion tests for whether two objects are not equal
// with != assert.notEqual(actual, expected, message_opt);
assert.notEqual = function notEqual(actual, expected, message) {
if (actual == expected) {
fail(actual, expected, message, '!=', assert.notEqual);
}
};
// 7. The equivalence assertion tests a deep equality relation.
// assert.deepEqual(actual, expected, message_opt);
assert.deepEqual = function deepEqual(actual, expected, message) {
if (!_deepEqual(actual, expected, false)) {
fail(actual, expected, message, 'deepEqual', assert.deepEqual);
}
};
assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
if (!_deepEqual(actual, expected, true)) {
fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
}
};
function _deepEqual(actual, expected, strict, memos) {
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (isBuffer(actual) && isBuffer(expected)) {
return compare(actual, expected) === 0;
// 7.2. If the expected value is a Date object, the actual value is
// equivalent if it is also a Date object that refers to the same time.
} else if (util.isDate(actual) && util.isDate(expected)) {
return actual.getTime() === expected.getTime();
// 7.3 If the expected value is a RegExp object, the actual value is
// equivalent if it is also a RegExp object with the same source and
// properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
} else if (util.isRegExp(actual) && util.isRegExp(expected)) {
return actual.source === expected.source &&
actual.global === expected.global &&
actual.multiline === expected.multiline &&
actual.lastIndex === expected.lastIndex &&
actual.ignoreCase === expected.ignoreCase;
// 7.4. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if ((actual === null || typeof actual !== 'object') &&
(expected === null || typeof expected !== 'object')) {
return strict ? actual === expected : actual == expected;
// If both values are instances of typed arrays, wrap their underlying
// ArrayBuffers in a Buffer each to increase performance
// This optimization requires the arrays to have the same type as checked by
// Object.prototype.toString (aka pToString). Never perform binary
// comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
// bit patterns are not identical.
} else if (isView(actual) && isView(expected) &&
pToString(actual) === pToString(expected) &&
!(actual instanceof Float32Array ||
actual instanceof Float64Array)) {
return compare(new Uint8Array(actual.buffer),
new Uint8Array(expected.buffer)) === 0;
// 7.5 For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else if (isBuffer(actual) !== isBuffer(expected)) {
return false;
} else {
memos = memos || {actual: [], expected: []};
var actualIndex = memos.actual.indexOf(actual);
if (actualIndex !== -1) {
if (actualIndex === memos.expected.indexOf(expected)) {
return true;
}
}
memos.actual.push(actual);
memos.expected.push(expected);
return objEquiv(actual, expected, strict, memos);
}
}
function isArguments(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
}
function objEquiv(a, b, strict, actualVisitedObjects) {
if (a === null || a === undefined || b === null || b === undefined)
return false;
// if one is a primitive, the other must be same
if (util.isPrimitive(a) || util.isPrimitive(b))
return a === b;
if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
return false;
var aIsArgs = isArguments(a);
var bIsArgs = isArguments(b);
if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
return false;
if (aIsArgs) {
a = pSlice.call(a);
b = pSlice.call(b);
return _deepEqual(a, b, strict);
}
var ka = objectKeys(a);
var kb = objectKeys(b);
var key, i;
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length !== kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] !== kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
return false;
}
return true;
}
// 8. The non-equivalence assertion tests for any deep inequality.
// assert.notDeepEqual(actual, expected, message_opt);
assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
if (_deepEqual(actual, expected, false)) {
fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
}
};
assert.notDeepStrictEqual = notDeepStrictEqual;
function notDeepStrictEqual(actual, expected, message) {
if (_deepEqual(actual, expected, true)) {
fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
}
}
// 9. The strict equality assertion tests strict equality, as determined by ===.
// assert.strictEqual(actual, expected, message_opt);
assert.strictEqual = function strictEqual(actual, expected, message) {
if (actual !== expected) {
fail(actual, expected, message, '===', assert.strictEqual);
}
};
// 10. The strict non-equality assertion tests for strict inequality, as
// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
if (actual === expected) {
fail(actual, expected, message, '!==', assert.notStrictEqual);
}
};
function expectedException(actual, expected) {
if (!actual || !expected) {
return false;
}
if (Object.prototype.toString.call(expected) == '[object RegExp]') {
return expected.test(actual);
}
try {
if (actual instanceof expected) {
return true;
}
} catch (e) {
// Ignore. The instanceof check doesn't work for arrow functions.
}
if (Error.isPrototypeOf(expected)) {
return false;
}
return expected.call({}, actual) === true;
}
function _tryBlock(block) {
var error;
try {
block();
} catch (e) {
error = e;
}
return error;
}
function _throws(shouldThrow, block, expected, message) {
var actual;
if (typeof block !== 'function') {
throw new TypeError('"block" argument must be a function');
}
if (typeof expected === 'string') {
message = expected;
expected = null;
}
actual = _tryBlock(block);
message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
(message ? ' ' + message : '.');
if (shouldThrow && !actual) {
fail(actual, expected, 'Missing expected exception' + message);
}
var userProvidedMessage = typeof message === 'string';
var isUnwantedException = !shouldThrow && util.isError(actual);
var isUnexpectedException = !shouldThrow && actual && !expected;
if ((isUnwantedException &&
userProvidedMessage &&
expectedException(actual, expected)) ||
isUnexpectedException) {
fail(actual, expected, 'Got unwanted exception' + message);
}
if ((shouldThrow && actual && expected &&
!expectedException(actual, expected)) || (!shouldThrow && actual)) {
throw actual;
}
}
// 11. Expected to throw an error:
// assert.throws(block, Error_opt, message_opt);
assert.throws = function(block, /*optional*/error, /*optional*/message) {
_throws(true, block, error, message);
};
// EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
_throws(false, block, error, message);
};
assert.ifError = function(err) { if (err) throw err; };
// Expose a strict only variant of assert
function strict(value, message) {
if (!value) fail(value, true, message, '==', strict);
}
assert.strict = objectAssign(strict, assert, {
equal: assert.strictEqual,
deepEqual: assert.deepStrictEqual,
notEqual: assert.notStrictEqual,
notDeepEqual: assert.notDeepStrictEqual
});
assert.strict.strict = assert.strict;
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
if (hasOwn.call(obj, key)) keys.push(key);
}
return keys;
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"object-assign":141,"util/":43}],41:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],42:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],43:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":42,"_process":142,"inherits":41}],44:[function(require,module,exports){
var upperCase = require('upper-case')
var sentenceCase = require('sentence-case')
/**
* Camel case a string.
*
* @param {String} string
* @param {String} [locale]
* @return {String}
*/
module.exports = function (string, locale, mergeNumbers) {
var result = sentenceCase(string, locale)
// Replace periods between numeric entities with an underscore.
if (!mergeNumbers) {
result = result.replace(/(\d) (?=\d)/g, '$1_')
}
// Replace spaces between words with an upper cased character.
return result.replace(/ (.)/g, function (m, $1) {
return upperCase($1, locale)
})
}
},{"sentence-case":143,"upper-case":158}],45:[function(require,module,exports){
"use strict";
var isValue = require("type/value/is")
, ensureValue = require("type/value/ensure")
, ensurePlainFunction = require("type/plain-function/ensure")
, copy = require("es5-ext/object/copy")
, normalizeOptions = require("es5-ext/object/normalize-options")
, map = require("es5-ext/object/map");
var bind = Function.prototype.bind
, defineProperty = Object.defineProperty
, hasOwnProperty = Object.prototype.hasOwnProperty
, define;
define = function (name, desc, options) {
var value = ensureValue(desc) && ensurePlainFunction(desc.value), dgs;
dgs = copy(desc);
delete dgs.writable;
delete dgs.value;
dgs.get = function () {
if (!options.overwriteDefinition && hasOwnProperty.call(this, name)) return value;
desc.value = bind.call(value, options.resolveContext ? options.resolveContext(this) : this);
defineProperty(this, name, desc);
return this[name];
};
return dgs;
};
module.exports = function (props/*, options*/) {
var options = normalizeOptions(arguments[1]);
if (isValue(options.resolveContext)) ensurePlainFunction(options.resolveContext);
return map(props, function (desc, name) { return define(name, desc, options); });
};
},{"es5-ext/object/copy":67,"es5-ext/object/map":75,"es5-ext/object/normalize-options":76,"type/plain-function/ensure":152,"type/value/ensure":156,"type/value/is":157}],46:[function(require,module,exports){
"use strict";
var isValue = require("type/value/is")
, isPlainFunction = require("type/plain-function/is")
, assign = require("es5-ext/object/assign")
, normalizeOpts = require("es5-ext/object/normalize-options")
, contains = require("es5-ext/string/#/contains");
var d = (module.exports = function (dscr, value/*, options*/) {
var c, e, w, options, desc;
if (arguments.length < 2 || typeof dscr !== "string") {
options = value;
value = dscr;
dscr = null;
} else {
options = arguments[2];
}
if (isValue(dscr)) {
c = contains.call(dscr, "c");
e = contains.call(dscr, "e");
w = contains.call(dscr, "w");
} else {
c = w = true;
e = false;
}
desc = { value: value, configurable: c, enumerable: e, writable: w };
return !options ? desc : assign(normalizeOpts(options), desc);
});
d.gs = function (dscr, get, set/*, options*/) {
var c, e, options, desc;
if (typeof dscr !== "string") {
options = set;
set = get;
get = dscr;
dscr = null;
} else {
options = arguments[3];
}
if (!isValue(get)) {
get = undefined;
} else if (!isPlainFunction(get)) {
options = get;
get = set = undefined;
} else if (!isValue(set)) {
set = undefined;
} else if (!isPlainFunction(set)) {
options = set;
set = undefined;
}
if (isValue(dscr)) {
c = contains.call(dscr, "c");
e = contains.call(dscr, "e");
} else {
c = true;
e = false;
}
desc = { get: get, set: set, configurable: c, enumerable: e };
return !options ? desc : assign(normalizeOpts(options), desc);
};
},{"es5-ext/object/assign":64,"es5-ext/object/normalize-options":76,"es5-ext/string/#/contains":84,"type/plain-function/is":153,"type/value/is":157}],47:[function(require,module,exports){
// Inspired by Google Closure:
// http://closure-library.googlecode.com/svn/docs/
// closure_goog_array_array.js.html#goog.array.clear
"use strict";
var value = require("../../object/valid-value");
module.exports = function () {
value(this).length = 0;
return this;
};
},{"../../object/valid-value":83}],48:[function(require,module,exports){
"use strict";
var numberIsNaN = require("../../number/is-nan")
, toPosInt = require("../../number/to-pos-integer")
, value = require("../../object/valid-value")
, indexOf = Array.prototype.indexOf
, objHasOwnProperty = Object.prototype.hasOwnProperty
, abs = Math.abs
, floor = Math.floor;
module.exports = function (searchElement/*, fromIndex*/) {
var i, length, fromIndex, val;
if (!numberIsNaN(searchElement)) return indexOf.apply(this, arguments);
length = toPosInt(value(this).length);
fromIndex = arguments[1];
if (isNaN(fromIndex)) fromIndex = 0;
else if (fromIndex >= 0) fromIndex = floor(fromIndex);
else fromIndex = toPosInt(this.length) - floor(abs(fromIndex));
for (i = fromIndex; i < length; ++i) {
if (objHasOwnProperty.call(this, i)) {
val = this[i];
if (numberIsNaN(val)) return i; // Jslint: ignore
}
}
return -1;
};
},{"../../number/is-nan":58,"../../number/to-pos-integer":62,"../../object/valid-value":83}],49:[function(require,module,exports){
"use strict";
module.exports = require("./is-implemented")() ? Array.from : require("./shim");
},{"./is-implemented":50,"./shim":51}],50:[function(require,module,exports){
"use strict";
module.exports = function () {
var from = Array.from, arr, result;
if (typeof from !== "function") return false;
arr = ["raz", "dwa"];
result = from(arr);
return Boolean(result && result !== arr && result[1] === "dwa");
};
},{}],51:[function(require,module,exports){
"use strict";
var iteratorSymbol = require("es6-symbol").iterator
, isArguments = require("../../function/is-arguments")
, isFunction = require("../../function/is-function")
, toPosInt = require("../../number/to-pos-integer")
, callable = require("../../object/valid-callable")
, validValue = require("../../object/valid-value")
, isValue = require("../../object/is-value")
, isString = require("../../string/is-string")
, isArray = Array.isArray
, call = Function.prototype.call
, desc = { configurable: true, enumerable: true, writable: true, value: null }
, defineProperty = Object.defineProperty;
// eslint-disable-next-line complexity, max-lines-per-function
module.exports = function (arrayLike/*, mapFn, thisArg*/) {
var mapFn = arguments[1]
, thisArg = arguments[2]
, Context
, i
, j
, arr
, length
, code
, iterator
, result
, getIterator
, value;
arrayLike = Object(validValue(arrayLike));
if (isValue(mapFn)) callable(mapFn);
if (!this || this === Array || !isFunction(this)) {
// Result: Plain array
if (!mapFn) {
if (isArguments(arrayLike)) {
// Source: Arguments
length = arrayLike.length;
if (length !== 1) return Array.apply(null, arrayLike);
arr = new Array(1);
arr[0] = arrayLike[0];
return arr;
}
if (isArray(arrayLike)) {
// Source: Array
arr = new Array((length = arrayLike.length));
for (i = 0; i < length; ++i) arr[i] = arrayLike[i];
return arr;
}
}
arr = [];
} else {
// Result: Non plain array
Context = this;
}
if (!isArray(arrayLike)) {
if ((getIterator = arrayLike[iteratorSymbol]) !== undefined) {
// Source: Iterator
iterator = callable(getIterator).call(arrayLike);
if (Context) arr = new Context();
result = iterator.next();
i = 0;
while (!result.done) {
value = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value;
if (Context) {
desc.value = value;
defineProperty(arr, i, desc);
} else {
arr[i] = value;
}
result = iterator.next();
++i;
}
length = i;
} else if (isString(arrayLike)) {
// Source: String
length = arrayLike.length;
if (Context) arr = new Context();
for (i = 0, j = 0; i < length; ++i) {
value = arrayLike[i];
if (i + 1 < length) {
code = value.charCodeAt(0);
// eslint-disable-next-line max-depth
if (code >= 0xd800 && code <= 0xdbff) value += arrayLike[++i];
}
value = mapFn ? call.call(mapFn, thisArg, value, j) : value;
if (Context) {
desc.value = value;
defineProperty(arr, j, desc);
} else {
arr[j] = value;
}
++j;
}
length = j;
}
}
if (length === undefined) {
// Source: array or array-like
length = toPosInt(arrayLike.length);
if (Context) arr = new Context(length);
for (i = 0; i < length; ++i) {
value = mapFn ? call.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i];
if (Context) {
desc.value = value;
defineProperty(arr, i, desc);
} else {
arr[i] = value;
}
}
}
if (Context) {
desc.value = null;
arr.length = length;
}
return arr;
};
},{"../../function/is-arguments":52,"../../function/is-function":53,"../../number/to-pos-integer":62,"../../object/is-value":71,"../../object/valid-callable":81,"../../object/valid-value":83,"../../string/is-string":87,"es6-symbol":102}],52:[function(require,module,exports){
"use strict";
var objToString = Object.prototype.toString
, id = objToString.call((function () { return arguments; })());
module.exports = function (value) { return objToString.call(value) === id; };
},{}],53:[function(require,module,exports){
"use strict";
var objToString = Object.prototype.toString
, isFunctionStringTag = RegExp.prototype.test.bind(/^[object [A-Za-z0-9]*Function]$/);
module.exports = function (value) {
return typeof value === "function" && isFunctionStringTag(objToString.call(value));
};
},{}],54:[function(require,module,exports){
"use strict";
// eslint-disable-next-line no-empty-function
module.exports = function () {};
},{}],55:[function(require,module,exports){
"use strict";
module.exports = require("./is-implemented")() ? Math.sign : require("./shim");
},{"./is-implemented":56,"./shim":57}],56:[function(require,module,exports){
"use strict";
module.exports = function () {
var sign = Math.sign;
if (typeof sign !== "function") return false;
return sign(10) === 1 && sign(-20) === -1;
};
},{}],57:[function(require,module,exports){
"use strict";
module.exports = function (value) {
value = Number(value);
if (isNaN(value) || value === 0) return value;
return value > 0 ? 1 : -1;
};
},{}],58:[function(require,module,exports){
"use strict";
module.exports = require("./is-implemented")() ? Number.isNaN : require("./shim");
},{"./is-implemented":59,"./shim":60}],59:[function(require,module,exports){
"use strict";
module.exports = function () {
var numberIsNaN = Number.isNaN;
if (typeof numberIsNaN !== "function") return false;
return !numberIsNaN({}) && numberIsNaN(NaN) && !numberIsNaN(34);
};
},{}],60:[function(require,module,exports){
"use strict";
module.exports = function (value) {
// eslint-disable-next-line no-self-compare
return value !== value;
};
},{}],61:[function(require,module,exports){
"use strict";
var sign = require("../math/sign")
, abs = Math.abs
, floor = Math.floor;
module.exports = function (value) {
if (isNaN(value)) return 0;
value = Number(value);
if (value === 0 || !isFinite(value)) return value;
return sign(value) * floor(abs(value));
};
},{"../math/sign":55}],62:[function(require,module,exports){
"use strict";
var toInteger = require("./to-integer")
, max = Math.max;
module.exports = function (value) { return max(0, toInteger(value)); };
},{"./to-integer":61}],63:[function(require,module,exports){
// Internal method, used by iteration functions.
// Calls a function for each key-value pair found in object
// Optionally takes compareFn to iterate object in specific order
"use strict";
var callable = require("./valid-callable")
, value = require("./valid-value")
, bind = Function.prototype.bind
, call = Function.prototype.call
, keys = Object.keys
, objPropertyIsEnumerable = Object.prototype.propertyIsEnumerable;
module.exports = function (method, defVal) {
return function (obj, cb/*, thisArg, compareFn*/) {
var list, thisArg = arguments[2], compareFn = arguments[3];
obj = Object(value(obj));
callable(cb);
list = keys(obj);
if (compareFn) {
list.sort(typeof compareFn === "function" ? bind.call(compareFn, obj) : undefined);
}
if (typeof method !== "function") method = list[method];
return call.call(method, list, function (key, index) {
if (!objPropertyIsEnumerable.call(obj, key)) return defVal;
return call.call(cb, thisArg, obj[key], key, obj, index);
});
};
};
},{"./valid-callable":81,"./valid-value":83}],64:[function(require,module,exports){
"use strict";
module.exports = require("./is-implemented")() ? Object.assign : require("./shim");
},{"./is-implemented":65,"./shim":66}],65:[function(require,module,exports){
"use strict";
module.exports = function () {
var assign = Object.assign, obj;
if (typeof assign !== "function") return false;
obj = { foo: "raz" };
assign(obj, { bar: "dwa" }, { trzy: "trzy" });
return obj.foo + obj.bar + obj.trzy === "razdwatrzy";
};
},{}],66:[function(require,module,exports){
"use strict";
var keys = require("../keys")
, value = require("../valid-value")
, max = Math.max;
module.exports = function (dest, src/*, …srcn*/) {
var error, i, length = max(arguments.length, 2), assign;
dest = Object(value(dest));
assign = function (key) {
try {
dest[key] = src[key];
} catch (e) {
if (!error) error = e;
}
};
for (i = 1; i < length; ++i) {
src = arguments[i];
keys(src).forEach(assign);
}
if (error !== undefined) throw error;
return dest;
};
},{"../keys":72,"../valid-value":83}],67:[function(require,module,exports){
"use strict";
var aFrom = require("../array/from")
, assign = require("./assign")
, value = require("./valid-value");
module.exports = function (obj/*, propertyNames, options*/) {
var copy = Object(value(obj)), propertyNames = arguments[1], options = Object(arguments[2]);
if (copy !== obj && !propertyNames) return copy;
var result = {};
if (propertyNames) {
aFrom(propertyNames, function (propertyName) {
if (options.ensure || propertyName in obj) result[propertyName] = obj[propertyName];
});
} else {
assign(result, obj);
}
return result;
};
},{"../array/from":49,"./assign":64,"./valid-value":83}],68:[function(require,module,exports){
// Workaround for http://code.google.com/p/v8/issues/detail?id=2804
"use strict";
var create = Object.create, shim;
if (!require("./set-prototype-of/is-implemented")()) {
shim = require("./set-prototype-of/shim");
}
module.exports = (function () {
var nullObject, polyProps, desc;
if (!shim) return create;
if (shim.level !== 1) return create;
nullObject = {};
polyProps = {};
desc = { configurable: false, enumerable: false, writable: true, value: undefined };
Object.getOwnPropertyNames(Object.prototype).forEach(function (name) {
if (name === "__proto__") {
polyProps[name] = {
configurable: true,
enumerable: false,
writable: true,
value: undefined
};
return;
}
polyProps[name] = desc;
});
Object.defineProperties(nullObject, polyProps);
Object.defineProperty(shim, "nullPolyfill", {
configurable: false,
enumerable: false,
writable: false,
value: nullObject
});
return function (prototype, props) {
return create(prototype === null ? nullObject : prototype, props);
};
})();
},{"./set-prototype-of/is-implemented":79,"./set-prototype-of/shim":80}],69:[function(require,module,exports){
"use strict";
module.exports = require("./_iterate")("forEach");
},{"./_iterate":63}],70:[function(require,module,exports){
"use strict";
var isValue = require("./is-value");
var map = { function: true, object: true };
module.exports = function (value) { return (isValue(value) && map[typeof value]) || false; };
},{"./is-value":71}],71:[function(require,module,exports){
"use strict";
var _undefined = require("../function/noop")(); // Support ES3 engines
module.exports = function (val) { return val !== _undefined && val !== null; };
},{"../function/noop":54}],72:[function(require,module,exports){
"use strict";
module.exports = require("./is-implemented")() ? Object.keys : require("./shim");
},{"./is-implemented":73,"./shim":74}],73:[function(require,module,exports){
"use strict";
module.exports = function () {
try {
Object.keys("primitive");
return true;
} catch (e) {
return false;
}
};
},{}],74:[function(require,module,exports){
"use strict";
var isValue = require("../is-value");
var keys = Object.keys;
module.exports = function (object) { return keys(isValue(object) ? Object(object) : object); };
},{"../is-value":71}],75:[function(require,module,exports){
"use strict";
var callable = require("./valid-callable")
, forEach = require("./for-each")
, call = Function.prototype.call;
module.exports = function (obj, cb/*, thisArg*/) {
var result = {}, thisArg = arguments[2];
callable(cb);
forEach(obj, function (value, key, targetObj, index) {
result[key] = call.call(cb, thisArg, value, key, targetObj, index);
});
return result;
};
},{"./for-each":69,"./valid-callable":81}],76:[function(require,module,exports){
"use strict";
var isValue = require("./is-value");
var forEach = Array.prototype.forEach, create = Object.create;
var process = function (src, obj) {
var key;
for (key in src) obj[key] = src[key];
};
// eslint-disable-next-line no-unused-vars
module.exports = function (opts1/*, …options*/) {
var result = create(null);
forEach.call(arguments, function (options) {
if (!isValue(options)) return;
process(Object(options), result);
});
return result;
};
},{"./is-value":71}],77:[function(require,module,exports){
"use strict";
var forEach = Array.prototype.forEach, create = Object.create;
// eslint-disable-next-line no-unused-vars
module.exports = function (arg/*, …args*/) {
var set = create(null);
forEach.call(arguments, function (name) { set[name] = true; });
return set;
};
},{}],78:[function(require,module,exports){
"use strict";
module.exports = require("./is-implemented")() ? Object.setPrototypeOf : require("./shim");
},{"./is-implemented":79,"./shim":80}],79:[function(require,module,exports){
"use strict";
var create = Object.create, getPrototypeOf = Object.getPrototypeOf, plainObject = {};
module.exports = function (/* CustomCreate*/) {
var setPrototypeOf = Object.setPrototypeOf, customCreate = arguments[0] || create;
if (typeof setPrototypeOf !== "function") return false;
return getPrototypeOf(setPrototypeOf(customCreate(null), plainObject)) === plainObject;
};
},{}],80:[function(require,module,exports){
/* eslint no-proto: "off" */
// Big thanks to @WebReflection for sorting this out
// https://gist.github.com/WebReflection/5593554
"use strict";
var isObject = require("../is-object")
, value = require("../valid-value")
, objIsPrototypeOf = Object.prototype.isPrototypeOf
, defineProperty = Object.defineProperty
, nullDesc = { configurable: true, enumerable: false, writable: true, value: undefined }
, validate;
validate = function (obj, prototype) {
value(obj);
if (prototype === null || isObject(prototype)) return obj;
throw new TypeError("Prototype must be null or an object");
};
module.exports = (function (status) {
var fn, set;
if (!status) return null;
if (status.level === 2) {
if (status.set) {
set = status.set;
fn = function (obj, prototype) {
set.call(validate(obj, prototype), prototype);
return obj;
};
} else {
fn = function (obj, prototype) {
validate(obj, prototype).__proto__ = prototype;
return obj;
};
}
} else {
fn = function self(obj, prototype) {
var isNullBase;
validate(obj, prototype);
isNullBase = objIsPrototypeOf.call(self.nullPolyfill, obj);
if (isNullBase) delete self.nullPolyfill.__proto__;
if (prototype === null) prototype = self.nullPolyfill;
obj.__proto__ = prototype;
if (isNullBase) defineProperty(self.nullPolyfill, "__proto__", nullDesc);
return obj;
};
}
return Object.defineProperty(fn, "level", {
configurable: false,
enumerable: false,
writable: false,
value: status.level
});
})(
(function () {
var tmpObj1 = Object.create(null)
, tmpObj2 = {}
, set
, desc = Object.getOwnPropertyDescriptor(Object.prototype, "__proto__");
if (desc) {
try {
set = desc.set; // Opera crashes at this point
set.call(tmpObj1, tmpObj2);
} catch (ignore) {}
if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { set: set, level: 2 };
}
tmpObj1.__proto__ = tmpObj2;
if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 2 };
tmpObj1 = {};
tmpObj1.__proto__ = tmpObj2;
if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 1 };
return false;
})()
);
require("../create");
},{"../create":68,"../is-object":70,"../valid-value":83}],81:[function(require,module,exports){
"use strict";
module.exports = function (fn) {
if (typeof fn !== "function") throw new TypeError(fn + " is not a function");
return fn;
};
},{}],82:[function(require,module,exports){
"use strict";
var isObject = require("./is-object");
module.exports = function (value) {
if (!isObject(value)) throw new TypeError(value + " is not an Object");
return value;
};
},{"./is-object":70}],83:[function(require,module,exports){
"use strict";
var isValue = require("./is-value");
module.exports = function (value) {
if (!isValue(value)) throw new TypeError("Cannot use null or undefined");
return value;
};
},{"./is-value":71}],84:[function(require,module,exports){
"use strict";
module.exports = require("./is-implemented")() ? String.prototype.contains : require("./shim");
},{"./is-implemented":85,"./shim":86}],85:[function(require,module,exports){
"use strict";
var str = "razdwatrzy";
module.exports = function () {
if (typeof str.contains !== "function") return false;
return str.contains("dwa") === true && str.contains("foo") === false;
};
},{}],86:[function(require,module,exports){
"use strict";
var indexOf = String.prototype.indexOf;
module.exports = function (searchString/*, position*/) {
return indexOf.call(this, searchString, arguments[1]) > -1;
};
},{}],87:[function(require,module,exports){
"use strict";
var objToString = Object.prototype.toString, id = objToString.call("");
module.exports = function (value) {
return (
typeof value === "string" ||
(value &&
typeof value === "object" &&
(value instanceof String || objToString.call(value) === id)) ||
false
);
};
},{}],88:[function(require,module,exports){
"use strict";
var generated = Object.create(null), random = Math.random;
module.exports = function () {
var str;
do {
str = random().toString(36).slice(2);
} while (generated[str]);
return str;
};
},{}],89:[function(require,module,exports){
"use strict";
var setPrototypeOf = require("es5-ext/object/set-prototype-of")
, contains = require("es5-ext/string/#/contains")
, d = require("d")
, Symbol = require("es6-symbol")
, Iterator = require("./");
var defineProperty = Object.defineProperty, ArrayIterator;
ArrayIterator = module.exports = function (arr, kind) {
if (!(this instanceof ArrayIterator)) throw new TypeError("Constructor requires 'new'");
Iterator.call(this, arr);
if (!kind) kind = "value";
else if (contains.call(kind, "key+value")) kind = "key+value";
else if (contains.call(kind, "key")) kind = "key";
else kind = "value";
defineProperty(this, "__kind__", d("", kind));
};
if (setPrototypeOf) setPrototypeOf(ArrayIterator, Iterator);
// Internal %ArrayIteratorPrototype% doesn't expose its constructor
delete ArrayIterator.prototype.constructor;
ArrayIterator.prototype = Object.create(Iterator.prototype, {
_resolve: d(function (i) {
if (this.__kind__ === "value") return this.__list__[i];
if (this.__kind__ === "key+value") return [i, this.__list__[i]];
return i;
})
});
defineProperty(ArrayIterator.prototype, Symbol.toStringTag, d("c", "Array Iterator"));
},{"./":92,"d":46,"es5-ext/object/set-prototype-of":78,"es5-ext/string/#/contains":84,"es6-symbol":102}],90:[function(require,module,exports){
"use strict";
var isArguments = require("es5-ext/function/is-arguments")
, callable = require("es5-ext/object/valid-callable")
, isString = require("es5-ext/string/is-string")
, get = require("./get");
var isArray = Array.isArray, call = Function.prototype.call, some = Array.prototype.some;
module.exports = function (iterable, cb /*, thisArg*/) {
var mode, thisArg = arguments[2], result, doBreak, broken, i, length, char, code;
if (isArray(iterable) || isArguments(iterable)) mode = "array";
else if (isString(iterable)) mode = "string";
else iterable = get(iterable);
callable(cb);
doBreak = function () {
broken = true;
};
if (mode === "array") {
some.call(iterable, function (value) {
call.call(cb, thisArg, value, doBreak);
return broken;
});
return;
}
if (mode === "string") {
length = iterable.length;
for (i = 0; i < length; ++i) {
char = iterable[i];
if (i + 1 < length) {
code = char.charCodeAt(0);
if (code >= 0xd800 && code <= 0xdbff) char += iterable[++i];
}
call.call(cb, thisArg, char, doBreak);
if (broken) break;
}
return;
}
result = iterable.next();
while (!result.done) {
call.call(cb, thisArg, result.value, doBreak);
if (broken) return;
result = iterable.next();
}
};
},{"./get":91,"es5-ext/function/is-arguments":52,"es5-ext/object/valid-callable":81,"es5-ext/string/is-string":87}],91:[function(require,module,exports){
"use strict";
var isArguments = require("es5-ext/function/is-arguments")
, isString = require("es5-ext/string/is-string")
, ArrayIterator = require("./array")
, StringIterator = require("./string")
, iterable = require("./valid-iterable")
, iteratorSymbol = require("es6-symbol").iterator;
module.exports = function (obj) {
if (typeof iterable(obj)[iteratorSymbol] === "function") return obj[iteratorSymbol]();
if (isArguments(obj)) return new ArrayIterator(obj);
if (isString(obj)) return new StringIterator(obj);
return new ArrayIterator(obj);
};
},{"./array":89,"./string":94,"./valid-iterable":95,"es5-ext/function/is-arguments":52,"es5-ext/string/is-string":87,"es6-symbol":102}],92:[function(require,module,exports){
"use strict";
var clear = require("es5-ext/array/#/clear")
, assign = require("es5-ext/object/assign")
, callable = require("es5-ext/object/valid-callable")
, value = require("es5-ext/object/valid-value")
, d = require("d")
, autoBind = require("d/auto-bind")
, Symbol = require("es6-symbol");
var defineProperty = Object.defineProperty, defineProperties = Object.defineProperties, Iterator;
module.exports = Iterator = function (list, context) {
if (!(this instanceof Iterator)) throw new TypeError("Constructor requires 'new'");
defineProperties(this, {
__list__: d("w", value(list)),
__context__: d("w", context),
__nextIndex__: d("w", 0)
});
if (!context) return;
callable(context.on);
context.on("_add", this._onAdd);
context.on("_delete", this._onDelete);
context.on("_clear", this._onClear);
};
// Internal %IteratorPrototype% doesn't expose its constructor
delete Iterator.prototype.constructor;
defineProperties(
Iterator.prototype,
assign(
{
_next: d(function () {
var i;
if (!this.__list__) return undefined;
if (this.__redo__) {
i = this.__redo__.shift();
if (i !== undefined) return i;
}
if (this.__nextIndex__ < this.__list__.length) return this.__nextIndex__++;
this._unBind();
return undefined;
}),
next: d(function () {
return this._createResult(this._next());
}),
_createResult: d(function (i) {
if (i === undefined) return { done: true, value: undefined };
return { done: false, value: this._resolve(i) };
}),
_resolve: d(function (i) {
return this.__list__[i];
}),
_unBind: d(function () {
this.__list__ = null;
delete this.__redo__;
if (!this.__context__) return;
this.__context__.off("_add", this._onAdd);
this.__context__.off("_delete", this._onDelete);
this.__context__.off("_clear", this._onClear);
this.__context__ = null;
}),
toString: d(function () {
return "[object " + (this[Symbol.toStringTag] || "Object") + "]";
})
},
autoBind({
_onAdd: d(function (index) {
if (index >= this.__nextIndex__) return;
++this.__nextIndex__;
if (!this.__redo__) {
defineProperty(this, "__redo__", d("c", [index]));
return;
}
this.__redo__.forEach(function (redo, i) {
if (redo >= index) this.__redo__[i] = ++redo;
}, this);
this.__redo__.push(index);
}),
_onDelete: d(function (index) {
var i;
if (index >= this.__nextIndex__) return;
--this.__nextIndex__;
if (!this.__redo__) return;
i = this.__redo__.indexOf(index);
if (i !== -1) this.__redo__.splice(i, 1);
this.__redo__.forEach(function (redo, j) {
if (redo > index) this.__redo__[j] = --redo;
}, this);
}),
_onClear: d(function () {
if (this.__redo__) clear.call(this.__redo__);
this.__nextIndex__ = 0;
})
})
)
);
defineProperty(
Iterator.prototype,
Symbol.iterator,
d(function () {
return this;
})
);
},{"d":46,"d/auto-bind":45,"es5-ext/array/#/clear":47,"es5-ext/object/assign":64,"es5-ext/object/valid-callable":81,"es5-ext/object/valid-value":83,"es6-symbol":102}],93:[function(require,module,exports){
"use strict";
var isArguments = require("es5-ext/function/is-arguments")
, isValue = require("es5-ext/object/is-value")
, isString = require("es5-ext/string/is-string");
var iteratorSymbol = require("es6-symbol").iterator
, isArray = Array.isArray;
module.exports = function (value) {
if (!isValue(value)) return false;
if (isArray(value)) return true;
if (isString(value)) return true;
if (isArguments(value)) return true;
return typeof value[iteratorSymbol] === "function";
};
},{"es5-ext/function/is-arguments":52,"es5-ext/object/is-value":71,"es5-ext/string/is-string":87,"es6-symbol":102}],94:[function(require,module,exports){
// Thanks @mathiasbynens
// http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols
"use strict";
var setPrototypeOf = require("es5-ext/object/set-prototype-of")
, d = require("d")
, Symbol = require("es6-symbol")
, Iterator = require("./");
var defineProperty = Object.defineProperty, StringIterator;
StringIterator = module.exports = function (str) {
if (!(this instanceof StringIterator)) throw new TypeError("Constructor requires 'new'");
str = String(str);
Iterator.call(this, str);
defineProperty(this, "__length__", d("", str.length));
};
if (setPrototypeOf) setPrototypeOf(StringIterator, Iterator);
// Internal %ArrayIteratorPrototype% doesn't expose its constructor
delete StringIterator.prototype.constructor;
StringIterator.prototype = Object.create(Iterator.prototype, {
_next: d(function () {
if (!this.__list__) return undefined;
if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++;
this._unBind();
return undefined;
}),
_resolve: d(function (i) {
var char = this.__list__[i], code;
if (this.__nextIndex__ === this.__length__) return char;
code = char.charCodeAt(0);
if (code >= 0xd800 && code <= 0xdbff) return char + this.__list__[this.__nextIndex__++];
return char;
})
});
defineProperty(StringIterator.prototype, Symbol.toStringTag, d("c", "String Iterator"));
},{"./":92,"d":46,"es5-ext/object/set-prototype-of":78,"es6-symbol":102}],95:[function(require,module,exports){
"use strict";
var isIterable = require("./is-iterable");
module.exports = function (value) {
if (!isIterable(value)) throw new TypeError(value + " is not iterable");
return value;
};
},{"./is-iterable":93}],96:[function(require,module,exports){
'use strict';
module.exports = require('./is-implemented')() ? Map : require('./polyfill');
},{"./is-implemented":97,"./polyfill":101}],97:[function(require,module,exports){
'use strict';
module.exports = function () {
var map, iterator, result;
if (typeof Map !== 'function') return false;
try {
// WebKit doesn't support arguments and crashes
map = new Map([['raz', 'one'], ['dwa', 'two'], ['trzy', 'three']]);
} catch (e) {
return false;
}
if (String(map) !== '[object Map]') return false;
if (map.size !== 3) return false;
if (typeof map.clear !== 'function') return false;
if (typeof map.delete !== 'function') return false;
if (typeof map.entries !== 'function') return false;
if (typeof map.forEach !== 'function') return false;
if (typeof map.get !== 'function') return false;
if (typeof map.has !== 'function') return false;
if (typeof map.keys !== 'function') return false;
if (typeof map.set !== 'function') return false;
if (typeof map.values !== 'function') return false;
iterator = map.entries();
result = iterator.next();
if (result.done !== false) return false;
if (!result.value) return false;
if (result.value[0] !== 'raz') return false;
if (result.value[1] !== 'one') return false;
return true;
};
},{}],98:[function(require,module,exports){
// Exports true if environment provides native `Map` implementation,
// whatever that is.
'use strict';
module.exports = (function () {
if (typeof Map === 'undefined') return false;
return (Object.prototype.toString.call(new Map()) === '[object Map]');
}());
},{}],99:[function(require,module,exports){
'use strict';
module.exports = require('es5-ext/object/primitive-set')('key',
'value', 'key+value');
},{"es5-ext/object/primitive-set":77}],100:[function(require,module,exports){
'use strict';
var setPrototypeOf = require('es5-ext/object/set-prototype-of')
, d = require('d')
, Iterator = require('es6-iterator')
, toStringTagSymbol = require('es6-symbol').toStringTag
, kinds = require('./iterator-kinds')
, defineProperties = Object.defineProperties
, unBind = Iterator.prototype._unBind
, MapIterator;
MapIterator = module.exports = function (map, kind) {
if (!(this instanceof MapIterator)) return new MapIterator(map, kind);
Iterator.call(this, map.__mapKeysData__, map);
if (!kind || !kinds[kind]) kind = 'key+value';
defineProperties(this, {
__kind__: d('', kind),
__values__: d('w', map.__mapValuesData__)
});
};
if (setPrototypeOf) setPrototypeOf(MapIterator, Iterator);
MapIterator.prototype = Object.create(Iterator.prototype, {
constructor: d(MapIterator),
_resolve: d(function (i) {
if (this.__kind__ === 'value') return this.__values__[i];
if (this.__kind__ === 'key') return this.__list__[i];
return [this.__list__[i], this.__values__[i]];
}),
_unBind: d(function () {
this.__values__ = null;
unBind.call(this);
}),
toString: d(function () { return '[object Map Iterator]'; })
});
Object.defineProperty(MapIterator.prototype, toStringTagSymbol,
d('c', 'Map Iterator'));
},{"./iterator-kinds":99,"d":46,"es5-ext/object/set-prototype-of":78,"es6-iterator":92,"es6-symbol":102}],101:[function(require,module,exports){
'use strict';
var clear = require('es5-ext/array/#/clear')
, eIndexOf = require('es5-ext/array/#/e-index-of')
, setPrototypeOf = require('es5-ext/object/set-prototype-of')
, callable = require('es5-ext/object/valid-callable')
, validValue = require('es5-ext/object/valid-value')
, d = require('d')
, ee = require('event-emitter')
, Symbol = require('es6-symbol')
, iterator = require('es6-iterator/valid-iterable')
, forOf = require('es6-iterator/for-of')
, Iterator = require('./lib/iterator')
, isNative = require('./is-native-implemented')
, call = Function.prototype.call
, defineProperties = Object.defineProperties, getPrototypeOf = Object.getPrototypeOf
, MapPoly;
module.exports = MapPoly = function (/*iterable*/) {
var iterable = arguments[0], keys, values, self;
if (!(this instanceof MapPoly)) throw new TypeError('Constructor requires \'new\'');
if (isNative && setPrototypeOf && (Map !== MapPoly)) {
self = setPrototypeOf(new Map(), getPrototypeOf(this));
} else {
self = this;
}
if (iterable != null) iterator(iterable);
defineProperties(self, {
__mapKeysData__: d('c', keys = []),
__mapValuesData__: d('c', values = [])
});
if (!iterable) return self;
forOf(iterable, function (value) {
var key = validValue(value)[0];
value = value[1];
if (eIndexOf.call(keys, key) !== -1) return;
keys.push(key);
values.push(value);
}, self);
return self;
};
if (isNative) {
if (setPrototypeOf) setPrototypeOf(MapPoly, Map);
MapPoly.prototype = Object.create(Map.prototype, {
constructor: d(MapPoly)
});
}
ee(defineProperties(MapPoly.prototype, {
clear: d(function () {
if (!this.__mapKeysData__.length) return;
clear.call(this.__mapKeysData__);
clear.call(this.__mapValuesData__);
this.emit('_clear');
}),
delete: d(function (key) {
var index = eIndexOf.call(this.__mapKeysData__, key);
if (index === -1) return false;
this.__mapKeysData__.splice(index, 1);
this.__mapValuesData__.splice(index, 1);
this.emit('_delete', index, key);
return true;
}),
entries: d(function () { return new Iterator(this, 'key+value'); }),
forEach: d(function (cb/*, thisArg*/) {
var thisArg = arguments[1], iterator, result;
callable(cb);
iterator = this.entries();
result = iterator._next();
while (result !== undefined) {
call.call(cb, thisArg, this.__mapValuesData__[result],
this.__mapKeysData__[result], this);
result = iterator._next();
}
}),
get: d(function (key) {
var index = eIndexOf.call(this.__mapKeysData__, key);
if (index === -1) return;
return this.__mapValuesData__[index];
}),
has: d(function (key) {
return (eIndexOf.call(this.__mapKeysData__, key) !== -1);
}),
keys: d(function () { return new Iterator(this, 'key'); }),
set: d(function (key, value) {
var index = eIndexOf.call(this.__mapKeysData__, key), emit;
if (index === -1) {
index = this.__mapKeysData__.push(key) - 1;
emit = true;
}
this.__mapValuesData__[index] = value;
if (emit) this.emit('_add', index, key);
return this;
}),
size: d.gs(function () { return this.__mapKeysData__.length; }),
values: d(function () { return new Iterator(this, 'value'); }),
toString: d(function () { return '[object Map]'; })
}));
Object.defineProperty(MapPoly.prototype, Symbol.iterator, d(function () {
return this.entries();
}));
Object.defineProperty(MapPoly.prototype, Symbol.toStringTag, d('c', 'Map'));
},{"./is-native-implemented":98,"./lib/iterator":100,"d":46,"es5-ext/array/#/clear":47,"es5-ext/array/#/e-index-of":48,"es5-ext/object/set-prototype-of":78,"es5-ext/object/valid-callable":81,"es5-ext/object/valid-value":83,"es6-iterator/for-of":90,"es6-iterator/valid-iterable":95,"es6-symbol":102,"event-emitter":135}],102:[function(require,module,exports){
"use strict";
module.exports = require("./is-implemented")()
? require("ext/global-this").Symbol
: require("./polyfill");
},{"./is-implemented":103,"./polyfill":108,"ext/global-this":137}],103:[function(require,module,exports){
"use strict";
var global = require("ext/global-this")
, validTypes = { object: true, symbol: true };
module.exports = function () {
var Symbol = global.Symbol;
var symbol;
if (typeof Symbol !== "function") return false;
symbol = Symbol("test symbol");
try { String(symbol); }
catch (e) { return false; }
// Return 'true' also for polyfills
if (!validTypes[typeof Symbol.iterator]) return false;
if (!validTypes[typeof Symbol.toPrimitive]) return false;
if (!validTypes[typeof Symbol.toStringTag]) return false;
return true;
};
},{"ext/global-this":137}],104:[function(require,module,exports){
"use strict";
module.exports = function (value) {
if (!value) return false;
if (typeof value === "symbol") return true;
if (!value.constructor) return false;
if (value.constructor.name !== "Symbol") return false;
return value[value.constructor.toStringTag] === "Symbol";
};
},{}],105:[function(require,module,exports){
"use strict";
var d = require("d");
var create = Object.create, defineProperty = Object.defineProperty, objPrototype = Object.prototype;
var created = create(null);
module.exports = function (desc) {
var postfix = 0, name, ie11BugWorkaround;
while (created[desc + (postfix || "")]) ++postfix;
desc += postfix || "";
created[desc] = true;
name = "@@" + desc;
defineProperty(
objPrototype,
name,
d.gs(null, function (value) {
// For IE11 issue see:
// https://connect.microsoft.com/IE/feedbackdetail/view/1928508/
// ie11-broken-getters-on-dom-objects
// https://github.com/medikoo/es6-symbol/issues/12
if (ie11BugWorkaround) return;
ie11BugWorkaround = true;
defineProperty(this, name, d(value));
ie11BugWorkaround = false;
})
);
return name;
};
},{"d":46}],106:[function(require,module,exports){
"use strict";
var d = require("d")
, NativeSymbol = require("ext/global-this").Symbol;
module.exports = function (SymbolPolyfill) {
return Object.defineProperties(SymbolPolyfill, {
// To ensure proper interoperability with other native functions (e.g. Array.from)
// fallback to eventual native implementation of given symbol
hasInstance: d(
"", (NativeSymbol && NativeSymbol.hasInstance) || SymbolPolyfill("hasInstance")
),
isConcatSpreadable: d(
"",
(NativeSymbol && NativeSymbol.isConcatSpreadable) ||
SymbolPolyfill("isConcatSpreadable")
),
iterator: d("", (NativeSymbol && NativeSymbol.iterator) || SymbolPolyfill("iterator")),
match: d("", (NativeSymbol && NativeSymbol.match) || SymbolPolyfill("match")),
replace: d("", (NativeSymbol && NativeSymbol.replace) || SymbolPolyfill("replace")),
search: d("", (NativeSymbol && NativeSymbol.search) || SymbolPolyfill("search")),
species: d("", (NativeSymbol && NativeSymbol.species) || SymbolPolyfill("species")),
split: d("", (NativeSymbol && NativeSymbol.split) || SymbolPolyfill("split")),
toPrimitive: d(
"", (NativeSymbol && NativeSymbol.toPrimitive) || SymbolPolyfill("toPrimitive")
),
toStringTag: d(
"", (NativeSymbol && NativeSymbol.toStringTag) || SymbolPolyfill("toStringTag")
),
unscopables: d(
"", (NativeSymbol && NativeSymbol.unscopables) || SymbolPolyfill("unscopables")
)
});
};
},{"d":46,"ext/global-this":137}],107:[function(require,module,exports){
"use strict";
var d = require("d")
, validateSymbol = require("../../../validate-symbol");
var registry = Object.create(null);
module.exports = function (SymbolPolyfill) {
return Object.defineProperties(SymbolPolyfill, {
for: d(function (key) {
if (registry[key]) return registry[key];
return (registry[key] = SymbolPolyfill(String(key)));
}),
keyFor: d(function (symbol) {
var key;
validateSymbol(symbol);
for (key in registry) {
if (registry[key] === symbol) return key;
}
return undefined;
})
});
};
},{"../../../validate-symbol":109,"d":46}],108:[function(require,module,exports){
// ES2015 Symbol polyfill for environments that do not (or partially) support it
"use strict";
var d = require("d")
, validateSymbol = require("./validate-symbol")
, NativeSymbol = require("ext/global-this").Symbol
, generateName = require("./lib/private/generate-name")
, setupStandardSymbols = require("./lib/private/setup/standard-symbols")
, setupSymbolRegistry = require("./lib/private/setup/symbol-registry");
var create = Object.create
, defineProperties = Object.defineProperties
, defineProperty = Object.defineProperty;
var SymbolPolyfill, HiddenSymbol, isNativeSafe;
if (typeof NativeSymbol === "function") {
try {
String(NativeSymbol());
isNativeSafe = true;
} catch (ignore) {}
} else {
NativeSymbol = null;
}
// Internal constructor (not one exposed) for creating Symbol instances.
// This one is used to ensure that `someSymbol instanceof Symbol` always return false
HiddenSymbol = function Symbol(description) {
if (this instanceof HiddenSymbol) throw new TypeError("Symbol is not a constructor");
return SymbolPolyfill(description);
};
// Exposed `Symbol` constructor
// (returns instances of HiddenSymbol)
module.exports = SymbolPolyfill = function Symbol(description) {
var symbol;
if (this instanceof Symbol) throw new TypeError("Symbol is not a constructor");
if (isNativeSafe) return NativeSymbol(description);
symbol = create(HiddenSymbol.prototype);
description = description === undefined ? "" : String(description);
return defineProperties(symbol, {
__description__: d("", description),
__name__: d("", generateName(description))
});
};
setupStandardSymbols(SymbolPolyfill);
setupSymbolRegistry(SymbolPolyfill);
// Internal tweaks for real symbol producer
defineProperties(HiddenSymbol.prototype, {
constructor: d(SymbolPolyfill),
toString: d("", function () { return this.__name__; })
});
// Proper implementation of methods exposed on Symbol.prototype
// They won't be accessible on produced symbol instances as they derive from HiddenSymbol.prototype
defineProperties(SymbolPolyfill.prototype, {
toString: d(function () { return "Symbol (" + validateSymbol(this).__description__ + ")"; }),
valueOf: d(function () { return validateSymbol(this); })
});
defineProperty(
SymbolPolyfill.prototype,
SymbolPolyfill.toPrimitive,
d("", function () {
var symbol = validateSymbol(this);
if (typeof symbol === "symbol") return symbol;
return symbol.toString();
})
);
defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d("c", "Symbol"));
// Proper implementaton of toPrimitive and toStringTag for returned symbol instances
defineProperty(
HiddenSymbol.prototype, SymbolPolyfill.toStringTag,
d("c", SymbolPolyfill.prototype[SymbolPolyfill.toStringTag])
);
// Note: It's important to define `toPrimitive` as last one, as some implementations
// implement `toPrimitive` natively without implementing `toStringTag` (or other specified symbols)
// And that may invoke error in definition flow:
// See: https://github.com/medikoo/es6-symbol/issues/13#issuecomment-164146149
defineProperty(
HiddenSymbol.prototype, SymbolPolyfill.toPrimitive,
d("c", SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive])
);
},{"./lib/private/generate-name":105,"./lib/private/setup/standard-symbols":106,"./lib/private/setup/symbol-registry":107,"./validate-symbol":109,"d":46,"ext/global-this":137}],109:[function(require,module,exports){
"use strict";
var isSymbol = require("./is-symbol");
module.exports = function (value) {
if (!isSymbol(value)) throw new TypeError(value + " is not a symbol");
return value;
};
},{"./is-symbol":104}],110:[function(require,module,exports){
"use strict";
module.exports = require("./is-implemented")() ? WeakMap : require("./polyfill");
},{"./is-implemented":111,"./polyfill":113}],111:[function(require,module,exports){
"use strict";
module.exports = function () {
var weakMap, obj;
if (typeof WeakMap !== "function") return false;
try {
// WebKit doesn't support arguments and crashes
weakMap = new WeakMap([[obj = {}, "one"], [{}, "two"], [{}, "three"]]);
} catch (e) {
return false;
}
if (String(weakMap) !== "[object WeakMap]") return false;
if (typeof weakMap.set !== "function") return false;
if (weakMap.set({}, 1) !== weakMap) return false;
if (typeof weakMap.delete !== "function") return false;
if (typeof weakMap.has !== "function") return false;
if (weakMap.get(obj) !== "one") return false;
return true;
};
},{}],112:[function(require,module,exports){
// Exports true if environment provides native `WeakMap` implementation, whatever that is.
"use strict";
module.exports = (function () {
if (typeof WeakMap !== "function") return false;
return Object.prototype.toString.call(new WeakMap()) === "[object WeakMap]";
}());
},{}],113:[function(require,module,exports){
"use strict";
var isValue = require("es5-ext/object/is-value")
, setPrototypeOf = require("es5-ext/object/set-prototype-of")
, object = require("es5-ext/object/valid-object")
, ensureValue = require("es5-ext/object/valid-value")
, randomUniq = require("es5-ext/string/random-uniq")
, d = require("d")
, getIterator = require("es6-iterator/get")
, forOf = require("es6-iterator/for-of")
, toStringTagSymbol = require("es6-symbol").toStringTag
, isNative = require("./is-native-implemented")
, isArray = Array.isArray, defineProperty = Object.defineProperty
, objHasOwnProperty = Object.prototype.hasOwnProperty, getPrototypeOf = Object.getPrototypeOf
, WeakMapPoly;
module.exports = WeakMapPoly = function (/* Iterable*/) {
var iterable = arguments[0], self;
if (!(this instanceof WeakMapPoly)) throw new TypeError("Constructor requires 'new'");
self = isNative && setPrototypeOf && (WeakMap !== WeakMapPoly)
? setPrototypeOf(new WeakMap(), getPrototypeOf(this)) : this;
if (isValue(iterable)) {
if (!isArray(iterable)) iterable = getIterator(iterable);
}
defineProperty(self, "__weakMapData__", d("c", "$weakMap$" + randomUniq()));
if (!iterable) return self;
forOf(iterable, function (val) {
ensureValue(val);
self.set(val[0], val[1]);
});
return self;
};
if (isNative) {
if (setPrototypeOf) setPrototypeOf(WeakMapPoly, WeakMap);
WeakMapPoly.prototype = Object.create(WeakMap.prototype, { constructor: d(WeakMapPoly) });
}
Object.defineProperties(WeakMapPoly.prototype, {
delete: d(function (key) {
if (objHasOwnProperty.call(object(key), this.__weakMapData__)) {
delete key[this.__weakMapData__];
return true;
}
return false;
}),
get: d(function (key) {
if (!objHasOwnProperty.call(object(key), this.__weakMapData__)) return undefined;
return key[this.__weakMapData__];
}),
has: d(function (key) {
return objHasOwnProperty.call(object(key), this.__weakMapData__);
}),
set: d(function (key, value) {
defineProperty(object(key), this.__weakMapData__, d("c", value));
return this;
}),
toString: d(function () {
return "[object WeakMap]";
})
});
defineProperty(WeakMapPoly.prototype, toStringTagSymbol, d("c", "WeakMap"));
},{"./is-native-implemented":112,"d":46,"es5-ext/object/is-value":71,"es5-ext/object/set-prototype-of":78,"es5-ext/object/valid-object":82,"es5-ext/object/valid-value":83,"es5-ext/string/random-uniq":88,"es6-iterator/for-of":90,"es6-iterator/get":91,"es6-symbol":102}],114:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Definition = exports.ParameterDefinition = undefined;
var _variable = require('./variable');
var _variable2 = _interopRequireDefault(_variable);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*
Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/**
* @class Definition
*/
var Definition = function Definition(type, name, node, parent, index, kind) {
_classCallCheck(this, Definition);
/**
* @member {String} Definition#type - type of the occurrence (e.g. "Parameter", "Variable", ...).
*/
this.type = type;
/**
* @member {esprima.Identifier} Definition#name - the identifier AST node of the occurrence.
*/
this.name = name;
/**
* @member {esprima.Node} Definition#node - the enclosing node of the identifier.
*/
this.node = node;
/**
* @member {esprima.Node?} Definition#parent - the enclosing statement node of the identifier.
*/
this.parent = parent;
/**
* @member {Number?} Definition#index - the index in the declaration statement.
*/
this.index = index;
/**
* @member {String?} Definition#kind - the kind of the declaration statement.
*/
this.kind = kind;
};
/**
* @class ParameterDefinition
*/
exports.default = Definition;
var ParameterDefinition = function (_Definition) {
_inherits(ParameterDefinition, _Definition);
function ParameterDefinition(name, node, index, rest) {
_classCallCheck(this, ParameterDefinition);
/**
* Whether the parameter definition is a part of a rest parameter.
* @member {boolean} ParameterDefinition#rest
*/
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(ParameterDefinition).call(this, _variable2.default.Parameter, name, node, null, index, null));
_this.rest = rest;
return _this;
}
return ParameterDefinition;
}(Definition);
exports.ParameterDefinition = ParameterDefinition;
exports.Definition = Definition;
/* vim: set sw=4 ts=4 et tw=80 : */
},{"./variable":121}],115:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ScopeManager = exports.Scope = exports.Variable = exports.Reference = exports.version = undefined;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; /*
Copyright (C) 2012-2014 Yusuke Suzuki <utatane.tea@gmail.com>
Copyright (C) 2013 Alex Seville <hi@alexanderseville.com>
Copyright (C) 2014 Thiago de Arruda <tpadilha84@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/**
* Escope (<a href="http://github.com/estools/escope">escope</a>) is an <a
* href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">ECMAScript</a>
* scope analyzer extracted from the <a
* href="http://github.com/estools/esmangle">esmangle project</a/>.
* <p>
* <em>escope</em> finds lexical scopes in a source program, i.e. areas of that
* program where different occurrences of the same identifier refer to the same
* variable. With each scope the contained variables are collected, and each
* identifier reference in code is linked to its corresponding variable (if
* possible).
* <p>
* <em>escope</em> works on a syntax tree of the parsed source code which has
* to adhere to the <a
* href="https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API">
* Mozilla Parser API</a>. E.g. <a href="http://esprima.org">esprima</a> is a parser
* that produces such syntax trees.
* <p>
* The main interface is the {@link analyze} function.
* @module escope
*/
/*jslint bitwise:true */
exports.analyze = analyze;
var _assert = require('assert');
var _assert2 = _interopRequireDefault(_assert);
var _scopeManager = require('./scope-manager');
var _scopeManager2 = _interopRequireDefault(_scopeManager);
var _referencer = require('./referencer');
var _referencer2 = _interopRequireDefault(_referencer);
var _reference = require('./reference');
var _reference2 = _interopRequireDefault(_reference);
var _variable = require('./variable');
var _variable2 = _interopRequireDefault(_variable);
var _scope = require('./scope');
var _scope2 = _interopRequireDefault(_scope);
var _package = require('../package.json');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function defaultOptions() {
return {
optimistic: false,
directive: false,
nodejsScope: false,
impliedStrict: false,
sourceType: 'script', // one of ['script', 'module']
ecmaVersion: 5,
childVisitorKeys: null,
fallback: 'iteration'
};
}
function updateDeeply(target, override) {
var key, val;
function isHashObject(target) {
return (typeof target === 'undefined' ? 'undefined' : _typeof(target)) === 'object' && target instanceof Object && !(target instanceof Array) && !(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;
}
/**
* Main interface function. Takes an Esprima syntax tree and returns the
* analyzed scopes.
* @function analyze
* @param {esprima.Tree} tree
* @param {Object} providedOptions - Options that tailor the scope analysis
* @param {boolean} [providedOptions.optimistic=false] - the optimistic flag
* @param {boolean} [providedOptions.directive=false]- the directive flag
* @param {boolean} [providedOptions.ignoreEval=false]- whether to check 'eval()' calls
* @param {boolean} [providedOptions.nodejsScope=false]- whether the whole
* script is executed under node.js environment. When enabled, escope adds
* a function scope immediately following the global scope.
* @param {boolean} [providedOptions.impliedStrict=false]- implied strict mode
* (if ecmaVersion >= 5).
* @param {string} [providedOptions.sourceType='script']- the source type of the script. one of 'script' and 'module'
* @param {number} [providedOptions.ecmaVersion=5]- which ECMAScript version is considered
* @param {Object} [providedOptions.childVisitorKeys=null] - Additional known visitor keys. See [esrecurse](https://github.com/estools/esrecurse)'s the `childVisitorKeys` option.
* @param {string} [providedOptions.fallback='iteration'] - A kind of the fallback in order to encounter with unknown node. See [esrecurse](https://github.com/estools/esrecurse)'s the `fallback` option.
* @return {ScopeManager}
*/
function analyze(tree, providedOptions) {
var scopeManager, referencer, options;
options = updateDeeply(defaultOptions(), providedOptions);
scopeManager = new _scopeManager2.default(options);
referencer = new _referencer2.default(options, scopeManager);
referencer.visit(tree);
(0, _assert2.default)(scopeManager.__currentScope === null, 'currentScope should be null.');
return scopeManager;
}
exports.
/** @name module:escope.version */
version = _package.version;
exports.
/** @name module:escope.Reference */
Reference = _reference2.default;
exports.
/** @name module:escope.Variable */
Variable = _variable2.default;
exports.
/** @name module:escope.Scope */
Scope = _scope2.default;
exports.
/** @name module:escope.ScopeManager */
ScopeManager = _scopeManager2.default;
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../package.json":122,"./reference":117,"./referencer":118,"./scope":120,"./scope-manager":119,"./variable":121,"assert":40}],116:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _estraverse = require('estraverse');
var _esrecurse = require('esrecurse');
var _esrecurse2 = _interopRequireDefault(_esrecurse);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /*
Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
function getLast(xs) {
return xs[xs.length - 1] || null;
}
var PatternVisitor = function (_esrecurse$Visitor) {
_inherits(PatternVisitor, _esrecurse$Visitor);
_createClass(PatternVisitor, null, [{
key: 'isPattern',
value: function isPattern(node) {
var nodeType = node.type;
return nodeType === _estraverse.Syntax.Identifier || nodeType === _estraverse.Syntax.ObjectPattern || nodeType === _estraverse.Syntax.ArrayPattern || nodeType === _estraverse.Syntax.SpreadElement || nodeType === _estraverse.Syntax.RestElement || nodeType === _estraverse.Syntax.AssignmentPattern;
}
}]);
function PatternVisitor(options, rootPattern, callback) {
_classCallCheck(this, PatternVisitor);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(PatternVisitor).call(this, null, options));
_this.rootPattern = rootPattern;
_this.callback = callback;
_this.assignments = [];
_this.rightHandNodes = [];
_this.restElements = [];
return _this;
}
_createClass(PatternVisitor, [{
key: 'Identifier',
value: function Identifier(pattern) {
var lastRestElement = getLast(this.restElements);
this.callback(pattern, {
topLevel: pattern === this.rootPattern,
rest: lastRestElement != null && lastRestElement.argument === pattern,
assignments: this.assignments
});
}
}, {
key: 'Property',
value: function Property(property) {
// Computed property's key is a right hand node.
if (property.computed) {
this.rightHandNodes.push(property.key);
}
// If it's shorthand, its key is same as its value.
// If it's shorthand and has its default value, its key is same as its value.left (the value is AssignmentPattern).
// If it's not shorthand, the name of new variable is its value's.
this.visit(property.value);
}
}, {
key: 'ArrayPattern',
value: function ArrayPattern(pattern) {
var i, iz, element;
for (i = 0, iz = pattern.elements.length; i < iz; ++i) {
element = pattern.elements[i];
this.visit(element);
}
}
}, {
key: 'AssignmentPattern',
value: function AssignmentPattern(pattern) {
this.assignments.push(pattern);
this.visit(pattern.left);
this.rightHandNodes.push(pattern.right);
this.assignments.pop();
}
}, {
key: 'RestElement',
value: function RestElement(pattern) {
this.restElements.push(pattern);
this.visit(pattern.argument);
this.restElements.pop();
}
}, {
key: 'MemberExpression',
value: function MemberExpression(node) {
// Computed property's key is a right hand node.
if (node.computed) {
this.rightHandNodes.push(node.property);
}
// the object is only read, write to its property.
this.rightHandNodes.push(node.object);
}
//
// ForInStatement.left and AssignmentExpression.left are LeftHandSideExpression.
// By spec, LeftHandSideExpression is Pattern or MemberExpression.
// (see also: https://github.com/estree/estree/pull/20#issuecomment-74584758)
// But espree 2.0 and esprima 2.0 parse to ArrayExpression, ObjectExpression, etc...
//
}, {
key: 'SpreadElement',
value: function SpreadElement(node) {
this.visit(node.argument);
}
}, {
key: 'ArrayExpression',
value: function ArrayExpression(node) {
node.elements.forEach(this.visit, this);
}
}, {
key: 'AssignmentExpression',
value: function AssignmentExpression(node) {
this.assignments.push(node);
this.visit(node.left);
this.rightHandNodes.push(node.right);
this.assignments.pop();
}
}, {
key: 'CallExpression',
value: function CallExpression(node) {
var _this2 = this;
// arguments are right hand nodes.
node.arguments.forEach(function (a) {
_this2.rightHandNodes.push(a);
});
this.visit(node.callee);
}
}]);
return PatternVisitor;
}(_esrecurse2.default.Visitor);
/* vim: set sw=4 ts=4 et tw=80 : */
exports.default = PatternVisitor;
},{"esrecurse":123,"estraverse":129}],117:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/*
Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
var READ = 0x1;
var WRITE = 0x2;
var RW = READ | WRITE;
/**
* A Reference represents a single occurrence of an identifier in code.
* @class Reference
*/
var Reference = function () {
function Reference(ident, scope, flag, writeExpr, maybeImplicitGlobal, partial, init) {
_classCallCheck(this, Reference);
/**
* Identifier syntax node.
* @member {esprima#Identifier} Reference#identifier
*/
this.identifier = ident;
/**
* Reference to the enclosing Scope.
* @member {Scope} Reference#from
*/
this.from = scope;
/**
* Whether the reference comes from a dynamic scope (such as 'eval',
* 'with', etc.), and may be trapped by dynamic scopes.
* @member {boolean} Reference#tainted
*/
this.tainted = false;
/**
* The variable this reference is resolved with.
* @member {Variable} Reference#resolved
*/
this.resolved = null;
/**
* The read-write mode of the reference. (Value is one of {@link
* Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}).
* @member {number} Reference#flag
* @private
*/
this.flag = flag;
if (this.isWrite()) {
/**
* If reference is writeable, this is the tree being written to it.
* @member {esprima#Node} Reference#writeExpr
*/
this.writeExpr = writeExpr;
/**
* Whether the Reference might refer to a partial value of writeExpr.
* @member {boolean} Reference#partial
*/
this.partial = partial;
/**
* Whether the Reference is to write of initialization.
* @member {boolean} Reference#init
*/
this.init = init;
}
this.__maybeImplicitGlobal = maybeImplicitGlobal;
}
/**
* Whether the reference is static.
* @method Reference#isStatic
* @return {boolean}
*/
_createClass(Reference, [{
key: "isStatic",
value: function isStatic() {
return !this.tainted && this.resolved && this.resolved.scope.isStatic();
}
/**
* Whether the reference is writeable.
* @method Reference#isWrite
* @return {boolean}
*/
}, {
key: "isWrite",
value: function isWrite() {
return !!(this.flag & Reference.WRITE);
}
/**
* Whether the reference is readable.
* @method Reference#isRead
* @return {boolean}
*/
}, {
key: "isRead",
value: function isRead() {
return !!(this.flag & Reference.READ);
}
/**
* Whether the reference is read-only.
* @method Reference#isReadOnly
* @return {boolean}
*/
}, {
key: "isReadOnly",
value: function isReadOnly() {
return this.flag === Reference.READ;
}
/**
* Whether the reference is write-only.
* @method Reference#isWriteOnly
* @return {boolean}
*/
}, {
key: "isWriteOnly",
value: function isWriteOnly() {
return this.flag === Reference.WRITE;
}
/**
* Whether the reference is read-write.
* @method Reference#isReadWrite
* @return {boolean}
*/
}, {
key: "isReadWrite",
value: function isReadWrite() {
return this.flag === Reference.RW;
}
}]);
return Reference;
}();
/**
* @constant Reference.READ
* @private
*/
exports.default = Reference;
Reference.READ = READ;
/**
* @constant Reference.WRITE
* @private
*/
Reference.WRITE = WRITE;
/**
* @constant Reference.RW
* @private
*/
Reference.RW = RW;
/* vim: set sw=4 ts=4 et tw=80 : */
},{}],118:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _estraverse = require('estraverse');
var _esrecurse = require('esrecurse');
var _esrecurse2 = _interopRequireDefault(_esrecurse);
var _reference = require('./reference');
var _reference2 = _interopRequireDefault(_reference);
var _variable = require('./variable');
var _variable2 = _interopRequireDefault(_variable);
var _patternVisitor = require('./pattern-visitor');
var _patternVisitor2 = _interopRequireDefault(_patternVisitor);
var _definition = require('./definition');
var _assert = require('assert');
var _assert2 = _interopRequireDefault(_assert);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /*
Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
function traverseIdentifierInPattern(options, rootPattern, referencer, callback) {
// Call the callback at left hand identifier nodes, and Collect right hand nodes.
var visitor = new _patternVisitor2.default(options, rootPattern, callback);
visitor.visit(rootPattern);
// Process the right hand nodes recursively.
if (referencer != null) {
visitor.rightHandNodes.forEach(referencer.visit, referencer);
}
}
// Importing ImportDeclaration.
// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-moduledeclarationinstantiation
// https://github.com/estree/estree/blob/master/es6.md#importdeclaration
// FIXME: Now, we don't create module environment, because the context is
// implementation dependent.
var Importer = function (_esrecurse$Visitor) {
_inherits(Importer, _esrecurse$Visitor);
function Importer(declaration, referencer) {
_classCallCheck(this, Importer);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Importer).call(this, null, referencer.options));
_this.declaration = declaration;
_this.referencer = referencer;
return _this;
}
_createClass(Importer, [{
key: 'visitImport',
value: function visitImport(id, specifier) {
var _this2 = this;
this.referencer.visitPattern(id, function (pattern) {
_this2.referencer.currentScope().__define(pattern, new _definition.Definition(_variable2.default.ImportBinding, pattern, specifier, _this2.declaration, null, null));
});
}
}, {
key: 'ImportNamespaceSpecifier',
value: function ImportNamespaceSpecifier(node) {
var local = node.local || node.id;
if (local) {
this.visitImport(local, node);
}
}
}, {
key: 'ImportDefaultSpecifier',
value: function ImportDefaultSpecifier(node) {
var local = node.local || node.id;
this.visitImport(local, node);
}
}, {
key: 'ImportSpecifier',
value: function ImportSpecifier(node) {
var local = node.local || node.id;
if (node.name) {
this.visitImport(node.name, node);
} else {
this.visitImport(local, node);
}
}
}]);
return Importer;
}(_esrecurse2.default.Visitor);
// Referencing variables and creating bindings.
var Referencer = function (_esrecurse$Visitor2) {
_inherits(Referencer, _esrecurse$Visitor2);
function Referencer(options, scopeManager) {
_classCallCheck(this, Referencer);
var _this3 = _possibleConstructorReturn(this, Object.getPrototypeOf(Referencer).call(this, null, options));
_this3.options = options;
_this3.scopeManager = scopeManager;
_this3.parent = null;
_this3.isInnerMethodDefinition = false;
return _this3;
}
_createClass(Referencer, [{
key: 'currentScope',
value: function currentScope() {
return this.scopeManager.__currentScope;
}
}, {
key: 'close',
value: function close(node) {
while (this.currentScope() && node === this.currentScope().block) {
this.scopeManager.__currentScope = this.currentScope().__close(this.scopeManager);
}
}
}, {
key: 'pushInnerMethodDefinition',
value: function pushInnerMethodDefinition(isInnerMethodDefinition) {
var previous = this.isInnerMethodDefinition;
this.isInnerMethodDefinition = isInnerMethodDefinition;
return previous;
}
}, {
key: 'popInnerMethodDefinition',
value: function popInnerMethodDefinition(isInnerMethodDefinition) {
this.isInnerMethodDefinition = isInnerMethodDefinition;
}
}, {
key: 'materializeTDZScope',
value: function materializeTDZScope(node, iterationNode) {
// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-runtime-semantics-forin-div-ofexpressionevaluation-abstract-operation
// TDZ scope hides the declaration's names.
this.scopeManager.__nestTDZScope(node, iterationNode);
this.visitVariableDeclaration(this.currentScope(), _variable2.default.TDZ, iterationNode.left, 0, true);
}
}, {
key: 'materializeIterationScope',
value: function materializeIterationScope(node) {
var _this4 = this;
// Generate iteration scope for upper ForIn/ForOf Statements.
var letOrConstDecl;
this.scopeManager.__nestForScope(node);
letOrConstDecl = node.left;
this.visitVariableDeclaration(this.currentScope(), _variable2.default.Variable, letOrConstDecl, 0);
this.visitPattern(letOrConstDecl.declarations[0].id, function (pattern) {
_this4.currentScope().__referencing(pattern, _reference2.default.WRITE, node.right, null, true, true);
});
}
}, {
key: 'referencingDefaultValue',
value: function referencingDefaultValue(pattern, assignments, maybeImplicitGlobal, init) {
var scope = this.currentScope();
assignments.forEach(function (assignment) {
scope.__referencing(pattern, _reference2.default.WRITE, assignment.right, maybeImplicitGlobal, pattern !== assignment.left, init);
});
}
}, {
key: 'visitPattern',
value: function visitPattern(node, options, callback) {
if (typeof options === 'function') {
callback = options;
options = { processRightHandNodes: false };
}
traverseIdentifierInPattern(this.options, node, options.processRightHandNodes ? this : null, callback);
}
}, {
key: 'visitFunction',
value: function visitFunction(node) {
var _this5 = this;
var i, iz;
// FunctionDeclaration name is defined in upper scope
// NOTE: Not referring variableScope. It is intended.
// Since
// in ES5, FunctionDeclaration should be in FunctionBody.
// in ES6, FunctionDeclaration should be block scoped.
if (node.type === _estraverse.Syntax.FunctionDeclaration) {
// id is defined in upper scope
this.currentScope().__define(node.id, new _definition.Definition(_variable2.default.FunctionName, node.id, node, null, null, null));
}
// FunctionExpression with name creates its special scope;
// FunctionExpressionNameScope.
if (node.type === _estraverse.Syntax.FunctionExpression && node.id) {
this.scopeManager.__nestFunctionExpressionNameScope(node);
}
// Consider this function is in the MethodDefinition.
this.scopeManager.__nestFunctionScope(node, this.isInnerMethodDefinition);
// Process parameter declarations.
for (i = 0, iz = node.params.length; i < iz; ++i) {
this.visitPattern(node.params[i], { processRightHandNodes: true }, function (pattern, info) {
_this5.currentScope().__define(pattern, new _definition.ParameterDefinition(pattern, node, i, info.rest));
_this5.referencingDefaultValue(pattern, info.assignments, null, true);
});
}
// if there's a rest argument, add that
if (node.rest) {
this.visitPattern({
type: 'RestElement',
argument: node.rest
}, function (pattern) {
_this5.currentScope().__define(pattern, new _definition.ParameterDefinition(pattern, node, node.params.length, true));
});
}
// Skip BlockStatement to prevent creating BlockStatement scope.
if (node.body.type === _estraverse.Syntax.BlockStatement) {
this.visitChildren(node.body);
} else {
this.visit(node.body);
}
this.close(node);
}
}, {
key: 'visitClass',
value: function visitClass(node) {
if (node.type === _estraverse.Syntax.ClassDeclaration) {
this.currentScope().__define(node.id, new _definition.Definition(_variable2.default.ClassName, node.id, node, null, null, null));
}
// FIXME: Maybe consider TDZ.
this.visit(node.superClass);
this.scopeManager.__nestClassScope(node);
if (node.id) {
this.currentScope().__define(node.id, new _definition.Definition(_variable2.default.ClassName, node.id, node));
}
this.visit(node.body);
this.close(node);
}
}, {
key: 'visitProperty',
value: function visitProperty(node) {
var previous, isMethodDefinition;
if (node.computed) {
this.visit(node.key);
}
isMethodDefinition = node.type === _estraverse.Syntax.MethodDefinition;
if (isMethodDefinition) {
previous = this.pushInnerMethodDefinition(true);
}
this.visit(node.value);
if (isMethodDefinition) {
this.popInnerMethodDefinition(previous);
}
}
}, {
key: 'visitForIn',
value: function visitForIn(node) {
var _this6 = this;
if (node.left.type === _estraverse.Syntax.VariableDeclaration && node.left.kind !== 'var') {
this.materializeTDZScope(node.right, node);
this.visit(node.right);
this.close(node.right);
this.materializeIterationScope(node);
this.visit(node.body);
this.close(node);
} else {
if (node.left.type === _estraverse.Syntax.VariableDeclaration) {
this.visit(node.left);
this.visitPattern(node.left.declarations[0].id, function (pattern) {
_this6.currentScope().__referencing(pattern, _reference2.default.WRITE, node.right, null, true, true);
});
} else {
this.visitPattern(node.left, { processRightHandNodes: true }, function (pattern, info) {
var maybeImplicitGlobal = null;
if (!_this6.currentScope().isStrict) {
maybeImplicitGlobal = {
pattern: pattern,
node: node
};
}
_this6.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false);
_this6.currentScope().__referencing(pattern, _reference2.default.WRITE, node.right, maybeImplicitGlobal, true, false);
});
}
this.visit(node.right);
this.visit(node.body);
}
}
}, {
key: 'visitVariableDeclaration',
value: function visitVariableDeclaration(variableTargetScope, type, node, index, fromTDZ) {
var _this7 = this;
// If this was called to initialize a TDZ scope, this needs to make definitions, but doesn't make references.
var decl, init;
decl = node.declarations[index];
init = decl.init;
this.visitPattern(decl.id, { processRightHandNodes: !fromTDZ }, function (pattern, info) {
variableTargetScope.__define(pattern, new _definition.Definition(type, pattern, decl, node, index, node.kind));
if (!fromTDZ) {
_this7.referencingDefaultValue(pattern, info.assignments, null, true);
}
if (init) {
_this7.currentScope().__referencing(pattern, _reference2.default.WRITE, init, null, !info.topLevel, true);
}
});
}
}, {
key: 'AssignmentExpression',
value: function AssignmentExpression(node) {
var _this8 = this;
if (_patternVisitor2.default.isPattern(node.left)) {
if (node.operator === '=') {
this.visitPattern(node.left, { processRightHandNodes: true }, function (pattern, info) {
var maybeImplicitGlobal = null;
if (!_this8.currentScope().isStrict) {
maybeImplicitGlobal = {
pattern: pattern,
node: node
};
}
_this8.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false);
_this8.currentScope().__referencing(pattern, _reference2.default.WRITE, node.right, maybeImplicitGlobal, !info.topLevel, false);
});
} else {
this.currentScope().__referencing(node.left, _reference2.default.RW, node.right);
}
} else {
this.visit(node.left);
}
this.visit(node.right);
}
}, {
key: 'CatchClause',
value: function CatchClause(node) {
var _this9 = this;
this.scopeManager.__nestCatchScope(node);
this.visitPattern(node.param, { processRightHandNodes: true }, function (pattern, info) {
_this9.currentScope().__define(pattern, new _definition.Definition(_variable2.default.CatchClause, node.param, node, null, null, null));
_this9.referencingDefaultValue(pattern, info.assignments, null, true);
});
this.visit(node.body);
this.close(node);
}
}, {
key: 'Program',
value: function Program(node) {
this.scopeManager.__nestGlobalScope(node);
if (this.scopeManager.__isNodejsScope()) {
// Force strictness of GlobalScope to false when using node.js scope.
this.currentScope().isStrict = false;
this.scopeManager.__nestFunctionScope(node, false);
}
if (this.scopeManager.__isES6() && this.scopeManager.isModule()) {
this.scopeManager.__nestModuleScope(node);
}
if (this.scopeManager.isStrictModeSupported() && this.scopeManager.isImpliedStrict()) {
this.currentScope().isStrict = true;
}
this.visitChildren(node);
this.close(node);
}
}, {
key: 'Identifier',
value: function Identifier(node) {
this.currentScope().__referencing(node);
}
}, {
key: 'UpdateExpression',
value: function UpdateExpression(node) {
if (_patternVisitor2.default.isPattern(node.argument)) {
this.currentScope().__referencing(node.argument, _reference2.default.RW, null);
} else {
this.visitChildren(node);
}
}
}, {
key: 'MemberExpression',
value: function MemberExpression(node) {
this.visit(node.object);
if (node.computed) {
this.visit(node.property);
}
}
}, {
key: 'Property',
value: function Property(node) {
this.visitProperty(node);
}
}, {
key: 'MethodDefinition',
value: function MethodDefinition(node) {
this.visitProperty(node);
}
}, {
key: 'BreakStatement',
value: function BreakStatement() {}
}, {
key: 'ContinueStatement',
value: function ContinueStatement() {}
}, {
key: 'LabeledStatement',
value: function LabeledStatement(node) {
this.visit(node.body);
}
}, {
key: 'ForStatement',
value: function ForStatement(node) {
// Create ForStatement declaration.
// NOTE: In ES6, ForStatement dynamically generates
// per iteration environment. However, escope is
// a static analyzer, we only generate one scope for ForStatement.
if (node.init && node.init.type === _estraverse.Syntax.VariableDeclaration && node.init.kind !== 'var') {
this.scopeManager.__nestForScope(node);
}
this.visitChildren(node);
this.close(node);
}
}, {
key: 'ClassExpression',
value: function ClassExpression(node) {
this.visitClass(node);
}
}, {
key: 'ClassDeclaration',
value: function ClassDeclaration(node) {
this.visitClass(node);
}
}, {
key: 'CallExpression',
value: function CallExpression(node) {
// Check this is direct call to eval
if (!this.scopeManager.__ignoreEval() && node.callee.type === _estraverse.Syntax.Identifier && node.callee.name === 'eval') {
// NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and
// let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment.
this.currentScope().variableScope.__detectEval();
}
this.visitChildren(node);
}
}, {
key: 'BlockStatement',
value: function BlockStatement(node) {
if (this.scopeManager.__isES6()) {
this.scopeManager.__nestBlockScope(node);
}
this.visitChildren(node);
this.close(node);
}
}, {
key: 'ThisExpression',
value: function ThisExpression() {
this.currentScope().variableScope.__detectThis();
}
}, {
key: 'WithStatement',
value: function WithStatement(node) {
this.visit(node.object);
// Then nest scope for WithStatement.
this.scopeManager.__nestWithScope(node);
this.visit(node.body);
this.close(node);
}
}, {
key: 'VariableDeclaration',
value: function VariableDeclaration(node) {
var variableTargetScope, i, iz, decl;
variableTargetScope = node.kind === 'var' ? this.currentScope().variableScope : this.currentScope();
for (i = 0, iz = node.declarations.length; i < iz; ++i) {
decl = node.declarations[i];
this.visitVariableDeclaration(variableTargetScope, _variable2.default.Variable, node, i);
if (decl.init) {
this.visit(decl.init);
}
}
}
// sec 13.11.8
}, {
key: 'SwitchStatement',
value: function SwitchStatement(node) {
var i, iz;
this.visit(node.discriminant);
if (this.scopeManager.__isES6()) {
this.scopeManager.__nestSwitchScope(node);
}
for (i = 0, iz = node.cases.length; i < iz; ++i) {
this.visit(node.cases[i]);
}
this.close(node);
}
}, {
key: 'FunctionDeclaration',
value: function FunctionDeclaration(node) {
this.visitFunction(node);
}
}, {
key: 'FunctionExpression',
value: function FunctionExpression(node) {
this.visitFunction(node);
}
}, {
key: 'ForOfStatement',
value: function ForOfStatement(node) {
this.visitForIn(node);
}
}, {
key: 'ForInStatement',
value: function ForInStatement(node) {
this.visitForIn(node);
}
}, {
key: 'ArrowFunctionExpression',
value: function ArrowFunctionExpression(node) {
this.visitFunction(node);
}
}, {
key: 'ImportDeclaration',
value: function ImportDeclaration(node) {
var importer;
(0, _assert2.default)(this.scopeManager.__isES6() && this.scopeManager.isModule(), 'ImportDeclaration should appear when the mode is ES6 and in the module context.');
importer = new Importer(node, this);
importer.visit(node);
}
}, {
key: 'visitExportDeclaration',
value: function visitExportDeclaration(node) {
if (node.source) {
return;
}
if (node.declaration) {
this.visit(node.declaration);
return;
}
this.visitChildren(node);
}
}, {
key: 'ExportDeclaration',
value: function ExportDeclaration(node) {
this.visitExportDeclaration(node);
}
}, {
key: 'ExportNamedDeclaration',
value: function ExportNamedDeclaration(node) {
this.visitExportDeclaration(node);
}
}, {
key: 'ExportSpecifier',
value: function ExportSpecifier(node) {
var local = node.id || node.local;
this.visit(local);
}
}, {
key: 'MetaProperty',
value: function MetaProperty() {
// do nothing.
}
}]);
return Referencer;
}(_esrecurse2.default.Visitor);
/* vim: set sw=4 ts=4 et tw=80 : */
exports.default = Referencer;
},{"./definition":114,"./pattern-visitor":116,"./reference":117,"./variable":121,"assert":40,"esrecurse":123,"estraverse":129}],119:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
var _es6WeakMap = require('es6-weak-map');
var _es6WeakMap2 = _interopRequireDefault(_es6WeakMap);
var _scope = require('./scope');
var _scope2 = _interopRequireDefault(_scope);
var _assert = require('assert');
var _assert2 = _interopRequireDefault(_assert);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* @class ScopeManager
*/
var ScopeManager = function () {
function ScopeManager(options) {
_classCallCheck(this, ScopeManager);
this.scopes = [];
this.globalScope = null;
this.__nodeToScope = new _es6WeakMap2.default();
this.__currentScope = null;
this.__options = options;
this.__declaredVariables = new _es6WeakMap2.default();
}
_createClass(ScopeManager, [{
key: '__useDirective',
value: function __useDirective() {
return this.__options.directive;
}
}, {
key: '__isOptimistic',
value: function __isOptimistic() {
return this.__options.optimistic;
}
}, {
key: '__ignoreEval',
value: function __ignoreEval() {
return this.__options.ignoreEval;
}
}, {
key: '__isNodejsScope',
value: function __isNodejsScope() {
return this.__options.nodejsScope;
}
}, {
key: 'isModule',
value: function isModule() {
return this.__options.sourceType === 'module';
}
}, {
key: 'isImpliedStrict',
value: function isImpliedStrict() {
return this.__options.impliedStrict;
}
}, {
key: 'isStrictModeSupported',
value: function isStrictModeSupported() {
return this.__options.ecmaVersion >= 5;
}
// Returns appropriate scope for this node.
}, {
key: '__get',
value: function __get(node) {
return this.__nodeToScope.get(node);
}
/**
* Get variables that are declared by the node.
*
* "are declared by the node" means the node is same as `Variable.defs[].node` or `Variable.defs[].parent`.
* If the node declares nothing, this method returns an empty array.
* CAUTION: This API is experimental. See https://github.com/estools/escope/pull/69 for more details.
*
* @param {Esprima.Node} node - a node to get.
* @returns {Variable[]} variables that declared by the node.
*/
}, {
key: 'getDeclaredVariables',
value: function getDeclaredVariables(node) {
return this.__declaredVariables.get(node) || [];
}
/**
* acquire scope from node.
* @method ScopeManager#acquire
* @param {Esprima.Node} node - node for the acquired scope.
* @param {boolean=} inner - look up the most inner scope, default value is false.
* @return {Scope?}
*/
}, {
key: 'acquire',
value: function acquire(node, inner) {
var scopes, scope, i, iz;
function predicate(scope) {
if (scope.type === 'function' && scope.functionExpressionScope) {
return false;
}
if (scope.type === 'TDZ') {
return false;
}
return true;
}
scopes = this.__get(node);
if (!scopes || scopes.length === 0) {
return null;
}
// Heuristic selection from all scopes.
// If you would like to get all scopes, please use ScopeManager#acquireAll.
if (scopes.length === 1) {
return scopes[0];
}
if (inner) {
for (i = scopes.length - 1; i >= 0; --i) {
scope = scopes[i];
if (predicate(scope)) {
return scope;
}
}
} else {
for (i = 0, iz = scopes.length; i < iz; ++i) {
scope = scopes[i];
if (predicate(scope)) {
return scope;
}
}
}
return null;
}
/**
* acquire all scopes from node.
* @method ScopeManager#acquireAll
* @param {Esprima.Node} node - node for the acquired scope.
* @return {Scope[]?}
*/
}, {
key: 'acquireAll',
value: function acquireAll(node) {
return this.__get(node);
}
/**
* release the node.
* @method ScopeManager#release
* @param {Esprima.Node} node - releasing node.
* @param {boolean=} inner - look up the most inner scope, default value is false.
* @return {Scope?} upper scope for the node.
*/
}, {
key: 'release',
value: function release(node, inner) {
var scopes, scope;
scopes = this.__get(node);
if (scopes && scopes.length) {
scope = scopes[0].upper;
if (!scope) {
return null;
}
return this.acquire(scope.block, inner);
}
return null;
}
}, {
key: 'attach',
value: function attach() {}
}, {
key: 'detach',
value: function detach() {}
}, {
key: '__nestScope',
value: function __nestScope(scope) {
if (scope instanceof _scope.GlobalScope) {
(0, _assert2.default)(this.__currentScope === null);
this.globalScope = scope;
}
this.__currentScope = scope;
return scope;
}
}, {
key: '__nestGlobalScope',
value: function __nestGlobalScope(node) {
return this.__nestScope(new _scope.GlobalScope(this, node));
}
}, {
key: '__nestBlockScope',
value: function __nestBlockScope(node, isMethodDefinition) {
return this.__nestScope(new _scope.BlockScope(this, this.__currentScope, node));
}
}, {
key: '__nestFunctionScope',
value: function __nestFunctionScope(node, isMethodDefinition) {
return this.__nestScope(new _scope.FunctionScope(this, this.__currentScope, node, isMethodDefinition));
}
}, {
key: '__nestForScope',
value: function __nestForScope(node) {
return this.__nestScope(new _scope.ForScope(this, this.__currentScope, node));
}
}, {
key: '__nestCatchScope',
value: function __nestCatchScope(node) {
return this.__nestScope(new _scope.CatchScope(this, this.__currentScope, node));
}
}, {
key: '__nestWithScope',
value: function __nestWithScope(node) {
return this.__nestScope(new _scope.WithScope(this, this.__currentScope, node));
}
}, {
key: '__nestClassScope',
value: function __nestClassScope(node) {
return this.__nestScope(new _scope.ClassScope(this, this.__currentScope, node));
}
}, {
key: '__nestSwitchScope',
value: function __nestSwitchScope(node) {
return this.__nestScope(new _scope.SwitchScope(this, this.__currentScope, node));
}
}, {
key: '__nestModuleScope',
value: function __nestModuleScope(node) {
return this.__nestScope(new _scope.ModuleScope(this, this.__currentScope, node));
}
}, {
key: '__nestTDZScope',
value: function __nestTDZScope(node) {
return this.__nestScope(new _scope.TDZScope(this, this.__currentScope, node));
}
}, {
key: '__nestFunctionExpressionNameScope',
value: function __nestFunctionExpressionNameScope(node) {
return this.__nestScope(new _scope.FunctionExpressionNameScope(this, this.__currentScope, node));
}
}, {
key: '__isES6',
value: function __isES6() {
return this.__options.ecmaVersion >= 6;
}
}]);
return ScopeManager;
}();
/* vim: set sw=4 ts=4 et tw=80 : */
exports.default = ScopeManager;
},{"./scope":120,"assert":40,"es6-weak-map":110}],120:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ClassScope = exports.ForScope = exports.FunctionScope = exports.SwitchScope = exports.BlockScope = exports.TDZScope = exports.WithScope = exports.CatchScope = exports.FunctionExpressionNameScope = exports.ModuleScope = exports.GlobalScope = undefined;
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
var _estraverse = require('estraverse');
var _es6Map = require('es6-map');
var _es6Map2 = _interopRequireDefault(_es6Map);
var _reference = require('./reference');
var _reference2 = _interopRequireDefault(_reference);
var _variable = require('./variable');
var _variable2 = _interopRequireDefault(_variable);
var _definition = require('./definition');
var _definition2 = _interopRequireDefault(_definition);
var _assert = require('assert');
var _assert2 = _interopRequireDefault(_assert);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function isStrictScope(scope, block, isMethodDefinition, useDirective) {
var body, i, iz, stmt, expr;
// When upper scope is exists and strict, inner scope is also strict.
if (scope.upper && scope.upper.isStrict) {
return true;
}
// ArrowFunctionExpression's scope is always strict scope.
if (block.type === _estraverse.Syntax.ArrowFunctionExpression) {
return true;
}
if (isMethodDefinition) {
return true;
}
if (scope.type === 'class' || scope.type === 'module') {
return true;
}
if (scope.type === 'block' || scope.type === 'switch') {
return false;
}
if (scope.type === 'function') {
if (block.type === _estraverse.Syntax.Program) {
body = block;
} else {
body = block.body;
}
} else if (scope.type === 'global') {
body = block;
} else {
return false;
}
// Search 'use strict' directive.
if (useDirective) {
for (i = 0, iz = body.body.length; i < iz; ++i) {
stmt = body.body[i];
if (stmt.type !== _estraverse.Syntax.DirectiveStatement) {
break;
}
if (stmt.raw === '"use strict"' || stmt.raw === '\'use strict\'') {
return true;
}
}
} else {
for (i = 0, iz = body.body.length; i < iz; ++i) {
stmt = body.body[i];
if (stmt.type !== _estraverse.Syntax.ExpressionStatement) {
break;
}
expr = stmt.expression;
if (expr.type !== _estraverse.Syntax.Literal || typeof expr.value !== 'string') {
break;
}
if (expr.raw != null) {
if (expr.raw === '"use strict"' || expr.raw === '\'use strict\'') {
return true;
}
} else {
if (expr.value === 'use strict') {
return true;
}
}
}
}
return false;
}
function registerScope(scopeManager, scope) {
var scopes;
scopeManager.scopes.push(scope);
scopes = scopeManager.__nodeToScope.get(scope.block);
if (scopes) {
scopes.push(scope);
} else {
scopeManager.__nodeToScope.set(scope.block, [scope]);
}
}
function shouldBeStatically(def) {
return def.type === _variable2.default.ClassName || def.type === _variable2.default.Variable && def.parent.kind !== 'var';
}
/**
* @class Scope
*/
var Scope = function () {
function Scope(scopeManager, type, upperScope, block, isMethodDefinition) {
_classCallCheck(this, Scope);
/**
* One of 'TDZ', 'module', 'block', 'switch', 'function', 'catch', 'with', 'function', 'class', 'global'.
* @member {String} Scope#type
*/
this.type = type;
/**
* The scoped {@link Variable}s of this scope, as <code>{ Variable.name
* : Variable }</code>.
* @member {Map} Scope#set
*/
this.set = new _es6Map2.default();
/**
* The tainted variables of this scope, as <code>{ Variable.name :
* boolean }</code>.
* @member {Map} Scope#taints */
this.taints = new _es6Map2.default();
/**
* Generally, through the lexical scoping of JS you can always know
* which variable an identifier in the source code refers to. There are
* a few exceptions to this rule. With 'global' and 'with' scopes you
* can only decide at runtime which variable a reference refers to.
* Moreover, if 'eval()' is used in a scope, it might introduce new
* bindings in this or its parent scopes.
* All those scopes are considered 'dynamic'.
* @member {boolean} Scope#dynamic
*/
this.dynamic = this.type === 'global' || this.type === 'with';
/**
* A reference to the scope-defining syntax node.
* @member {esprima.Node} Scope#block
*/
this.block = block;
/**
* The {@link Reference|references} that are not resolved with this scope.
* @member {Reference[]} Scope#through
*/
this.through = [];
/**
* The scoped {@link Variable}s of this scope. In the case of a
* 'function' scope this includes the automatic argument <em>arguments</em> as
* its first element, as well as all further formal arguments.
* @member {Variable[]} Scope#variables
*/
this.variables = [];
/**
* Any variable {@link Reference|reference} found in this scope. This
* includes occurrences of local variables as well as variables from
* parent scopes (including the global scope). For local variables
* this also includes defining occurrences (like in a 'var' statement).
* In a 'function' scope this does not include the occurrences of the
* formal parameter in the parameter list.
* @member {Reference[]} Scope#references
*/
this.references = [];
/**
* For 'global' and 'function' scopes, this is a self-reference. For
* other scope types this is the <em>variableScope</em> value of the
* parent scope.
* @member {Scope} Scope#variableScope
*/
this.variableScope = this.type === 'global' || this.type === 'function' || this.type === 'module' ? this : upperScope.variableScope;
/**
* Whether this scope is created by a FunctionExpression.
* @member {boolean} Scope#functionExpressionScope
*/
this.functionExpressionScope = false;
/**
* Whether this is a scope that contains an 'eval()' invocation.
* @member {boolean} Scope#directCallToEvalScope
*/
this.directCallToEvalScope = false;
/**
* @member {boolean} Scope#thisFound
*/
this.thisFound = false;
this.__left = [];
/**
* Reference to the parent {@link Scope|scope}.
* @member {Scope} Scope#upper
*/
this.upper = upperScope;
/**
* Whether 'use strict' is in effect in this scope.
* @member {boolean} Scope#isStrict
*/
this.isStrict = isStrictScope(this, block, isMethodDefinition, scopeManager.__useDirective());
/**
* List of nested {@link Scope}s.
* @member {Scope[]} Scope#childScopes
*/
this.childScopes = [];
if (this.upper) {
this.upper.childScopes.push(this);
}
this.__declaredVariables = scopeManager.__declaredVariables;
registerScope(scopeManager, this);
}
_createClass(Scope, [{
key: '__shouldStaticallyClose',
value: function __shouldStaticallyClose(scopeManager) {
return !this.dynamic || scopeManager.__isOptimistic();
}
}, {
key: '__shouldStaticallyCloseForGlobal',
value: function __shouldStaticallyCloseForGlobal(ref) {
// On global scope, let/const/class declarations should be resolved statically.
var name = ref.identifier.name;
if (!this.set.has(name)) {
return false;
}
var variable = this.set.get(name);
var defs = variable.defs;
return defs.length > 0 && defs.every(shouldBeStatically);
}
}, {
key: '__staticCloseRef',
value: function __staticCloseRef(ref) {
if (!this.__resolve(ref)) {
this.__delegateToUpperScope(ref);
}
}
}, {
key: '__dynamicCloseRef',
value: function __dynamicCloseRef(ref) {
// notify all names are through to global
var current = this;
do {
current.through.push(ref);
current = current.upper;
} while (current);
}
}, {
key: '__globalCloseRef',
value: function __globalCloseRef(ref) {
// let/const/class declarations should be resolved statically.
// others should be resolved dynamically.
if (this.__shouldStaticallyCloseForGlobal(ref)) {
this.__staticCloseRef(ref);
} else {
this.__dynamicCloseRef(ref);
}
}
}, {
key: '__close',
value: function __close(scopeManager) {
var closeRef;
if (this.__shouldStaticallyClose(scopeManager)) {
closeRef = this.__staticCloseRef;
} else if (this.type !== 'global') {
closeRef = this.__dynamicCloseRef;
} else {
closeRef = this.__globalCloseRef;
}
// Try Resolving all references in this scope.
for (var i = 0, iz = this.__left.length; i < iz; ++i) {
var ref = this.__left[i];
closeRef.call(this, ref);
}
this.__left = null;
return this.upper;
}
}, {
key: '__resolve',
value: function __resolve(ref) {
var variable, name;
name = ref.identifier.name;
if (this.set.has(name)) {
variable = this.set.get(name);
variable.references.push(ref);
variable.stack = variable.stack && ref.from.variableScope === this.variableScope;
if (ref.tainted) {
variable.tainted = true;
this.taints.set(variable.name, true);
}
ref.resolved = variable;
return true;
}
return false;
}
}, {
key: '__delegateToUpperScope',
value: function __delegateToUpperScope(ref) {
if (this.upper) {
this.upper.__left.push(ref);
}
this.through.push(ref);
}
}, {
key: '__addDeclaredVariablesOfNode',
value: function __addDeclaredVariablesOfNode(variable, node) {
if (node == null) {
return;
}
var variables = this.__declaredVariables.get(node);
if (variables == null) {
variables = [];
this.__declaredVariables.set(node, variables);
}
if (variables.indexOf(variable) === -1) {
variables.push(variable);
}
}
}, {
key: '__defineGeneric',
value: function __defineGeneric(name, set, variables, node, def) {
var variable;
variable = set.get(name);
if (!variable) {
variable = new _variable2.default(name, this);
set.set(name, variable);
variables.push(variable);
}
if (def) {
variable.defs.push(def);
if (def.type !== _variable2.default.TDZ) {
this.__addDeclaredVariablesOfNode(variable, def.node);
this.__addDeclaredVariablesOfNode(variable, def.parent);
}
}
if (node) {
variable.identifiers.push(node);
}
}
}, {
key: '__define',
value: function __define(node, def) {
if (node && node.type === _estraverse.Syntax.Identifier) {
this.__defineGeneric(node.name, this.set, this.variables, node, def);
}
}
}, {
key: '__referencing',
value: function __referencing(node, assign, writeExpr, maybeImplicitGlobal, partial, init) {
// because Array element may be null
if (!node || node.type !== _estraverse.Syntax.Identifier) {
return;
}
// Specially handle like `this`.
if (node.name === 'super') {
return;
}
var ref = new _reference2.default(node, this, assign || _reference2.default.READ, writeExpr, maybeImplicitGlobal, !!partial, !!init);
this.references.push(ref);
this.__left.push(ref);
}
}, {
key: '__detectEval',
value: function __detectEval() {
var current;
current = this;
this.directCallToEvalScope = true;
do {
current.dynamic = true;
current = current.upper;
} while (current);
}
}, {
key: '__detectThis',
value: function __detectThis() {
this.thisFound = true;
}
}, {
key: '__isClosed',
value: function __isClosed() {
return this.__left === null;
}
/**
* returns resolved {Reference}
* @method Scope#resolve
* @param {Esprima.Identifier} ident - identifier to be resolved.
* @return {Reference}
*/
}, {
key: 'resolve',
value: function resolve(ident) {
var ref, i, iz;
(0, _assert2.default)(this.__isClosed(), 'Scope should be closed.');
(0, _assert2.default)(ident.type === _estraverse.Syntax.Identifier, 'Target should be identifier.');
for (i = 0, iz = this.references.length; i < iz; ++i) {
ref = this.references[i];
if (ref.identifier === ident) {
return ref;
}
}
return null;
}
/**
* returns this scope is static
* @method Scope#isStatic
* @return {boolean}
*/
}, {
key: 'isStatic',
value: function isStatic() {
return !this.dynamic;
}
/**
* returns this scope has materialized arguments
* @method Scope#isArgumentsMaterialized
* @return {boolean}
*/
}, {
key: 'isArgumentsMaterialized',
value: function isArgumentsMaterialized() {
return true;
}
/**
* returns this scope has materialized `this` reference
* @method Scope#isThisMaterialized
* @return {boolean}
*/
}, {
key: 'isThisMaterialized',
value: function isThisMaterialized() {
return true;
}
}, {
key: 'isUsedName',
value: function isUsedName(name) {
if (this.set.has(name)) {
return true;
}
for (var i = 0, iz = this.through.length; i < iz; ++i) {
if (this.through[i].identifier.name === name) {
return true;
}
}
return false;
}
}]);
return Scope;
}();
exports.default = Scope;
var GlobalScope = exports.GlobalScope = function (_Scope) {
_inherits(GlobalScope, _Scope);
function GlobalScope(scopeManager, block) {
_classCallCheck(this, GlobalScope);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(GlobalScope).call(this, scopeManager, 'global', null, block, false));
_this.implicit = {
set: new _es6Map2.default(),
variables: [],
/**
* List of {@link Reference}s that are left to be resolved (i.e. which
* need to be linked to the variable they refer to).
* @member {Reference[]} Scope#implicit#left
*/
left: []
};
return _this;
}
_createClass(GlobalScope, [{
key: '__close',
value: function __close(scopeManager) {
var implicit = [];
for (var i = 0, iz = this.__left.length; i < iz; ++i) {
var ref = this.__left[i];
if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) {
implicit.push(ref.__maybeImplicitGlobal);
}
}
// create an implicit global variable from assignment expression
for (var _i = 0, _iz = implicit.length; _i < _iz; ++_i) {
var info = implicit[_i];
this.__defineImplicit(info.pattern, new _definition2.default(_variable2.default.ImplicitGlobalVariable, info.pattern, info.node, null, null, null));
}
this.implicit.left = this.__left;
return _get(Object.getPrototypeOf(GlobalScope.prototype), '__close', this).call(this, scopeManager);
}
}, {
key: '__defineImplicit',
value: function __defineImplicit(node, def) {
if (node && node.type === _estraverse.Syntax.Identifier) {
this.__defineGeneric(node.name, this.implicit.set, this.implicit.variables, node, def);
}
}
}]);
return GlobalScope;
}(Scope);
var ModuleScope = exports.ModuleScope = function (_Scope2) {
_inherits(ModuleScope, _Scope2);
function ModuleScope(scopeManager, upperScope, block) {
_classCallCheck(this, ModuleScope);
return _possibleConstructorReturn(this, Object.getPrototypeOf(ModuleScope).call(this, scopeManager, 'module', upperScope, block, false));
}
return ModuleScope;
}(Scope);
var FunctionExpressionNameScope = exports.FunctionExpressionNameScope = function (_Scope3) {
_inherits(FunctionExpressionNameScope, _Scope3);
function FunctionExpressionNameScope(scopeManager, upperScope, block) {
_classCallCheck(this, FunctionExpressionNameScope);
var _this3 = _possibleConstructorReturn(this, Object.getPrototypeOf(FunctionExpressionNameScope).call(this, scopeManager, 'function-expression-name', upperScope, block, false));
_this3.__define(block.id, new _definition2.default(_variable2.default.FunctionName, block.id, block, null, null, null));
_this3.functionExpressionScope = true;
return _this3;
}
return FunctionExpressionNameScope;
}(Scope);
var CatchScope = exports.CatchScope = function (_Scope4) {
_inherits(CatchScope, _Scope4);
function CatchScope(scopeManager, upperScope, block) {
_classCallCheck(this, CatchScope);
return _possibleConstructorReturn(this, Object.getPrototypeOf(CatchScope).call(this, scopeManager, 'catch', upperScope, block, false));
}
return CatchScope;
}(Scope);
var WithScope = exports.WithScope = function (_Scope5) {
_inherits(WithScope, _Scope5);
function WithScope(scopeManager, upperScope, block) {
_classCallCheck(this, WithScope);
return _possibleConstructorReturn(this, Object.getPrototypeOf(WithScope).call(this, scopeManager, 'with', upperScope, block, false));
}
_createClass(WithScope, [{
key: '__close',
value: function __close(scopeManager) {
if (this.__shouldStaticallyClose(scopeManager)) {
return _get(Object.getPrototypeOf(WithScope.prototype), '__close', this).call(this, scopeManager);
}
for (var i = 0, iz = this.__left.length; i < iz; ++i) {
var ref = this.__left[i];
ref.tainted = true;
this.__delegateToUpperScope(ref);
}
this.__left = null;
return this.upper;
}
}]);
return WithScope;
}(Scope);
var TDZScope = exports.TDZScope = function (_Scope6) {
_inherits(TDZScope, _Scope6);
function TDZScope(scopeManager, upperScope, block) {
_classCallCheck(this, TDZScope);
return _possibleConstructorReturn(this, Object.getPrototypeOf(TDZScope).call(this, scopeManager, 'TDZ', upperScope, block, false));
}
return TDZScope;
}(Scope);
var BlockScope = exports.BlockScope = function (_Scope7) {
_inherits(BlockScope, _Scope7);
function BlockScope(scopeManager, upperScope, block) {
_classCallCheck(this, BlockScope);
return _possibleConstructorReturn(this, Object.getPrototypeOf(BlockScope).call(this, scopeManager, 'block', upperScope, block, false));
}
return BlockScope;
}(Scope);
var SwitchScope = exports.SwitchScope = function (_Scope8) {
_inherits(SwitchScope, _Scope8);
function SwitchScope(scopeManager, upperScope, block) {
_classCallCheck(this, SwitchScope);
return _possibleConstructorReturn(this, Object.getPrototypeOf(SwitchScope).call(this, scopeManager, 'switch', upperScope, block, false));
}
return SwitchScope;
}(Scope);
var FunctionScope = exports.FunctionScope = function (_Scope9) {
_inherits(FunctionScope, _Scope9);
function FunctionScope(scopeManager, upperScope, block, isMethodDefinition) {
_classCallCheck(this, FunctionScope);
// section 9.2.13, FunctionDeclarationInstantiation.
// NOTE Arrow functions never have an arguments objects.
var _this9 = _possibleConstructorReturn(this, Object.getPrototypeOf(FunctionScope).call(this, scopeManager, 'function', upperScope, block, isMethodDefinition));
if (_this9.block.type !== _estraverse.Syntax.ArrowFunctionExpression) {
_this9.__defineArguments();
}
return _this9;
}
_createClass(FunctionScope, [{
key: 'isArgumentsMaterialized',
value: function isArgumentsMaterialized() {
// TODO(Constellation)
// We can more aggressive on this condition like this.
//
// function t() {
// // arguments of t is always hidden.
// function arguments() {
// }
// }
if (this.block.type === _estraverse.Syntax.ArrowFunctionExpression) {
return false;
}
if (!this.isStatic()) {
return true;
}
var variable = this.set.get('arguments');
(0, _assert2.default)(variable, 'Always have arguments variable.');
return variable.tainted || variable.references.length !== 0;
}
}, {
key: 'isThisMaterialized',
value: function isThisMaterialized() {
if (!this.isStatic()) {
return true;
}
return this.thisFound;
}
}, {
key: '__defineArguments',
value: function __defineArguments() {
this.__defineGeneric('arguments', this.set, this.variables, null, null);
this.taints.set('arguments', true);
}
}]);
return FunctionScope;
}(Scope);
var ForScope = exports.ForScope = function (_Scope10) {
_inherits(ForScope, _Scope10);
function ForScope(scopeManager, upperScope, block) {
_classCallCheck(this, ForScope);
return _possibleConstructorReturn(this, Object.getPrototypeOf(ForScope).call(this, scopeManager, 'for', upperScope, block, false));
}
return ForScope;
}(Scope);
var ClassScope = exports.ClassScope = function (_Scope11) {
_inherits(ClassScope, _Scope11);
function ClassScope(scopeManager, upperScope, block) {
_classCallCheck(this, ClassScope);
return _possibleConstructorReturn(this, Object.getPrototypeOf(ClassScope).call(this, scopeManager, 'class', upperScope, block, false));
}
return ClassScope;
}(Scope);
/* vim: set sw=4 ts=4 et tw=80 : */
},{"./definition":114,"./reference":117,"./variable":121,"assert":40,"es6-map":96,"estraverse":129}],121:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/*
Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/**
* A Variable represents a locally scoped identifier. These include arguments to
* functions.
* @class Variable
*/
var Variable = function Variable(name, scope) {
_classCallCheck(this, Variable);
/**
* The variable name, as given in the source code.
* @member {String} Variable#name
*/
this.name = name;
/**
* List of defining occurrences of this variable (like in 'var ...'
* statements or as parameter), as AST nodes.
* @member {esprima.Identifier[]} Variable#identifiers
*/
this.identifiers = [];
/**
* List of {@link Reference|references} of this variable (excluding parameter entries)
* in its defining scope and all nested scopes. For defining
* occurrences only see {@link Variable#defs}.
* @member {Reference[]} Variable#references
*/
this.references = [];
/**
* List of defining occurrences of this variable (like in 'var ...'
* statements or as parameter), as custom objects.
* @member {Definition[]} Variable#defs
*/
this.defs = [];
this.tainted = false;
/**
* Whether this is a stack variable.
* @member {boolean} Variable#stack
*/
this.stack = true;
/**
* Reference to the enclosing Scope.
* @member {Scope} Variable#scope
*/
this.scope = scope;
};
exports.default = Variable;
Variable.CatchClause = 'CatchClause';
Variable.Parameter = 'Parameter';
Variable.FunctionName = 'FunctionName';
Variable.ClassName = 'ClassName';
Variable.Variable = 'Variable';
Variable.ImportBinding = 'ImportBinding';
Variable.TDZ = 'TDZ';
Variable.ImplicitGlobalVariable = 'ImplicitGlobalVariable';
/* vim: set sw=4 ts=4 et tw=80 : */
},{}],122:[function(require,module,exports){
module.exports={
"_from": "escope@~3.6.0",
"_id": "escope@3.6.0",
"_inBundle": false,
"_integrity": "sha1-4Bl16BJ4GhY6ba392AOY3GTIicM=",
"_location": "/escope",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "escope@~3.6.0",
"name": "escope",
"escapedName": "escope",
"rawSpec": "~3.6.0",
"saveSpec": null,
"fetchSpec": "~3.6.0"
},
"_requiredBy": [
"/",
"/esshorten2"
],
"_resolved": "https://registry.npmjs.org/escope/-/escope-3.6.0.tgz",
"_shasum": "e01975e812781a163a6dadfdd80398dc64c889c3",
"_spec": "escope@~3.6.0",
"_where": "/home/gw/workspace/esmangle",
"bugs": {
"url": "https://github.com/estools/escope/issues"
},
"bundleDependencies": false,
"dependencies": {
"es6-map": "^0.1.3",
"es6-weak-map": "^2.0.1",
"esrecurse": "^4.1.0",
"estraverse": "^4.1.1"
},
"deprecated": false,
"description": "ECMAScript scope analyzer",
"devDependencies": {
"babel": "^6.3.26",
"babel-preset-es2015": "^6.3.13",
"babel-register": "^6.3.13",
"browserify": "^13.0.0",
"chai": "^3.4.1",
"espree": "^3.1.1",
"esprima": "^2.7.1",
"gulp": "^3.9.0",
"gulp-babel": "^6.1.1",
"gulp-bump": "^1.0.0",
"gulp-eslint": "^1.1.1",
"gulp-espower": "^1.0.2",
"gulp-filter": "^3.0.1",
"gulp-git": "^1.6.1",
"gulp-mocha": "^2.2.0",
"gulp-plumber": "^1.0.1",
"gulp-sourcemaps": "^1.6.0",
"gulp-tag-version": "^1.3.0",
"jsdoc": "^3.4.0",
"lazypipe": "^1.0.1",
"vinyl-source-stream": "^1.1.0"
},
"engines": {
"node": ">=0.4.0"
},
"homepage": "http://github.com/estools/escope",
"license": "BSD-2-Clause",
"main": "lib/index.js",
"maintainers": [
{
"name": "Yusuke Suzuki",
"email": "utatane.tea@gmail.com",
"url": "http://github.com/Constellation"
}
],
"name": "escope",
"repository": {
"type": "git",
"url": "git+https://github.com/estools/escope.git"
},
"scripts": {
"jsdoc": "jsdoc src/*.js README.md",
"lint": "gulp lint",
"test": "gulp travis",
"unit-test": "gulp test"
},
"version": "3.6.0"
}
},{}],123:[function(require,module,exports){
/*
Copyright (C) 2014 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
(function () {
'use strict';
var estraverse = require('estraverse');
function isNode(node) {
if (node == null) {
return false;
}
return typeof node === 'object' && typeof node.type === 'string';
}
function isProperty(nodeType, key) {
return (nodeType === estraverse.Syntax.ObjectExpression || nodeType === estraverse.Syntax.ObjectPattern) && key === 'properties';
}
function Visitor(visitor, options) {
options = options || {};
this.__visitor = visitor || this;
this.__childVisitorKeys = options.childVisitorKeys
? Object.assign({}, estraverse.VisitorKeys, options.childVisitorKeys)
: estraverse.VisitorKeys;
if (options.fallback === 'iteration') {
this.__fallback = Object.keys;
} else if (typeof options.fallback === 'function') {
this.__fallback = options.fallback;
}
}
/* Default method for visiting children.
* When you need to call default visiting operation inside custom visiting
* operation, you can use it with `this.visitChildren(node)`.
*/
Visitor.prototype.visitChildren = function (node) {
var type, children, i, iz, j, jz, child;
if (node == null) {
return;
}
type = node.type || estraverse.Syntax.Property;
children = this.__childVisitorKeys[type];
if (!children) {
if (this.__fallback) {
children = this.__fallback(node);
} else {
throw new Error('Unknown node type ' + type + '.');
}
}
for (i = 0, iz = children.length; i < iz; ++i) {
child = node[children[i]];
if (child) {
if (Array.isArray(child)) {
for (j = 0, jz = child.length; j < jz; ++j) {
if (child[j]) {
if (isNode(child[j]) || isProperty(type, children[i])) {
this.visit(child[j]);
}
}
}
} else if (isNode(child)) {
this.visit(child);
}
}
}
};
/* Dispatching node. */
Visitor.prototype.visit = function (node) {
var type;
if (node == null) {
return;
}
type = node.type || estraverse.Syntax.Property;
if (this.__visitor[type]) {
this.__visitor[type].call(this, node);
return;
}
this.visitChildren(node);
};
exports.version = require('./package.json').version;
exports.Visitor = Visitor;
exports.visit = function (node, visitor, options) {
var v = new Visitor(visitor, options);
v.visit(node);
};
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"./package.json":124,"estraverse":129}],124:[function(require,module,exports){
module.exports={
"_from": "esrecurse@^4.1.0",
"_id": "esrecurse@4.2.1",
"_inBundle": false,
"_integrity": "sha512-64RBB++fIOAXPw3P9cy89qfMlvZEXZkqqJkjqqXIvzP5ezRZjW+lPWjw35UX/3EhUPFYbg5ER4JYgDw4007/DQ==",
"_location": "/esrecurse",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "esrecurse@^4.1.0",
"name": "esrecurse",
"escapedName": "esrecurse",
"rawSpec": "^4.1.0",
"saveSpec": null,
"fetchSpec": "^4.1.0"
},
"_requiredBy": [
"/escope"
],
"_resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.1.tgz",
"_shasum": "007a3b9fdbc2b3bb87e4879ea19c92fdbd3942cf",
"_spec": "esrecurse@^4.1.0",
"_where": "/home/gw/workspace/esmangle/node_modules/escope",
"babel": {
"presets": [
"es2015"
]
},
"bugs": {
"url": "https://github.com/estools/esrecurse/issues"
},
"bundleDependencies": false,
"dependencies": {
"estraverse": "^4.1.0"
},
"deprecated": false,
"description": "ECMAScript AST recursive visitor",
"devDependencies": {
"babel-cli": "^6.24.1",
"babel-eslint": "^7.2.3",
"babel-preset-es2015": "^6.24.1",
"babel-register": "^6.24.1",
"chai": "^4.0.2",
"esprima": "^4.0.0",
"gulp": "^3.9.0",
"gulp-bump": "^2.7.0",
"gulp-eslint": "^4.0.0",
"gulp-filter": "^5.0.0",
"gulp-git": "^2.4.1",
"gulp-mocha": "^4.3.1",
"gulp-tag-version": "^1.2.1",
"jsdoc": "^3.3.0-alpha10",
"minimist": "^1.1.0"
},
"engines": {
"node": ">=4.0"
},
"homepage": "https://github.com/estools/esrecurse",
"license": "BSD-2-Clause",
"main": "esrecurse.js",
"maintainers": [
{
"name": "Yusuke Suzuki",
"email": "utatane.tea@gmail.com",
"url": "https://github.com/Constellation"
}
],
"name": "esrecurse",
"repository": {
"type": "git",
"url": "git+https://github.com/estools/esrecurse.git"
},
"scripts": {
"lint": "gulp lint",
"test": "gulp travis",
"unit-test": "gulp test"
},
"version": "4.2.1"
}
},{}],125:[function(require,module,exports){
/*!
Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*global exports:true*/
(function () {
'use strict';
var escope,
estraverse,
esutils,
utility,
version,
assert,
Syntax,
Map;
escope = require('escope');
estraverse = require('estraverse');
esutils = require('esutils');
utility = require('./utility');
Map = require('./map');
version = require('../package.json').version;
Syntax = estraverse.Syntax;
assert = function assert(cond, message) {
if (!cond) {
throw new Error(message);
}
};
if (version.indexOf('-dev', version.length - 4) === -1) {
assert = function () { };
}
function NameGenerator(scope, options) {
this._scope = scope;
this._functionName = '';
if (!options.distinguishFunctionExpressionScope &&
this._scope.upper &&
this._scope.upper.functionExpressionScope) {
this._functionName = this._scope.upper.block.id.name;
}
}
NameGenerator.prototype.passAsUnique = function passAsUnique(name) {
var i, iz;
if (this._functionName === name) {
return false;
}
if (esutils.keyword.isKeywordES5(name, true) || esutils.keyword.isRestrictedWord(name)) {
return false;
}
if (this._scope.taints.has(name)) {
return false;
}
for (i = 0, iz = this._scope.through.length; i < iz; ++i) {
if (this._scope.through[i].identifier.name === name) {
return false;
}
}
if (this._scope.type === 'for' &&
this._scope.variableScope.__id_map__ &&
this._scope.variableScope.__id_map__[name]
) {
return false;
}
return true;
};
NameGenerator.prototype.generateName = function generateName(tip) {
do {
tip = utility.generateNextName(tip);
} while (!this.passAsUnique(tip));
return tip;
};
function run(scope, options) {
var i, iz, j, jz, variable, name, def, ref, generator;
var varMap = {};
var idMap = {};
generator = new NameGenerator(scope, options);
if (scope.isStatic()) {
// skip TDZ scope for now
if (scope.type === 'TDZ') {
return;
}
name = '9';
scope.variables.sort(function (a, b) {
if (a.tainted) {
return 1;
}
if (b.tainted) {
return -1;
}
return (b.identifiers.length + b.references.length) - (a.identifiers.length + a.references.length);
});
/**
* fix through
*/
scope.through.forEach(function (n) {
var name = n.identifier.name;
var upper = scope.upper;
var map;
if (n.identifier.__done__) {
return;
}
while (upper) {
map = upper.__var_map__;
if (map && map[name]) {
n.identifier.name = map[name];
n.identifier.__done__ = true;
break;
}
upper = upper.upper;
}
});
for (i = 0, iz = scope.variables.length; i < iz; ++i) {
variable = scope.variables[i];
if (variable.tainted) {
continue;
}
// Because `arguments` definition is nothing.
// But if `var arguments` is defined, identifiers.length !== 0
// and this doesn't indicate arguments.
if (variable.identifiers.length === 0) {
// do not change names because this is special name
continue;
}
name = generator.generateName(name);
for (j = 0, jz = variable.identifiers.length; j < jz; ++j) {
def = variable.identifiers[j];
if (def.__done__) {
continue;
}
varMap[variable.name] = name;
idMap[name] = variable.name;
// change definition's name
def.name = name;
def.__done__ = true;
}
for (j = 0, jz = variable.references.length; j < jz; ++j) {
ref = variable.references[j];
if (ref.identifier.__done__) {
continue;
}
// change reference's name
ref.identifier.name = name;
ref.identifier.__done__ = true;
}
}
scope.__var_map__ = varMap;
scope.__id_map__ = idMap;
var scopeFrom;
for (j = 0, jz = scope.references.length; j < jz; ++j) {
ref = scope.references[j];
if (ref.identifier.__done__) {
continue;
}
scopeFrom = ref.from;
while (scopeFrom) {
varMap = scopeFrom.__var_map__;
if (varMap && varMap[ref.identifier.name]) {
// change reference's name
ref.identifier.name = varMap[ref.identifier.name];
break;
}
scopeFrom = scopeFrom.upper;
}
}
}
}
function Label(node, upper) {
this.node = node;
this.upper = upper;
this.users = [];
this.names = new Map();
this.name = null;
}
Label.prototype.mangle = function () {
var tip, current, i, iz;
tip = '9';
// merge already used names
for (current = this.upper; current; current = current.upper) {
if (current.name !== null) {
this.names.set(current.name, true);
}
}
do {
tip = utility.generateNextName(tip);
} while (this.names.has(tip));
this.name = tip;
for (current = this.upper; current; current = current.upper) {
current.names.set(tip, true);
}
this.node.label.name = tip;
for (i = 0, iz = this.users.length; i < iz; ++i) {
this.users[i].label.name = tip;
}
};
function LabelScope(upper) {
this.map = new Map();
this.upper = upper;
this.label = null;
this.labels = [];
}
LabelScope.prototype.register = function register(node) {
var name;
assert(node.type === Syntax.LabeledStatement, 'node should be LabeledStatement');
this.label = new Label(node, this.label);
this.labels.push(this.label);
name = node.label.name;
assert(!this.map.has(name), 'duplicate label is found');
this.map.set(name, this.label);
};
LabelScope.prototype.unregister = function unregister(node) {
var name, ref;
if (node.type !== Syntax.LabeledStatement) {
return;
}
name = node.label.name;
ref = this.map.get(name);
this.map['delete'](name);
this.label = ref.upper;
};
LabelScope.prototype.resolve = function resolve(node) {
var name;
if (node.label) {
name = node.label.name;
assert(this.map.has(name), 'unresolved label');
this.map.get(name).users.push(node);
}
};
LabelScope.prototype.close = function close() {
var i, iz, label;
this.labels.sort(function (lhs, rhs) {
return rhs.users.length - lhs.users.length;
});
for (i = 0, iz = this.labels.length; i < iz; ++i) {
label = this.labels[i];
label.mangle();
}
return this.upper;
};
function mangleLabels(tree) {
var labelScope;
var FuncOrProgram = [Syntax.Program, Syntax.FunctionExpression, Syntax.FunctionDeclaration];
estraverse.traverse(tree, {
enter: function (node) {
if (FuncOrProgram.indexOf(node.type) >= 0) {
labelScope = new LabelScope(labelScope);
return;
}
switch (node.type) {
case Syntax.LabeledStatement:
labelScope.register(node);
break;
case Syntax.BreakStatement:
case Syntax.ContinueStatement:
labelScope.resolve(node);
break;
}
},
leave: function (node) {
labelScope.unregister(node);
if (FuncOrProgram.indexOf(node.type) >= 0) {
labelScope = labelScope.close();
}
}
});
return tree;
}
function mangle(tree, options) {
var result, manager, i, iz;
if (options == null) {
options = { destructive: false };
}
result = (options.destructive == null || options.destructive) ? tree : utility.deepCopy(tree);
manager = escope.analyze(result, {
directive: true,
ecmaVersion: options.esmaVersion || 6,
sourceType: options.sourceType || 'script'
});
// mangling names
for (i = 0, iz = manager.scopes.length; i < iz; ++i) {
run(manager.scopes[i], options);
}
// mangling labels
return mangleLabels(result);
}
exports.mangle = mangle;
exports.version = version;
exports.generateNextName = utility.generateNextName;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../package.json":128,"./map":126,"./utility":127,"escope":115,"estraverse":129,"esutils":134}],126:[function(require,module,exports){
arguments[4][5][0].apply(exports,arguments)
},{"dup":5}],127:[function(require,module,exports){
/*
Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*global exports:true*/
(function () {
'use strict';
var isArray, NameSequence, ZeroSequenceCache;
isArray = Array.isArray;
if (!isArray) {
isArray = function isArray(array) {
return Object.prototype.toString.call(array) === '[object Array]';
};
}
function deepCopy(obj) {
function deepCopyInternal(obj, result) {
var key, val;
for (key in obj) {
if (key.lastIndexOf('__', 0) === 0) {
continue;
}
if (obj.hasOwnProperty(key)) {
val = obj[key];
if (typeof val === 'object' && val !== null) {
if (val instanceof RegExp) {
val = new RegExp(val);
} else {
val = deepCopyInternal(val, isArray(val) ? [] : {});
}
}
result[key] = val;
}
}
return result;
}
return deepCopyInternal(obj, isArray(obj) ? [] : {});
}
function stringRepeat(str, num) {
var result = '';
for (num |= 0; num > 0; num >>>= 1, str += str) {
if (num & 1) {
result += str;
}
}
return result;
}
// generateNextName
ZeroSequenceCache = [];
function zeroSequence(num) {
var res = ZeroSequenceCache[num];
if (res !== undefined) {
return res;
}
res = stringRepeat('0', num);
ZeroSequenceCache[num] = res;
return res;
}
NameSequence = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$'.split('');
function generateNextName(name) {
var ch, index, cur;
cur = name.length - 1;
do {
ch = name.charAt(cur);
index = NameSequence.indexOf(ch);
if (index !== (NameSequence.length - 1)) {
return name.substring(0, cur) + NameSequence[index + 1] + zeroSequence(name.length - (cur + 1));
}
--cur;
} while (cur >= 0);
return 'a' + zeroSequence(name.length);
}
exports.generateNextName = generateNextName;
exports.deepCopy = deepCopy;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{}],128:[function(require,module,exports){
module.exports={
"_from": "esshorten2@~1.1.20",
"_id": "esshorten2@1.1.20",
"_inBundle": false,
"_integrity": "sha1-j/2kZFpeDztZNuzR/Zu8apo2DpU=",
"_location": "/esshorten2",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "esshorten2@~1.1.20",
"name": "esshorten2",
"escapedName": "esshorten2",
"rawSpec": "~1.1.20",
"saveSpec": null,
"fetchSpec": "~1.1.20"
},
"_requiredBy": [
"/"
],
"_resolved": "https://registry.npmjs.org/esshorten2/-/esshorten2-1.1.20.tgz",
"_shasum": "8ffda4645a5e0f3b5936ecd1fd9bbc6a9a360e95",
"_spec": "esshorten2@~1.1.20",
"_where": "/home/gw/workspace/esmangle",
"bugs": {
"url": "https://github.com/estools/esshorten/issues"
},
"bundleDependencies": false,
"dependencies": {
"escope": "~3.6.0",
"estraverse": "~4.1.1",
"esutils": "~2.0.2"
},
"deprecated": false,
"description": "Shorten (mangle) names in JavaScript code",
"devDependencies": {
"chai": "*",
"coffee-script": "~1.10.0",
"commonjs-everywhere": "~0.9.7",
"gulp": "~3.9.0",
"gulp-jshint": "~1.11.2",
"gulp-mocha": "~2.1.3",
"jshint-stylish": "~2.0.1"
},
"directories": {
"lib": "./lib"
},
"engines": {
"node": ">=0.6.0"
},
"homepage": "https://github.com/estools/esshorten#readme",
"licenses": [
{
"type": "BSD",
"url": "http://github.com/estools/esshorten/raw/master/LICENSE.BSD"
}
],
"main": "lib/esshorten.js",
"maintainers": [
{
"name": "Yusuke Suzuki",
"email": "utatane.tea@gmail.com",
"url": "http://github.com/Constellation"
}
],
"name": "esshorten2",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/estools/esshorten.git"
},
"scripts": {
"lint": "gulp lint",
"test": "gulp travis",
"unit-test": "gulp test"
},
"version": "1.1.20"
}
},{}],129:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
/*jslint vars:false, bitwise:true*/
/*jshint indent:4*/
/*global exports:true*/
(function clone(exports) {
'use strict';
var Syntax,
isArray,
VisitorOption,
VisitorKeys,
objectCreate,
objectKeys,
BREAK,
SKIP,
REMOVE;
function ignoreJSHintError() { }
isArray = Array.isArray;
if (!isArray) {
isArray = function isArray(array) {
return Object.prototype.toString.call(array) === '[object Array]';
};
}
function deepCopy(obj) {
var ret = {}, key, val;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
val = obj[key];
if (typeof val === 'object' && val !== null) {
ret[key] = deepCopy(val);
} else {
ret[key] = val;
}
}
}
return ret;
}
function shallowCopy(obj) {
var ret = {}, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
ret[key] = obj[key];
}
}
return ret;
}
ignoreJSHintError(shallowCopy);
// based on LLVM libc++ upper_bound / lower_bound
// MIT License
function upperBound(array, func) {
var diff, len, i, current;
len = array.length;
i = 0;
while (len) {
diff = len >>> 1;
current = i + diff;
if (func(array[current])) {
len = diff;
} else {
i = current + 1;
len -= diff + 1;
}
}
return i;
}
function lowerBound(array, func) {
var diff, len, i, current;
len = array.length;
i = 0;
while (len) {
diff = len >>> 1;
current = i + diff;
if (func(array[current])) {
i = current + 1;
len -= diff + 1;
} else {
len = diff;
}
}
return i;
}
ignoreJSHintError(lowerBound);
objectCreate = Object.create || (function () {
function F() { }
return function (o) {
F.prototype = o;
return new F();
};
})();
objectKeys = Object.keys || function (o) {
var keys = [], key;
for (key in o) {
keys.push(key);
}
return keys;
};
function extend(to, from) {
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',
AssignmentPattern: 'AssignmentPattern',
ArrayExpression: 'ArrayExpression',
ArrayPattern: 'ArrayPattern',
ArrowFunctionExpression: 'ArrowFunctionExpression',
AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7.
BlockStatement: 'BlockStatement',
BinaryExpression: 'BinaryExpression',
BreakStatement: 'BreakStatement',
CallExpression: 'CallExpression',
CatchClause: 'CatchClause',
ClassBody: 'ClassBody',
ClassDeclaration: 'ClassDeclaration',
ClassExpression: 'ClassExpression',
ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7.
ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7.
ConditionalExpression: 'ConditionalExpression',
ContinueStatement: 'ContinueStatement',
DebuggerStatement: 'DebuggerStatement',
DirectiveStatement: 'DirectiveStatement',
DoWhileStatement: 'DoWhileStatement',
EmptyStatement: 'EmptyStatement',
ExportAllDeclaration: 'ExportAllDeclaration',
ExportDefaultDeclaration: 'ExportDefaultDeclaration',
ExportNamedDeclaration: 'ExportNamedDeclaration',
ExportSpecifier: 'ExportSpecifier',
ExpressionStatement: 'ExpressionStatement',
ForStatement: 'ForStatement',
ForInStatement: 'ForInStatement',
ForOfStatement: 'ForOfStatement',
FunctionDeclaration: 'FunctionDeclaration',
FunctionExpression: 'FunctionExpression',
GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7.
Identifier: 'Identifier',
IfStatement: 'IfStatement',
ImportDeclaration: 'ImportDeclaration',
ImportDefaultSpecifier: 'ImportDefaultSpecifier',
ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
ImportSpecifier: 'ImportSpecifier',
Literal: 'Literal',
LabeledStatement: 'LabeledStatement',
LogicalExpression: 'LogicalExpression',
MemberExpression: 'MemberExpression',
MetaProperty: 'MetaProperty',
MethodDefinition: 'MethodDefinition',
ModuleSpecifier: 'ModuleSpecifier',
NewExpression: 'NewExpression',
ObjectExpression: 'ObjectExpression',
ObjectPattern: 'ObjectPattern',
Program: 'Program',
Property: 'Property',
RestElement: 'RestElement',
ReturnStatement: 'ReturnStatement',
SequenceExpression: 'SequenceExpression',
SpreadElement: 'SpreadElement',
Super: 'Super',
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'],
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'],
MemberExpression: ['object', 'property'],
MetaProperty: ['meta', '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']
};
// unique id
BREAK = {};
SKIP = {};
REMOVE = {};
VisitorOption = {
Break: BREAK,
Skip: SKIP,
Remove: REMOVE
};
function Reference(parent, key) {
this.parent = parent;
this.key = key;
}
Reference.prototype.replace = function replace(node) {
this.parent[this.key] = node;
};
Reference.prototype.remove = function remove() {
if (isArray(this.parent)) {
this.parent.splice(this.key, 1);
return true;
} else {
this.replace(null);
return false;
}
};
function Element(node, path, wrap, ref) {
this.node = node;
this.path = path;
this.wrap = wrap;
this.ref = ref;
}
function Controller() { }
// API:
// return property path array from root to current node
Controller.prototype.path = function path() {
var i, iz, j, jz, result, element;
function addToPath(result, path) {
if (isArray(path)) {
for (j = 0, jz = path.length; j < jz; ++j) {
result.push(path[j]);
}
} else {
result.push(path);
}
}
// root node
if (!this.__current.path) {
return null;
}
// first node is sentinel, second node is root element
result = [];
for (i = 2, iz = this.__leavelist.length; i < iz; ++i) {
element = this.__leavelist[i];
addToPath(result, element.path);
}
addToPath(result, this.__current.path);
return result;
};
// API:
// return type of current node
Controller.prototype.type = function () {
var node = this.current();
return node.type || this.__current.wrap;
};
// API:
// return array of parent elements
Controller.prototype.parents = function parents() {
var i, iz, result;
// first node is sentinel
result = [];
for (i = 1, iz = this.__leavelist.length; i < iz; ++i) {
result.push(this.__leavelist[i].node);
}
return result;
};
// API:
// return current node
Controller.prototype.current = function current() {
return this.__current.node;
};
Controller.prototype.__execute = function __execute(callback, element) {
var previous, result;
result = undefined;
previous = this.__current;
this.__current = element;
this.__state = null;
if (callback) {
result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node);
}
this.__current = previous;
return result;
};
// API:
// notify control skip / break
Controller.prototype.notify = function notify(flag) {
this.__state = flag;
};
// API:
// skip child nodes of current node
Controller.prototype.skip = function () {
this.notify(SKIP);
};
// API:
// break traversals
Controller.prototype['break'] = function () {
this.notify(BREAK);
};
// API:
// remove node
Controller.prototype.remove = function () {
this.notify(REMOVE);
};
Controller.prototype.__initialize = function(root, visitor) {
this.visitor = visitor;
this.root = root;
this.__worklist = [];
this.__leavelist = [];
this.__current = null;
this.__state = null;
this.__fallback = visitor.fallback === 'iteration';
this.__keys = VisitorKeys;
if (visitor.keys) {
this.__keys = extend(objectCreate(this.__keys), visitor.keys);
}
};
function isNode(node) {
if (node == null) {
return false;
}
return typeof node === 'object' && typeof node.type === 'string';
}
function isProperty(nodeType, key) {
return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key;
}
Controller.prototype.traverse = function traverse(root, visitor) {
var worklist,
leavelist,
element,
node,
nodeType,
ret,
key,
current,
current2,
candidates,
candidate,
sentinel;
this.__initialize(root, visitor);
sentinel = {};
// reference
worklist = this.__worklist;
leavelist = this.__leavelist;
// initialize
worklist.push(new Element(root, null, null, null));
leavelist.push(new Element(null, null, null, null));
while (worklist.length) {
element = worklist.pop();
if (element === sentinel) {
element = leavelist.pop();
ret = this.__execute(visitor.leave, element);
if (this.__state === BREAK || ret === BREAK) {
return;
}
continue;
}
if (element.node) {
ret = this.__execute(visitor.enter, element);
if (this.__state === BREAK || ret === BREAK) {
return;
}
worklist.push(sentinel);
leavelist.push(element);
if (this.__state === SKIP || ret === SKIP) {
continue;
}
node = element.node;
nodeType = node.type || element.wrap;
candidates = this.__keys[nodeType];
if (!candidates) {
if (this.__fallback) {
candidates = objectKeys(node);
} else {
throw new Error('Unknown node type ' + nodeType + '.');
}
}
current = candidates.length;
while ((current -= 1) >= 0) {
key = candidates[current];
candidate = node[key];
if (!candidate) {
continue;
}
if (isArray(candidate)) {
current2 = candidate.length;
while ((current2 -= 1) >= 0) {
if (!candidate[current2]) {
continue;
}
if (isProperty(nodeType, candidates[current])) {
element = new Element(candidate[current2], [key, current2], 'Property', null);
} else if (isNode(candidate[current2])) {
element = new Element(candidate[current2], [key, current2], null, null);
} else {
continue;
}
worklist.push(element);
}
} else if (isNode(candidate)) {
worklist.push(new Element(candidate, key, null, null));
}
}
}
}
};
Controller.prototype.replace = function replace(root, visitor) {
function removeElem(element) {
var i,
key,
nextElem,
parent;
if (element.ref.remove()) {
// When the reference is an element of an array.
key = element.ref.key;
parent = element.ref.parent;
// If removed from array, then decrease following items' keys.
i = worklist.length;
while (i--) {
nextElem = worklist[i];
if (nextElem.ref && nextElem.ref.parent === parent) {
if (nextElem.ref.key < key) {
break;
}
--nextElem.ref.key;
}
}
}
}
var worklist,
leavelist,
node,
nodeType,
target,
element,
current,
current2,
candidates,
candidate,
sentinel,
outer,
key;
this.__initialize(root, visitor);
sentinel = {};
// reference
worklist = this.__worklist;
leavelist = this.__leavelist;
// initialize
outer = {
root: root
};
element = new Element(root, null, null, new Reference(outer, 'root'));
worklist.push(element);
leavelist.push(element);
while (worklist.length) {
element = worklist.pop();
if (element === sentinel) {
element = leavelist.pop();
target = this.__execute(visitor.leave, element);
// node may be replaced with null,
// so distinguish between undefined and null in this place
if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
// replace
element.ref.replace(target);
}
if (this.__state === REMOVE || target === REMOVE) {
removeElem(element);
}
if (this.__state === BREAK || target === BREAK) {
return outer.root;
}
continue;
}
target = this.__execute(visitor.enter, element);
// node may be replaced with null,
// so distinguish between undefined and null in this place
if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
// replace
element.ref.replace(target);
element.node = target;
}
if (this.__state === REMOVE || target === REMOVE) {
removeElem(element);
element.node = null;
}
if (this.__state === BREAK || target === BREAK) {
return outer.root;
}
// node may be null
node = element.node;
if (!node) {
continue;
}
worklist.push(sentinel);
leavelist.push(element);
if (this.__state === SKIP || target === SKIP) {
continue;
}
nodeType = node.type || element.wrap;
candidates = this.__keys[nodeType];
if (!candidates) {
if (this.__fallback) {
candidates = objectKeys(node);
} else {
throw new Error('Unknown node type ' + nodeType + '.');
}
}
current = candidates.length;
while ((current -= 1) >= 0) {
key = candidates[current];
candidate = node[key];
if (!candidate) {
continue;
}
if (isArray(candidate)) {
current2 = candidate.length;
while ((current2 -= 1) >= 0) {
if (!candidate[current2]) {
continue;
}
if (isProperty(nodeType, candidates[current])) {
element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2));
} else if (isNode(candidate[current2])) {
element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2));
} else {
continue;
}
worklist.push(element);
}
} else if (isNode(candidate)) {
worklist.push(new Element(candidate, key, null, new Reference(node, key)));
}
}
}
return outer.root;
};
function traverse(root, visitor) {
var controller = new Controller();
return controller.traverse(root, visitor);
}
function replace(root, visitor) {
var controller = new Controller();
return controller.replace(root, visitor);
}
function extendCommentRange(comment, tokens) {
var target;
target = upperBound(tokens, function search(token) {
return token.range[0] > comment.range[0];
});
comment.extendedRange = [comment.range[0], comment.range[1]];
if (target !== tokens.length) {
comment.extendedRange[1] = tokens[target].range[0];
}
target -= 1;
if (target >= 0) {
comment.extendedRange[0] = tokens[target].range[1];
}
return comment;
}
function attachComments(tree, providedComments, tokens) {
// At first, we should calculate extended comment ranges.
var comments = [], comment, len, i, cursor;
if (!tree.range) {
throw new Error('attachComments needs range information');
}
// tokens array is empty, we attach comments to tree as 'leadingComments'
if (!tokens.length) {
if (providedComments.length) {
for (i = 0, len = providedComments.length; i < len; i += 1) {
comment = deepCopy(providedComments[i]);
comment.extendedRange = [0, tree.range[0]];
comments.push(comment);
}
tree.leadingComments = comments;
}
return tree;
}
for (i = 0, len = providedComments.length; i < len; i += 1) {
comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens));
}
// This is based on John Freeman's implementation.
cursor = 0;
traverse(tree, {
enter: function (node) {
var comment;
while (cursor < comments.length) {
comment = comments[cursor];
if (comment.extendedRange[1] > node.range[0]) {
break;
}
if (comment.extendedRange[1] === node.range[0]) {
if (!node.leadingComments) {
node.leadingComments = [];
}
node.leadingComments.push(comment);
comments.splice(cursor, 1);
} else {
cursor += 1;
}
}
// already out of owned node
if (cursor === comments.length) {
return VisitorOption.Break;
}
if (comments[cursor].extendedRange[0] > node.range[1]) {
return VisitorOption.Skip;
}
}
});
cursor = 0;
traverse(tree, {
leave: function (node) {
var comment;
while (cursor < comments.length) {
comment = comments[cursor];
if (node.range[1] < comment.extendedRange[0]) {
break;
}
if (node.range[1] === comment.extendedRange[0]) {
if (!node.trailingComments) {
node.trailingComments = [];
}
node.trailingComments.push(comment);
comments.splice(cursor, 1);
} else {
cursor += 1;
}
}
// already out of owned node
if (cursor === comments.length) {
return VisitorOption.Break;
}
if (comments[cursor].extendedRange[0] > node.range[1]) {
return VisitorOption.Skip;
}
}
});
return tree;
}
exports.version = require('./package.json').version;
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;
}(exports));
/* vim: set sw=4 ts=4 et tw=80 : */
},{"./package.json":130}],130:[function(require,module,exports){
module.exports={
"_from": "estraverse@~4.1.1",
"_id": "estraverse@4.1.1",
"_inBundle": false,
"_integrity": "sha1-9srKcokzqFDvkGYdDheYK6RxEaI=",
"_location": "/estraverse",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "estraverse@~4.1.1",
"name": "estraverse",
"escapedName": "estraverse",
"rawSpec": "~4.1.1",
"saveSpec": null,
"fetchSpec": "~4.1.1"
},
"_requiredBy": [
"/",
"/escope",
"/esrecurse",
"/esshorten2"
],
"_resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.1.1.tgz",
"_shasum": "f6caca728933a850ef90661d0e17982ba47111a2",
"_spec": "estraverse@~4.1.1",
"_where": "/home/gw/workspace/esmangle",
"bugs": {
"url": "https://github.com/estools/estraverse/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "ECMAScript JS AST traversal functions",
"devDependencies": {
"chai": "^2.1.1",
"coffee-script": "^1.8.0",
"espree": "^1.11.0",
"gulp": "^3.8.10",
"gulp-bump": "^0.2.2",
"gulp-filter": "^2.0.0",
"gulp-git": "^1.0.1",
"gulp-tag-version": "^1.2.1",
"jshint": "^2.5.6",
"mocha": "^2.1.0"
},
"engines": {
"node": ">=0.10.0"
},
"homepage": "https://github.com/estools/estraverse",
"license": "BSD-2-Clause",
"main": "estraverse.js",
"maintainers": [
{
"name": "Yusuke Suzuki",
"email": "utatane.tea@gmail.com",
"url": "http://github.com/Constellation"
}
],
"name": "estraverse",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/estools/estraverse.git"
},
"scripts": {
"lint": "jshint estraverse.js",
"test": "npm run-script lint && npm run-script unit-test",
"unit-test": "mocha --compilers coffee:coffee-script/register"
},
"version": "4.1.1"
}
},{}],131:[function(require,module,exports){
/*
Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
(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
};
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{}],132:[function(require,module,exports){
/*
Copyright (C) 2013-2014 Yusuke Suzuki <utatane.tea@gmail.com>
Copyright (C) 2014 Ivan Nikulin <ifaaan@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
(function () {
'use strict';
var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch;
// See `tools/generate-identifier-regex.js`.
ES5Regex = {
// ECMAScript 5.1/Unicode v9.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\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB
// ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierPart:
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-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30
};
ES6Regex = {
// ECMAScript 6/Unicode v9.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\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uF
// ECMAScript 6/Unicode v9.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\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u310
};
function isDecimalDigit(ch) {
return 0x30 <= ch && ch <= 0x39; // 0..9
}
function isHexDigit(ch) {
return 0x30 <= ch && ch <= 0x39 || // 0..9
0x61 <= ch && ch <= 0x66 || // a..f
0x41 <= ch && ch <= 0x46; // A..F
}
function isOctalDigit(ch) {
return ch >= 0x30 && ch <= 0x37; // 0..7
}
// 7.2 White Space
NON_ASCII_WHITESPACES = [
0x1680,
0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A,
0x202F, 0x205F,
0x3000,
0xFEFF
];
function isWhiteSpace(ch) {
return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 ||
ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0;
}
// 7.3 Line Terminators
function isLineTerminator(ch) {
return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029;
}
// 7.6 Identifier Names and Identifiers
function fromCodePoint(cp) {
if (cp <= 0xFFFF) { return String.fromCharCode(cp); }
var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800);
var cu2 = String.fromCharCode(((cp - 0x10000) % 0x400) + 0xDC00);
return cu1 + cu2;
}
IDENTIFIER_START = new Array(0x80);
for(ch = 0; ch < 0x80; ++ch) {
IDENTIFIER_START[ch] =
ch >= 0x61 && ch <= 0x7A || // a..z
ch >= 0x41 && ch <= 0x5A || // A..Z
ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
}
IDENTIFIER_PART = new Array(0x80);
for(ch = 0; ch < 0x80; ++ch) {
IDENTIFIER_PART[ch] =
ch >= 0x61 && ch <= 0x7A || // a..z
ch >= 0x41 && ch <= 0x5A || // A..Z
ch >= 0x30 && ch <= 0x39 || // 0..9
ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
}
function isIdentifierStartES5(ch) {
return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
}
function isIdentifierPartES5(ch) {
return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
}
function isIdentifierStartES6(ch) {
return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
}
function isIdentifierPartES6(ch) {
return ch < 0x80 ? 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
};
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{}],133:[function(require,module,exports){
/*
Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
(function () {
'use strict';
var code = require('./code');
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) {
// yield should not be treated as keyword under non-strict mode.
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 - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
}
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 (0xD800 <= ch && ch <= 0xDBFF) {
++i;
if (i >= iz) { return false; }
lowCh = id.charCodeAt(i);
if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) {
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
};
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"./code":132}],134:[function(require,module,exports){
/*
Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
*/
(function () {
'use strict';
exports.ast = require('./ast');
exports.code = require('./code');
exports.keyword = require('./keyword');
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"./ast":131,"./code":132,"./keyword":133}],135:[function(require,module,exports){
'use strict';
var d = require('d')
, callable = require('es5-ext/object/valid-callable')
, apply = Function.prototype.apply, call = Function.prototype.call
, create = Object.create, defineProperty = Object.defineProperty
, defineProperties = Object.defineProperties
, hasOwnProperty = Object.prototype.hasOwnProperty
, descriptor = { configurable: true, enumerable: false, writable: true }
, on, once, off, emit, methods, descriptors, base;
on = function (type, listener) {
var data;
callable(listener);
if (!hasOwnProperty.call(this, '__ee__')) {
data = descriptor.value = create(null);
defineProperty(this, '__ee__', descriptor);
descriptor.value = null;
} else {
data = this.__ee__;
}
if (!data[type]) data[type] = listener;
else if (typeof data[type] === 'object') data[type].push(listener);
else data[type] = [data[type], listener];
return this;
};
once = function (type, listener) {
var once, self;
callable(listener);
self = this;
on.call(this, type, once = function () {
off.call(self, type, once);
apply.call(listener, this, arguments);
});
once.__eeOnceListener__ = listener;
return this;
};
off = function (type, listener) {
var data, listeners, candidate, i;
callable(listener);
if (!hasOwnProperty.call(this, '__ee__')) return this;
data = this.__ee__;
if (!data[type]) return this;
listeners = data[type];
if (typeof listeners === 'object') {
for (i = 0; (candidate = listeners[i]); ++i) {
if ((candidate === listener) ||
(candidate.__eeOnceListener__ === listener)) {
if (listeners.length === 2) data[type] = listeners[i ? 0 : 1];
else listeners.splice(i, 1);
}
}
} else {
if ((listeners === listener) ||
(listeners.__eeOnceListener__ === listener)) {
delete data[type];
}
}
return this;
};
emit = function (type) {
var i, l, listener, listeners, args;
if (!hasOwnProperty.call(this, '__ee__')) return;
listeners = this.__ee__[type];
if (!listeners) return;
if (typeof listeners === 'object') {
l = arguments.length;
args = new Array(l - 1);
for (i = 1; i < l; ++i) args[i - 1] = arguments[i];
listeners = listeners.slice();
for (i = 0; (listener = listeners[i]); ++i) {
apply.call(listener, this, args);
}
} else {
switch (arguments.length) {
case 1:
call.call(listeners, this);
break;
case 2:
call.call(listeners, this, arguments[1]);
break;
case 3:
call.call(listeners, this, arguments[1], arguments[2]);
break;
default:
l = arguments.length;
args = new Array(l - 1);
for (i = 1; i < l; ++i) {
args[i - 1] = arguments[i];
}
apply.call(listeners, this, args);
}
}
};
methods = {
on: on,
once: once,
off: off,
emit: emit
};
descriptors = {
on: d(on),
once: d(once),
off: d(off),
emit: d(emit)
};
base = defineProperties({}, descriptors);
module.exports = exports = function (o) {
return (o == null) ? create(base) : defineProperties(Object(o), descriptors);
};
exports.methods = methods;
},{"d":46,"es5-ext/object/valid-callable":81}],136:[function(require,module,exports){
var naiveFallback = function () {
if (typeof self === "object" && self) return self;
if (typeof window === "object" && window) return window;
throw new Error("Unable to resolve global `this`");
};
module.exports = (function () {
if (this) return this;
// Unexpected strict mode (may happen if e.g. bundled into ESM module)
// Thanks @mathiasbynens -> https://mathiasbynens.be/notes/globalthis
// In all ES5+ engines global object inherits from Object.prototype
// (if you approached one that doesn't please report)
try {
Object.defineProperty(Object.prototype, "__global__", {
get: function () { return this; },
configurable: true
});
} catch (error) {
// Unfortunate case of Object.prototype being sealed (via preventExtensions, seal or freeze)
return naiveFallback();
}
try {
// Safari case (window.__global__ is resolved with global context, but __global__ does not)
if (!__global__) return naiveFallback();
return __global__;
} finally {
delete Object.prototype.__global__;
}
})();
},{}],137:[function(require,module,exports){
"use strict";
module.exports = require("./is-implemented")() ? globalThis : require("./implementation");
},{"./implementation":136,"./is-implemented":138}],138:[function(require,module,exports){
"use strict";
module.exports = function () {
if (typeof globalThis !== "object") return false;
if (!globalThis) return false;
return globalThis.Array === Array;
};
},{}],139:[function(require,module,exports){
module.exports = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) == '[object Array]';
};
},{}],140:[function(require,module,exports){
/**
* Special language-specific overrides.
*
* Source: ftp://ftp.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
*
* @type {Object}
*/
var LANGUAGES = {
tr: {
regexp: /\u0130|\u0049|\u0049\u0307/g,
map: {
'\u0130': '\u0069',
'\u0049': '\u0131',
'\u0049\u0307': '\u0069'
}
},
az: {
regexp: /[\u0130]/g,
map: {
'\u0130': '\u0069',
'\u0049': '\u0131',
'\u0049\u0307': '\u0069'
}
},
lt: {
regexp: /[\u0049\u004A\u012E\u00CC\u00CD\u0128]/g,
map: {
'\u0049': '\u0069\u0307',
'\u004A': '\u006A\u0307',
'\u012E': '\u012F\u0307',
'\u00CC': '\u0069\u0307\u0300',
'\u00CD': '\u0069\u0307\u0301',
'\u0128': '\u0069\u0307\u0303'
}
}
}
/**
* Lowercase a string.
*
* @param {String} str
* @return {String}
*/
module.exports = function (str, locale) {
var lang = LANGUAGES[locale]
str = str == null ? '' : String(str)
if (lang) {
str = str.replace(lang.regexp, function (m) { return lang.map[m] })
}
return str.toLowerCase()
}
},{}],141:[function(require,module,exports){
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
'use strict';
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
module.exports = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
},{}],142:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],143:[function(require,module,exports){
var lowerCase = require('lower-case')
var NON_WORD_REGEXP = require('./vendor/non-word-regexp')
var CAMEL_CASE_REGEXP = require('./vendor/camel-case-regexp')
var TRAILING_DIGIT_REGEXP = require('./vendor/trailing-digit-regexp')
/**
* Sentence case a string.
*
* @param {String} str
* @param {String} locale
* @param {String} replacement
* @return {String}
*/
module.exports = function (str, locale, replacement) {
if (str == null) {
return ''
}
replacement = replacement || ' '
function replace (match, index, string) {
if (index === 0 || index === (string.length - match.length)) {
return ''
}
return replacement
}
str = String(str)
// Support camel case ("camelCase" -> "camel Case").
.replace(CAMEL_CASE_REGEXP, '$1 $2')
// Support digit groups ("test2012" -> "test 2012").
.replace(TRAILING_DIGIT_REGEXP, '$1 $2')
// Remove all non-word characters and replace with a single space.
.replace(NON_WORD_REGEXP, replace)
// Lower case the entire string.
return lowerCase(str, locale)
}
},{"./vendor/camel-case-regexp":144,"./vendor/non-word-regexp":145,"./vendor/trailing-digit-regexp":146,"lower-case":140}],144:[function(require,module,exports){
module.exports = /([\u0061-\u007A\u00B5\u00DF-\u00F6\u00F8-\u00FF\u0101\u0103\u0105\u0107\u0109\u010B\u010D\u010F\u0111\u0113\u0115\u0117\u0119\u011B\u011D\u011F\u0121\u0123\u0125\u0127\u0129\u012B\u012D\u012F\u0131\u0133\u0135\u0137\u0138\u013A\u013C\u013E\u0140\u0142\u0144\u0146\u0148\u0149\u014B\u014D\u014F\u0151\u0153\u0155\u0157\u0159\u015B\u015D\u015F\u0161\u0163\u0165\u0167\u0169\u016B\u016D\u016F\u0171\u0173\u0175\u0177\u017A\u017C\u017E-\u0180\u0183\u0185\u0188\u018C\u018D\u0192\u0195\u0199-\u019B\u019E\u01A1\u01A3\u01A5\u01A8\u01AA\u01AB\u01AD\u01B0\u01B4\u01B6\u01B9\u01BA\u01BD-\u01BF\u01C6\u01C9\u01CC\u01CE\u01D0\u01D2\u01D4\u01D6\u01D8\u01DA\u01DC\u01DD\u01DF\u01E1\u01E3\u01E5\u01E7\u01E9\u01EB\u01ED\u01EF\u01F0\u01F3\u01F5\u01F9\u01FB\u01FD\u01FF\u0201\u0203\u0205\u0207\u0209\u020B\u020D\u020F\u0211\u0213\u0215\u0217\u0219\u021B\u021D\u021F\u0221\u0223\u0225\u0227\u0229\u022B\u022D\u022F\u0231\u0233-\u0239\u023C\u023F\u0240\u0242\u0247\u0249\u024B\u024D\u024F-\u0293\u0295-\u02AF\u0371\u0373\u0377\u037B-\u037D\u0390\u03AC-\u03CE\u03D0\u03D1\u03D5-\u03D7\u03D9\u03DB\u03DD\u03DF\u03E1\u03E3\u03E5\u03E7\u03E9\u03EB\u03ED\u03EF-\u03F3\u03F5\u03F8\u03FB\u03FC\u0430-\u045F\u0461\u0463\u0465\u0467\u0469\u046B\u046D\u046F\u0471\u0473\u0475\u0477\u0479\u047B\u047D\u047F\u0481\u048B\u048D\u048F\u0491\u0493\u0495\u0497\u0499\u049B\u049D\u049F\u04A1\u04A3\u04A5\u04A7\u04A9\u04AB\u04AD\u04AF\u04B1\u04B3\u04B5\u04B7\u04B9\u04BB\u04BD\u04BF\u04C2\u04C4\u04C6\u04C8\u04CA\u04CC\u04CE\u04CF\u04D1\u04D3\u04D5\u04D7\u04D9\u04DB\u04DD\u04DF\u04E1\u04E3\u04E5\u04E7\u04E9\u04EB\u04ED\u04EF\u04F1\u04F3\u04F5\u04F7\u04F9\u04FB\u04FD\u04FF\u0501\u0503\u0505\u0507\u0509\u050B\u050D\u050F\u0511\u0513\u0515\u0517\u0519\u051B\u051D\u051F\u0521\u0523\u0525\u0527\u0561-\u0587\u1D00-\u1D2B\u1D6B-\u1D77\u1D79-\u1D9A\u1E01\u1E03\u1E05\u1E07\u1E09\u1E0B\u1E0D\u1E0F\u1E11\u1E13\u1E15\u1E17\u1E19\u1E1B\u1E1D\u1E1F\u1E21\u1E23\u1E25\u1E27\u1E29\u1E2B\u1E2D\u1E2F\u1E31\u1E33\u1E35\u1E37\u1E39\u1E3B\u1E3D\u1E3F\u1E41\u1E43\u1E45\u1E47\u1E49\u1E4B\u1E4D\u1E4F\u1E51\u1E53\u1E55\u1E57\u1E59\u1E5B\u1E5D\u1E5F\u1E61\u1E63\u1E65\u1E67\u1E69\u1E6B\u1E6D\u1E6F\u1E71\u1E73\u1E75\u1E77\u1E79\u1E7B\u1E7D\u1E7F\u1E81\u1E83\u1E85\u1E87\u1E89\u1E8B\u1E8D\u1E8F\u1E91\u1E93\u1E95-\u1E9D\u1E9F\u1EA1\u1EA3\u1EA5\u1EA7\u1EA9\u1EAB\u1EAD\u1EAF\u1EB1\u1EB3\u1EB5\u1EB7\u1EB9\u1EBB\u1EBD\u1EBF\u1EC1\u1EC3\u1EC5\u1EC7\u1EC9\u1ECB\u1ECD\u1ECF\u1ED1\u1ED3\u1ED5\u1ED7\u1ED9\u1EDB\u1EDD\u1EDF\u1EE1\u1EE3\u1EE5\u1EE7\u1EE9\u1EEB\u1EED\u1EEF\u1EF1\u1EF3\u1EF5\u1EF7\u1EF9\u1EFB\u1EFD\u1EFF-\u1F07\u1F10-\u1F15\u1F20-\u1F27\u1F30-\u1F37\u1F40-\u1F45\u1F50-\u1F57\u1F60-\u1F67\u1F70-\u1F7D\u1F80-\u1F87\u1F90-\u1F97\u1FA0-\u1FA7\u1FB0-\u1FB4\u1FB6\u1FB7\u1FBE\u1FC2-\u1FC4\u1FC6\u1FC7\u1FD0-\u1FD3\u1FD6\u1FD7\u1FE0-\u1FE7\u1FF2-\u1FF4\u1FF6\u1FF7\u210A\u210E\u210F\u2113\u212F\u2134\u2139\u213C\u213D\u2146-\u2149\u214E\u2184\u2C30-\u2C5E\u2C61\u2C65\u2C66\u2C68\u2C6A\u2C6C\u2C71\u2C73\u2C74\u2C76-\u2C7B\u2C81\u2C83\u2C85\u2C87\u2C89\u2C8B\u2C8D\u2C8F\u2C91\u2C93\u2C95\u2C97\u2C99\u2C9B\u2C9D\u2C9F\u2CA1\u2CA3\u2CA5\u2CA7\u2CA9\u2CAB\u2CAD\u2CAF\u2CB1\u2CB3\u2CB5\u2CB7\u2CB9\u2CBB\u2CBD\u2CBF\u2CC1\u2CC3\u2CC5\u2CC7\u2CC9\u2CCB\u2CCD\u2CCF\u2CD1\u2CD3\u2CD5\u2CD7\u2CD9\u2CDB\u2CDD\u2CDF\u2CE1\u2CE3\u2CE4\u2CEC\u2CEE\u2CF3\u2D00-\u2D25\u2D27\u2D2D\uA641\uA643\uA645\uA647\uA649\uA64B\uA64D\uA64F\uA651\uA653\uA655\uA657\uA659\uA65B\uA65D\uA65F\uA661\uA663\uA665\uA667\uA669\uA66B\uA66D\uA681\uA683\uA685\uA687\uA689\uA68B\uA68D\uA68F\uA691\uA693\uA695\uA697\uA723\uA725\uA727\uA729\uA72B\uA72D\uA72F-\uA731\uA733\uA735\uA737\uA739\uA73B\uA73D\uA73F\uA741\uA743\uA745\uA747\uA749\uA74B\uA74D\uA74F\uA751\uA753\uA755\uA757\uA759\uA75B\uA75D\uA75F\uA761\uA763\uA765\uA767\uA769\uA76B\uA76D\uA76F\uA771-\uA778\uA77A\uA77C\uA77F\uA781\uA783\uA785\uA787\uA78C\uA78E\uA791\uA793\uA7A1\uA7A3\uA7A5\uA7A7\uA7A9\uA7FA\uFB00-\uFB06\uFB13-\uFB17\uFF41-\uFF5A])([\u0041-\u005A\u00C0-\u00D6\u00D8-\u00DE\u0100\u0102\u0104\u0106\u0108\u010A\u010C\u010E\u0110\u0112\u0114\u0116\u0118\u011A\u011C\u011E\u0120\u0122\u01
},{}],145:[function(require,module,exports){
module.exports = /[^\u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\u
},{}],146:[function(require,module,exports){
module.exports = /([\u0030-\u0039\u00B2\u00B3\u00B9\u00BC-\u00BE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D66-\u0D75\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19])([^\u0030-\u0039\u00B2\u00B3\u00B9\u00BC-\u00BE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D66-\u0D75\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19])/g
},{}],147:[function(require,module,exports){
"use strict";
var isPrototype = require("../prototype/is");
module.exports = function (value) {
if (typeof value !== "function") return false;
if (!hasOwnProperty.call(value, "length")) return false;
try {
if (typeof value.length !== "number") return false;
if (typeof value.call !== "function") return false;
if (typeof value.apply !== "function") return false;
} catch (error) {
return false;
}
return !isPrototype(value);
};
},{"../prototype/is":154}],148:[function(require,module,exports){
"use strict";
var isValue = require("../value/is")
, isObject = require("../object/is")
, stringCoerce = require("../string/coerce")
, toShortString = require("./to-short-string");
var resolveMessage = function (message, value) {
return message.replace("%v", toShortString(value));
};
module.exports = function (value, defaultMessage, inputOptions) {
if (!isObject(inputOptions)) throw new TypeError(resolveMessage(defaultMessage, value));
if (!isValue(value)) {
if ("default" in inputOptions) return inputOptions["default"];
if (inputOptions.isOptional) return null;
}
var errorMessage = stringCoerce(inputOptions.errorMessage);
if (!isValue(errorMessage)) errorMessage = defaultMessage;
throw new TypeError(resolveMessage(errorMessage, value));
};
},{"../object/is":151,"../string/coerce":155,"../value/is":157,"./to-short-string":150}],149:[function(require,module,exports){
"use strict";
module.exports = function (value) {
try {
return value.toString();
} catch (error) {
try { return String(value); }
catch (error2) { return null; }
}
};
},{}],150:[function(require,module,exports){
"use strict";
var safeToString = require("./safe-to-string");
var reNewLine = /[\n\r\u2028\u2029]/g;
module.exports = function (value) {
var string = safeToString(value);
if (string === null) return "<Non-coercible to string value>";
// Trim if too long
if (string.length > 100) string = string.slice(0, 99) + "…";
// Replace eventual new lines
string = string.replace(reNewLine, function (char) {
switch (char) {
case "\n":
return "\\n";
case "\r":
return "\\r";
case "\u2028":
return "\\u2028";
case "\u2029":
return "\\u2029";
/* istanbul ignore next */
default:
throw new Error("Unexpected character");
}
});
return string;
};
},{"./safe-to-string":149}],151:[function(require,module,exports){
"use strict";
var isValue = require("../value/is");
// prettier-ignore
var possibleTypes = { "object": true, "function": true, "undefined": true /* document.all */ };
module.exports = function (value) {
if (!isValue(value)) return false;
return hasOwnProperty.call(possibleTypes, typeof value);
};
},{"../value/is":157}],152:[function(require,module,exports){
"use strict";
var resolveException = require("../lib/resolve-exception")
, is = require("./is");
module.exports = function (value/*, options*/) {
if (is(value)) return value;
return resolveException(value, "%v is not a plain function", arguments[1]);
};
},{"../lib/resolve-exception":148,"./is":153}],153:[function(require,module,exports){
"use strict";
var isFunction = require("../function/is");
var classRe = /^\s*class[\s{/}]/, functionToString = Function.prototype.toString;
module.exports = function (value) {
if (!isFunction(value)) return false;
if (classRe.test(functionToString.call(value))) return false;
return true;
};
},{"../function/is":147}],154:[function(require,module,exports){
"use strict";
var isObject = require("../object/is");
module.exports = function (value) {
if (!isObject(value)) return false;
try {
if (!value.constructor) return false;
return value.constructor.prototype === value;
} catch (error) {
return false;
}
};
},{"../object/is":151}],155:[function(require,module,exports){
"use strict";
var isValue = require("../value/is")
, isObject = require("../object/is");
var objectToString = Object.prototype.toString;
module.exports = function (value) {
if (!isValue(value)) return null;
if (isObject(value)) {
// Reject Object.prototype.toString coercion
var valueToString = value.toString;
if (typeof valueToString !== "function") return null;
if (valueToString === objectToString) return null;
// Note: It can be object coming from other realm, still as there's no ES3 and CSP compliant
// way to resolve its realm's Object.prototype.toString it's left as not addressed edge case
}
try {
return "" + value; // Ensure implicit coercion
} catch (error) {
return null;
}
};
},{"../object/is":151,"../value/is":157}],156:[function(require,module,exports){
"use strict";
var resolveException = require("../lib/resolve-exception")
, is = require("./is");
module.exports = function (value/*, options*/) {
if (is(value)) return value;
return resolveException(value, "Cannot use %v", arguments[1]);
};
},{"../lib/resolve-exception":148,"./is":157}],157:[function(require,module,exports){
"use strict";
// ES3 safe
var _undefined = void 0;
module.exports = function (value) { return value !== _undefined && value !== null; };
},{}],158:[function(require,module,exports){
/**
* Special language-specific overrides.
*
* Source: ftp://ftp.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
*
* @type {Object}
*/
var LANGUAGES = {
tr: {
regexp: /[\u0069]/g,
map: {
'\u0069': '\u0130'
}
},
az: {
regexp: /[\u0069]/g,
map: {
'\u0069': '\u0130'
}
},
lt: {
regexp: /[\u0069\u006A\u012F]\u0307|\u0069\u0307[\u0300\u0301\u0303]/g,
map: {
'\u0069\u0307': '\u0049',
'\u006A\u0307': '\u004A',
'\u012F\u0307': '\u012E',
'\u0069\u0307\u0300': '\u00CC',
'\u0069\u0307\u0301': '\u00CD',
'\u0069\u0307\u0303': '\u0128'
}
}
}
/**
* Upper case a string.
*
* @param {String} str
* @return {String}
*/
module.exports = function (str, locale) {
var lang = LANGUAGES[locale]
str = str == null ? '' : String(str)
if (lang) {
str = str.replace(lang.regexp, function (m) { return lang.map[m] })
}
return str.toUpperCase()
}
},{}],159:[function(require,module,exports){
module.exports={
"name": "esmangle2",
"description": "ECMAScript code mangler / minifier",
"homepage": "http://github.com/estools/esmangle.html",
"main": "lib/esmangle.js",
"bin": {
"esmangle": "./bin/esmangle.js"
},
"version": "1.0.11",
"engines": {
"node": ">=0.10.0"
},
"directories": {
"lib": "./lib"
},
"maintainers": [
{
"name": "Yusuke Suzuki",
"email": "utatane.tea@gmail.com",
"web": "http://github.com/Constellation"
}
],
"repository": {
"type": "git",
"url": "http://github.com/estools/esmangle.git"
},
"dependencies": {
"browserify": "^16.5.0",
"build": "^0.1.4",
"camel-case": "^1.1.2",
"escodegen": "~1.8.0",
"escope": "~3.6.0",
"esprima": "^2.7.2",
"esshorten2": "~1.1.20",
"estraverse": "~4.1.1",
"esutils": "~2.0.2",
"isarray": "0.0.1",
"mocha": "^7.0.1",
"optionator": "^0.5.0",
"source-map": "^0.5.3"
},
"devDependencies": {
"async": "~1.5.2",
"chai": "*",
"clone": "^1.0.0",
"commonjs-everywhere": "~0.9.7",
"grunt": "~0.4.5",
"grunt-cli": "~0.1.13",
"grunt-contrib-clean": "~0.6.0",
"grunt-contrib-copy": "^0.8.0",
"grunt-contrib-jshint": "^0.11.0",
"grunt-mocha-test": "~0.12.4",
"grunt-shell": "~1.1.1",
"grunt-update-submodules": "~0.4.1",
"q": "^1.2.0",
"xyz": "^0.5.0"
},
"license": "BSD-2-Clause",
"scripts": {
"test": "grunt travis",
"lint": "grunt lint",
"regression-test": "grunt test:regression",
"unit-test": "grunt test",
"build": "grunt build"
}
}
},{}],160:[function(require,module,exports){
(function (global){
global.esmangle = require('../lib/esmangle');
(function () {
// entry points
require('../lib/pass/tree-based-constant-folding');
require('../lib/pass/hoist-variable-to-arguments');
require('../lib/pass/transform-dynamic-to-static-property-access');
require('../lib/pass/transform-dynamic-to-static-property-definition');
require('../lib/pass/transform-immediate-function-call');
require('../lib/pass/transform-logical-association');
require('../lib/pass/reordering-function-declarations');
require('../lib/pass/remove-unused-label');
require('../lib/pass/remove-empty-statement');
require('../lib/pass/remove-wasted-blocks');
require('../lib/pass/transform-to-compound-assignment');
require('../lib/pass/transform-to-sequence-expression');
require('../lib/pass/transform-branch-to-expression');
require('../lib/pass/transform-typeof-undefined');
require('../lib/pass/reduce-sequence-expression');
require('../lib/pass/reduce-branch-jump');
require('../lib/pass/reduce-multiple-if-statements');
require('../lib/pass/dead-code-elimination');
require('../lib/pass/remove-side-effect-free-expressions');
require('../lib/pass/remove-context-sensitive-expressions');
require('../lib/pass/concatenate-variable-definition');
require('../lib/pass/drop-variable-definition');
require('../lib/pass/remove-unreachable-branch');
require('../lib/post/transform-static-to-dynamic-property-access');
require('../lib/post/transform-infinity');
require('../lib/post/rewrite-boolean');
require('../lib/post/rewrite-conditional-expression');
require('../lib/post/omit-parens-in-void-context-iife');
});
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../lib/esmangle":3,"../lib/pass/concatenate-variable-definition":8,"../lib/pass/dead-code-elimination":9,"../lib/pass/drop-variable-definition":10,"../lib/pass/hoist-variable-to-arguments":12,"../lib/pass/reduce-branch-jump":13,"../lib/pass/reduce-multiple-if-statements":14,"../lib/pass/reduce-sequence-expression":15,"../lib/pass/remove-context-sensitive-expressions":16,"../lib/pass/remove-empty-statement":17,"../lib/pass/remove-side-effect-free-expressions":18,"../lib/pass/remove-unreachable-branch":19,"../lib/pass/remove-unused-label":20,"../lib/pass/remove-wasted-blocks":21,"../lib/pass/reordering-function-declarations":22,"../lib/pass/transform-branch-to-expression":24,"../lib/pass/transform-dynamic-to-static-property-access":25,"../lib/pass/transform-dynamic-to-static-property-definition":26,"../lib/pass/transform-immediate-function-call":27,"../lib/pass/transform-logical-association":28,"../lib/pass/transform-to-compound-assignment":29,"../lib/pass/transform-to-sequence-expression":30,"../lib/pass/transform-typeof-undefined":31,"../lib/pass/tree-based-constant-folding":32,"../lib/post/omit-parens-in-void-context-iife":34,"../lib/post/rewrite-boolean":35,"../lib/post/rewrite-conditional-expression":36,"../lib/post/transform-infinity":37,"../lib/post/transform-static-to-dynamic-property-access":38}]},{},[160]);
// 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: 'v4.2.2',
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) {
var result = [];
if (computed) {
result.push('[');
}
result.push(this.generateExpression(expr, Precedence.Sequence, E_TTT));
if (computed) {
result.push(']');
}
return result;
};
CodeGenerator.prototype.generateAssignment = function (left, right, operator, precedence, flags) {
if (Precedence.Assignment < precedence) {
flags |= F_ALLOW_IN;
}
return parenthesize([
this.generateExpression(left, Precedence.Call, flags),
space + operator + space,
this.generateExpression(right, Precedence.Assignment, flags)
], Precedence.Assignment, precedence);
};
CodeGenerator.prototype.semicolon = function (flags) {
if (!semicolons && flags & F_SEMICOLON_OPT) {
return '';
}
return ';';
};
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 ' + stmt.id.name];
if (stmt.superClass) {
fragment = join('extends', this.generateExpression(stmt.superClass, Precedence.Assignment, E_TTT));
result = join(result, fragment);
}
result.push(space);
result.push(this.generateStatement(stmt.body, S_TFFT));
return result;
},
DirectiveStatement: function (stmt, flags) {
if (extra.raw && stmt.raw) {
return stmt.raw + this.semicolon(flags);
}
return escapeDirective(stmt.directive) + this.semicolon(flags);
},
DoWhileStatement: function (stmt, flags) {
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)),
this.generateFunctionBody(expr.value)
];
} else {
fragment = [
generateMethodPrefix(expr),
this.generatePropertyKey(expr.key, expr.computed),
this.generateFunctionBody(expr.value)
];
}
return join(result, fragment);
},
Property: function (expr, precedence, flags) {
if (expr.kind === 'get' || expr.kind === 'set') {
return [
expr.kind,
noEmptySpace(),
this.generatePropertyKey(expr.key, expr.computed),
this.generateFunctionBody(expr.value)
];
}
if (expr.shorthand) {
return this.generatePropertyKey(expr.key, expr.computed);
}
if (expr.method) {
return [
generateMethodPrefix(expr),
this.generatePropertyKey(expr.key, expr.computed),
this.generateFunctionBody(expr.value)
];
}
return [
this.generatePropertyKey(expr.key, expr.computed),
':' + space,
this.generateExpression(expr.value, Precedence.Assignment, E_TTT)
];
},
ObjectExpression: function (expr, precedence, flags) {
var multiline, result, fragment, that = this;
if (!expr.properties.length) {
return '{}';
}
multiline = expr.properties.length > 1;
withIndent(function () {
fragment = that.generateExpression(expr.properties[0], Precedence.Sequence, E_TTT);
});
if (!multiline) {
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, expr.operator, 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';
}
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.0',
'engines': { 'node': '>=0.12.0' },
'maintainers': [{
'name': 'Yusuke Suzuki',
'email': 'utatane.tea@gmail.com',
'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-6to5': '^0.11.1-25',
'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/source-map/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/source-map/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/source-map/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/source-map/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/source-map/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/source-map/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/source-map/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/source-map/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/source-map/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/source-map/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/source-map/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/source-map/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-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\u
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-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31F
};
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-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\u
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\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00
};
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));
/**
Copyright 2014 Gordon Williams (gw@pur3.co.uk)
This Source Code is subject to the terms of the Mozilla Public
License, v2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
------------------------------------------------------------------
Automatically minify code before it is sent to Espruino
------------------------------------------------------------------
**/
"use strict";
(function(){
var minifyUrl = "https://closure-compiler.appspot.com/compile";
var minifyCache = [];
function init() {
Espruino.Core.Config.addSection("Minification", {
sortOrder:600,
description: "Minification takes your JavaScript code and makes it smaller by removing comments and whitespace. "+
"It can make your code execute faster and will save memory, but it will also make it harder to debug.\n"+
"Esprima is a minifier built in to the Web IDE, so it can be used without an internet connection. "+
"The Closure Compiler is an online service offered by Google. It produces more efficient code, but you need an internet connection to use it."
});
Espruino.Core.Config.add("MINIFICATION_LEVEL", {
section : "Minification",
name : "Minification",
description : "Automatically minify code from the Editor window?",
type : { "":"No Minification",
"ESPRIMA":"Esprima (offline)",
"WHITESPACE_ONLY":"Closure (online) - Whitespace Only",
"SIMPLE_OPTIMIZATIONS":"Closure (online) - Simple Optimizations",
"ADVANCED_OPTIMIZATIONS":"Closure (online) - Advanced Optimizations (not recommended)"},
defaultValue : ""
});
Espruino.Core.Config.add("MODULE_MINIFICATION_LEVEL", {
section : "Minification",
name : "Module Minification",
description : "Automatically minify modules? Only modules with a .js extension will be minified - if a file with a .min.js extension exists then it will be used instead.",
type : { "":"No Minification",
"ESPRIMA":"Esprima (offline)",
"WHITESPACE_ONLY":"Closure (online) - Whitespace Only",
"SIMPLE_OPTIMIZATIONS":"Closure (online) - Simple Optimizations",
"ADVANCED_OPTIMIZATIONS":"Closure (online) - Advanced Optimizations (not recommended)"},
defaultValue : "ESPRIMA"
});
Espruino.Core.Config.add("MINIFICATION_Mangle",{
section : "Minification",
name : "Esprima: Mangle",
description : "Shorten variable names",
type : "boolean",
defaultValue : true
});
// When code is sent to Espruino, search it for modules and add extra code required to load them
Espruino.addProcessor("transformForEspruino", function(code, callback) {
minify(code, callback, Espruino.Config.MINIFICATION_LEVEL, false, "");
});
// When code is sent to Espruino, search it for modules and add extra code required to load them
Espruino.addProcessor("transformModuleForEspruino", function(module, callback) {
minify(module.code, function(code) {
module.code = code;
callback(module);
}, Espruino.Config.MODULE_MINIFICATION_LEVEL, true, " in "+module.name);
});
}
// Use the 'offline' Esprima compile
function minifyCodeEsprima(code,callback,description) {
if ((typeof esprima == "undefined") ||
(typeof esmangle == "undefined") ||
(typeof escodegen == "undefined")) {
console.warn("esprima/esmangle/escodegen not defined - not minifying")
return callback(code);
}
var code, syntax, option, str, before, after;
var options = {};
options["mangle"] = Espruino.Config.MINIFICATION_Mangle;
option = {format: {
renumber: true,
hexadecimal: true,
escapeless: true,
indent: {style: ''},
quotes: 'auto',
compact: true,
semicolons: false,
parentheses: false
}};
str = '';
try {
before = code.length;
syntax = esprima.parse(code, { raw: true, loc: true });
syntax = obfuscate(syntax,options);
code = escodegen.generate(syntax, option);
after = code.length;
if (before > after) {
Espruino.Core.Notifications.info('No errors'+description+'. Minified ' + before + ' bytes to ' + after + ' bytes.');
} else {
Espruino.Core.Notifications.info('Can not minify further'+description+', code is already optimized.');
}
callback(code);
} catch (e) {
Espruino.Core.Notifications.error(e.toString()+description);
console.error(e.stack);
callback(code);
} finally { }
}
function obfuscate(syntax,options) {
// hack for random changes between version we have included for Web IDE and node.js version
if (typeof esmangle.require == "undefined")
esmangle.require = esmangle.pass.require;
syntax = esmangle.optimize(syntax, null,{
destructive: true,
directive: true,
preserveCompletionValue: false,
legacy: false,
topLevelContext: false,
inStrictCode: false
});
if (options.mangle) syntax = esmangle.mangle(syntax);
return syntax;
}
// Use the 'online' Closure compiler
function minifyCodeGoogle(code, callback, minificationLevel, description){
for (var i in minifyCache) {
var item = minifyCache[i];
if (item.code==code && item.level==minificationLevel) {
console.log("Found code in minification cache - using that"+description);
// move to front of cache
minifyCache.splice(i,1); // remove old
minifyCache.push(item); // add at front
// callback
callback(item.minified);
return;
}
}
closureCompilerGoogle(code, minificationLevel, 'compiled_code', function(minified) {
if (minified.trim()!="") {
Espruino.Core.Notifications.info('No errors'+description+'. Minifying ' + code.length + ' bytes to ' + minified.length + ' bytes');
if (minifyCache.length>100)
minifyCache = minifyCache.slice(-100);
minifyCache.push({ level : minificationLevel, code : code, minified : minified });
callback(minified);
} else {
Espruino.Core.Notifications.warning("Errors while minifying"+description+" - sending unminified code.");
callback(code);
// get errors...
closureCompilerGoogle(code, minificationLevel, 'errors',function(errors) {
errors.split("\n").forEach(function (err) {
if (err.trim()!="")
Espruino.Core.Notifications.error(err.trim()+description);
});
});
}
});
}
function closureCompilerGoogle(code, minificationLevel, output_info, callback){
if(minificationLevel !== ""){
var minifyObj = $.param({
compilation_level: minificationLevel,
output_format: "text",
output_info: output_info,
js_code: code,
language : "ECMASCRIPT6", // so no need to mess with binary numbers now. \o/
language_out : "ECMASCRIPT5" // ES6 output uses some now features now that Espruino doesn't like
});
$.post(minifyUrl, minifyObj, function(minifiedCode) {
code = minifiedCode;
},"text")
.error(function() {
Espruino.Core.Notifications.error("HTTP error while minifying");
})
.complete(function() {
// ensure we call the callback even if minification failes
callback(code);
});
}
}
function minify(code, callback, level, isModule, description) {
(function() {
Espruino.Core.Status.setStatus("Minifying"+(isModule?description.substr(2):""));
var _callback = callback;
callback = function(code) {
Espruino.Core.Status.setStatus("Minification complete");
_callback(code);
};
})();
var minifyCode = code;
var minifyCallback = callback;
if (isModule) {
/* if we're a module, we wrap this in a function so that unused constants
and functions can be removed */
var header = "(function(){";
var footer = "})();";
minifyCode = header+code+footer;
minifyCallback = function (minified){
callback(minified.substr(header.length, minified.length-(header.length+footer.length+1)));
}
}
switch(level){
case "WHITESPACE_ONLY":
case "SIMPLE_OPTIMIZATIONS":
case "ADVANCED_OPTIMIZATIONS": minifyCodeGoogle(code, callback, level, description); break;
case "ESPRIMA": minifyCodeEsprima(code, callback, description); break;
default: callback(code); break;
}
}
Espruino.Plugins.Minify = {
init : init,
};
}());
/**
Copyright 2014 Gordon Williams (gw@pur3.co.uk)
This Source Code is subject to the terms of the Mozilla Public
License, v2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
------------------------------------------------------------------
Pretokenise code before it uploads
------------------------------------------------------------------
**/
"use strict";
(function(){
function init() {
Espruino.Core.Config.add("PRETOKENISE", {
section : "Minification",
name : "Pretokenise code before upload (BETA)",
description : "All whitespace and comments are removed and all reserved words are converted to tokens before upload. This means a faster upload, less memory used, and increased performance (+10%) at the expense of code readability.",
type : "boolean",
defaultValue : false
});
// When code is sent to Espruino, search it for modules and add extra code required to load them
Espruino.addProcessor("transformForEspruino", function(code, callback) {
if (!Espruino.Config.PRETOKENISE) return callback(code);
pretokenise(code, callback);
});
// When code is sent to Espruino, search it for modules and add extra code required to load them
Espruino.addProcessor("transformModuleForEspruino", function(module, callback) {
if (!Espruino.Config.PRETOKENISE) return callback(module);
pretokenise(module.code, function(code) {
module.code = code;
callback(module);
});
});
}
var LEX_OPERATOR_START = 138;
var TOKENS = [// plundered from jslex.c
/* LEX_EQUAL : */ "==",
/* LEX_TYPEEQUAL : */ "===",
/* LEX_NEQUAL : */ "!=",
/* LEX_NTYPEEQUAL : */ "!==",
/* LEX_LEQUAL : */ "<=",
/* LEX_LSHIFT : */ "<<",
/* LEX_LSHIFTEQUAL : */ "<<=",
/* LEX_GEQUAL : */ ">=",
/* LEX_RSHIFT : */ ">>",
/* LEX_RSHIFTUNSIGNED */ ">>>",
/* LEX_RSHIFTEQUAL : */ ">>=",
/* LEX_RSHIFTUNSIGNEDEQUAL */ ">>>=",
/* LEX_PLUSEQUAL : */ "+=",
/* LEX_MINUSEQUAL : */ "-=",
/* LEX_PLUSPLUS : */ "++",
/* LEX_MINUSMINUS */ "--",
/* LEX_MULEQUAL : */ "*=",
/* LEX_DIVEQUAL : */ "/=",
/* LEX_MODEQUAL : */ "%=",
/* LEX_ANDEQUAL : */ "&=",
/* LEX_ANDAND : */ "&&",
/* LEX_OREQUAL : */ "|=",
/* LEX_OROR : */ "||",
/* LEX_XOREQUAL : */ "^=",
/* LEX_ARROW_FUNCTION */ "=>",
// reserved words
/*LEX_R_IF : */ "if",
/*LEX_R_ELSE : */ "else",
/*LEX_R_DO : */ "do",
/*LEX_R_WHILE : */ "while",
/*LEX_R_FOR : */ "for",
/*LEX_R_BREAK : */ "break",
/*LEX_R_CONTINUE */ "continue",
/*LEX_R_FUNCTION */ "function",
/*LEX_R_RETURN */ "return",
/*LEX_R_VAR : */ "var",
/*LEX_R_LET : */ "let",
/*LEX_R_CONST : */ "const",
/*LEX_R_THIS : */ "this",
/*LEX_R_THROW : */ "throw",
/*LEX_R_TRY : */ "try",
/*LEX_R_CATCH : */ "catch",
/*LEX_R_FINALLY : */ "finally",
/*LEX_R_TRUE : */ "true",
/*LEX_R_FALSE : */ "false",
/*LEX_R_NULL : */ "null",
/*LEX_R_UNDEFINED */ "undefined",
/*LEX_R_NEW : */ "new",
/*LEX_R_IN : */ "in",
/*LEX_R_INSTANCEOF */ "instanceof",
/*LEX_R_SWITCH */ "switch",
/*LEX_R_CASE */ "case",
/*LEX_R_DEFAULT */ "default",
/*LEX_R_DELETE */ "delete",
/*LEX_R_TYPEOF : */ "typeof",
/*LEX_R_VOID : */ "void",
/*LEX_R_DEBUGGER : */ "debugger",
/*LEX_R_CLASS : */ "class",
/*LEX_R_EXTENDS : */ "extends",
/*LEX_R_SUPER : */ "super",
/*LEX_R_STATIC : */ "static",
/*LEX_R_OF : */ "of"
];
function pretokenise(code, callback) {
var lex = Espruino.Core.Utils.getLexer(code);
var brackets = 0;
var resultCode = "";
var lastIdx = 0;
var lastTok = {str:""};
var tok = lex.next();
while (tok!==undefined) {
var previousString = code.substring(lastIdx, tok.startIdx);
var tokenString = code.substring(tok.startIdx, tok.endIdx);
var tokenId = LEX_OPERATOR_START + TOKENS.indexOf(tokenString);
if (tokenId<LEX_OPERATOR_START) tokenId=undefined;
//console.log("prev "+JSON.stringify(previousString)+" next "+tokenString);
if (tok.str=="(" || tok.str=="{" || tok.str=="[") brackets++;
if (tok.str==")" || tok.str=="}" || tok.str=="]") brackets--;
// TODO: check for eg. two IDs/similar which can't be merged without a space
// preserve newlines at root scope to avoid us filling up the command buffer all at once
if (brackets==0 && previousString.indexOf("\n")>=0)
resultCode += "\n";
// if we have a token for something, use that - else use the string
if (tokenId) {
//console.log(JSON.stringify(tok.str)+" => "+tokenId);
resultCode += String.fromCharCode(tokenId);
} else {
if ((tok.type=="ID" || tok.type=="NUMBER") &&
(lastTok.type=="ID" || lastTok.type=="NUMBER"))
resultCode += " ";
resultCode += tokenString;
}
// next
lastIdx = tok.endIdx;
lastTok = tok;
tok = lex.next();
}
callback(resultCode);
}
Espruino.Plugins.Pretokenise = {
init : init,
};
}());
/**
Copyright 2014 Gordon Williams (gw@pur3.co.uk),
Victor Nakoryakov (victor@amperka.ru)
This Source Code is subject to the terms of the Mozilla Public
License, v2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
------------------------------------------------------------------
Wrap whole code in `onInit` function before send and save() it
after upload. Wrapping is necessary to avoid execution start
before save() is executed
------------------------------------------------------------------
**/
"use strict";
(function(){
function init() {
Espruino.Core.Config.add("SAVE_ON_SEND", {
section : "Communications",
name : "Save on Send",
descriptionHTML : 'How should code be uploaded? See <a href="http://www.espruino.com/Saving" target="_blank">espruino.com/Saving</a> for more information.<br>'+
"<b>NOTE:</b> Avoid 'Direct to flash, even after <code>reset()</code>' for normal development - it can make it hard to recover if your code crashes the device.",
type : {
0: "To RAM (default) - execute code while uploading. Use 'save()' to save a RAM image to Flash",
1: "Direct to Flash (execute code at boot)",
2: "Direct to Flash (execute code at boot, even after 'reset()') - USE WITH CARE",
3: "To Storage File (see 'File in Storage to send to')",
},
defaultValue : 0
});
Espruino.Core.Config.add("SAVE_STORAGE_FILE", {
section : "Communications",
name : "Send to File in Storage",
descriptionHTML : "If <code>Save on Send</code> is set to <code>To Storage File</code>, this is the name of the file to write to.",
type : "string",
defaultValue : "myapp"
});
Espruino.Core.Config.add("LOAD_STORAGE_FILE", {
section : "Communications",
name : "Load after saving",
descriptionHTML : "This applies only if saving to Flash (not RAM)",
type : {
0: "Don't load",
1: "Load default application",
2: "Load the Storage File just written to"
},
defaultValue : 2
});
Espruino.addProcessor("transformForEspruino", function(code, callback) {
wrap(code, callback);
});
}
function wrap(code, callback) {
var isFlashPersistent = Espruino.Config.SAVE_ON_SEND == 2;
var isStorageUpload = Espruino.Config.SAVE_ON_SEND == 3;
var isFlashUpload = Espruino.Config.SAVE_ON_SEND == 1 || isFlashPersistent || isStorageUpload;
if (!isFlashUpload) return callback(code);
// Check environment vars
var hasStorage = false;
var ENV = Espruino.Core.Env.getData();
if (ENV &&
ENV.VERSION_MAJOR &&
ENV.VERSION_MINOR!==undefined) {
if (ENV.VERSION_MAJOR>1 ||
ENV.VERSION_MINOR>=96) {
hasStorage = true;
}
}
//
console.log("Uploading "+code.length+" bytes to flash");
if (!hasStorage) { // old style
if (isStorageUpload) {
Espruino.Core.Notifications.error("You have pre-1v96 firmware - unable to upload to Storage");
code = "";
} else {
Espruino.Core.Notifications.error("You have pre-1v96 firmware. Upload size is limited by available RAM");
code = "E.setBootCode("+JSON.stringify(code)+(isFlashPersistent?",true":"")+");load()\n";
}
} else { // new style
var filename;
if (isStorageUpload)
filename = Espruino.Config.SAVE_STORAGE_FILE;
else
filename = isFlashPersistent ? ".bootrst" : ".bootcde";
if (!filename || filename.length>28) {
Espruino.Core.Notifications.error("Invalid Storage file name "+JSON.stringify(filename));
code = "";
} else {
var CHUNKSIZE = 1024;
var newCode = [];
var len = code.length;
newCode.push('require("Storage").write("'+filename+'",'+JSON.stringify(code.substr(0,CHUNKSIZE))+',0,'+len+');');
for (var i=CHUNKSIZE;i<len;i+=CHUNKSIZE)
newCode.push('require("Storage").write("'+filename+'",'+JSON.stringify(code.substr(i,CHUNKSIZE))+','+i+');');
code = newCode.join("\n");
if (Espruino.Config.LOAD_STORAGE_FILE==2 && isStorageUpload)
code += "\nload("+JSON.stringify(filename)+")\n";
else if (Espruino.Config.LOAD_STORAGE_FILE!=0)
code += "\nload()\n";
}
}
callback(code);
}
Espruino.Plugins.SaveOnSend = {
init : init,
};
}());
/**
Copyright 2014 Gordon Williams (gw@pur3.co.uk)
This Source Code is subject to the terms of the Mozilla Public
License, v2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
------------------------------------------------------------------
Ability to set the current time in Espruino
------------------------------------------------------------------
**/
"use strict";
(function(){
function init() {
Espruino.Core.Config.add("SET_TIME_ON_WRITE", {
section : "Communications",
name : "Set Current Time",
description : "When sending code, set Espruino's clock to the current time",
type : "boolean",
defaultValue : true,
onChange : function(newValue) { }
});
// When code is sent to Espruino, append code to set the current time
Espruino.addProcessor("transformForEspruino", function(code, callback) {
if (Espruino.Config.SET_TIME_ON_WRITE) {
var time = new Date();
code = "setTime("+(time.getTime()/1000)+");E.setTimeZone("+(-time.getTimezoneOffset()/60)+")\n"+code;
}
callback(code);
});
}
Espruino.Plugins.SetTime = {
init : init,
};
}());
Espruino.transform = function(code, options) {
return new Promise(function(resolve,reject) {
Object.keys(options).forEach(function(key) {
if (key==key.toUpperCase())
Espruino.Config[key] = options[key];
});
if (options.builtinModules) {
var d = Espruino.Core.Env.getData();
d.MODULES = options.builtinModules;
}
Espruino.callProcessor("transformForEspruino", code, resolve);
});
};
// Finally init everything
jqReady.forEach(function(cb){cb();});