removed jspm_package

This commit is contained in:
casperlamboo 2015-07-15 15:53:37 +02:00
parent ee6fef70d3
commit 13070c96e2
1146 changed files with 0 additions and 150345 deletions

View File

@ -1 +0,0 @@
^0.16.5,^0.16.9

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +0,0 @@
define(["github:components/jquery@2.1.4/jquery"], function(main) {
return main;
});

View File

@ -1 +0,0 @@
build

View File

@ -1 +0,0 @@
7b1d1104656a092423fbfba13c5920e9bbba290c44ca7a5ccba37a3d7d6ab2331f3a6540jspm-github@0.11.10.15

View File

@ -1,37 +0,0 @@
{
"name": "jquery",
"description": "JavaScript library for DOM operations",
"version": "2.1.4",
"homepage": "http://jquery.com",
"author": {
"name": "jQuery Foundation and other contributors",
"url": "https://github.com/jquery/jquery/blob/master/AUTHORS.txt"
},
"repository": {
"type": "git",
"url": "https://github.com/jquery/jquery.git"
},
"keywords": [
"jquery",
"javascript",
"browser",
"library"
],
"bugs": {
"url": "http://bugs.jquery.com"
},
"licenses": [
{
"type": "MIT",
"url": "https://github.com/jquery/jquery/blob/master/MIT-LICENSE.txt"
}
],
"spm": {
"main": "jquery.js"
},
"jspm": {
"main": "jquery"
},
"main": "jquery",
"registry": "github"
}

View File

@ -1,12 +0,0 @@
jQuery Component
================
Shim [repository](https://github.com/components/jquery) for the [jQuery](http://jquery.com).
Package Managers
----------------
* [Bower](http://bower.io/): `jquery`
* [Component](https://github.com/component/component): `components/jquery`
* [Composer](http://packagist.org/packages/components/jquery): `components/jquery`
* [spm](http://spmjs.io/package/jquery): `jquery`

View File

@ -1,11 +0,0 @@
{
"name": "jquery",
"version": "2.1.4",
"description": "jQuery component",
"keywords": [
"jquery",
"component"
],
"main": "jquery.js",
"license": "MIT"
}

View File

@ -1,15 +0,0 @@
{
"name": "jquery",
"repo": "components/jquery",
"version": "2.1.4",
"description": "jQuery component",
"keywords": [
"jquery",
"component"
],
"main": "jquery.js",
"scripts": [
"jquery.js"
],
"license": "MIT"
}

View File

@ -1,33 +0,0 @@
{
"name": "components/jquery",
"description": "jQuery JavaScript Library",
"type": "component",
"homepage": "http://jquery.com",
"license": "MIT",
"support": {
"irc": "irc://irc.freenode.org/jquery",
"issues": "http://bugs.jquery.com",
"forum": "http://forum.jquery.com",
"wiki": "http://docs.jquery.com/",
"source": "https://github.com/jquery/jquery"
},
"authors": [
{
"name": "John Resig",
"email": "jeresig@gmail.com"
}
],
"extra": {
"component": {
"scripts": [
"jquery.js"
],
"files": [
"jquery.min.js",
"jquery.min.map",
"jquery-migrate.js",
"jquery-migrate.min.js"
]
}
}
}

View File

@ -1,521 +0,0 @@
/*!
* jQuery Migrate - v1.2.1 - 2013-05-08
* https://github.com/jquery/jquery-migrate
* Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors; Licensed MIT
*/
(function( jQuery, window, undefined ) {
// See http://bugs.jquery.com/ticket/13335
// "use strict";
var warnedAbout = {};
// List of warnings already given; public read only
jQuery.migrateWarnings = [];
// Set to true to prevent console output; migrateWarnings still maintained
// jQuery.migrateMute = false;
// Show a message on the console so devs know we're active
if ( !jQuery.migrateMute && window.console && window.console.log ) {
window.console.log("JQMIGRATE: Logging is active");
}
// Set to false to disable traces that appear with warnings
if ( jQuery.migrateTrace === undefined ) {
jQuery.migrateTrace = true;
}
// Forget any warnings we've already given; public
jQuery.migrateReset = function() {
warnedAbout = {};
jQuery.migrateWarnings.length = 0;
};
function migrateWarn( msg) {
var console = window.console;
if ( !warnedAbout[ msg ] ) {
warnedAbout[ msg ] = true;
jQuery.migrateWarnings.push( msg );
if ( console && console.warn && !jQuery.migrateMute ) {
console.warn( "JQMIGRATE: " + msg );
if ( jQuery.migrateTrace && console.trace ) {
console.trace();
}
}
}
}
function migrateWarnProp( obj, prop, value, msg ) {
if ( Object.defineProperty ) {
// On ES5 browsers (non-oldIE), warn if the code tries to get prop;
// allow property to be overwritten in case some other plugin wants it
try {
Object.defineProperty( obj, prop, {
configurable: true,
enumerable: true,
get: function() {
migrateWarn( msg );
return value;
},
set: function( newValue ) {
migrateWarn( msg );
value = newValue;
}
});
return;
} catch( err ) {
// IE8 is a dope about Object.defineProperty, can't warn there
}
}
// Non-ES5 (or broken) browser; just set the property
jQuery._definePropertyBroken = true;
obj[ prop ] = value;
}
if ( document.compatMode === "BackCompat" ) {
// jQuery has never supported or tested Quirks Mode
migrateWarn( "jQuery is not compatible with Quirks Mode" );
}
var attrFn = jQuery( "<input/>", { size: 1 } ).attr("size") && jQuery.attrFn,
oldAttr = jQuery.attr,
valueAttrGet = jQuery.attrHooks.value && jQuery.attrHooks.value.get ||
function() { return null; },
valueAttrSet = jQuery.attrHooks.value && jQuery.attrHooks.value.set ||
function() { return undefined; },
rnoType = /^(?:input|button)$/i,
rnoAttrNodeType = /^[238]$/,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
ruseDefault = /^(?:checked|selected)$/i;
// jQuery.attrFn
migrateWarnProp( jQuery, "attrFn", attrFn || {}, "jQuery.attrFn is deprecated" );
jQuery.attr = function( elem, name, value, pass ) {
var lowerName = name.toLowerCase(),
nType = elem && elem.nodeType;
if ( pass ) {
// Since pass is used internally, we only warn for new jQuery
// versions where there isn't a pass arg in the formal params
if ( oldAttr.length < 4 ) {
migrateWarn("jQuery.fn.attr( props, pass ) is deprecated");
}
if ( elem && !rnoAttrNodeType.test( nType ) &&
(attrFn ? name in attrFn : jQuery.isFunction(jQuery.fn[name])) ) {
return jQuery( elem )[ name ]( value );
}
}
// Warn if user tries to set `type`, since it breaks on IE 6/7/8; by checking
// for disconnected elements we don't warn on $( "<button>", { type: "button" } ).
if ( name === "type" && value !== undefined && rnoType.test( elem.nodeName ) && elem.parentNode ) {
migrateWarn("Can't change the 'type' of an input or button in IE 6/7/8");
}
// Restore boolHook for boolean property/attribute synchronization
if ( !jQuery.attrHooks[ lowerName ] && rboolean.test( lowerName ) ) {
jQuery.attrHooks[ lowerName ] = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" &&
( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// Warn only for attributes that can remain distinct from their properties post-1.9
if ( ruseDefault.test( lowerName ) ) {
migrateWarn( "jQuery.fn.attr('" + lowerName + "') may use property instead of attribute" );
}
}
return oldAttr.call( jQuery, elem, name, value );
};
// attrHooks: value
jQuery.attrHooks.value = {
get: function( elem, name ) {
var nodeName = ( elem.nodeName || "" ).toLowerCase();
if ( nodeName === "button" ) {
return valueAttrGet.apply( this, arguments );
}
if ( nodeName !== "input" && nodeName !== "option" ) {
migrateWarn("jQuery.fn.attr('value') no longer gets properties");
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value ) {
var nodeName = ( elem.nodeName || "" ).toLowerCase();
if ( nodeName === "button" ) {
return valueAttrSet.apply( this, arguments );
}
if ( nodeName !== "input" && nodeName !== "option" ) {
migrateWarn("jQuery.fn.attr('value', val) no longer sets properties");
}
// Does not return so that setAttribute is also used
elem.value = value;
}
};
var matched, browser,
oldInit = jQuery.fn.init,
oldParseJSON = jQuery.parseJSON,
// Note: XSS check is done below after string is trimmed
rquickExpr = /^([^<]*)(<[\w\W]+>)([^>]*)$/;
// $(html) "looks like html" rule change
jQuery.fn.init = function( selector, context, rootjQuery ) {
var match;
if ( selector && typeof selector === "string" && !jQuery.isPlainObject( context ) &&
(match = rquickExpr.exec( jQuery.trim( selector ) )) && match[ 0 ] ) {
// This is an HTML string according to the "old" rules; is it still?
if ( selector.charAt( 0 ) !== "<" ) {
migrateWarn("$(html) HTML strings must start with '<' character");
}
if ( match[ 3 ] ) {
migrateWarn("$(html) HTML text after last tag is ignored");
}
// Consistently reject any HTML-like string starting with a hash (#9521)
// Note that this may break jQuery 1.6.x code that otherwise would work.
if ( match[ 0 ].charAt( 0 ) === "#" ) {
migrateWarn("HTML string cannot start with a '#' character");
jQuery.error("JQMIGRATE: Invalid selector string (XSS)");
}
// Now process using loose rules; let pre-1.8 play too
if ( context && context.context ) {
// jQuery object as context; parseHTML expects a DOM object
context = context.context;
}
if ( jQuery.parseHTML ) {
return oldInit.call( this, jQuery.parseHTML( match[ 2 ], context, true ),
context, rootjQuery );
}
}
return oldInit.apply( this, arguments );
};
jQuery.fn.init.prototype = jQuery.fn;
// Let $.parseJSON(falsy_value) return null
jQuery.parseJSON = function( json ) {
if ( !json && json !== null ) {
migrateWarn("jQuery.parseJSON requires a valid JSON string");
return null;
}
return oldParseJSON.apply( this, arguments );
};
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
// Don't clobber any existing jQuery.browser in case it's different
if ( !jQuery.browser ) {
matched = jQuery.uaMatch( navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
}
// Warn if the code tries to get jQuery.browser
migrateWarnProp( jQuery, "browser", jQuery.browser, "jQuery.browser is deprecated" );
jQuery.sub = function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
migrateWarn( "jQuery.sub() is deprecated" );
return jQuerySub;
};
// Ensure that $.ajax gets the new parseJSON defined in core.js
jQuery.ajaxSetup({
converters: {
"text json": jQuery.parseJSON
}
});
var oldFnData = jQuery.fn.data;
jQuery.fn.data = function( name ) {
var ret, evt,
elem = this[0];
// Handles 1.7 which has this behavior and 1.8 which doesn't
if ( elem && name === "events" && arguments.length === 1 ) {
ret = jQuery.data( elem, name );
evt = jQuery._data( elem, name );
if ( ( ret === undefined || ret === evt ) && evt !== undefined ) {
migrateWarn("Use of jQuery.fn.data('events') is deprecated");
return evt;
}
}
return oldFnData.apply( this, arguments );
};
var rscriptType = /\/(java|ecma)script/i,
oldSelf = jQuery.fn.andSelf || jQuery.fn.addBack;
jQuery.fn.andSelf = function() {
migrateWarn("jQuery.fn.andSelf() replaced by jQuery.fn.addBack()");
return oldSelf.apply( this, arguments );
};
// Since jQuery.clean is used internally on older versions, we only shim if it's missing
if ( !jQuery.clean ) {
jQuery.clean = function( elems, context, fragment, scripts ) {
// Set context per 1.8 logic
context = context || document;
context = !context.nodeType && context[0] || context;
context = context.ownerDocument || context;
migrateWarn("jQuery.clean() is deprecated");
var i, elem, handleScript, jsTags,
ret = [];
jQuery.merge( ret, jQuery.buildFragment( elems, context ).childNodes );
// Complex logic lifted directly from jQuery 1.8
if ( fragment ) {
// Special handling of each script element
handleScript = function( elem ) {
// Check if we consider it executable
if ( !elem.type || rscriptType.test( elem.type ) ) {
// Detach the script and store it in the scripts array (if provided) or the fragment
// Return truthy to indicate that it has been handled
return scripts ?
scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) :
fragment.appendChild( elem );
}
};
for ( i = 0; (elem = ret[i]) != null; i++ ) {
// Check if we're done after handling an executable script
if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) {
// Append to fragment and handle embedded scripts
fragment.appendChild( elem );
if ( typeof elem.getElementsByTagName !== "undefined" ) {
// handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration
jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript );
// Splice the scripts into ret after their former ancestor and advance our index beyond them
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
i += jsTags.length;
}
}
}
}
return ret;
};
}
var eventAdd = jQuery.event.add,
eventRemove = jQuery.event.remove,
eventTrigger = jQuery.event.trigger,
oldToggle = jQuery.fn.toggle,
oldLive = jQuery.fn.live,
oldDie = jQuery.fn.die,
ajaxEvents = "ajaxStart|ajaxStop|ajaxSend|ajaxComplete|ajaxError|ajaxSuccess",
rajaxEvent = new RegExp( "\\b(?:" + ajaxEvents + ")\\b" ),
rhoverHack = /(?:^|\s)hover(\.\S+|)\b/,
hoverHack = function( events ) {
if ( typeof( events ) !== "string" || jQuery.event.special.hover ) {
return events;
}
if ( rhoverHack.test( events ) ) {
migrateWarn("'hover' pseudo-event is deprecated, use 'mouseenter mouseleave'");
}
return events && events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
// Event props removed in 1.9, put them back if needed; no practical way to warn them
if ( jQuery.event.props && jQuery.event.props[ 0 ] !== "attrChange" ) {
jQuery.event.props.unshift( "attrChange", "attrName", "relatedNode", "srcElement" );
}
// Undocumented jQuery.event.handle was "deprecated" in jQuery 1.7
if ( jQuery.event.dispatch ) {
migrateWarnProp( jQuery.event, "handle", jQuery.event.dispatch, "jQuery.event.handle is undocumented and deprecated" );
}
// Support for 'hover' pseudo-event and ajax event warnings
jQuery.event.add = function( elem, types, handler, data, selector ){
if ( elem !== document && rajaxEvent.test( types ) ) {
migrateWarn( "AJAX events should be attached to document: " + types );
}
eventAdd.call( this, elem, hoverHack( types || "" ), handler, data, selector );
};
jQuery.event.remove = function( elem, types, handler, selector, mappedTypes ){
eventRemove.call( this, elem, hoverHack( types ) || "", handler, selector, mappedTypes );
};
jQuery.fn.error = function() {
var args = Array.prototype.slice.call( arguments, 0);
migrateWarn("jQuery.fn.error() is deprecated");
args.splice( 0, 0, "error" );
if ( arguments.length ) {
return this.bind.apply( this, args );
}
// error event should not bubble to window, although it does pre-1.7
this.triggerHandler.apply( this, args );
return this;
};
jQuery.fn.toggle = function( fn, fn2 ) {
// Don't mess with animation or css toggles
if ( !jQuery.isFunction( fn ) || !jQuery.isFunction( fn2 ) ) {
return oldToggle.apply( this, arguments );
}
migrateWarn("jQuery.fn.toggle(handler, handler...) is deprecated");
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
};
jQuery.fn.live = function( types, data, fn ) {
migrateWarn("jQuery.fn.live() is deprecated");
if ( oldLive ) {
return oldLive.apply( this, arguments );
}
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
};
jQuery.fn.die = function( types, fn ) {
migrateWarn("jQuery.fn.die() is deprecated");
if ( oldDie ) {
return oldDie.apply( this, arguments );
}
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
};
// Turn global events into document-triggered events
jQuery.event.trigger = function( event, data, elem, onlyHandlers ){
if ( !elem && !rajaxEvent.test( event ) ) {
migrateWarn( "Global events are undocumented and deprecated" );
}
return eventTrigger.call( this, event, data, elem || document, onlyHandlers );
};
jQuery.each( ajaxEvents.split("|"),
function( _, name ) {
jQuery.event.special[ name ] = {
setup: function() {
var elem = this;
// The document needs no shimming; must be !== for oldIE
if ( elem !== document ) {
jQuery.event.add( document, name + "." + jQuery.guid, function() {
jQuery.event.trigger( name, null, elem, true );
});
jQuery._data( this, name, jQuery.guid++ );
}
return false;
},
teardown: function() {
if ( this !== document ) {
jQuery.event.remove( document, name + "." + jQuery._data( this, name ) );
}
return false;
}
};
}
);
})( jQuery, window );

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,33 +0,0 @@
{
"name": "jquery",
"description": "JavaScript library for DOM operations",
"version": "2.1.4",
"homepage": "http://jquery.com",
"author": {
"name": "jQuery Foundation and other contributors",
"url": "https://github.com/jquery/jquery/blob/master/AUTHORS.txt"
},
"repository": {
"type": "git",
"url": "https://github.com/jquery/jquery.git"
},
"keywords": [
"jquery",
"javascript",
"browser",
"library"
],
"bugs": {
"url": "http://bugs.jquery.com"
},
"licenses": [
{
"type": "MIT",
"url": "https://github.com/jquery/jquery/blob/master/MIT-LICENSE.txt"
}
],
"spm": {
"main": "jquery.js"
}
}

View File

@ -1 +0,0 @@
module.exports = require("github:jspm/nodelibs-fs@0.1.2/index");

View File

@ -1 +0,0 @@
e295454174ed9e95b9383f8184859d76c610d19c99914b932bd37a50b983c5e7c90ae93bjspm-github@0.11.10.15

View File

@ -1,8 +0,0 @@
{
"registry": "npm",
"format": "cjs",
"ignore": [
"node_modules"
],
"dependencies": {}
}

View File

@ -1,25 +0,0 @@
/* */
if (System._nodeRequire) {
module.exports = System._nodeRequire('fs');
}
else {
exports.readFileSync = function(address) {
var output;
var xhr = new XMLHttpRequest();
xhr.open('GET', address, false);
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4) {
var status = xhr.status;
if ((status > 399 && status < 600) || status == 400) {
throw 'File read error on ' + address;
}
else
output = xhr.responseText;
}
}
xhr.send(null);
return output;
};
}

View File

@ -1,3 +0,0 @@
{
"registry": "npm"
}

View File

@ -1 +0,0 @@
module.exports = require("github:jspm/nodelibs-process@0.1.1/index");

View File

@ -1 +0,0 @@
2dd9498d7e5ce134e4ff9dd41319cda4e31f993c99914b932bd37a50b983c5e7c90ae93bjspm-github@0.11.10.15

View File

@ -1,6 +0,0 @@
{
"registry": "jspm",
"dependencies": {
"process": "npm:process@^0.10.0"
}
}

View File

@ -1 +0,0 @@
module.exports = System._nodeRequire ? process : require('process');

View File

@ -1,6 +0,0 @@
{
"registry": "jspm",
"dependencies": {
"process": "npm:process@^0.10.0"
}
}

View File

@ -1 +0,0 @@
module.exports = require("github:systemjs/plugin-json@0.1.0/json");

View File

@ -1 +0,0 @@
476c01034237dfec4dec8c94a59e3bd0750bdf0399914b932bd37a50b983c5e7c90ae93bjspm-github@0.11.10.15

View File

@ -1,4 +0,0 @@
{
"main": "json",
"registry": "github"
}

View File

@ -1,20 +0,0 @@
The MIT License (MIT)
Copyright (c) 2013 jspm
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.

View File

@ -1,4 +0,0 @@
plugin-json
===========
JSON loader plugin

View File

@ -1,6 +0,0 @@
/*
JSON plugin
*/
exports.translate = function(load) {
return 'module.exports = ' + load.source;
}

View File

@ -1,3 +0,0 @@
{
"some": "json"
}

View File

@ -1,3 +0,0 @@
{
"main": "json"
}

View File

@ -1,5 +0,0 @@
<script src="../es6-module-loader/dist/es6-module-loader.js"></script>
<script src="../systemjs/dist/system.js"></script>
<script>
System.import('json.json!').then(console.log.bind(console));
</script>

View File

@ -1 +0,0 @@
module.exports = require("npm:babel-core@5.6.20/browser");

View File

@ -1 +0,0 @@
d82d01487ecc8ed3134b28710afd8aabf2b597362615f3cffc60555b3aeaacf1dd14b06ejspm-npm@0.210.15

View File

@ -1,96 +0,0 @@
{
"name": "babel-core",
"description": "A compiler for writing next generation JavaScript",
"version": "5.6.20",
"author": {
"name": "Sebastian McKenzie",
"email": "sebmck@gmail.com"
},
"homepage": "https://babeljs.io/",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel"
},
"browser": {
"./lib/babel/api/register/node.js": "./lib/babel/api/register/browser.js"
},
"keywords": [
"6to5",
"babel",
"classes",
"const",
"es6",
"harmony",
"let",
"modules",
"transpile",
"transpiler",
"var"
],
"scripts": {
"bench": "make bench",
"test": "make test"
},
"devDependencies": {
"babel": "5.6.10",
"babel-eslint": "^3.1.19",
"browserify": "^9.0.8",
"chai": "^2.2.0",
"eslint": "^0.21.2",
"esvalid": "^1.1.0",
"istanbul": "^0.3.5",
"matcha": "^0.6.0",
"mocha": "2.2.0",
"rimraf": "^2.3.2",
"uglify-js": "^2.4.16"
},
"gitHead": "d28716cf9377c331b40205d1be8119c6591d2403",
"bugs": {
"url": "https://github.com/babel/babel/issues"
},
"_id": "babel-core@5.6.20",
"_shasum": "d82d01487ecc8ed3134b28710afd8aabf2b59736",
"_from": ".",
"_npmVersion": "1.4.28",
"_npmUser": {
"name": "sebmck",
"email": "sebmck@gmail.com"
},
"maintainers": [
{
"name": "sebmck",
"email": "sebmck@gmail.com"
}
],
"dist": {
"shasum": "d82d01487ecc8ed3134b28710afd8aabf2b59736",
"tarball": "http://registry.npmjs.org/babel-core/-/babel-core-5.6.20.tgz"
},
"directories": {},
"jspm": {
"main": "browser.js",
"dependencies": {},
"jspmNodeConversion": false,
"shim": {
"browser": {
"exports": "babel"
}
},
"map": {
"regenerator/runtime": "babel-runtime/regenerator/runtime"
}
},
"main": "browser.js",
"jspmNodeConversion": false,
"shim": {
"browser": {
"exports": "babel"
}
},
"map": {
"regenerator/runtime": "babel-runtime/regenerator/runtime"
},
"registry": "npm",
"dependencies": {}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,13 +0,0 @@
# Contributor Code of Conduct
As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, age, or religion.
Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)

View File

@ -1,180 +0,0 @@
# NOTE: BEFORE OPENING AN ISSUE PLEASE SEE THE [README](https://github.com/babel/babel#readme).
----
<p align="center">
<strong><a href="#setup">Setup</a></strong>
|
<strong><a href="#running-tests">Running tests</a></strong>
|
<strong><a href="#workflow">Workflow</a></strong>
|
<strong><a href="#dependencies">Dependencies</a></strong>
|
<strong><a href="#code-standards">Code Standards</a></strong>
|
<strong><a href="#internals">Internals</a></strong>
</p>
----
# Contributing
Contributions are always welcome, no matter how large or small. Before
contributing, please read the
[code of conduct](https://github.com/babel/babel/blob/master/CODE_OF_CONDUCT.md).
## Developing
> Note: Babel moves fast. Only the latest release is guaranteed to build correctly.
> Older releases are not officially supported. If you attempt to build them, do that at your own risk.
#### Setup
```sh
$ git clone https://github.com/babel/babel
$ cd babel
$ make bootstrap
```
Then you can either run:
```sh
$ make build-core
```
to build Babel **once** or:
```sh
$ make watch-core
```
to have Babel build itself then incrementally build files on change.
#### Running tests
You can run tests via:
```sh
$ make test
```
This is mostly overkill and you can limit the tests to a select few by directly
running them with `mocha`:
```sh
$ mocha test/core/transformation.js
```
Use mocha's `--grep` option to run a subset of tests by name:
```sh
$ mocha test/core/transformation.js --grep es7
```
If you don't have `mocha` installed globally, you can still use it from Babel's
dependencies in `node_modules`, but make sure `node_modules/.bin` is added to
your [`$PATH`](http://unix.stackexchange.com/questions/26047/how-to-correctly-add-a-path-to-path) environment variable.
#### Workflow
* Fork the repository
* Clone your fork and change directory to it (`git clone git@github.com:yourUserName/babel.git && cd babel`)
* Install the project dependencies (`make bootstrap`)
* Link your forked clone (`npm link`)
* Develop your changes ensuring you're fetching updates from upstream often
* Ensure the test are passing (`make test`)
* Create new pull request explaining your proposed change or reference an issue in your commit message
#### Dependencies
+ [ast-types](http://ghub.io/ast-types) This is required to monkeypatch regenerators AST definitions. Could be improved in the future.
+ [chalk](http://ghub.io/chalk) This is used for terminal color highlighting for syntax errors.
+ [convert-source-map](http://ghub.io/convert-source-map) Turns a source map object into a comment etc.
+ [core-js](http://ghub.io/core-js) Used for the polyfill.
+ [debug](http://ghub.io/debug) Used to output debugging information when NODE_DEBUG is set to babel.
+ [detect-indent](http://ghub.io/detect-indent) This is used in the code generator so it can infer indentation.
+ [estraverse](http://ghub.io/estraverse) The only method on this is attachComments. I'd like to implement our own comment attachment algorithm eventually though.
+ [esutils](http://ghub.io/esutils) Various ES related utilities. Check whether something is a keyword etc.
+ [fs-readdir-recursive](http://ghub.io/fs-readdir-recursive) Recursively search a directory for.
+ [globals](http://ghub.io/globals) A list of JavaScript global variables. This is used by the scope tracking to check for colliding variables.
+ [is-integer](http://ghub.io/is-integer) Checks if something is an integer.
+ [js-tokens](http://ghub.io/js-tokens) This is used to get tokens for syntax error highlighting.
+ [line-numbers](http://ghub.io/line-numbers) Used to produce the code frames in syntax errors.
+ [lodash](http://ghub.io/lodash) Used for various utilities.
+ [minimatch](http://ghub.io/minimatch) This is used to match glob-style ignore/only filters.
+ [output-file-sync](http://ghub.io/output-file-sync) Synchronously writes a file and create its ancestor directories if needed.
+ [path-is-absolute](http://ghub.io/path-is-absolute) Checks if a path is absolute. C:\foo and \foo are considered absolute.
+ [regenerator](http://ghub.io/regenerator) This is used to transform generators/async functions.
+ [regexpu](http://ghub.io/regexpu) Used to transform unicode regex patterns.
+ [repeating](http://ghub.io/repeating) Repeats a string.
+ [shebang-regex](http://ghub.io/shebang-regex) Literally just a regex that matches shebangs.
+ [slash](http://ghub.io/slash) Normalises path separators.
+ [source-map](http://ghub.io/source-map) Generates sourcemaps.
+ [source-map-support](http://ghub.io/source-map-support) Adds source map support to babel-node/babel/register.
+ [strip-json-comments](http://ghub.io/strip-json-comments) Remove comments from a JSON string. This is used for .babelrc files.
+ [to-fast-properties](http://ghub.io/to-fast-properties) A V8 trick to put an object into fast properties mode.
+ [trim-right](http://ghub.io/trim-right) Trims the rightside whitespace.
+ [path-exists](https://www.npmjs.com/package/path-exists) Checks if a path exists. (replaces the deprecated `fs.exists` methods)
+ [home-or-tmp](https://github.com/sindresorhus/home-or-tmp) Gets the user home directory with fallback to the system temporary directory. This is used to resolve the babel-node/babel/register cache.
+ [resolve](https://www.npmjs.com/package/resolve) Implements the [`require.resolve()` algorithm](http://nodejs.org/docs/v0.12.0/api/all.html#all_require_resolve) such that we can `require.resolve()` on behalf of a file asynchronously and synchronously.
#### Code Standards
* **General**
* Max of five arguments for functions
* Max depth of four nested blocks
* 2-spaced soft tabs
* **Naming**
* CamelCase all class names
* camelBack all variable names
* **Spacing**
* Spaces after all keywords
* Spaces before all left curly braces
* **Comments**
* Use JSDoc-style comments for methods
* Single-line comments for ambiguous code
* **Quotes**
* Always use double quotes
* Only use single quotes when the string contains a double quote
* **Declaration**
* No unused variables
* No pollution of global variables and prototypes
#### Internals
Please see [`/doc`](/doc) for internals documentation relevant to developing babel.

View File

@ -1,22 +0,0 @@
Copyright (c) 2014-2015 Sebastian McKenzie <sebmck@gmail.com>
MIT License
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.

View File

@ -1,30 +0,0 @@
<p align="center">
<a href="https://babeljs.io/">
<img alt="babel" src="https://raw.githubusercontent.com/babel/logo/master/babel.png" width="546">
</a>
</p>
<p align="center">
The compiler for writing next generation JavaScript.
</p>
<p align="center">
<a href="https://travis-ci.org/babel/babel"><img alt="Build Status" src="https://img.shields.io/travis/babel/babel.svg?style=flat"></a>
<a href="http://badge.fury.io/js/babel-core"><img alt="npm version" src="https://badge.fury.io/js/babel-core.svg"></a>
<a href="https://npmjs.org/package/babel-core"><img alt="Downloads" src="http://img.shields.io/npm/dm/babel-core.svg"></a>
</p>
<p align="center">
<a href="http://issuestats.com/github/babel/babel"><img alt="Issue Stats" src="http://issuestats.com/github/babel/babel/badge/pr?style=flat"></a>
<a href="http://issuestats.com/github/babel/babel"><img alt="Issue Stats" src="http://issuestats.com/github/babel/babel/badge/issue?style=flat"></a>
</p>
----
<p align="center">
For questions and support please visit the <a href="https://babel-slack.herokuapp.com">Slack community</a> or <a href="http://stackoverflow.com/questions/tagged/babeljs">StackOverflow</a>. The Babel issue tracker is <strong>exclusively</strong> for bug reports and feature requests.
</p>
<p align="center">
For documentation and website issues please visit the <a href="https://github.com/babel/babel.github.io">babel.github.io</a> repo.
</p>

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,4 +0,0 @@
This is a collection of documentation about babel internals, for use in development of babel.
# [Properties of nodes](/doc/node-props.md)
These are properties babel stores in AST node objects for internal use, as opposed to properties that are part of the AST spec (ESTree at the time of this writing).

View File

@ -1,11 +0,0 @@
# Properties of nodes
These are properties babel stores in AST node objects for internal use, as opposed to properties that are part of the AST spec ([ESTree](https://github.com/estree/estree) at the time of this writing).
## `_blockHoist`
`node._blockHoist != null` triggers the [block-hoist transformer](/src/babel/transformation/transformers/internal/block-hoist.js). Value should be `true` or an integer in the range `0..3`. `true` is equivalent to `2`. The value indicates whether the node should be hoisted and to what degree. See the source code for more detailed information.
## `_paths`
Stores a representation of a node's position in the tree and relationship to other nodes.
## `shadow`
A truthy value on a function node triggers the [shadow-functions transformer](/src/babel/transformation/transformers/internal/shadow-functions.js), which transforms the node so that it references (or inherits) `arguments` and the `this` context from the parent scope. It is invoked for arrow functions, for example.

View File

@ -1,416 +0,0 @@
/* */
"format global";
(function (global) {
var babelHelpers = global.babelHelpers = {};
babelHelpers.inherits = function (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) subClass.__proto__ = superClass;
};
babelHelpers.defaults = function (obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = Object.getOwnPropertyDescriptor(defaults, key);
if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}
return obj;
};
babelHelpers.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;
};
})();
babelHelpers.createDecoratedClass = (function () {
function defineProperties(target, descriptors, initializers) {
for (var i = 0; i < descriptors.length; i++) {
var descriptor = descriptors[i];
var decorators = descriptor.decorators;
var key = descriptor.key;
delete descriptor.key;
delete descriptor.decorators;
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor || descriptor.initializer) descriptor.writable = true;
if (decorators) {
for (var f = 0; f < decorators.length; f++) {
var decorator = decorators[f];
if (typeof decorator === "function") {
descriptor = decorator(target, key, descriptor) || descriptor;
} else {
throw new TypeError("The decorator for method " + descriptor.key + " is of the invalid type " + typeof decorator);
}
}
if (descriptor.initializer !== undefined) {
initializers[key] = descriptor;
continue;
}
}
Object.defineProperty(target, key, descriptor);
}
}
return function (Constructor, protoProps, staticProps, protoInitializers, staticInitializers) {
if (protoProps) defineProperties(Constructor.prototype, protoProps, protoInitializers);
if (staticProps) defineProperties(Constructor, staticProps, staticInitializers);
return Constructor;
};
})();
babelHelpers.createDecoratedObject = function (descriptors) {
var target = {};
for (var i = 0; i < descriptors.length; i++) {
var descriptor = descriptors[i];
var decorators = descriptor.decorators;
var key = descriptor.key;
delete descriptor.key;
delete descriptor.decorators;
descriptor.enumerable = true;
descriptor.configurable = true;
if ("value" in descriptor || descriptor.initializer) descriptor.writable = true;
if (decorators) {
for (var f = 0; f < decorators.length; f++) {
var decorator = decorators[f];
if (typeof decorator === "function") {
descriptor = decorator(target, key, descriptor) || descriptor;
} else {
throw new TypeError("The decorator for method " + descriptor.key + " is of the invalid type " + typeof decorator);
}
}
}
if (descriptor.initializer) {
descriptor.value = descriptor.initializer.call(target);
}
Object.defineProperty(target, key, descriptor);
}
return target;
};
babelHelpers.defineDecoratedPropertyDescriptor = function (target, key, descriptors) {
var _descriptor = descriptors[key];
if (!_descriptor) return;
var descriptor = {};
for (var _key in _descriptor) descriptor[_key] = _descriptor[_key];
descriptor.value = descriptor.initializer.call(target);
Object.defineProperty(target, key, descriptor);
};
babelHelpers.taggedTemplateLiteral = function (strings, raw) {
return Object.freeze(Object.defineProperties(strings, {
raw: {
value: Object.freeze(raw)
}
}));
};
babelHelpers.taggedTemplateLiteralLoose = function (strings, raw) {
strings.raw = raw;
return strings;
};
babelHelpers.toArray = function (arr) {
return Array.isArray(arr) ? arr : Array.from(arr);
};
babelHelpers.toConsumableArray = function (arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
} else {
return Array.from(arr);
}
};
babelHelpers.slicedToArray = (function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
})();
babelHelpers.slicedToArrayLoose = function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
var _arr = [];
for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) {
_arr.push(_step.value);
if (i && _arr.length === i) break;
}
return _arr;
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
babelHelpers.objectWithoutProperties = function (obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
};
babelHelpers.hasOwn = Object.prototype.hasOwnProperty;
babelHelpers.slice = Array.prototype.slice;
babelHelpers.bind = Function.prototype.bind;
babelHelpers.defineProperty = function (obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
babelHelpers.asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
var callNext = step.bind(null, "next");
var callThrow = step.bind(null, "throw");
function step(key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(callNext, callThrow);
}
}
callNext();
});
};
};
babelHelpers.interopRequireWildcard = function (obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
}
newObj["default"] = obj;
return newObj;
}
};
babelHelpers.interopRequireDefault = function (obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
};
babelHelpers._typeof = function (obj) {
return obj && obj.constructor === Symbol ? "symbol" : typeof obj;
};
babelHelpers._extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
babelHelpers.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);
}
};
babelHelpers.set = function set(object, property, value, receiver) {
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent !== null) {
set(parent, property, value, receiver);
}
} else if ("value" in desc && desc.writable) {
desc.value = value;
} else {
var setter = desc.set;
if (setter !== undefined) {
setter.call(receiver, value);
}
}
return value;
};
babelHelpers.classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
babelHelpers.objectDestructuringEmpty = function (obj) {
if (obj == null) throw new TypeError("Cannot destructure undefined");
};
babelHelpers.temporalUndefined = {};
babelHelpers.temporalAssertDefined = function (val, name, undef) {
if (val === undef) {
throw new ReferenceError(name + " is not defined - temporal dead zone");
}
return true;
};
babelHelpers.selfGlobal = typeof global === "undefined" ? self : global;
babelHelpers.defaultProps = function (defaultProps, props) {
if (defaultProps) {
for (var propName in defaultProps) {
if (typeof props[propName] === "undefined") {
props[propName] = defaultProps[propName];
}
}
}
return props;
};
babelHelpers._instanceof = function (left, right) {
if (right != null && right[Symbol.hasInstance]) {
return right[Symbol.hasInstance](left);
} else {
return left instanceof right;
}
};
babelHelpers.interopRequire = function (obj) {
return obj && obj.__esModule ? obj["default"] : obj;
};
})(typeof global === "undefined" ? self : global);

File diff suppressed because one or more lines are too long

View File

@ -1,3 +0,0 @@
/* */
"format cjs";
module.exports = require("./lib/babel/api/node.js");

View File

@ -1,27 +0,0 @@
## Welcome to the Babel Codebase
Babel is broken down into three parts:
- Parsing
- [Transformation](babel/transformation/)
- [Generation](babel/generation/)
**Parsing** is the process of turning a piece of code into an [ESTree spec](https://github.com/estree/estree) compatible AST (Abstract
Syntax Tree) which is a tree-like object of nodes that _describes_ the code.
This makes it easier to transform the code over direct string manpulation.
**Transformation** is the process of taking an AST and manipulating it into
a new one. For example, Babel might take an ES2015 ArrowFunction and transform
it into a normal Function which will work in ES5 environments.
**Generation** is the process of turning an AST back into code. After Babel is
done transforming the AST, the generation takes over to return normal code.
---
Babel's parsing step is done by [Acorn](https://github.com/marijnh/acorn). However, because Babel is implementing
future standards it maintains a [fork of Acorn](acorn/) in order to do it's job. You can
see that fork in the "acorn" folder.
The transformation and generation steps are both handled inside of the Babel
codebase itself, which is in the "babel" folder here.

View File

@ -1,32 +0,0 @@
List of Acorn contributors. Updated before every release.
Alistair Braidwood
Aparajita Fishman
Arian Stolwijk
Artem Govorov
Brandon Mills
Charles Hughes
Conrad Irwin
David Bonnet
impinball
Ingvar Stepanyan
Jiaxing Wang
Johannes Herr
Jürg Lehni
keeyipchan
krator
Marijn Haverbeke
Martin Carlberg
Mathias Bynens
Mathieu 'p01' Henri
Max Schaefer
Mihai Bazon
Mike Rennie
Oskar Schöldström
Paul Harper
Peter Rust
PlNG
r-e-d
Rich Harris
Sebastian McKenzie
zsjforcn

View File

@ -1,19 +0,0 @@
Copyright (C) 2012-2014 by various contributors (see AUTHORS)
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.

View File

@ -1,31 +0,0 @@
/* */
"format cjs";
"use strict";
var _babelToolsProtectJs2 = require("./../babel/tools/protect.js");
var _babelToolsProtectJs3 = _interopRequireDefault(_babelToolsProtectJs2);
exports.__esModule = true;
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } }
require("./plugins/flow");
var _acornJsxInject = require("acorn-jsx/inject");
var _acornJsxInject2 = _interopRequireDefault(_acornJsxInject);
var _srcIndex = require("./src/index");
var acorn = _interopRequireWildcard(_srcIndex);
_babelToolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
_defaults(exports, _interopRequireWildcard(_srcIndex));
_acornJsxInject2["default"](acorn);

View File

@ -1,44 +0,0 @@
{
"name": "acorn",
"description": "ECMAScript parser",
"homepage": "https://github.com/marijnh/acorn",
"main": "index.js",
"version": "1.0.0",
"engines": {
"node": ">=0.4.0"
},
"maintainers": [
{
"name": "Marijn Haverbeke",
"email": "marijnh@gmail.com",
"web": "http://marijnhaverbeke.nl"
},
{
"name": "Ingvar Stepanyan",
"email": "me@rreverser.com",
"web": "http://rreverser.com/"
}
],
"repository": {
"type": "git",
"url": "https://github.com/marijnh/acorn.git"
},
"licenses": [
{
"type": "MIT",
"url": "https://raw.githubusercontent.com/marijnh/acorn/master/LICENSE"
}
],
"scripts": {
"test": "node test/run.js",
"prepublish": "node bin/prepublish.sh"
},
"bin": {
"acorn": "./bin/acorn"
},
"devDependencies": {
"babelify": "^5.0.4",
"browserify": "^9.0.3",
"unicode-7.0.0": "~0.1.5"
}
}

View File

@ -1,832 +0,0 @@
/* */
"format cjs";
"use strict";
var _babelToolsProtectJs2 = require("./../../babel/tools/protect.js");
var _babelToolsProtectJs3 = _interopRequireDefault(_babelToolsProtectJs2);
_babelToolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var acorn = require("../src/index");
var pp = acorn.Parser.prototype;
var tt = acorn.tokTypes;
pp.isRelational = function (op) {
return this.type === tt.relational && this.value === op;
};
pp.expectRelational = function (op) {
if (this.isRelational(op)) {
this.next();
} else {
this.unexpected();
}
};
pp.flow_parseTypeInitialiser = function (tok) {
var oldInType = this.inType;
this.inType = true;
this.expect(tok || tt.colon);
var type = this.flow_parseType();
this.inType = oldInType;
return type;
};
pp.flow_parseDeclareClass = function (node) {
this.next();
this.flow_parseInterfaceish(node, true);
return this.finishNode(node, "DeclareClass");
};
pp.flow_parseDeclareFunction = function (node) {
this.next();
var id = node.id = this.parseIdent();
var typeNode = this.startNode();
var typeContainer = this.startNode();
if (this.isRelational("<")) {
typeNode.typeParameters = this.flow_parseTypeParameterDeclaration();
} else {
typeNode.typeParameters = null;
}
this.expect(tt.parenL);
var tmp = this.flow_parseFunctionTypeParams();
typeNode.params = tmp.params;
typeNode.rest = tmp.rest;
this.expect(tt.parenR);
typeNode.returnType = this.flow_parseTypeInitialiser();
typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
this.finishNode(id, id.type);
this.semicolon();
return this.finishNode(node, "DeclareFunction");
};
pp.flow_parseDeclare = function (node) {
if (this.type === tt._class) {
return this.flow_parseDeclareClass(node);
} else if (this.type === tt._function) {
return this.flow_parseDeclareFunction(node);
} else if (this.type === tt._var) {
return this.flow_parseDeclareVariable(node);
} else if (this.isContextual("module")) {
return this.flow_parseDeclareModule(node);
} else {
this.unexpected();
}
};
pp.flow_parseDeclareVariable = function (node) {
this.next();
node.id = this.flow_parseTypeAnnotatableIdentifier();
this.semicolon();
return this.finishNode(node, "DeclareVariable");
};
pp.flow_parseDeclareModule = function (node) {
this.next();
if (this.type === tt.string) {
node.id = this.parseExprAtom();
} else {
node.id = this.parseIdent();
}
var bodyNode = node.body = this.startNode();
var body = bodyNode.body = [];
this.expect(tt.braceL);
while (this.type !== tt.braceR) {
var node2 = this.startNode();
// todo: declare check
this.next();
body.push(this.flow_parseDeclare(node2));
}
this.expect(tt.braceR);
this.finishNode(bodyNode, "BlockStatement");
return this.finishNode(node, "DeclareModule");
};
// Interfaces
pp.flow_parseInterfaceish = function (node, allowStatic) {
node.id = this.parseIdent();
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterDeclaration();
} else {
node.typeParameters = null;
}
node["extends"] = [];
if (this.eat(tt._extends)) {
do {
node["extends"].push(this.flow_parseInterfaceExtends());
} while (this.eat(tt.comma));
}
node.body = this.flow_parseObjectType(allowStatic);
};
pp.flow_parseInterfaceExtends = function () {
var node = this.startNode();
node.id = this.parseIdent();
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterInstantiation();
} else {
node.typeParameters = null;
}
return this.finishNode(node, "InterfaceExtends");
};
pp.flow_parseInterface = function (node) {
this.flow_parseInterfaceish(node, false);
return this.finishNode(node, "InterfaceDeclaration");
};
// Type aliases
pp.flow_parseTypeAlias = function (node) {
node.id = this.parseIdent();
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterDeclaration();
} else {
node.typeParameters = null;
}
node.right = this.flow_parseTypeInitialiser(tt.eq);
this.semicolon();
return this.finishNode(node, "TypeAlias");
};
// Type annotations
pp.flow_parseTypeParameterDeclaration = function () {
var node = this.startNode();
node.params = [];
this.expectRelational("<");
while (!this.isRelational(">")) {
node.params.push(this.flow_parseTypeAnnotatableIdentifier());
if (!this.isRelational(">")) {
this.expect(tt.comma);
}
}
this.expectRelational(">");
return this.finishNode(node, "TypeParameterDeclaration");
};
pp.flow_parseTypeParameterInstantiation = function () {
var node = this.startNode(),
oldInType = this.inType;
node.params = [];
this.inType = true;
this.expectRelational("<");
while (!this.isRelational(">")) {
node.params.push(this.flow_parseType());
if (!this.isRelational(">")) {
this.expect(tt.comma);
}
}
this.expectRelational(">");
this.inType = oldInType;
return this.finishNode(node, "TypeParameterInstantiation");
};
pp.flow_parseObjectPropertyKey = function () {
return this.type === tt.num || this.type === tt.string ? this.parseExprAtom() : this.parseIdent(true);
};
pp.flow_parseObjectTypeIndexer = function (node, isStatic) {
node["static"] = isStatic;
this.expect(tt.bracketL);
node.id = this.flow_parseObjectPropertyKey();
node.key = this.flow_parseTypeInitialiser();
this.expect(tt.bracketR);
node.value = this.flow_parseTypeInitialiser();
this.flow_objectTypeSemicolon();
return this.finishNode(node, "ObjectTypeIndexer");
};
pp.flow_parseObjectTypeMethodish = function (node) {
node.params = [];
node.rest = null;
node.typeParameters = null;
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterDeclaration();
}
this.expect(tt.parenL);
while (this.type === tt.name) {
node.params.push(this.flow_parseFunctionTypeParam());
if (this.type !== tt.parenR) {
this.expect(tt.comma);
}
}
if (this.eat(tt.ellipsis)) {
node.rest = this.flow_parseFunctionTypeParam();
}
this.expect(tt.parenR);
node.returnType = this.flow_parseTypeInitialiser();
return this.finishNode(node, "FunctionTypeAnnotation");
};
pp.flow_parseObjectTypeMethod = function (start, isStatic, key) {
var node = this.startNodeAt(start);
node.value = this.flow_parseObjectTypeMethodish(this.startNodeAt(start));
node["static"] = isStatic;
node.key = key;
node.optional = false;
this.flow_objectTypeSemicolon();
return this.finishNode(node, "ObjectTypeProperty");
};
pp.flow_parseObjectTypeCallProperty = function (node, isStatic) {
var valueNode = this.startNode();
node["static"] = isStatic;
node.value = this.flow_parseObjectTypeMethodish(valueNode);
this.flow_objectTypeSemicolon();
return this.finishNode(node, "ObjectTypeCallProperty");
};
pp.flow_parseObjectType = function (allowStatic) {
var nodeStart = this.startNode();
var node;
var optional = false;
var property;
var propertyKey;
var propertyTypeAnnotation;
var token;
var isStatic;
nodeStart.callProperties = [];
nodeStart.properties = [];
nodeStart.indexers = [];
this.expect(tt.braceL);
while (this.type !== tt.braceR) {
var start = this.markPosition();
node = this.startNode();
if (allowStatic && this.isContextual("static")) {
this.next();
isStatic = true;
}
if (this.type === tt.bracketL) {
nodeStart.indexers.push(this.flow_parseObjectTypeIndexer(node, isStatic));
} else if (this.type === tt.parenL || this.isRelational("<")) {
nodeStart.callProperties.push(this.flow_parseObjectTypeCallProperty(node, allowStatic));
} else {
if (isStatic && this.type === tt.colon) {
propertyKey = this.parseIdent();
} else {
propertyKey = this.flow_parseObjectPropertyKey();
}
if (this.isRelational("<") || this.type === tt.parenL) {
// This is a method property
nodeStart.properties.push(this.flow_parseObjectTypeMethod(start, isStatic, propertyKey));
} else {
if (this.eat(tt.question)) {
optional = true;
}
node.key = propertyKey;
node.value = this.flow_parseTypeInitialiser();
node.optional = optional;
node["static"] = isStatic;
this.flow_objectTypeSemicolon();
nodeStart.properties.push(this.finishNode(node, "ObjectTypeProperty"));
}
}
}
this.expect(tt.braceR);
return this.finishNode(nodeStart, "ObjectTypeAnnotation");
};
pp.flow_objectTypeSemicolon = function () {
if (!this.eat(tt.semi) && !this.eat(tt.comma) && this.type !== tt.braceR) {
this.unexpected();
}
};
pp.flow_parseGenericType = function (start, id) {
var node = this.startNodeAt(start);
node.typeParameters = null;
node.id = id;
while (this.eat(tt.dot)) {
var node2 = this.startNodeAt(start);
node2.qualification = node.id;
node2.id = this.parseIdent();
node.id = this.finishNode(node2, "QualifiedTypeIdentifier");
}
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterInstantiation();
}
return this.finishNode(node, "GenericTypeAnnotation");
};
pp.flow_parseTypeofType = function () {
var node = this.startNode();
this.expect(tt._typeof);
node.argument = this.flow_parsePrimaryType();
return this.finishNode(node, "TypeofTypeAnnotation");
};
pp.flow_parseTupleType = function () {
var node = this.startNode();
node.types = [];
this.expect(tt.bracketL);
// We allow trailing commas
while (this.pos < this.input.length && this.type !== tt.bracketR) {
node.types.push(this.flow_parseType());
if (this.type === tt.bracketR) break;
this.expect(tt.comma);
}
this.expect(tt.bracketR);
return this.finishNode(node, "TupleTypeAnnotation");
};
pp.flow_parseFunctionTypeParam = function () {
var optional = false;
var node = this.startNode();
node.name = this.parseIdent();
if (this.eat(tt.question)) {
optional = true;
}
node.optional = optional;
node.typeAnnotation = this.flow_parseTypeInitialiser();
return this.finishNode(node, "FunctionTypeParam");
};
pp.flow_parseFunctionTypeParams = function () {
var ret = { params: [], rest: null };
while (this.type === tt.name) {
ret.params.push(this.flow_parseFunctionTypeParam());
if (this.type !== tt.parenR) {
this.expect(tt.comma);
}
}
if (this.eat(tt.ellipsis)) {
ret.rest = this.flow_parseFunctionTypeParam();
}
return ret;
};
pp.flow_identToTypeAnnotation = function (start, node, id) {
switch (id.name) {
case "any":
return this.finishNode(node, "AnyTypeAnnotation");
case "void":
return this.finishNode(node, "VoidTypeAnnotation");
case "bool":
case "boolean":
return this.finishNode(node, "BooleanTypeAnnotation");
case "mixed":
return this.finishNode(node, "MixedTypeAnnotation");
case "number":
return this.finishNode(node, "NumberTypeAnnotation");
case "string":
return this.finishNode(node, "StringTypeAnnotation");
default:
return this.flow_parseGenericType(start, id);
}
};
// The parsing of types roughly parallels the parsing of expressions, and
// primary types are kind of like primary expressions...they're the
// primitives with which other types are constructed.
pp.flow_parsePrimaryType = function () {
var typeIdentifier = null;
var params = null;
var returnType = null;
var start = this.markPosition();
var node = this.startNode();
var rest = null;
var tmp;
var typeParameters;
var token;
var type;
var isGroupedType = false;
switch (this.type) {
case tt.name:
return this.flow_identToTypeAnnotation(start, node, this.parseIdent());
case tt.braceL:
return this.flow_parseObjectType();
case tt.bracketL:
return this.flow_parseTupleType();
case tt.relational:
if (this.value === "<") {
node.typeParameters = this.flow_parseTypeParameterDeclaration();
this.expect(tt.parenL);
tmp = this.flow_parseFunctionTypeParams();
node.params = tmp.params;
node.rest = tmp.rest;
this.expect(tt.parenR);
this.expect(tt.arrow);
node.returnType = this.flow_parseType();
return this.finishNode(node, "FunctionTypeAnnotation");
}
case tt.parenL:
this.next();
// Check to see if this is actually a grouped type
if (this.type !== tt.parenR && this.type !== tt.ellipsis) {
if (this.type === tt.name) {
var token = this.lookahead().type;
isGroupedType = token !== tt.question && token !== tt.colon;
} else {
isGroupedType = true;
}
}
if (isGroupedType) {
type = this.flow_parseType();
this.expect(tt.parenR);
// If we see a => next then someone was probably confused about
// function types, so we can provide a better error message
if (this.eat(tt.arrow)) {
this.raise(node, "Unexpected token =>. It looks like " + "you are trying to write a function type, but you ended up " + "writing a grouped type followed by an =>, which is a syntax " + "error. Remember, function type parameters are named so function " + "types look like (name1: type1, name2: type2) => returnType. You " + "probably wrote (type1) => returnType");
}
return type;
}
tmp = this.flow_parseFunctionTypeParams();
node.params = tmp.params;
node.rest = tmp.rest;
this.expect(tt.parenR);
this.expect(tt.arrow);
node.returnType = this.flow_parseType();
node.typeParameters = null;
return this.finishNode(node, "FunctionTypeAnnotation");
case tt.string:
node.value = this.value;
node.raw = this.input.slice(this.start, this.end);
this.next();
return this.finishNode(node, "StringLiteralTypeAnnotation");
default:
if (this.type.keyword === "typeof") {
return this.flow_parseTypeofType();
}
}
this.unexpected();
};
pp.flow_parsePostfixType = function () {
var node = this.startNode();
var type = node.elementType = this.flow_parsePrimaryType();
if (this.type === tt.bracketL) {
this.expect(tt.bracketL);
this.expect(tt.bracketR);
return this.finishNode(node, "ArrayTypeAnnotation");
}
return type;
};
pp.flow_parsePrefixType = function () {
var node = this.startNode();
if (this.eat(tt.question)) {
node.typeAnnotation = this.flow_parsePrefixType();
return this.finishNode(node, "NullableTypeAnnotation");
}
return this.flow_parsePostfixType();
};
pp.flow_parseIntersectionType = function () {
var node = this.startNode();
var type = this.flow_parsePrefixType();
node.types = [type];
while (this.eat(tt.bitwiseAND)) {
node.types.push(this.flow_parsePrefixType());
}
return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
};
pp.flow_parseUnionType = function () {
var node = this.startNode();
var type = this.flow_parseIntersectionType();
node.types = [type];
while (this.eat(tt.bitwiseOR)) {
node.types.push(this.flow_parseIntersectionType());
}
return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
};
pp.flow_parseType = function () {
var oldInType = this.inType;
this.inType = true;
var type = this.flow_parseUnionType();
this.inType = oldInType;
return type;
};
pp.flow_parseTypeAnnotation = function () {
var node = this.startNode();
node.typeAnnotation = this.flow_parseTypeInitialiser();
return this.finishNode(node, "TypeAnnotation");
};
pp.flow_parseTypeAnnotatableIdentifier = function (requireTypeAnnotation, canBeOptionalParam) {
var node = this.startNode();
var ident = this.parseIdent();
var isOptionalParam = false;
if (canBeOptionalParam && this.eat(tt.question)) {
this.expect(tt.question);
isOptionalParam = true;
}
if (requireTypeAnnotation || this.type === tt.colon) {
ident.typeAnnotation = this.flow_parseTypeAnnotation();
this.finishNode(ident, ident.type);
}
if (isOptionalParam) {
ident.optional = true;
this.finishNode(ident, ident.type);
}
return ident;
};
acorn.plugins.flow = function (instance) {
// function name(): string {}
instance.extend("parseFunctionBody", function (inner) {
return function (node, allowExpression) {
if (this.type === tt.colon) {
node.returnType = this.flow_parseTypeAnnotation();
}
return inner.call(this, node, allowExpression);
};
});
instance.extend("parseStatement", function (inner) {
return function (declaration, topLevel) {
// strict mode handling of `interface` since it's a reserved word
if (this.strict && this.type === tt.name && this.value === "interface") {
var node = this.startNode();
this.next();
return this.flow_parseInterface(node);
} else {
return inner.call(this, declaration, topLevel);
}
};
});
instance.extend("parseExpressionStatement", function (inner) {
return function (node, expr) {
if (expr.type === "Identifier") {
if (expr.name === "declare") {
if (this.type === tt._class || this.type === tt.name || this.type === tt._function || this.type === tt._var) {
return this.flow_parseDeclare(node);
}
} else if (this.type === tt.name) {
if (expr.name === "interface") {
return this.flow_parseInterface(node);
} else if (expr.name === "type") {
return this.flow_parseTypeAlias(node);
}
}
}
return inner.call(this, node, expr);
};
});
instance.extend("shouldParseExportDeclaration", function (inner) {
return function () {
return this.isContextual("type") || inner.call(this);
};
});
instance.extend("parseParenItem", function (inner) {
return function (node, start) {
if (this.type === tt.colon) {
var typeCastNode = this.startNodeAt(start);
typeCastNode.expression = node;
typeCastNode.typeAnnotation = this.flow_parseTypeAnnotation();
return this.finishNode(typeCastNode, "TypeCastExpression");
} else {
return node;
}
};
});
instance.extend("parseClassId", function (inner) {
return function (node, isStatement) {
inner.call(this, node, isStatement);
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterDeclaration();
}
};
});
// don't consider `void` to be a keyword as then it'll use the void token type
// and set startExpr
instance.extend("isKeyword", function (inner) {
return function (name) {
if (this.inType && name === "void") {
return false;
} else {
return inner.call(this, name);
}
};
});
instance.extend("readToken", function (inner) {
return function (code) {
if (this.inType && (code === 62 || code === 60)) {
return this.finishOp(tt.relational, 1);
} else {
return inner.call(this, code);
}
};
});
instance.extend("jsx_readToken", function (inner) {
return function () {
if (!this.inType) return inner.call(this);
};
});
instance.extend("parseParenArrowList", function (inner) {
return function (start, exprList, isAsync) {
for (var i = 0; i < exprList.length; i++) {
var listItem = exprList[i];
if (listItem.type === "TypeCastExpression") {
var expr = listItem.expression;
expr.typeAnnotation = listItem.typeAnnotation;
exprList[i] = expr;
}
}
return inner.call(this, start, exprList, isAsync);
};
});
instance.extend("parseClassProperty", function (inner) {
return function (node) {
if (this.type === tt.colon) {
node.typeAnnotation = this.flow_parseTypeAnnotation();
}
return inner.call(this, node);
};
});
instance.extend("isClassProperty", function (inner) {
return function () {
return this.type === tt.colon || inner.call(this);
};
});
instance.extend("parseClassMethod", function (inner) {
return function (classBody, method, isGenerator, isAsync) {
var typeParameters;
if (this.isRelational("<")) {
typeParameters = this.flow_parseTypeParameterDeclaration();
}
method.value = this.parseMethod(isGenerator, isAsync);
method.value.typeParameters = typeParameters;
classBody.body.push(this.finishNode(method, "MethodDefinition"));
};
});
instance.extend("parseClassSuper", function (inner) {
return function (node, isStatement) {
inner.call(this, node, isStatement);
if (node.superClass && this.isRelational("<")) {
node.superTypeParameters = this.flow_parseTypeParameterInstantiation();
}
if (this.isContextual("implements")) {
this.next();
var implemented = node["implements"] = [];
do {
var node = this.startNode();
node.id = this.parseIdent();
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterInstantiation();
} else {
node.typeParameters = null;
}
implemented.push(this.finishNode(node, "ClassImplements"));
} while (this.eat(tt.comma));
}
};
});
instance.extend("parseObjPropValue", function (inner) {
return function (prop) {
var typeParameters;
if (this.isRelational("<")) {
typeParameters = this.flow_parseTypeParameterDeclaration();
if (this.type !== tt.parenL) this.unexpected();
}
inner.apply(this, arguments);
prop.value.typeParameters = typeParameters;
};
});
instance.extend("parseAssignableListItemTypes", function (inner) {
return function (param) {
if (this.eat(tt.question)) {
param.optional = true;
}
if (this.type === tt.colon) {
param.typeAnnotation = this.flow_parseTypeAnnotation();
}
this.finishNode(param, param.type);
return param;
};
});
instance.extend("parseImportSpecifiers", function (inner) {
return function (node) {
node.importKind = "value";
var kind = this.type === tt._typeof ? "typeof" : this.isContextual("type") ? "type" : null;
if (kind) {
var lh = this.lookahead();
if (lh.type === tt.name && lh.value !== "from" || lh.type === tt.braceL || lh.type === tt.star) {
this.next();
node.importKind = kind;
}
}
inner.call(this, node);
};
});
// function foo<T>() {}
instance.extend("parseFunctionParams", function (inner) {
return function (node) {
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterDeclaration();
}
inner.call(this, node);
};
});
// var foo: string = bar
instance.extend("parseVarHead", function (inner) {
return function (decl) {
inner.call(this, decl);
if (this.type === tt.colon) {
decl.id.typeAnnotation = this.flow_parseTypeAnnotation();
this.finishNode(decl.id, decl.id.type);
}
};
});
};

View File

@ -1,842 +0,0 @@
/* */
"format cjs";
"use strict";
var _babelToolsProtectJs2 = require("./../../babel/tools/protect.js");
var _babelToolsProtectJs3 = _interopRequireDefault(_babelToolsProtectJs2);
// 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 _tokentype = require("./tokentype");
var _state = require("./state");
var _identifier = require("./identifier");
var _util = require("./util");
_babelToolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var pp = _state.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.checkPropClash = function (prop, propHash) {
if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) return;
var key = prop.key,
name = undefined;
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) this.raise(key.start, "Redefinition of __proto__ property");
propHash.proto = true;
}
return;
}
var other = undefined;
if (_util.has(propHash, name)) {
other = propHash[name];
var isGetSet = kind !== "init";
if ((this.strict || isGetSet) && other[kind] || !(isGetSet ^ other.init)) this.raise(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.parseExpression = function (noIn, refShorthandDefaultPos) {
var start = this.markPosition();
var expr = this.parseMaybeAssign(noIn, refShorthandDefaultPos);
if (this.type === _tokentype.types.comma) {
var node = this.startNodeAt(start);
node.expressions = [expr];
while (this.eat(_tokentype.types.comma)) node.expressions.push(this.parseMaybeAssign(noIn, refShorthandDefaultPos));
return this.finishNode(node, "SequenceExpression");
}
return expr;
};
// Parse an assignment expression. This includes applications of
// operators like `+=`.
pp.parseMaybeAssign = function (noIn, refShorthandDefaultPos, afterLeftParse) {
if (this.type == _tokentype.types._yield && this.inGenerator) return this.parseYield();
var failOnShorthandAssign = undefined;
if (!refShorthandDefaultPos) {
refShorthandDefaultPos = { start: 0 };
failOnShorthandAssign = true;
} else {
failOnShorthandAssign = false;
}
var start = this.markPosition();
if (this.type == _tokentype.types.parenL || this.type == _tokentype.types.name) this.potentialArrowAt = this.start;
var left = this.parseMaybeConditional(noIn, refShorthandDefaultPos);
if (afterLeftParse) left = afterLeftParse.call(this, left, start);
if (this.type.isAssign) {
var node = this.startNodeAt(start);
node.operator = this.value;
node.left = this.type === _tokentype.types.eq ? this.toAssignable(left) : left;
refShorthandDefaultPos.start = 0; // reset because shorthand default was used correctly
this.checkLVal(left);
if (left.parenthesizedExpression) {
var errorMsg = undefined;
if (left.type === "ObjectPattern") {
errorMsg = "`({a}) = 0` use `({a} = 0)`";
} else if (left.type === "ArrayPattern") {
errorMsg = "`([a]) = 0` use `([a] = 0)`";
}
if (errorMsg) {
this.raise(left.start, "You're trying to assign to a parenthesized expression, eg. instead of " + errorMsg);
}
}
this.next();
node.right = this.parseMaybeAssign(noIn);
return this.finishNode(node, "AssignmentExpression");
} else if (failOnShorthandAssign && refShorthandDefaultPos.start) {
this.unexpected(refShorthandDefaultPos.start);
}
return left;
};
// Parse a ternary conditional (`?:`) operator.
pp.parseMaybeConditional = function (noIn, refShorthandDefaultPos) {
var start = this.markPosition();
var expr = this.parseExprOps(noIn, refShorthandDefaultPos);
if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
if (this.eat(_tokentype.types.question)) {
var node = this.startNodeAt(start);
node.test = expr;
node.consequent = this.parseMaybeAssign();
this.expect(_tokentype.types.colon);
node.alternate = this.parseMaybeAssign(noIn);
return this.finishNode(node, "ConditionalExpression");
}
return expr;
};
// Start the precedence parser.
pp.parseExprOps = function (noIn, refShorthandDefaultPos) {
var start = this.markPosition();
var expr = this.parseMaybeUnary(refShorthandDefaultPos);
if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
return this.parseExprOp(expr, start, -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.parseExprOp = function (left, leftStart, minPrec, noIn) {
var prec = this.type.binop;
if (prec != null && (!noIn || this.type !== _tokentype.types._in)) {
if (prec > minPrec) {
var node = this.startNodeAt(leftStart);
node.left = left;
node.operator = this.value;
var op = this.type;
this.next();
var start = this.markPosition();
node.right = this.parseExprOp(this.parseMaybeUnary(), start, op.rightAssociative ? prec - 1 : prec, noIn);
this.finishNode(node, op === _tokentype.types.logicalOR || op === _tokentype.types.logicalAND ? "LogicalExpression" : "BinaryExpression");
return this.parseExprOp(node, leftStart, minPrec, noIn);
}
}
return left;
};
// Parse unary operators, both prefix and postfix.
pp.parseMaybeUnary = function (refShorthandDefaultPos) {
if (this.type.prefix) {
var node = this.startNode(),
update = this.type === _tokentype.types.incDec;
node.operator = this.value;
node.prefix = true;
this.next();
node.argument = this.parseMaybeUnary();
if (refShorthandDefaultPos && refShorthandDefaultPos.start) this.unexpected(refShorthandDefaultPos.start);
if (update) this.checkLVal(node.argument);else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") this.raise(node.start, "Deleting local variable in strict mode");
return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
}
var start = this.markPosition();
var expr = this.parseExprSubscripts(refShorthandDefaultPos);
if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
while (this.type.postfix && !this.canInsertSemicolon()) {
var node = this.startNodeAt(start);
node.operator = this.value;
node.prefix = false;
node.argument = expr;
this.checkLVal(expr);
this.next();
expr = this.finishNode(node, "UpdateExpression");
}
return expr;
};
// Parse call, dot, and `[]`-subscript expressions.
pp.parseExprSubscripts = function (refShorthandDefaultPos) {
var start = this.markPosition();
var expr = this.parseExprAtom(refShorthandDefaultPos);
if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
return this.parseSubscripts(expr, start);
};
pp.parseSubscripts = function (base, start, noCalls) {
if (!noCalls && this.eat(_tokentype.types.doubleColon)) {
var node = this.startNodeAt(start);
node.object = base;
node.callee = this.parseNoCallExpr();
return this.parseSubscripts(this.finishNode(node, "BindExpression"), start, noCalls);
} else if (this.eat(_tokentype.types.dot)) {
var node = this.startNodeAt(start);
node.object = base;
node.property = this.parseIdent(true);
node.computed = false;
return this.parseSubscripts(this.finishNode(node, "MemberExpression"), start, noCalls);
} else if (this.eat(_tokentype.types.bracketL)) {
var node = this.startNodeAt(start);
node.object = base;
node.property = this.parseExpression();
node.computed = true;
this.expect(_tokentype.types.bracketR);
return this.parseSubscripts(this.finishNode(node, "MemberExpression"), start, noCalls);
} else if (!noCalls && this.eat(_tokentype.types.parenL)) {
var node = this.startNodeAt(start);
node.callee = base;
node.arguments = this.parseExprList(_tokentype.types.parenR, this.options.features["es7.trailingFunctionCommas"]);
return this.parseSubscripts(this.finishNode(node, "CallExpression"), start, noCalls);
} else if (this.type === _tokentype.types.backQuote) {
var node = this.startNodeAt(start);
node.tag = base;
node.quasi = this.parseTemplate();
return this.parseSubscripts(this.finishNode(node, "TaggedTemplateExpression"), start, noCalls);
}return base;
};
// Parse a no-call expression (like argument of `new` or `::` operators).
pp.parseNoCallExpr = function () {
var start = this.markPosition();
return this.parseSubscripts(this.parseExprAtom(), start, true);
};
// 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.parseExprAtom = function (refShorthandDefaultPos) {
var node = undefined,
canBeArrow = this.potentialArrowAt == this.start;
switch (this.type) {
case _tokentype.types._super:
if (!this.inFunction) this.raise(this.start, "'super' outside of function or class");
case _tokentype.types._this:
var type = this.type === _tokentype.types._this ? "ThisExpression" : "Super";
node = this.startNode();
this.next();
return this.finishNode(node, type);
case _tokentype.types._yield:
if (this.inGenerator) this.unexpected();
case _tokentype.types._do:
if (this.options.features["es7.doExpressions"]) {
var _node = this.startNode();
this.next();
var oldInFunction = this.inFunction;
var oldLabels = this.labels;
this.labels = [];
this.inFunction = false;
_node.body = this.parseBlock();
this.inFunction = oldInFunction;
this.labels = oldLabels;
return this.finishNode(_node, "DoExpression");
}
case _tokentype.types.name:
var start = this.markPosition();
node = this.startNode();
var id = this.parseIdent(this.type !== _tokentype.types.name);
//
if (this.options.features["es7.asyncFunctions"]) {
// async functions!
if (id.name === "async" && !this.canInsertSemicolon()) {
// arrow functions
if (this.type === _tokentype.types.parenL) {
var expr = this.parseParenAndDistinguishExpression(start, true, true);
if (expr && expr.type === "ArrowFunctionExpression") {
return expr;
} else {
node.callee = id;
if (!expr) {
node.arguments = [];
} else if (expr.type === "SequenceExpression") {
node.arguments = expr.expressions;
} else {
node.arguments = [expr];
}
return this.parseSubscripts(this.finishNode(node, "CallExpression"), start);
}
} else if (this.type === _tokentype.types.name) {
id = this.parseIdent();
this.expect(_tokentype.types.arrow);
return this.parseArrowExpression(node, [id], true);
}
// normal functions
if (this.type === _tokentype.types._function && !this.canInsertSemicolon()) {
this.next();
return this.parseFunction(node, false, false, true);
}
} else if (id.name === "await") {
if (this.inAsync) return this.parseAwait(node);
}
}
//
if (canBeArrow && !this.canInsertSemicolon() && this.eat(_tokentype.types.arrow)) return this.parseArrowExpression(this.startNodeAt(start), [id]);
return id;
case _tokentype.types.regexp:
var value = this.value;
node = this.parseLiteral(value.value);
node.regex = { pattern: value.pattern, flags: value.flags };
return node;
case _tokentype.types.num:case _tokentype.types.string:
return this.parseLiteral(this.value);
case _tokentype.types._null:case _tokentype.types._true:case _tokentype.types._false:
node = this.startNode();
node.value = this.type === _tokentype.types._null ? null : this.type === _tokentype.types._true;
node.raw = this.type.keyword;
this.next();
return this.finishNode(node, "Literal");
case _tokentype.types.parenL:
return this.parseParenAndDistinguishExpression(null, null, canBeArrow);
case _tokentype.types.bracketL:
node = this.startNode();
this.next();
// check whether this is array comprehension or regular array
if ((this.options.ecmaVersion >= 7 || this.options.features["es7.comprehensions"]) && this.type === _tokentype.types._for) {
return this.parseComprehension(node, false);
}
node.elements = this.parseExprList(_tokentype.types.bracketR, true, true, refShorthandDefaultPos);
return this.finishNode(node, "ArrayExpression");
case _tokentype.types.braceL:
return this.parseObj(false, refShorthandDefaultPos);
case _tokentype.types._function:
node = this.startNode();
this.next();
return this.parseFunction(node, false);
case _tokentype.types.at:
this.parseDecorators();
case _tokentype.types._class:
node = this.startNode();
this.takeDecorators(node);
return this.parseClass(node, false);
case _tokentype.types._new:
return this.parseNew();
case _tokentype.types.backQuote:
return this.parseTemplate();
case _tokentype.types.doubleColon:
node = this.startNode();
this.next();
node.object = null;
var callee = node.callee = this.parseNoCallExpr();
if (callee.type !== "MemberExpression") this.raise(callee.start, "Binding should be performed on object property.");
return this.finishNode(node, "BindExpression");
default:
this.unexpected();
}
};
pp.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.parseParenExpression = function () {
this.expect(_tokentype.types.parenL);
var val = this.parseExpression();
this.expect(_tokentype.types.parenR);
return val;
};
pp.parseParenAndDistinguishExpression = function (start, isAsync, canBeArrow) {
start = start || this.markPosition();
var val = undefined;
if (this.options.ecmaVersion >= 6) {
this.next();
if ((this.options.features["es7.comprehensions"] || this.options.ecmaVersion >= 7) && this.type === _tokentype.types._for) {
return this.parseComprehension(this.startNodeAt(start), true);
}
var innerStart = this.markPosition(),
exprList = [],
first = true;
var refShorthandDefaultPos = { start: 0 },
spreadStart = undefined,
innerParenStart = undefined,
optionalCommaStart = undefined;
while (this.type !== _tokentype.types.parenR) {
if (first) {
first = false;
} else {
this.expect(_tokentype.types.comma);
if (this.type === _tokentype.types.parenR && this.options.features["es7.trailingFunctionCommas"]) {
optionalCommaStart = this.start;
break;
}
}
if (this.type === _tokentype.types.ellipsis) {
var spreadNodeStart = this.markPosition();
spreadStart = this.start;
exprList.push(this.parseParenItem(this.parseRest(), spreadNodeStart));
break;
} else {
if (this.type === _tokentype.types.parenL && !innerParenStart) {
innerParenStart = this.start;
}
exprList.push(this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem));
}
}
var innerEnd = this.markPosition();
this.expect(_tokentype.types.parenR);
if (canBeArrow && !this.canInsertSemicolon() && this.eat(_tokentype.types.arrow)) {
if (innerParenStart) this.unexpected(innerParenStart);
return this.parseParenArrowList(start, exprList, isAsync);
}
if (!exprList.length) {
if (isAsync) {
return;
} else {
this.unexpected(this.lastTokStart);
}
}
if (optionalCommaStart) this.unexpected(optionalCommaStart);
if (spreadStart) this.unexpected(spreadStart);
if (refShorthandDefaultPos.start) this.unexpected(refShorthandDefaultPos.start);
if (exprList.length > 1) {
val = this.startNodeAt(innerStart);
val.expressions = exprList;
this.finishNodeAt(val, "SequenceExpression", innerEnd);
} else {
val = exprList[0];
}
} else {
val = this.parseParenExpression();
}
if (this.options.preserveParens) {
var par = this.startNodeAt(start);
par.expression = val;
return this.finishNode(par, "ParenthesizedExpression");
} else {
val.parenthesizedExpression = true;
return val;
}
};
pp.parseParenArrowList = function (start, exprList, isAsync) {
return this.parseArrowExpression(this.startNodeAt(start), exprList, isAsync);
};
pp.parseParenItem = function (node, start) {
return node;
};
// 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
var empty = [];
pp.parseNew = function () {
var node = this.startNode();
var meta = this.parseIdent(true);
if (this.options.ecmaVersion >= 6 && this.eat(_tokentype.types.dot)) {
node.meta = meta;
node.property = this.parseIdent(true);
if (node.property.name !== "target") this.raise(node.property.start, "The only valid meta property for new is new.target");
return this.finishNode(node, "MetaProperty");
}
node.callee = this.parseNoCallExpr();
if (this.eat(_tokentype.types.parenL)) node.arguments = this.parseExprList(_tokentype.types.parenR, this.options.features["es7.trailingFunctionCommas"]);else node.arguments = empty;
return this.finishNode(node, "NewExpression");
};
// Parse template expression.
pp.parseTemplateElement = function () {
var elem = this.startNode();
elem.value = {
raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
cooked: this.value
};
this.next();
elem.tail = this.type === _tokentype.types.backQuote;
return this.finishNode(elem, "TemplateElement");
};
pp.parseTemplate = function () {
var node = this.startNode();
this.next();
node.expressions = [];
var curElt = this.parseTemplateElement();
node.quasis = [curElt];
while (!curElt.tail) {
this.expect(_tokentype.types.dollarBraceL);
node.expressions.push(this.parseExpression());
this.expect(_tokentype.types.braceR);
node.quasis.push(curElt = this.parseTemplateElement());
}
this.next();
return this.finishNode(node, "TemplateLiteral");
};
// Parse an object literal or binding pattern.
pp.parseObj = function (isPattern, refShorthandDefaultPos) {
var node = this.startNode(),
first = true,
propHash = {};
node.properties = [];
var decorators = [];
this.next();
while (!this.eat(_tokentype.types.braceR)) {
if (!first) {
this.expect(_tokentype.types.comma);
if (this.afterTrailingComma(_tokentype.types.braceR)) break;
} else first = false;
while (this.type === _tokentype.types.at) {
decorators.push(this.parseDecorator());
}
var prop = this.startNode(),
isGenerator = false,
isAsync = false,
start = undefined;
if (decorators.length) {
prop.decorators = decorators;
decorators = [];
}
if (this.options.features["es7.objectRestSpread"] && this.type === _tokentype.types.ellipsis) {
prop = this.parseSpread();
prop.type = "SpreadProperty";
node.properties.push(prop);
continue;
}
if (this.options.ecmaVersion >= 6) {
prop.method = false;
prop.shorthand = false;
if (isPattern || refShorthandDefaultPos) start = this.markPosition();
if (!isPattern) isGenerator = this.eat(_tokentype.types.star);
}
if (this.options.features["es7.asyncFunctions"] && this.isContextual("async")) {
if (isGenerator || isPattern) this.unexpected();
var asyncId = this.parseIdent();
if (this.type === _tokentype.types.colon || this.type === _tokentype.types.parenL) {
prop.key = asyncId;
} else {
isAsync = true;
this.parsePropertyName(prop);
}
} else {
this.parsePropertyName(prop);
}
this.parseObjPropValue(prop, start, isGenerator, isAsync, isPattern, refShorthandDefaultPos);
this.checkPropClash(prop, propHash);
node.properties.push(this.finishNode(prop, "Property"));
}
if (decorators.length) {
this.raise(this.start, "You have trailing decorators with no property");
}
return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression");
};
pp.parseObjPropValue = function (prop, start, isGenerator, isAsync, isPattern, refShorthandDefaultPos) {
if (this.eat(_tokentype.types.colon)) {
prop.value = isPattern ? this.parseMaybeDefault() : this.parseMaybeAssign(false, refShorthandDefaultPos);
prop.kind = "init";
} else if (this.options.ecmaVersion >= 6 && this.type === _tokentype.types.parenL) {
if (isPattern) this.unexpected();
prop.kind = "init";
prop.method = true;
prop.value = this.parseMethod(isGenerator, isAsync);
} else if (this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.type != _tokentype.types.comma && this.type != _tokentype.types.braceR)) {
if (isGenerator || isAsync || isPattern) 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.raise(_start, "getter should have no params");else this.raise(_start, "setter should have exactly one param");
}
} else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
prop.kind = "init";
if (isPattern) {
if (this.isKeyword(prop.key.name) || this.strict && (_identifier.reservedWords.strictBind(prop.key.name) || _identifier.reservedWords.strict(prop.key.name)) || !this.options.allowReserved && this.isReservedWord(prop.key.name)) this.raise(prop.key.start, "Binding " + prop.key.name);
prop.value = this.parseMaybeDefault(start, prop.key);
} else if (this.type === _tokentype.types.eq && refShorthandDefaultPos) {
if (!refShorthandDefaultPos.start) refShorthandDefaultPos.start = this.start;
prop.value = this.parseMaybeDefault(start, prop.key);
} else {
prop.value = prop.key;
}
prop.shorthand = true;
} else this.unexpected();
};
pp.parsePropertyName = function (prop) {
if (this.options.ecmaVersion >= 6) {
if (this.eat(_tokentype.types.bracketL)) {
prop.computed = true;
prop.key = this.parseMaybeAssign();
this.expect(_tokentype.types.bracketR);
return prop.key;
} else {
prop.computed = false;
}
}
return prop.key = this.type === _tokentype.types.num || this.type === _tokentype.types.string ? this.parseExprAtom() : this.parseIdent(true);
};
// Initialize empty function node.
pp.initFunction = function (node, isAsync) {
node.id = null;
if (this.options.ecmaVersion >= 6) {
node.generator = false;
node.expression = false;
}
if (this.options.features["es7.asyncFunctions"]) {
node.async = !!isAsync;
}
};
// Parse object or class method.
pp.parseMethod = function (isGenerator, isAsync) {
var node = this.startNode();
this.initFunction(node, isAsync);
this.expect(_tokentype.types.parenL);
node.params = this.parseBindingList(_tokentype.types.parenR, false, this.options.features["es7.trailingFunctionCommas"]);
if (this.options.ecmaVersion >= 6) {
node.generator = isGenerator;
}
this.parseFunctionBody(node);
return this.finishNode(node, "FunctionExpression");
};
// Parse arrow function expression with given parameters.
pp.parseArrowExpression = function (node, params, isAsync) {
this.initFunction(node, isAsync);
node.params = this.toAssignableList(params, true);
this.parseFunctionBody(node, true);
return this.finishNode(node, "ArrowFunctionExpression");
};
// Parse function body and check parameters.
pp.parseFunctionBody = function (node, allowExpression) {
var isExpression = allowExpression && this.type !== _tokentype.types.braceL;
var oldInAsync = this.inAsync;
this.inAsync = node.async;
if (isExpression) {
node.body = this.parseMaybeAssign();
node.expression = true;
} else {
// Start a new scope with regard to labels and the `inFunction`
// flag (restore them to their old value afterwards).
var oldInFunc = this.inFunction,
oldInGen = this.inGenerator,
oldLabels = this.labels;
this.inFunction = true;this.inGenerator = node.generator;this.labels = [];
node.body = this.parseBlock(true);
node.expression = false;
this.inFunction = oldInFunc;this.inGenerator = oldInGen;this.labels = oldLabels;
}
this.inAsync = oldInAsync;
// 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 (this.strict || !isExpression && node.body.body.length && this.isUseStrict(node.body.body[0])) {
var nameHash = {},
oldStrict = this.strict;
this.strict = true;
if (node.id) this.checkLVal(node.id, true);
for (var i = 0; i < node.params.length; i++) {
this.checkLVal(node.params[i], true, nameHash);
}this.strict = oldStrict;
}
};
// 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.parseExprList = function (close, allowTrailingComma, allowEmpty, refShorthandDefaultPos) {
var elts = [],
first = true;
while (!this.eat(close)) {
if (!first) {
this.expect(_tokentype.types.comma);
if (allowTrailingComma && this.afterTrailingComma(close)) break;
} else first = false;
if (allowEmpty && this.type === _tokentype.types.comma) {
elts.push(null);
} else {
if (this.type === _tokentype.types.ellipsis) elts.push(this.parseSpread(refShorthandDefaultPos));else elts.push(this.parseMaybeAssign(false, refShorthandDefaultPos));
}
}
return elts;
};
// Parse the next token as an identifier. If `liberal` is true (used
// when parsing properties), it will also convert keywords into
// identifiers.
pp.parseIdent = function (liberal) {
var node = this.startNode();
if (liberal && this.options.allowReserved == "never") liberal = false;
if (this.type === _tokentype.types.name) {
if (!liberal && (!this.options.allowReserved && this.isReservedWord(this.value) || this.strict && _identifier.reservedWords.strict(this.value) && (this.options.ecmaVersion >= 6 || this.input.slice(this.start, this.end).indexOf("\\") == -1))) this.raise(this.start, "The keyword '" + this.value + "' is reserved");
node.name = this.value;
} else if (liberal && this.type.keyword) {
node.name = this.type.keyword;
} else {
this.unexpected();
}
this.next();
return this.finishNode(node, "Identifier");
};
// Parses await expression inside async function.
pp.parseAwait = function (node) {
if (this.eat(_tokentype.types.semi) || this.canInsertSemicolon()) {
this.unexpected();
}
node.all = this.eat(_tokentype.types.star);
node.argument = this.parseMaybeUnary();
return this.finishNode(node, "AwaitExpression");
};
// Parses yield expression inside generator.
pp.parseYield = function () {
var node = this.startNode();
this.next();
if (this.type == _tokentype.types.semi || this.canInsertSemicolon() || this.type != _tokentype.types.star && !this.type.startsExpr) {
node.delegate = false;
node.argument = null;
} else {
node.delegate = this.eat(_tokentype.types.star);
node.argument = this.parseMaybeAssign();
}
return this.finishNode(node, "YieldExpression");
};
// Parses array and generator comprehensions.
pp.parseComprehension = function (node, isGenerator) {
node.blocks = [];
while (this.type === _tokentype.types._for) {
var block = this.startNode();
this.next();
this.expect(_tokentype.types.parenL);
block.left = this.parseBindingAtom();
this.checkLVal(block.left, true);
this.expectContextual("of");
block.right = this.parseExpression();
this.expect(_tokentype.types.parenR);
node.blocks.push(this.finishNode(block, "ComprehensionBlock"));
}
node.filter = this.eat(_tokentype.types._if) ? this.parseParenExpression() : null;
node.body = this.parseExpression();
this.expect(isGenerator ? _tokentype.types.parenR : _tokentype.types.bracketR);
node.generator = isGenerator;
return this.finishNode(node, "ComprehensionExpression");
};

View File

@ -1,115 +0,0 @@
/* */
"format cjs";
"use strict";
var _babelToolsProtectJs2 = require("./../../babel/tools/protect.js");
var _babelToolsProtectJs3 = _interopRequireDefault(_babelToolsProtectJs2);
exports.__esModule = true;
exports.isIdentifierStart = isIdentifierStart;
exports.isIdentifierChar = isIdentifierChar;
_babelToolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
// This is a trick taken from Esprima. It turns out that, on
// non-Chrome browsers, to check whether a string is in a set, a
// predicate containing a big ugly `switch` statement is faster than
// a regular expression, and on Chrome the two are about on par.
// This function uses `eval` (non-lexical) to produce such a
// predicate from a space-separated string of words.
//
// It starts by sorting the words by length.
function makePredicate(words) {
words = words.split(" ");
return function (str) {
return words.indexOf(str) >= 0;
};
}
// Reserved word lists for various dialects of the language
var reservedWords = {
3: makePredicate("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: makePredicate("class enum extends super const export import"),
6: makePredicate("enum await"),
strict: makePredicate("implements interface let package private protected public static yield"),
strictBind: makePredicate("eval arguments")
};
exports.reservedWords = reservedWords;
// 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: makePredicate(ecma5AndLessKeywords),
6: makePredicate(ecma5AndLessKeywords + " let const class extends export import yield super")
};
exports.keywords = keywords;
// ## 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 `tools/generate-identifier-regex.js`.
var nonASCIIidentifierStartChars = "ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢲऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA--zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";
var nonASCIIidentifierChars = "‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣤ-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏ᦰ-ᧀᧈᧉ᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷼-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-꣄꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︭︳︴﹍--_";
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 tools/generate-identifier-regex.js
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, 99, 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, 98, 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, 955, 52, 76, 44, 33, 24, 27, 35, 42, 34, 4, 0, 13, 47, 15, 3, 22, 0, 38, 17, 2, 24, 133, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 32, 4, 287, 47, 21, 1, 2, 0, 185, 46, 82, 47, 21, 0, 60, 42, 502, 63, 32, 0, 449, 56, 1288, 920, 104, 110, 2962, 1070, 13266, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 881, 68, 12, 0, 67, 12, 16481, 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, 1340, 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, 16355, 541];
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, 16, 9, 83, 11, 168, 11, 6, 9, 8, 2, 57, 0, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 316, 19, 13, 9, 214, 6, 3, 8, 112, 16, 16, 9, 82, 12, 9, 9, 535, 9, 20855, 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, 4305, 6, 792618, 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);
}

View File

@ -1,128 +0,0 @@
/* */
"format cjs";
"use strict";
var _babelToolsProtectJs2 = require("./../../babel/tools/protect.js");
var _babelToolsProtectJs3 = _interopRequireDefault(_babelToolsProtectJs2);
exports.__esModule = true;
exports.parse = parse;
exports.parseExpressionAt = parseExpressionAt;
exports.tokenizer = tokenizer;
// 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/marijnh/acorn.git
//
// Please use the [github bug tracker][ghbt] to report issues.
//
// [ghbt]: https://github.com/marijnh/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 _state = require("./state");
var _options = require("./options");
require("./parseutil");
require("./statement");
require("./lval");
require("./expression");
require("./lookahead");
_babelToolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
exports.Parser = _state.Parser;
exports.plugins = _state.plugins;
exports.defaultOptions = _options.defaultOptions;
var _location = require("./location");
exports.SourceLocation = _location.SourceLocation;
exports.getLineInfo = _location.getLineInfo;
var _node = require("./node");
exports.Node = _node.Node;
var _tokentype = require("./tokentype");
exports.TokenType = _tokentype.TokenType;
exports.tokTypes = _tokentype.types;
var _tokencontext = require("./tokencontext");
exports.TokContext = _tokencontext.TokContext;
exports.tokContexts = _tokencontext.types;
var _identifier = require("./identifier");
exports.isIdentifierChar = _identifier.isIdentifierChar;
exports.isIdentifierStart = _identifier.isIdentifierStart;
var _tokenize = require("./tokenize");
exports.Token = _tokenize.Token;
var _whitespace = require("./whitespace");
exports.isNewLine = _whitespace.isNewLine;
exports.lineBreak = _whitespace.lineBreak;
exports.lineBreakG = _whitespace.lineBreakG;
var version = "1.0.0";
exports.version = version;
// 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) {
var p = parser(options, input);
var startPos = p.options.locations ? [p.pos, p.curPosition()] : p.pos;
p.nextToken();
return p.parseTopLevel(p.options.program || p.startNodeAt(startPos));
}
// 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 = parser(options, input, pos);
p.nextToken();
return p.parseExpression();
}
// Acorn is organized as a tokenizer and a recursive-descent parser.
// The `tokenize` export provides an interface to the tokenizer.
// Because the tokenizer is optimized for being efficiently used by
// the Acorn parser itself, this interface is somewhat crude and not
// very modular.
function tokenizer(input, options) {
return parser(options, input);
}
function parser(options, input) {
return new _state.Parser(_options.getOptions(options), String(input));
}

View File

@ -1,93 +0,0 @@
/* */
"format cjs";
"use strict";
var _babelToolsProtectJs2 = require("./../../babel/tools/protect.js");
var _babelToolsProtectJs3 = _interopRequireDefault(_babelToolsProtectJs2);
exports.__esModule = true;
exports.getLineInfo = getLineInfo;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var _state = require("./state");
var _whitespace = require("./whitespace");
_babelToolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
// These are used when `options.locations` is on, for the
// `startLoc` and `endLoc` properties.
var Position = (function () {
function Position(line, col) {
_classCallCheck(this, Position);
this.line = line;
this.column = col;
}
Position.prototype.offset = function offset(n) {
return new Position(this.line, this.column + n);
};
return Position;
})();
exports.Position = Position;
var SourceLocation = function SourceLocation(p, start, end) {
_classCallCheck(this, SourceLocation);
this.start = start;
this.end = end;
if (p.sourceFile !== null) this.source = p.sourceFile;
};
exports.SourceLocation = SourceLocation;
// 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;;) {
_whitespace.lineBreakG.lastIndex = cur;
var match = _whitespace.lineBreakG.exec(input);
if (match && match.index < offset) {
++line;
cur = match.index + match[0].length;
} else {
return new Position(line, offset - cur);
}
}
}
var pp = _state.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.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.curPosition = function () {
return new Position(this.curLine, this.pos - this.lineStart);
};
pp.markPosition = function () {
return this.options.locations ? [this.start, this.startLoc] : this.start;
};

View File

@ -1,38 +0,0 @@
/* */
"format cjs";
"use strict";
var _babelToolsProtectJs2 = require("./../../babel/tools/protect.js");
var _babelToolsProtectJs3 = _interopRequireDefault(_babelToolsProtectJs2);
var _state = require("./state");
_babelToolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var pp = _state.Parser.prototype;
var STATE_KEYS = ["lastTokStartLoc", "lastTokEndLoc", "lastTokStart", "lastTokEnd", "lineStart", "startLoc", "curLine", "endLoc", "start", "pos", "end", "type", "value", "exprAllowed", "potentialArrowAt", "currLine", "input", "inType", "inFunction", "inGenerator", "labels"];
pp.getState = function () {
var state = {};
for (var i = 0; i < STATE_KEYS.length; i++) {
var key = STATE_KEYS[i];
state[key] = this[key];
}
state.context = this.context.slice();
state.labels = this.labels.slice();
return state;
};
pp.lookahead = function () {
var old = this.getState();
this.isLookahead = true;
this.next();
this.isLookahead = false;
var curr = this.getState();
for (var key in old) this[key] = old[key];
return curr;
};

View File

@ -1,217 +0,0 @@
/* */
"format cjs";
"use strict";
var _babelToolsProtectJs2 = require("./../../babel/tools/protect.js");
var _babelToolsProtectJs3 = _interopRequireDefault(_babelToolsProtectJs2);
var _tokentype = require("./tokentype");
var _state = require("./state");
var _identifier = require("./identifier");
var _util = require("./util");
_babelToolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var pp = _state.Parser.prototype;
// Convert existing expression atom to assignable pattern
// if possible.
pp.toAssignable = function (node, isBinding) {
if (this.options.ecmaVersion >= 6 && node) {
switch (node.type) {
case "Identifier":
case "ObjectPattern":
case "ArrayPattern":
case "AssignmentPattern":
break;
case "ObjectExpression":
node.type = "ObjectPattern";
for (var i = 0; i < node.properties.length; i++) {
var prop = node.properties[i];
if (prop.type === "SpreadProperty") continue;
if (prop.kind !== "init") this.raise(prop.key.start, "Object pattern can't contain getter or setter");
this.toAssignable(prop.value, isBinding);
}
break;
case "ArrayExpression":
node.type = "ArrayPattern";
this.toAssignableList(node.elements, isBinding);
break;
case "AssignmentExpression":
if (node.operator === "=") {
node.type = "AssignmentPattern";
delete node.operator;
} else {
this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
}
break;
case "MemberExpression":
if (!isBinding) break;
default:
this.raise(node.start, "Assigning to rvalue");
}
}
return node;
};
// Convert list of expression atoms to binding list.
pp.toAssignableList = function (exprList, isBinding) {
var end = exprList.length;
if (end) {
var last = exprList[end - 1];
if (last && last.type == "RestElement") {
--end;
} else if (last && last.type == "SpreadElement") {
last.type = "RestElement";
var arg = last.argument;
this.toAssignable(arg, isBinding);
if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern") this.unexpected(arg.start);
--end;
}
}
for (var i = 0; i < end; i++) {
var elt = exprList[i];
if (elt) this.toAssignable(elt, isBinding);
}
return exprList;
};
// Parses spread element.
pp.parseSpread = function (refShorthandDefaultPos) {
var node = this.startNode();
this.next();
node.argument = this.parseMaybeAssign(refShorthandDefaultPos);
return this.finishNode(node, "SpreadElement");
};
pp.parseRest = function () {
var node = this.startNode();
this.next();
node.argument = this.type === _tokentype.types.name || this.type === _tokentype.types.bracketL ? this.parseBindingAtom() : this.unexpected();
return this.finishNode(node, "RestElement");
};
// Parses lvalue (assignable) atom.
pp.parseBindingAtom = function () {
if (this.options.ecmaVersion < 6) return this.parseIdent();
switch (this.type) {
case _tokentype.types.name:
return this.parseIdent();
case _tokentype.types.bracketL:
var node = this.startNode();
this.next();
node.elements = this.parseBindingList(_tokentype.types.bracketR, true, true);
return this.finishNode(node, "ArrayPattern");
case _tokentype.types.braceL:
return this.parseObj(true);
default:
this.unexpected();
}
};
pp.parseBindingList = function (close, allowEmpty, allowTrailingComma) {
var elts = [],
first = true;
while (!this.eat(close)) {
if (first) first = false;else this.expect(_tokentype.types.comma);
if (allowEmpty && this.type === _tokentype.types.comma) {
elts.push(null);
} else if (allowTrailingComma && this.afterTrailingComma(close)) {
break;
} else if (this.type === _tokentype.types.ellipsis) {
elts.push(this.parseAssignableListItemTypes(this.parseRest()));
this.expect(close);
break;
} else {
var left = this.parseMaybeDefault();
this.parseAssignableListItemTypes(left);
elts.push(this.parseMaybeDefault(null, left));
}
}
return elts;
};
pp.parseAssignableListItemTypes = function (param) {
return param;
};
// Parses assignment pattern around given atom if possible.
pp.parseMaybeDefault = function (startPos, left) {
startPos = startPos || this.markPosition();
left = left || this.parseBindingAtom();
if (!this.eat(_tokentype.types.eq)) return left;
var node = this.startNodeAt(startPos);
node.operator = "=";
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.
pp.checkLVal = function (expr, isBinding, checkClashes) {
switch (expr.type) {
case "Identifier":
if (this.strict && (_identifier.reservedWords.strictBind(expr.name) || _identifier.reservedWords.strict(expr.name))) this.raise(expr.start, (isBinding ? "Binding " : "Assigning to ") + expr.name + " in strict mode");
if (checkClashes) {
if (_util.has(checkClashes, expr.name)) this.raise(expr.start, "Argument name clash in strict mode");
checkClashes[expr.name] = true;
}
break;
case "MemberExpression":
if (isBinding) this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " member expression");
break;
case "ObjectPattern":
for (var i = 0; i < expr.properties.length; i++) {
var prop = expr.properties[i];
if (prop.type === "Property") prop = prop.value;
this.checkLVal(prop, isBinding, checkClashes);
}
break;
case "ArrayPattern":
for (var i = 0; i < expr.elements.length; i++) {
var elem = expr.elements[i];
if (elem) this.checkLVal(elem, isBinding, checkClashes);
}
break;
case "AssignmentPattern":
this.checkLVal(expr.left, isBinding, checkClashes);
break;
case "SpreadProperty":
case "RestElement":
this.checkLVal(expr.argument, isBinding, checkClashes);
break;
case "ParenthesizedExpression":
this.checkLVal(expr.expression, isBinding, checkClashes);
break;
default:
this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " rvalue");
}
};

View File

@ -1,73 +0,0 @@
/* */
"format cjs";
"use strict";
var _babelToolsProtectJs2 = require("./../../babel/tools/protect.js");
var _babelToolsProtectJs3 = _interopRequireDefault(_babelToolsProtectJs2);
exports.__esModule = true;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var _state = require("./state");
var _location = require("./location");
_babelToolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
// Start an AST node, attaching a start offset.
var pp = _state.Parser.prototype;
var Node = function Node() {
_classCallCheck(this, Node);
};
exports.Node = Node;
pp.startNode = function () {
var node = new Node();
node.start = this.start;
if (this.options.locations) node.loc = new _location.SourceLocation(this, this.startLoc);
if (this.options.directSourceFile) node.sourceFile = this.options.directSourceFile;
if (this.options.ranges) node.range = [this.start, 0];
return node;
};
pp.startNodeAt = function (pos) {
var node = new Node(),
start = pos;
if (this.options.locations) {
node.loc = new _location.SourceLocation(this, start[1]);
start = pos[0];
}
node.start = start;
if (this.options.directSourceFile) node.sourceFile = this.options.directSourceFile;
if (this.options.ranges) node.range = [start, 0];
return node;
};
// Finish an AST node, adding `type` and `end` properties.
pp.finishNode = function (node, type) {
node.type = type;
node.end = this.lastTokEnd;
if (this.options.locations) node.loc.end = this.lastTokEndLoc;
if (this.options.ranges) node.range[1] = this.lastTokEnd;
return node;
};
// Finish node at given position
pp.finishNodeAt = function (node, type, pos) {
if (this.options.locations) {
node.loc.end = pos[1];pos = pos[0];
}
node.type = type;
node.end = pos;
if (this.options.ranges) node.range[1] = pos;
return node;
};

View File

@ -1,138 +0,0 @@
/* */
"format cjs";
"use strict";
var _babelToolsProtectJs2 = require("./../../babel/tools/protect.js");
var _babelToolsProtectJs3 = _interopRequireDefault(_babelToolsProtectJs2);
exports.__esModule = true;
exports.getOptions = getOptions;
var _util = require("./util");
var _location = require("./location");
_babelToolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
// 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, or 5, or 6. This influences support for strict
// mode, the set of reserved words, support for getters and
// setters and other features.
ecmaVersion: 5,
// Source type ("script" or "module") for different semantics
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 not enforced. Disable
// `allowReserved` to enforce them. When this option has the
// value "never", reserved words and keywords can also not be
// used as property names.
allowReserved: true,
// 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 tokenize() returns. 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: {},
// Babel-specific options
features: {},
strictMode: null
};
exports.defaultOptions = defaultOptions;
// Interpret and default an options object
function getOptions(opts) {
var options = {};
for (var opt in defaultOptions) {
options[opt] = opts && _util.has(opts, opt) ? opts[opt] : defaultOptions[opt];
}if (Array.isArray(options.onToken)) {
(function () {
var tokens = options.onToken;
options.onToken = function (token) {
return tokens.push(token);
};
})();
}
if (Array.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 _location.SourceLocation(this, startLoc, endLoc);
if (options.ranges) comment.range = [start, end];
array.push(comment);
};
}

View File

@ -1,98 +0,0 @@
/* */
"format cjs";
"use strict";
var _babelToolsProtectJs2 = require("./../../babel/tools/protect.js");
var _babelToolsProtectJs3 = _interopRequireDefault(_babelToolsProtectJs2);
var _tokentype = require("./tokentype");
var _state = require("./state");
var _whitespace = require("./whitespace");
_babelToolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var pp = _state.Parser.prototype;
// ## Parser utilities
// Test whether a statement node is the string literal `"use strict"`.
pp.isUseStrict = function (stmt) {
return this.options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && stmt.expression.value === "use strict";
};
// 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 === _tokentype.types.name && this.value === name;
};
// Consumes contextual keyword if possible.
pp.eatContextual = function (name) {
return this.value === name && this.eat(_tokentype.types.name);
};
// 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 === _tokentype.types.eof || this.type === _tokentype.types.braceR || _whitespace.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(_tokentype.types.semi) && !this.insertSemicolon()) this.unexpected();
};
pp.afterTrailingComma = function (tokType) {
if (this.type == tokType) {
if (this.options.onTrailingComma) this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc);
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");
};

View File

@ -1,96 +0,0 @@
/* */
"format cjs";
"use strict";
var _babelToolsProtectJs2 = require("./../../babel/tools/protect.js");
var _babelToolsProtectJs3 = _interopRequireDefault(_babelToolsProtectJs2);
exports.__esModule = true;
exports.Parser = Parser;
var _identifier = require("./identifier");
var _tokentype = require("./tokentype");
var _whitespace = require("./whitespace");
_babelToolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function Parser(options, input, startPos) {
this.options = options;
this.sourceFile = this.options.sourceFile || null;
this.isKeyword = _identifier.keywords[this.options.ecmaVersion >= 6 ? 6 : 5];
this.isReservedWord = _identifier.reservedWords[this.options.ecmaVersion];
this.input = input;
this.loadPlugins(this.options.plugins);
// Set up token state
// The current position of the tokenizer in the input.
if (startPos) {
this.pos = startPos;
this.lineStart = Math.max(0, this.input.lastIndexOf("\n", startPos));
this.curLine = this.input.slice(0, this.lineStart).split(_whitespace.lineBreak).length;
} else {
this.pos = this.lineStart = 0;
this.curLine = 1;
}
// Properties of the current token:
// Its type
this.type = _tokentype.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 = null;
// 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 = this.options.sourceType === "module";
this.strict = this.options.strictMode === false ? false : this.inModule;
// Used to signify the start of a potential arrow function
this.potentialArrowAt = -1;
// Flags to track whether we are in a function, a generator.
this.inFunction = this.inGenerator = false;
// Labels in scope.
this.labels = [];
this.decorators = [];
// If enabled, skip leading hashbang line.
if (this.pos === 0 && this.options.allowHashBang && this.input.slice(0, 2) === "#!") this.skipLineComment(2);
}
Parser.prototype.extend = function (name, f) {
this[name] = f(this[name]);
};
// Registered plugins
var plugins = {};
exports.plugins = plugins;
Parser.prototype.loadPlugins = function (plugins) {
for (var _name in plugins) {
var plugin = exports.plugins[_name];
if (!plugin) throw new Error("Plugin '" + _name + "' not found");
plugin(this, plugins[_name]);
}
};

View File

@ -1,779 +0,0 @@
/* */
"format cjs";
"use strict";
var _babelToolsProtectJs2 = require("./../../babel/tools/protect.js");
var _babelToolsProtectJs3 = _interopRequireDefault(_babelToolsProtectJs2);
var _tokentype = require("./tokentype");
var _state = require("./state");
var _whitespace = require("./whitespace");
_babelToolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var pp = _state.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.parseTopLevel = function (node) {
var first = true;
if (!node.body) node.body = [];
while (this.type !== _tokentype.types.eof) {
var stmt = this.parseStatement(true, true);
node.body.push(stmt);
if (first && this.isUseStrict(stmt)) this.setStrict(true);
first = false;
}
this.next();
if (this.options.ecmaVersion >= 6) {
node.sourceType = this.options.sourceType;
}
return this.finishNode(node, "Program");
};
var loopLabel = { kind: "loop" },
switchLabel = { kind: "switch" };
// 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.parseStatement = function (declaration, topLevel) {
if (this.type === _tokentype.types.at) {
this.parseDecorators(true);
}
var starttype = this.type,
node = this.startNode();
// 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 _tokentype.types._break:case _tokentype.types._continue:
return this.parseBreakContinueStatement(node, starttype.keyword);
case _tokentype.types._debugger:
return this.parseDebuggerStatement(node);
case _tokentype.types._do:
return this.parseDoStatement(node);
case _tokentype.types._for:
return this.parseForStatement(node);
case _tokentype.types._function:
if (!declaration && this.options.ecmaVersion >= 6) this.unexpected();
return this.parseFunctionStatement(node);
case _tokentype.types._class:
if (!declaration) this.unexpected();
this.takeDecorators(node);
return this.parseClass(node, true);
case _tokentype.types._if:
return this.parseIfStatement(node);
case _tokentype.types._return:
return this.parseReturnStatement(node);
case _tokentype.types._switch:
return this.parseSwitchStatement(node);
case _tokentype.types._throw:
return this.parseThrowStatement(node);
case _tokentype.types._try:
return this.parseTryStatement(node);
case _tokentype.types._let:case _tokentype.types._const:
if (!declaration) this.unexpected(); // NOTE: falls through to _var
case _tokentype.types._var:
return this.parseVarStatement(node, starttype);
case _tokentype.types._while:
return this.parseWhileStatement(node);
case _tokentype.types._with:
return this.parseWithStatement(node);
case _tokentype.types.braceL:
return this.parseBlock();
case _tokentype.types.semi:
return this.parseEmptyStatement(node);
case _tokentype.types._export:
case _tokentype.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 === _tokentype.types._import ? this.parseImport(node) : this.parseExport(node);
case _tokentype.types.name:
if (this.options.features["es7.asyncFunctions"] && this.value === "async") {
var lookahead = this.lookahead();
if (lookahead.type === _tokentype.types._function && !this.canInsertSemicolon.call(lookahead)) {
this.next();
this.expect(_tokentype.types._function);
return this.parseFunction(node, true, false, true);
}
}
// 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:
var maybeName = this.value,
expr = this.parseExpression();
if (starttype === _tokentype.types.name && expr.type === "Identifier" && this.eat(_tokentype.types.colon)) return this.parseLabeledStatement(node, maybeName, expr);else return this.parseExpressionStatement(node, expr);
}
};
pp.takeDecorators = function (node) {
if (this.decorators.length) {
node.decorators = this.decorators;
this.decorators = [];
}
};
pp.parseDecorators = function (allowExport) {
while (this.type === _tokentype.types.at) {
this.decorators.push(this.parseDecorator());
}
if (allowExport && this.type === _tokentype.types._export) {
return;
}
if (this.type !== _tokentype.types._class) {
this.raise(this.start, "Leading decorators must be attached to a class declaration");
}
};
pp.parseDecorator = function (allowExport) {
if (!this.options.features["es7.decorators"]) {
this.unexpected();
}
var node = this.startNode();
this.next();
node.expression = this.parseMaybeAssign();
return this.finishNode(node, "Decorator");
};
pp.parseBreakContinueStatement = function (node, keyword) {
var isBreak = keyword == "break";
this.next();
if (this.eat(_tokentype.types.semi) || this.insertSemicolon()) node.label = null;else if (this.type !== _tokentype.types.name) this.unexpected();else {
node.label = this.parseIdent();
this.semicolon();
}
// Verify that there is an actual destination to break or
// continue to.
for (var i = 0; i < this.labels.length; ++i) {
var lab = this.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.parseDebuggerStatement = function (node) {
this.next();
this.semicolon();
return this.finishNode(node, "DebuggerStatement");
};
pp.parseDoStatement = function (node) {
var start = this.markPosition();
this.next();
this.labels.push(loopLabel);
node.body = this.parseStatement(false);
this.labels.pop();
this.expect(_tokentype.types._while);
node.test = this.parseParenExpression();
if (this.options.ecmaVersion >= 6) this.eat(_tokentype.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.parseForStatement = function (node) {
this.next();
this.labels.push(loopLabel);
this.expect(_tokentype.types.parenL);
if (this.type === _tokentype.types.semi) return this.parseFor(node, null);
if (this.type === _tokentype.types._var || this.type === _tokentype.types._let || this.type === _tokentype.types._const) {
var _init = this.startNode(),
varKind = this.type;
this.next();
this.parseVar(_init, true, varKind);
this.finishNode(_init, "VariableDeclaration");
if ((this.type === _tokentype.types._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && _init.declarations.length === 1 && !(varKind !== _tokentype.types._var && _init.declarations[0].init)) return this.parseForIn(node, _init);
return this.parseFor(node, _init);
}
var refShorthandDefaultPos = { start: 0 };
var init = this.parseExpression(true, refShorthandDefaultPos);
if (this.type === _tokentype.types._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) {
this.toAssignable(init);
this.checkLVal(init);
return this.parseForIn(node, init);
} else if (refShorthandDefaultPos.start) {
this.unexpected(refShorthandDefaultPos.start);
}
return this.parseFor(node, init);
};
pp.parseFunctionStatement = function (node) {
this.next();
return this.parseFunction(node, true);
};
pp.parseIfStatement = function (node) {
this.next();
node.test = this.parseParenExpression();
node.consequent = this.parseStatement(false);
node.alternate = this.eat(_tokentype.types._else) ? this.parseStatement(false) : null;
return this.finishNode(node, "IfStatement");
};
pp.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(_tokentype.types.semi) || this.insertSemicolon()) node.argument = null;else {
node.argument = this.parseExpression();this.semicolon();
}
return this.finishNode(node, "ReturnStatement");
};
pp.parseSwitchStatement = function (node) {
this.next();
node.discriminant = this.parseParenExpression();
node.cases = [];
this.expect(_tokentype.types.braceL);
this.labels.push(switchLabel);
// Statements under must be grouped (by label) in SwitchCase
// nodes. `cur` is used to keep the node that we are currently
// adding statements to.
for (var cur, sawDefault; this.type != _tokentype.types.braceR;) {
if (this.type === _tokentype.types._case || this.type === _tokentype.types._default) {
var isCase = this.type === _tokentype.types._case;
if (cur) this.finishNode(cur, "SwitchCase");
node.cases.push(cur = this.startNode());
cur.consequent = [];
this.next();
if (isCase) {
cur.test = this.parseExpression();
} else {
if (sawDefault) this.raise(this.lastTokStart, "Multiple default clauses");
sawDefault = true;
cur.test = null;
}
this.expect(_tokentype.types.colon);
} else {
if (!cur) this.unexpected();
cur.consequent.push(this.parseStatement(true));
}
}
if (cur) this.finishNode(cur, "SwitchCase");
this.next(); // Closing brace
this.labels.pop();
return this.finishNode(node, "SwitchStatement");
};
pp.parseThrowStatement = function (node) {
this.next();
if (_whitespace.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.parseTryStatement = function (node) {
this.next();
node.block = this.parseBlock();
node.handler = null;
if (this.type === _tokentype.types._catch) {
var clause = this.startNode();
this.next();
this.expect(_tokentype.types.parenL);
clause.param = this.parseBindingAtom();
this.checkLVal(clause.param, true);
this.expect(_tokentype.types.parenR);
clause.guard = null;
clause.body = this.parseBlock();
node.handler = this.finishNode(clause, "CatchClause");
}
node.guardedHandlers = empty;
node.finalizer = this.eat(_tokentype.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.parseVarStatement = function (node, kind) {
this.next();
this.parseVar(node, false, kind);
this.semicolon();
return this.finishNode(node, "VariableDeclaration");
};
pp.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.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.parseEmptyStatement = function (node) {
this.next();
return this.finishNode(node, "EmptyStatement");
};
pp.parseLabeledStatement = function (node, maybeName, expr) {
for (var i = 0; i < this.labels.length; ++i) {
if (this.labels[i].name === maybeName) this.raise(expr.start, "Label '" + maybeName + "' is already declared");
}var kind = this.type.isLoop ? "loop" : this.type === _tokentype.types._switch ? "switch" : null;
for (var i = this.labels.length - 1; i >= 0; i--) {
var label = this.labels[i];
if (label.statementStart == node.start) {
label.statementStart = this.start;
label.kind = kind;
} else break;
}
this.labels.push({ name: maybeName, kind: kind, statementStart: this.start });
node.body = this.parseStatement(true);
this.labels.pop();
node.label = expr;
return this.finishNode(node, "LabeledStatement");
};
pp.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.parseBlock = function (allowStrict) {
var node = this.startNode(),
first = true,
oldStrict = undefined;
node.body = [];
this.expect(_tokentype.types.braceL);
while (!this.eat(_tokentype.types.braceR)) {
var stmt = this.parseStatement(true);
node.body.push(stmt);
if (first && allowStrict && this.isUseStrict(stmt)) {
oldStrict = this.strict;
this.setStrict(this.strict = true);
}
first = false;
}
if (oldStrict === false) this.setStrict(false);
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.parseFor = function (node, init) {
node.init = init;
this.expect(_tokentype.types.semi);
node.test = this.type === _tokentype.types.semi ? null : this.parseExpression();
this.expect(_tokentype.types.semi);
node.update = this.type === _tokentype.types.parenR ? null : this.parseExpression();
this.expect(_tokentype.types.parenR);
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.parseForIn = function (node, init) {
var type = this.type === _tokentype.types._in ? "ForInStatement" : "ForOfStatement";
this.next();
node.left = init;
node.right = this.parseExpression();
this.expect(_tokentype.types.parenR);
node.body = this.parseStatement(false);
this.labels.pop();
return this.finishNode(node, type);
};
// Parse a list of variable declarations.
pp.parseVar = function (node, isFor, kind) {
node.declarations = [];
node.kind = kind.keyword;
for (;;) {
var decl = this.startNode();
this.parseVarHead(decl);
if (this.eat(_tokentype.types.eq)) {
decl.init = this.parseMaybeAssign(isFor);
} else if (kind === _tokentype.types._const && !(this.type === _tokentype.types._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
this.unexpected();
} else if (decl.id.type != "Identifier" && !(isFor && (this.type === _tokentype.types._in || this.isContextual("of")))) {
this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
} else {
decl.init = null;
}
node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
if (!this.eat(_tokentype.types.comma)) break;
}
return node;
};
pp.parseVarHead = function (decl) {
decl.id = this.parseBindingAtom();
this.checkLVal(decl.id, true);
};
// Parse a function declaration or literal (depending on the
// `isStatement` parameter).
pp.parseFunction = function (node, isStatement, allowExpressionBody, isAsync) {
this.initFunction(node, isAsync);
if (this.options.ecmaVersion >= 6) node.generator = this.eat(_tokentype.types.star);
if (isStatement || this.type === _tokentype.types.name) node.id = this.parseIdent();
this.parseFunctionParams(node);
this.parseFunctionBody(node, allowExpressionBody);
return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
};
pp.parseFunctionParams = function (node) {
this.expect(_tokentype.types.parenL);
node.params = this.parseBindingList(_tokentype.types.parenR, false, this.options.features["es7.trailingFunctionCommas"]);
};
// Parse a class declaration or literal (depending on the
// `isStatement` parameter).
pp.parseClass = function (node, isStatement) {
this.next();
this.parseClassId(node, isStatement);
this.parseClassSuper(node);
var classBody = this.startNode();
var hadConstructor = false;
classBody.body = [];
this.expect(_tokentype.types.braceL);
var decorators = [];
while (!this.eat(_tokentype.types.braceR)) {
if (this.eat(_tokentype.types.semi)) continue;
if (this.type === _tokentype.types.at) {
decorators.push(this.parseDecorator());
continue;
}
var method = this.startNode();
if (decorators.length) {
method.decorators = decorators;
decorators = [];
}
var isMaybeStatic = this.type === _tokentype.types.name && this.value === "static";
var isGenerator = this.eat(_tokentype.types.star),
isAsync = false;
this.parsePropertyName(method);
method["static"] = isMaybeStatic && this.type !== _tokentype.types.parenL;
if (method["static"]) {
if (isGenerator) this.unexpected();
isGenerator = this.eat(_tokentype.types.star);
this.parsePropertyName(method);
}
if (!isGenerator && method.key.type === "Identifier" && !method.computed && this.isClassProperty()) {
classBody.body.push(this.parseClassProperty(method));
continue;
}
if (this.options.features["es7.asyncFunctions"] && this.type !== _tokentype.types.parenL && !method.computed && method.key.type === "Identifier" && method.key.name === "async") {
isAsync = true;
this.parsePropertyName(method);
}
var isGetSet = false;
method.kind = "method";
if (!method.computed) {
var key = method.key;
if (!isAsync && !isGenerator && key.type === "Identifier" && this.type !== _tokentype.types.parenL && (key.name === "get" || key.name === "set")) {
isGetSet = true;
method.kind = key.name;
key = this.parsePropertyName(method);
}
if (!method["static"] && (key.type === "Identifier" && key.name === "constructor" || key.type === "Literal" && key.value === "constructor")) {
if (hadConstructor) this.raise(key.start, "Duplicate constructor in the same class");
if (isGetSet) 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 function");
method.kind = "constructor";
hadConstructor = true;
}
}
if (method.kind === "constructor" && method.decorators) {
this.raise(method.start, "You can't attach decorators to a class constructor");
}
this.parseClassMethod(classBody, method, isGenerator, isAsync);
if (isGetSet) {
var paramCount = method.kind === "get" ? 0 : 1;
if (method.value.params.length !== paramCount) {
var start = method.value.start;
if (method.kind === "get") this.raise(start, "getter should have no params");else this.raise(start, "setter should have exactly one param");
}
}
}
if (decorators.length) {
this.raise(this.start, "You have trailing decorators with no method");
}
node.body = this.finishNode(classBody, "ClassBody");
return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
};
pp.isClassProperty = function () {
return this.type === _tokentype.types.eq || (this.type === _tokentype.types.semi || this.canInsertSemicolon());
};
pp.parseClassProperty = function (node) {
if (this.type === _tokentype.types.eq) {
if (!this.options.features["es7.classProperties"]) this.unexpected();
this.next();
node.value = this.parseMaybeAssign();
} else {
node.value = null;
}
this.semicolon();
return this.finishNode(node, "ClassProperty");
};
pp.parseClassMethod = function (classBody, method, isGenerator, isAsync) {
method.value = this.parseMethod(isGenerator, isAsync);
classBody.body.push(this.finishNode(method, "MethodDefinition"));
};
pp.parseClassId = function (node, isStatement) {
node.id = this.type === _tokentype.types.name ? this.parseIdent() : isStatement ? this.unexpected() : null;
};
pp.parseClassSuper = function (node) {
node.superClass = this.eat(_tokentype.types._extends) ? this.parseExprSubscripts() : null;
};
// Parses module export declaration.
pp.parseExport = function (node) {
this.next();
// export * from '...'
if (this.type === _tokentype.types.star) {
var specifier = this.startNode();
this.next();
if (this.options.features["es7.exportExtensions"] && this.eatContextual("as")) {
specifier.exported = this.parseIdent();
node.specifiers = [this.finishNode(specifier, "ExportNamespaceSpecifier")];
this.parseExportSpecifiersMaybe(node);
this.parseExportFrom(node);
} else {
this.parseExportFrom(node);
return this.finishNode(node, "ExportAllDeclaration");
}
} else if (this.options.features["es7.exportExtensions"] && this.isExportDefaultSpecifier()) {
var specifier = this.startNode();
specifier.exported = this.parseIdent(true);
node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
if (this.type === _tokentype.types.comma && this.lookahead().type === _tokentype.types.star) {
this.expect(_tokentype.types.comma);
var _specifier = this.startNode();
this.expect(_tokentype.types.star);
this.expectContextual("as");
_specifier.exported = this.parseIdent();
node.specifiers.push(this.finishNode(_specifier, "ExportNamespaceSpecifier"));
} else {
this.parseExportSpecifiersMaybe(node);
}
this.parseExportFrom(node);
} else if (this.eat(_tokentype.types._default)) {
// export default ...
var expr = this.parseMaybeAssign();
var needsSemi = true;
if (expr.type == "FunctionExpression" || expr.type == "ClassExpression") {
needsSemi = false;
if (expr.id) {
expr.type = expr.type == "FunctionExpression" ? "FunctionDeclaration" : "ClassDeclaration";
}
}
node.declaration = expr;
if (needsSemi) this.semicolon();
this.checkExport(node);
return this.finishNode(node, "ExportDefaultDeclaration");
} else if (this.type.keyword || this.shouldParseExportDeclaration()) {
node.declaration = this.parseStatement(true);
node.specifiers = [];
node.source = null;
} else {
// export { x, y as z } [from '...']
node.declaration = null;
node.specifiers = this.parseExportSpecifiers();
if (this.eatContextual("from")) {
node.source = this.type === _tokentype.types.string ? this.parseExprAtom() : this.unexpected();
} else {
node.source = null;
}
this.semicolon();
}
this.checkExport(node);
return this.finishNode(node, "ExportNamedDeclaration");
};
pp.isExportDefaultSpecifier = function () {
if (this.type === _tokentype.types.name) {
return this.value !== "type" && this.value !== "async";
}
if (this.type !== _tokentype.types._default) {
return false;
}
var lookahead = this.lookahead();
return lookahead.type === _tokentype.types.comma || lookahead.type === _tokentype.types.name && lookahead.value === "from";
};
pp.parseExportSpecifiersMaybe = function (node) {
if (this.eat(_tokentype.types.comma)) {
node.specifiers = node.specifiers.concat(this.parseExportSpecifiers());
}
};
pp.parseExportFrom = function (node) {
this.expectContextual("from");
node.source = this.type === _tokentype.types.string ? this.parseExprAtom() : this.unexpected();
this.semicolon();
this.checkExport(node);
};
pp.shouldParseExportDeclaration = function () {
return this.options.features["es7.asyncFunctions"] && this.isContextual("async");
};
pp.checkExport = function (node) {
if (this.decorators.length) {
var isClass = node.declaration && (node.declaration.type === "ClassDeclaration" || node.declaration.type === "ClassExpression");
if (!node.declaration || !isClass) {
this.raise(node.start, "You can only use decorators on an export when exporting a class");
}
this.takeDecorators(node.declaration);
}
};
// Parses a comma-separated list of module exports.
pp.parseExportSpecifiers = function () {
var nodes = [],
first = true;
// export { x, y as z } [from '...']
this.expect(_tokentype.types.braceL);
while (!this.eat(_tokentype.types.braceR)) {
if (!first) {
this.expect(_tokentype.types.comma);
if (this.afterTrailingComma(_tokentype.types.braceR)) break;
} else first = false;
var node = this.startNode();
node.local = this.parseIdent(this.type === _tokentype.types._default);
node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
nodes.push(this.finishNode(node, "ExportSpecifier"));
}
return nodes;
};
// Parses import declaration.
pp.parseImport = function (node) {
this.next();
// import '...'
if (this.type === _tokentype.types.string) {
node.specifiers = empty;
node.source = this.parseExprAtom();
} else {
node.specifiers = [];
this.parseImportSpecifiers(node);
this.expectContextual("from");
node.source = this.type === _tokentype.types.string ? this.parseExprAtom() : this.unexpected();
}
this.semicolon();
return this.finishNode(node, "ImportDeclaration");
};
// Parses a comma-separated list of module imports.
pp.parseImportSpecifiers = function (node) {
var first = true;
if (this.type === _tokentype.types.name) {
// import defaultObj, { x, y as z } from '...'
var start = this.markPosition();
node.specifiers.push(this.parseImportSpecifierDefault(this.parseIdent(), start));
if (!this.eat(_tokentype.types.comma)) return;
}
if (this.type === _tokentype.types.star) {
var specifier = this.startNode();
this.next();
this.expectContextual("as");
specifier.local = this.parseIdent();
this.checkLVal(specifier.local, true);
node.specifiers.push(this.finishNode(specifier, "ImportNamespaceSpecifier"));
return;
}
this.expect(_tokentype.types.braceL);
while (!this.eat(_tokentype.types.braceR)) {
if (!first) {
this.expect(_tokentype.types.comma);
if (this.afterTrailingComma(_tokentype.types.braceR)) break;
} else first = false;
var specifier = this.startNode();
specifier.imported = this.parseIdent(true);
specifier.local = this.eatContextual("as") ? this.parseIdent() : specifier.imported;
this.checkLVal(specifier.local, true);
node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
}
};
pp.parseImportSpecifierDefault = function (id, start) {
var node = this.startNodeAt(start);
node.local = id;
this.checkLVal(node.local, true);
return this.finishNode(node, "ImportDefaultSpecifier");
};

View File

@ -1,117 +0,0 @@
/* */
"format cjs";
"use strict";
var _babelToolsProtectJs2 = require("./../../babel/tools/protect.js");
var _babelToolsProtectJs3 = _interopRequireDefault(_babelToolsProtectJs2);
exports.__esModule = true;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
// 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 _state = require("./state");
var _tokentype = require("./tokentype");
var _whitespace = require("./whitespace");
_babelToolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var TokContext = function TokContext(token, isExpr, preserveSpace, override) {
_classCallCheck(this, TokContext);
this.token = token;
this.isExpr = isExpr;
this.preserveSpace = preserveSpace;
this.override = override;
};
exports.TokContext = TokContext;
var types = {
b_stat: new TokContext("{", false),
b_expr: new TokContext("{", true),
b_tmpl: new TokContext("${", true),
p_stat: new TokContext("(", false),
p_expr: new TokContext("(", true),
q_tmpl: new TokContext("`", true, true, function (p) {
return p.readTmplToken();
}),
f_expr: new TokContext("function", true)
};
exports.types = types;
var pp = _state.Parser.prototype;
pp.initialContext = function () {
return [types.b_stat];
};
pp.braceIsBlock = function (prevType) {
var parent = undefined;
if (prevType === _tokentype.types.colon && (parent = this.curContext()).token == "{") return !parent.isExpr;
if (prevType === _tokentype.types._return) return _whitespace.lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
if (prevType === _tokentype.types._else || prevType === _tokentype.types.semi || prevType === _tokentype.types.eof) return true;
if (prevType == _tokentype.types.braceL) return this.curContext() === types.b_stat;
return !this.exprAllowed;
};
pp.updateContext = function (prevType) {
var update = undefined,
type = this.type;
if (type.keyword && prevType == _tokentype.types.dot) this.exprAllowed = false;else if (update = type.updateContext) update.call(this, prevType);else this.exprAllowed = type.beforeExpr;
};
// Token-specific context update code
_tokentype.types.parenR.updateContext = _tokentype.types.braceR.updateContext = function () {
if (this.context.length == 1) {
this.exprAllowed = true;
return;
}
var out = this.context.pop();
if (out === types.b_stat && this.curContext() === types.f_expr) {
this.context.pop();
this.exprAllowed = false;
} else if (out === types.b_tmpl) {
this.exprAllowed = true;
} else {
this.exprAllowed = !out.isExpr;
}
};
_tokentype.types.braceL.updateContext = function (prevType) {
this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
this.exprAllowed = true;
};
_tokentype.types.dollarBraceL.updateContext = function () {
this.context.push(types.b_tmpl);
this.exprAllowed = true;
};
_tokentype.types.parenL.updateContext = function (prevType) {
var statementParens = prevType === _tokentype.types._if || prevType === _tokentype.types._for || prevType === _tokentype.types._with || prevType === _tokentype.types._while;
this.context.push(statementParens ? types.p_stat : types.p_expr);
this.exprAllowed = true;
};
_tokentype.types.incDec.updateContext = function () {};
_tokentype.types._function.updateContext = function () {
if (this.curContext() !== types.b_stat) this.context.push(types.f_expr);
this.exprAllowed = false;
};
_tokentype.types.backQuote.updateContext = function () {
if (this.curContext() === types.q_tmpl) this.context.pop();else this.context.push(types.q_tmpl);
this.exprAllowed = false;
};
// tokExprAllowed stays unchanged

View File

@ -1,778 +0,0 @@
/* */
"format cjs";
"use strict";
var _babelToolsProtectJs2 = require("./../../babel/tools/protect.js");
var _babelToolsProtectJs3 = _interopRequireDefault(_babelToolsProtectJs2);
exports.__esModule = true;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var _identifier = require("./identifier");
var _tokentype = require("./tokentype");
var _state = require("./state");
var _location = require("./location");
var _whitespace = require("./whitespace");
_babelToolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
// 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) {
_classCallCheck(this, Token);
this.type = p.type;
this.value = p.value;
this.start = p.start;
this.end = p.end;
if (p.options.locations) this.loc = new _location.SourceLocation(p, p.startLoc, p.endLoc);
if (p.options.ranges) this.range = [p.start, p.end];
};
exports.Token = Token;
// ## Tokenizer
var pp = _state.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.next = function () {
if (this.options.onToken && !this.isLookahead) 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.getToken = function () {
this.next();
return new Token(this);
};
// If we're in an ES6 environment, make parsers iterable
if (typeof Symbol !== "undefined") pp[Symbol.iterator] = function () {
var self = this;
return { next: function next() {
var token = self.getToken();
return {
done: token.type === _tokentype.types.eof,
value: token
};
} };
};
// Toggle strict mode. Re-reads the next number or string to please
// pedantic tests (`"use strict"; 010;` should fail).
pp.setStrict = function (strict) {
this.strict = strict;
if (this.type !== _tokentype.types.num && this.type !== _tokentype.types.string) return;
this.pos = this.start;
if (this.options.locations) {
while (this.pos < this.lineStart) {
this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1;
--this.curLine;
}
}
this.nextToken();
};
pp.curContext = function () {
return this.context[this.context.length - 1];
};
// Read a single token, updating the parser object's token-related
// properties.
pp.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(_tokentype.types.eof);
if (curContext.override) return curContext.override(this);else this.readToken(this.fullCharCodeAtPos());
};
pp.readToken = function (code) {
// Identifier or keyword. '\uXXXX' sequences are allowed in
// identifiers, so '\' also dispatches to that.
if (_identifier.isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) return this.readWord();
return this.getTokenFromCode(code);
};
pp.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.skipBlockComment = function () {
var startLoc = this.options.onComment && this.options.locations && 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) {
_whitespace.lineBreakG.lastIndex = start;
var match = undefined;
while ((match = _whitespace.lineBreakG.exec(this.input)) && match.index < this.pos) {
++this.curLine;
this.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.options.locations && this.curPosition());
};
pp.skipLineComment = function (startSkip) {
var start = this.pos;
var startLoc = this.options.onComment && this.options.locations && this.curPosition();
var ch = this.input.charCodeAt(this.pos += startSkip);
while (this.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) {
++this.pos;
ch = this.input.charCodeAt(this.pos);
}
if (this.options.onComment) this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.options.locations && this.curPosition());
};
// Called at the start of the parse and after every token. Skips
// whitespace and comments, and.
pp.skipSpace = function () {
while (this.pos < this.input.length) {
var ch = this.input.charCodeAt(this.pos);
if (ch === 32) {
// ' '
++this.pos;
} else if (ch === 13) {
++this.pos;
var next = this.input.charCodeAt(this.pos);
if (next === 10) {
++this.pos;
}
if (this.options.locations) {
++this.curLine;
this.lineStart = this.pos;
}
} else if (ch === 10 || ch === 8232 || ch === 8233) {
++this.pos;
if (this.options.locations) {
++this.curLine;
this.lineStart = this.pos;
}
} else if (ch > 8 && ch < 14) {
++this.pos;
} else if (ch === 47) {
// '/'
var next = this.input.charCodeAt(this.pos + 1);
if (next === 42) {
// '*'
this.skipBlockComment();
} else if (next === 47) {
// '/'
this.skipLineComment(2);
} else break;
} else if (ch === 160) {
// '\xa0'
++this.pos;
} else if (ch >= 5760 && _whitespace.nonASCIIwhitespace.test(String.fromCharCode(ch))) {
++this.pos;
} else {
break;
}
}
};
// 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.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.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(_tokentype.types.ellipsis);
} else {
++this.pos;
return this.finishToken(_tokentype.types.dot);
}
};
pp.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(_tokentype.types.assign, 2);
return this.finishOp(_tokentype.types.slash, 1);
};
pp.readToken_mult_modulo = function (code) {
// '%*'
var type = code === 42 ? _tokentype.types.star : _tokentype.types.modulo;
var width = 1;
var next = this.input.charCodeAt(this.pos + 1);
if (next === 42) {
// '*'
width++;
next = this.input.charCodeAt(this.pos + 2);
type = _tokentype.types.exponent;
}
if (next === 61) {
width++;
type = _tokentype.types.assign;
}
return this.finishOp(type, width);
};
pp.readToken_pipe_amp = function (code) {
// '|&'
var next = this.input.charCodeAt(this.pos + 1);
if (next === code) return this.finishOp(code === 124 ? _tokentype.types.logicalOR : _tokentype.types.logicalAND, 2);
if (next === 61) return this.finishOp(_tokentype.types.assign, 2);
return this.finishOp(code === 124 ? _tokentype.types.bitwiseOR : _tokentype.types.bitwiseAND, 1);
};
pp.readToken_caret = function () {
// '^'
var next = this.input.charCodeAt(this.pos + 1);
if (next === 61) return this.finishOp(_tokentype.types.assign, 2);
return this.finishOp(_tokentype.types.bitwiseXOR, 1);
};
pp.readToken_plus_min = function (code) {
// '+-'
var next = this.input.charCodeAt(this.pos + 1);
if (next === code) {
if (next == 45 && this.input.charCodeAt(this.pos + 2) == 62 && _whitespace.lineBreak.test(this.input.slice(this.lastTokEnd, this.pos))) {
// A `-->` line comment
this.skipLineComment(3);
this.skipSpace();
return this.nextToken();
}
return this.finishOp(_tokentype.types.incDec, 2);
}
if (next === 61) return this.finishOp(_tokentype.types.assign, 2);
return this.finishOp(_tokentype.types.plusMin, 1);
};
pp.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(_tokentype.types.assign, size + 1);
return this.finishOp(_tokentype.types.bitShift, size);
}
if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 && this.input.charCodeAt(this.pos + 3) == 45) {
if (this.inModule) this.unexpected();
// `<!--`, an XML-style comment that should be interpreted as a line comment
this.skipLineComment(4);
this.skipSpace();
return this.nextToken();
}
if (next === 61) size = this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2;
return this.finishOp(_tokentype.types.relational, size);
};
pp.readToken_eq_excl = function (code) {
// '=!'
var next = this.input.charCodeAt(this.pos + 1);
if (next === 61) return this.finishOp(_tokentype.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(_tokentype.types.arrow);
}
return this.finishOp(code === 61 ? _tokentype.types.eq : _tokentype.types.prefix, 1);
};
pp.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(_tokentype.types.parenL);
case 41:
++this.pos;return this.finishToken(_tokentype.types.parenR);
case 59:
++this.pos;return this.finishToken(_tokentype.types.semi);
case 44:
++this.pos;return this.finishToken(_tokentype.types.comma);
case 91:
++this.pos;return this.finishToken(_tokentype.types.bracketL);
case 93:
++this.pos;return this.finishToken(_tokentype.types.bracketR);
case 123:
++this.pos;return this.finishToken(_tokentype.types.braceL);
case 125:
++this.pos;return this.finishToken(_tokentype.types.braceR);
case 58:
if (this.options.features["es7.functionBind"] && this.input.charCodeAt(this.pos + 1) === 58) return this.finishOp(_tokentype.types.doubleColon, 2);
++this.pos;
return this.finishToken(_tokentype.types.colon);
case 63:
++this.pos;return this.finishToken(_tokentype.types.question);
case 64:
++this.pos;return this.finishToken(_tokentype.types.at);
case 96:
// '`'
if (this.options.ecmaVersion < 6) break;
++this.pos;
return this.finishToken(_tokentype.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(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(_tokentype.types.prefix, 1);
}
this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
};
pp.finishOp = function (type, size) {
var str = this.input.slice(this.pos, this.pos + size);
this.pos += size;
return this.finishToken(type, str);
};
var regexpUnicodeSupport = false;
try {
new RegExp("￿", "u");regexpUnicodeSupport = true;
} catch (e) {}
// Parse a regular expression. Some context-awareness is necessary,
// since a '/' inside a '[]' set does not end the expression.
pp.readRegexp = function () {
var _this = this;
var escaped = undefined,
inClass = undefined,
start = this.pos;
for (;;) {
if (this.pos >= this.input.length) this.raise(start, "Unterminated regular expression");
var ch = this.input.charAt(this.pos);
if (_whitespace.lineBreak.test(ch)) this.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.pos;
}
var content = this.input.slice(start, this.pos);
++this.pos;
// Need to use `readWord1` because '\uXXXX' sequences are allowed
// here (don't ask).
var mods = this.readWord1();
var tmp = content;
if (mods) {
var validFlags = /^[gmsiy]*$/;
if (this.options.ecmaVersion >= 6) validFlags = /^[gmsiyu]*$/;
if (!validFlags.test(mods)) this.raise(start, "Invalid regular expression flag");
if (mods.indexOf("u") >= 0 && !regexpUnicodeSupport) {
// 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.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");
}
}
// 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) {
try {
new RegExp(tmp);
} catch (e) {
if (e instanceof SyntaxError) this.raise(start, "Error parsing regular expression: " + e.message);
this.raise(e);
}
// Get a regular expression object for this pattern-flag pair, or `null` in
// case the current environment doesn't support the flags it uses.
try {
value = new RegExp(content, mods);
} catch (err) {}
}
return this.finishToken(_tokentype.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.readInt = function (radix, len) {
var start = this.pos,
total = 0;
for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) {
var code = this.input.charCodeAt(this.pos),
val = undefined;
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.pos;
total = total * radix + val;
}
if (this.pos === start || len != null && this.pos - start !== len) return null;
return total;
};
pp.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 (_identifier.isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
return this.finishToken(_tokentype.types.num, val);
};
// Read an integer, octal integer, or floating-point number.
pp.readNumber = function (startsWithDot) {
var start = this.pos,
isFloat = false,
octal = this.input.charCodeAt(this.pos) === 48;
if (!startsWithDot && this.readInt(10) === null) this.raise(start, "Invalid number");
if (this.input.charCodeAt(this.pos) === 46) {
++this.pos;
this.readInt(10);
isFloat = true;
}
var next = this.input.charCodeAt(this.pos);
if (next === 69 || next === 101) {
// 'eE'
next = this.input.charCodeAt(++this.pos);
if (next === 43 || next === 45) ++this.pos; // '+-'
if (this.readInt(10) === null) this.raise(start, "Invalid number");
isFloat = true;
}
if (_identifier.isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
var str = this.input.slice(start, this.pos),
val = undefined;
if (isFloat) val = parseFloat(str);else if (!octal || str.length === 1) val = parseInt(str, 10);else if (/[89]/.test(str) || this.strict) this.raise(start, "Invalid number");else val = parseInt(str, 8);
return this.finishToken(_tokentype.types.num, val);
};
// Read a string value, interpreting backslash-escapes.
pp.readCodePoint = function () {
var ch = this.input.charCodeAt(this.pos),
code = undefined;
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.raise(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);
return String.fromCharCode((code - 0x10000 >> 10) + 0xD800, (code - 0x10000 & 1023) + 0xDC00);
}
pp.readString = function (quote) {
var out = "",
chunkStart = ++this.pos;
for (;;) {
if (this.pos >= this.input.length) this.raise(this.start, "Unterminated string constant");
var ch = this.input.charCodeAt(this.pos);
if (ch === quote) break;
if (ch === 92) {
// '\'
out += this.input.slice(chunkStart, this.pos);
out += this.readEscapedChar(false);
chunkStart = this.pos;
} else {
if (_whitespace.isNewLine(ch)) this.raise(this.start, "Unterminated string constant");
++this.pos;
}
}
out += this.input.slice(chunkStart, this.pos++);
return this.finishToken(_tokentype.types.string, out);
};
// Reads template string tokens.
pp.readTmplToken = function () {
var out = "",
chunkStart = this.pos;
for (;;) {
if (this.pos >= this.input.length) this.raise(this.start, "Unterminated template");
var ch = this.input.charCodeAt(this.pos);
if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) {
// '`', '${'
if (this.pos === this.start && this.type === _tokentype.types.template) {
if (ch === 36) {
this.pos += 2;
return this.finishToken(_tokentype.types.dollarBraceL);
} else {
++this.pos;
return this.finishToken(_tokentype.types.backQuote);
}
}
out += this.input.slice(chunkStart, this.pos);
return this.finishToken(_tokentype.types.template, out);
}
if (ch === 92) {
// '\'
out += this.input.slice(chunkStart, this.pos);
out += this.readEscapedChar(true);
chunkStart = this.pos;
} else if (_whitespace.isNewLine(ch)) {
out += this.input.slice(chunkStart, this.pos);
++this.pos;
switch (ch) {
case 13:
if (this.input.charCodeAt(this.pos) === 10) ++this.pos;
case 10:
out += "\n";
break;
default:
out += String.fromCharCode(ch);
break;
}
if (this.options.locations) {
++this.curLine;
this.lineStart = this.pos;
}
chunkStart = this.pos;
} else {
++this.pos;
}
}
};
// Used to read escaped characters
pp.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);
}
if (octal > 0 && (this.strict || inTemplate)) {
this.raise(this.pos - 2, "Octal literal in strict mode");
}
this.pos += octalStr.length - 1;
return String.fromCharCode(octal);
}
return String.fromCharCode(ch);
}
};
// Used to read character escape sequences ('\x', '\u', '\U').
pp.readHexChar = function (len) {
var codePos = this.pos;
var n = this.readInt(16, len);
if (n === null) this.raise(codePos, "Bad character escape sequence");
return n;
};
// 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.
var containsEsc;
// Read an identifier, and return it as a string. Sets `containsEsc`
// to whether the word contained a '\u' escape.
//
// Incrementally adds only escaped chars, adding other chunks as-is
// as a micro-optimization.
pp.readWord1 = function () {
containsEsc = false;
var word = "",
first = true,
chunkStart = this.pos;
var astral = this.options.ecmaVersion >= 6;
while (this.pos < this.input.length) {
var ch = this.fullCharCodeAtPos();
if (_identifier.isIdentifierChar(ch, astral)) {
this.pos += ch <= 0xffff ? 1 : 2;
} else if (ch === 92) {
// "\"
containsEsc = true;
word += this.input.slice(chunkStart, this.pos);
var escStart = this.pos;
if (this.input.charCodeAt(++this.pos) != 117) // "u"
this.raise(this.pos, "Expecting Unicode escape sequence \\uXXXX");
++this.pos;
var esc = this.readCodePoint();
if (!(first ? _identifier.isIdentifierStart : _identifier.isIdentifierChar)(esc, astral)) this.raise(escStart, "Invalid Unicode escape");
word += codePointToString(esc);
chunkStart = this.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.readWord = function () {
var word = this.readWord1();
var type = _tokentype.types.name;
if ((this.options.ecmaVersion >= 6 || !containsEsc) && this.isKeyword(word)) type = _tokentype.keywords[word];
return this.finishToken(type, word);
};

View File

@ -1,171 +0,0 @@
/* */
"format cjs";
"use strict";
var _babelToolsProtectJs2 = require("./../../babel/tools/protect.js");
var _babelToolsProtectJs3 = _interopRequireDefault(_babelToolsProtectJs2);
exports.__esModule = true;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
_babelToolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
// ## 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).
//
// `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) {
var conf = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
_classCallCheck(this, TokenType);
this.label = label;
this.keyword = conf.keyword;
this.beforeExpr = !!conf.beforeExpr;
this.startsExpr = !!conf.startsExpr;
this.rightAssociative = !!conf.rightAssociative;
this.isLoop = !!conf.isLoop;
this.isAssign = !!conf.isAssign;
this.prefix = !!conf.prefix;
this.postfix = !!conf.postfix;
this.binop = conf.binop || null;
this.updateContext = null;
};
exports.TokenType = TokenType;
function binop(name, prec) {
return new TokenType(name, { beforeExpr: true, binop: prec });
}
var beforeExpr = { beforeExpr: true },
startsExpr = { startsExpr: true };
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),
doubleColon: new TokenType("::", beforeExpr),
dot: new TokenType("."),
question: new TokenType("?", beforeExpr),
arrow: new TokenType("=>", beforeExpr),
template: new TokenType("template"),
ellipsis: new TokenType("...", beforeExpr),
backQuote: new TokenType("`", startsExpr),
dollarBraceL: new TokenType("${", { beforeExpr: true, startsExpr: true }),
at: new TokenType("@"),
// 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("prefix", { 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),
exponent: new TokenType("**", { beforeExpr: true, binop: 11, rightAssociative: true })
};
exports.types = types;
// Map keyword names to token types.
var keywords = {};
exports.keywords = keywords;
// Succinct definitions of keyword token types
function kw(name) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
options.keyword = name;
keywords[name] = types["_" + name] = new TokenType(name, options);
}
kw("break");
kw("case", beforeExpr);
kw("catch");
kw("continue");
kw("debugger");
kw("default", beforeExpr);
kw("do", { isLoop: true });
kw("else", beforeExpr);
kw("finally");
kw("for", { isLoop: true });
kw("function", startsExpr);
kw("if");
kw("return", beforeExpr);
kw("switch");
kw("throw", beforeExpr);
kw("try");
kw("var");
kw("let");
kw("const");
kw("while", { isLoop: true });
kw("with");
kw("new", { beforeExpr: true, startsExpr: true });
kw("this", startsExpr);
kw("super", startsExpr);
kw("class");
kw("extends", beforeExpr);
kw("export");
kw("import");
kw("yield", { beforeExpr: true, startsExpr: true });
kw("null", startsExpr);
kw("true", startsExpr);
kw("false", startsExpr);
kw("in", { beforeExpr: true, binop: 7 });
kw("instanceof", { beforeExpr: true, binop: 7 });
kw("typeof", { beforeExpr: true, prefix: true, startsExpr: true });
kw("void", { beforeExpr: true, prefix: true, startsExpr: true });
kw("delete", { beforeExpr: true, prefix: true, startsExpr: true });

View File

@ -1,20 +0,0 @@
/* */
"format cjs";
"use strict";
var _babelToolsProtectJs2 = require("./../../babel/tools/protect.js");
var _babelToolsProtectJs3 = _interopRequireDefault(_babelToolsProtectJs2);
exports.__esModule = true;
exports.has = has;
_babelToolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
// Checks if an object has a property.
function has(obj, propName) {
return Object.prototype.hasOwnProperty.call(obj, propName);
}

View File

@ -1,30 +0,0 @@
/* */
"format cjs";
"use strict";
var _babelToolsProtectJs2 = require("./../../babel/tools/protect.js");
var _babelToolsProtectJs3 = _interopRequireDefault(_babelToolsProtectJs2);
exports.__esModule = true;
exports.isNewLine = isNewLine;
_babelToolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
// Matches a whole line break (where CRLF is considered a single
// line break). Used to count lines.
var lineBreak = /\r\n?|\n|\u2028|\u2029/;
exports.lineBreak = lineBreak;
var lineBreakG = new RegExp(lineBreak.source, "g");
exports.lineBreakG = lineBreakG;
function isNewLine(code) {
return code === 10 || code === 13 || code === 0x2028 || code == 0x2029;
}
var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
exports.nonASCIIwhitespace = nonASCIIwhitespace;

View File

@ -1,4 +0,0 @@
## Diving into Babel
If you look around in the various directories in here you'll find some details
about the organization of the Babel codebase.

View File

@ -1,18 +0,0 @@
## API
In this directory you'll find all the public interfaces to using Babel for both
node and the browser.
### Node
There are two ways people use Babel within Node, they either are manipulating
strings of code with `babel.transform` or `babel.parse`, they also might be
running their code through Babel before execution via `register` or `polyfill`.
### Browser
Usage of Babel in the browser is extremely uncommon and in most cases
considered A Bad Idea™. However it works by loading `<script>`'s with XHR,
transforming them and then executing them. These `<script>`'s need to have a
`type` of "text/ecmascript-6", "text/babel", or "module" ("text/6to5" exists as
well for legacy reasons).

View File

@ -1,142 +0,0 @@
/* */
"format cjs";
"use strict";
var _toolsProtectJs2 = require("./../tools/protect.js");
var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2);
_toolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/* eslint no-new-func: 0 */
require("./node");
var transform = module.exports = require("../transformation");
/**
* Add `options` and `version` to `babel` global.
*/
transform.options = require("../transformation/file/options");
transform.version = require("../../../package").version;
/**
* Add `transform` api to `babel` global.
*/
transform.transform = transform;
/**
* Tranform and execute script, adding in inline sourcemaps.
*/
transform.run = function (code) {
var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
opts.sourceMaps = "inline";
return new Function(transform(code, opts).code)();
};
/**
* Load scripts via xhr, and `transform` when complete (optional).
*/
transform.load = function (url, callback, opts, hold) {
if (opts === undefined) opts = {};
opts.filename = opts.filename || url;
var xhr = global.ActiveXObject ? new global.ActiveXObject("Microsoft.XMLHTTP") : new global.XMLHttpRequest();
xhr.open("GET", url, true);
if ("overrideMimeType" in xhr) xhr.overrideMimeType("text/plain");
/**
* When successfully loaded, transform (optional), and call `callback`.
*/
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return;
var status = xhr.status;
if (status === 0 || status === 200) {
var param = [xhr.responseText, opts];
if (!hold) transform.run.apply(transform, param);
if (callback) callback(param);
} else {
throw new Error("Could not load " + url);
}
};
xhr.send(null);
};
/**
* Load and transform all scripts of `types`.
*
* @example
* <script type="module"></script>
*/
var runScripts = function runScripts() {
var scripts = [];
var types = ["text/ecmascript-6", "text/6to5", "text/babel", "module"];
var index = 0;
/**
* Transform and execute script. Ensures correct load order.
*/
var exec = function exec() {
var param = scripts[index];
if (param instanceof Array) {
transform.run.apply(transform, param);
index++;
exec();
}
};
/**
* Load, transform, and execute all scripts.
*/
var run = function run(script, i) {
var opts = {};
if (script.src) {
transform.load(script.src, function (param) {
scripts[i] = param;
exec();
}, opts, true);
} else {
opts.filename = "embedded";
scripts[i] = [script.innerHTML, opts];
}
};
// Collect scripts with Babel `types`.
var _scripts = global.document.getElementsByTagName("script");
for (var i = 0; i < _scripts.length; ++i) {
var _script = _scripts[i];
if (types.indexOf(_script.type) >= 0) scripts.push(_script);
}
for (i in scripts) {
run(scripts[i], i);
}
exec();
};
/**
* Register load event to transform and execute scripts.
*/
if (global.addEventListener) {
global.addEventListener("DOMContentLoaded", runScripts, false);
} else if (global.attachEvent) {
global.attachEvent("onload", runScripts);
}

View File

@ -1,160 +0,0 @@
/* */
"format cjs";
"use strict";
var _toolsProtectJs2 = require("./../tools/protect.js");
var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2);
exports.__esModule = true;
exports.register = register;
exports.polyfill = polyfill;
exports.transformFile = transformFile;
exports.transformFileSync = transformFileSync;
exports.parse = parse;
function _interopRequire(obj) { return obj && obj.__esModule ? obj["default"] : obj; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } }
var _lodashLangIsFunction = require("lodash/lang/isFunction");
var _lodashLangIsFunction2 = _interopRequireDefault(_lodashLangIsFunction);
var _transformation = require("../transformation");
var _transformation2 = _interopRequireDefault(_transformation);
var _acorn = require("../../acorn");
var acorn = _interopRequireWildcard(_acorn);
var _util = require("../util");
var util = _interopRequireWildcard(_util);
var _fs = require("fs");
var _fs2 = _interopRequireDefault(_fs);
var _types = require("../types");
var t = _interopRequireWildcard(_types);
_toolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
exports.util = util;
exports.acorn = acorn;
exports.transform = _transformation2["default"];
exports.pipeline = _transformation.pipeline;
exports.canCompile = _util.canCompile;
var _transformationFileOptionsConfig = require("../transformation/file/options/config");
exports.options = _interopRequire(_transformationFileOptionsConfig);
var _transformationPlugin = require("../transformation/plugin");
exports.Plugin = _interopRequire(_transformationPlugin);
var _transformationTransformer = require("../transformation/transformer");
exports.Transformer = _interopRequire(_transformationTransformer);
var _transformationPipeline = require("../transformation/pipeline");
exports.Pipeline = _interopRequire(_transformationPipeline);
var _traversal = require("../traversal");
exports.traverse = _interopRequire(_traversal);
var _toolsBuildExternalHelpers = require("../tools/build-external-helpers");
exports.buildExternalHelpers = _interopRequire(_toolsBuildExternalHelpers);
var _package = require("../../../package");
exports.version = _package.version;
exports.types = t;
/**
* Register Babel and polyfill globally.
*/
function register(opts) {
var callback = require("./register/node-polyfill");
if (opts != null) callback(opts);
return callback;
}
/**
* Register polyfill globally.
*/
function polyfill() {
require("../polyfill");
}
/**
* Asynchronously transform `filename` with optional `opts`, calls `callback` when complete.
*/
function transformFile(filename, opts, callback) {
if (_lodashLangIsFunction2["default"](opts)) {
callback = opts;
opts = {};
}
opts.filename = filename;
_fs2["default"].readFile(filename, function (err, code) {
if (err) return callback(err);
var result;
try {
result = _transformation2["default"](code, opts);
} catch (err) {
return callback(err);
}
callback(null, result);
});
}
/**
* Synchronous form of `transformFile`.
*/
function transformFileSync(filename) {
var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
opts.filename = filename;
return _transformation2["default"](_fs2["default"].readFileSync(filename, "utf8"), opts);
}
/**
* Parse script with Babel's parser.
*/
function parse(code) {
var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
opts.allowHashBang = true;
opts.sourceType = "module";
opts.ecmaVersion = Infinity;
opts.plugins = {
jsx: true,
flow: true
};
opts.features = {};
for (var key in _transformation2["default"].pipeline.transformers) {
opts.features[key] = true;
}
return acorn.parse(code, opts);
}

View File

@ -1,21 +0,0 @@
/* */
"format cjs";
"use strict";
var _toolsProtectJs2 = require("./../../tools/protect.js");
var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2);
exports.__esModule = true;
require("../../polyfill");
_toolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
// required to safely use babel/register within a browserify codebase
exports["default"] = function () {};
module.exports = exports["default"];

View File

@ -1,70 +0,0 @@
/* */
"format cjs";
"use strict";
var _toolsProtectJs2 = require("./../../tools/protect.js");
var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2);
exports.__esModule = true;
exports.save = save;
exports.load = load;
exports.get = get;
var _path = require("path");
var _path2 = _interopRequireDefault(_path);
var _fs = require("fs");
var _fs2 = _interopRequireDefault(_fs);
var _homeOrTmp = require("home-or-tmp");
var _homeOrTmp2 = _interopRequireDefault(_homeOrTmp);
var _pathExists = require("path-exists");
var _pathExists2 = _interopRequireDefault(_pathExists);
_toolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var FILENAME = process.env.BABEL_CACHE_PATH || _path2["default"].join(_homeOrTmp2["default"], ".babel.json");
var data = {};
/**
* Write stringified cache to disk.
*/
function save() {
_fs2["default"].writeFileSync(FILENAME, JSON.stringify(data, null, " "));
}
/**
* Load cache from disk and parse.
*/
function load() {
if (process.env.BABEL_DISABLE_CACHE) return;
process.on("exit", save);
process.nextTick(save);
if (!_pathExists2["default"].sync(FILENAME)) return;
try {
data = JSON.parse(_fs2["default"].readFileSync(FILENAME));
} catch (err) {
return;
}
}
/**
* Retrieve data from cache.
*/
function get() {
return data;
}

View File

@ -1,22 +0,0 @@
/* */
"format cjs";
"use strict";
var _toolsProtectJs2 = require("./../../tools/protect.js");
var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2);
exports.__esModule = true;
function _interopRequire(obj) { return obj && obj.__esModule ? obj["default"] : obj; }
require("../../polyfill");
_toolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var _node = require("./node");
exports["default"] = _interopRequire(_node);
module.exports = exports["default"];

View File

@ -1,273 +0,0 @@
/* */
"format cjs";
"use strict";
var _toolsProtectJs2 = require("./../../tools/protect.js");
var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2);
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } }
var _sourceMapSupport = require("source-map-support");
var _sourceMapSupport2 = _interopRequireDefault(_sourceMapSupport);
var _cache = require("./cache");
var registerCache = _interopRequireWildcard(_cache);
var _transformationFileOptionsOptionManager = require("../../transformation/file/options/option-manager");
var _transformationFileOptionsOptionManager2 = _interopRequireDefault(_transformationFileOptionsOptionManager);
var _lodashObjectExtend = require("lodash/object/extend");
var _lodashObjectExtend2 = _interopRequireDefault(_lodashObjectExtend);
var _node = require("../node");
var babel = _interopRequireWildcard(_node);
var _lodashCollectionEach = require("lodash/collection/each");
var _lodashCollectionEach2 = _interopRequireDefault(_lodashCollectionEach);
var _util = require("../../util");
var util = _interopRequireWildcard(_util);
var _fs = require("fs");
var _fs2 = _interopRequireDefault(_fs);
var _path = require("path");
var _path2 = _interopRequireDefault(_path);
_toolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* Install sourcemaps into node.
*/
_sourceMapSupport2["default"].install({
handleUncaughtExceptions: false,
retrieveSourceMap: function retrieveSourceMap(source) {
var map = maps && maps[source];
if (map) {
return {
url: null,
map: map
};
} else {
return null;
}
}
});
/**
* Load and setup cache.
*/
registerCache.load();
var cache = registerCache.get();
/**
* Store options.
*/
var transformOpts = {};
var ignore;
var only;
var oldHandlers = {};
var maps = {};
var cwd = process.cwd();
/**
* Get path from `filename` relative to the current working directory.
*/
var getRelativePath = function getRelativePath(filename) {
return _path2["default"].relative(cwd, filename);
};
/**
* Get last modified time for a `filename`.
*/
var mtime = function mtime(filename) {
return +_fs2["default"].statSync(filename).mtime;
};
/**
* Compile a `filename` with optional `opts`.
*/
var compile = function compile(filename) {
var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var result;
var optsManager = new _transformationFileOptionsOptionManager2["default"]();
optsManager.mergeOptions(transformOpts);
opts = optsManager.init(opts);
var cacheKey = filename + ":" + JSON.stringify(opts) + ":" + babel.version;
var env = process.env.BABEL_ENV || process.env.NODE_ENV;
if (env) cacheKey += ":" + env;
if (cache) {
var cached = cache[cacheKey];
if (cached && cached.mtime === mtime(filename)) {
result = cached;
}
}
if (!result) {
result = babel.transformFileSync(filename, _lodashObjectExtend2["default"](opts, {
sourceMap: "both",
ast: false
}));
}
if (cache) {
result.mtime = mtime(filename);
cache[cacheKey] = result;
}
maps[filename] = result.map;
return result.code;
};
/**
* Test if a `filename` should be ignored by Babel.
*/
var shouldIgnore = function shouldIgnore(filename) {
if (!ignore && !only) {
return getRelativePath(filename).split(_path2["default"].sep).indexOf("node_modules") >= 0;
} else {
return util.shouldIgnore(filename, ignore || [], only);
}
};
/**
* Monkey patch istanbul if it is running so that it works properly.
*/
var istanbulMonkey = {};
if (process.env.running_under_istanbul) {
// we need to monkey patch fs.readFileSync so we can hook into
// what istanbul gets, it's extremely dirty but it's the only way
var _readFileSync = _fs2["default"].readFileSync;
_fs2["default"].readFileSync = function (filename) {
if (istanbulMonkey[filename]) {
delete istanbulMonkey[filename];
var code = compile(filename, {
auxiliaryCommentBefore: "istanbul ignore next"
});
istanbulMonkey[filename] = true;
return code;
} else {
return _readFileSync.apply(this, arguments);
}
};
}
/**
* Replacement for the loader for istanbul.
*/
var istanbulLoader = function istanbulLoader(m, filename, old) {
istanbulMonkey[filename] = true;
old(m, filename);
};
/**
* Default loader.
*/
var normalLoader = function normalLoader(m, filename) {
m._compile(compile(filename), filename);
};
/**
* Register a loader for an extension.
*/
var registerExtension = function registerExtension(ext) {
var old = oldHandlers[ext] || oldHandlers[".js"] || require.extensions[".js"];
var loader = normalLoader;
if (process.env.running_under_istanbul) loader = istanbulLoader;
require.extensions[ext] = function (m, filename) {
if (shouldIgnore(filename)) {
old(m, filename);
} else {
loader(m, filename, old);
}
};
};
/**
* Register loader for given extensions.
*/
var hookExtensions = function hookExtensions(_exts) {
_lodashCollectionEach2["default"](oldHandlers, function (old, ext) {
if (old === undefined) {
delete require.extensions[ext];
} else {
require.extensions[ext] = old;
}
});
oldHandlers = {};
_lodashCollectionEach2["default"](_exts, function (ext) {
oldHandlers[ext] = require.extensions[ext];
registerExtension(ext);
});
};
/**
* Register loader for default extensions.
*/
hookExtensions(util.canCompile.EXTENSIONS);
/**
* Update options at runtime.
*/
exports["default"] = function () {
var opts = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
if (opts.only != null) only = util.arrayify(opts.only, util.regexify);
if (opts.ignore != null) ignore = util.arrayify(opts.ignore, util.regexify);
if (opts.extensions) hookExtensions(util.arrayify(opts.extensions));
if (opts.cache === false) cache = null;
delete opts.extensions;
delete opts.ignore;
delete opts.cache;
delete opts.only;
_lodashObjectExtend2["default"](transformOpts, opts);
};
module.exports = exports["default"];

View File

@ -1,16 +0,0 @@
## Generation
Here is Babel's code generator, here you'll find all of the code to turn an AST
back into a string of code.
[TBD: To Be Documented:]
- Code Generator
- Buffer
- Source Maps
- Position
- Printer
- Code Style
- Whitespace
- Parenthesis
- Generators

View File

@ -1,291 +0,0 @@
/* */
"format cjs";
"use strict";
var _toolsProtectJs2 = require("./../tools/protect.js");
var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2);
exports.__esModule = true;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var _repeating = require("repeating");
var _repeating2 = _interopRequireDefault(_repeating);
var _trimRight = require("trim-right");
var _trimRight2 = _interopRequireDefault(_trimRight);
var _lodashLangIsBoolean = require("lodash/lang/isBoolean");
var _lodashLangIsBoolean2 = _interopRequireDefault(_lodashLangIsBoolean);
var _lodashCollectionIncludes = require("lodash/collection/includes");
var _lodashCollectionIncludes2 = _interopRequireDefault(_lodashCollectionIncludes);
var _lodashLangIsNumber = require("lodash/lang/isNumber");
var _lodashLangIsNumber2 = _interopRequireDefault(_lodashLangIsNumber);
_toolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* Buffer for collecting generated output.
*/
var Buffer = (function () {
function Buffer(position, format) {
_classCallCheck(this, Buffer);
this.position = position;
this._indent = format.indent.base;
this.format = format;
this.buf = "";
}
/**
* Get the current trimmed buffer.
*/
Buffer.prototype.get = function get() {
return _trimRight2["default"](this.buf);
};
/**
* Get the current indent.
*/
Buffer.prototype.getIndent = function getIndent() {
if (this.format.compact || this.format.concise) {
return "";
} else {
return _repeating2["default"](this.format.indent.style, this._indent);
}
};
/**
* Get the current indent size.
*/
Buffer.prototype.indentSize = function indentSize() {
return this.getIndent().length;
};
/**
* Increment indent size.
*/
Buffer.prototype.indent = function indent() {
this._indent++;
};
/**
* Decrement indent size.
*/
Buffer.prototype.dedent = function dedent() {
this._indent--;
};
/**
* Add a semicolon to the buffer.
*/
Buffer.prototype.semicolon = function semicolon() {
this.push(";");
};
/**
* Ensure last character is a semicolon.
*/
Buffer.prototype.ensureSemicolon = function ensureSemicolon() {
if (!this.isLast(";")) this.semicolon();
};
/**
* Add a right brace to the buffer.
*/
Buffer.prototype.rightBrace = function rightBrace() {
this.newline(true);
this.push("}");
};
/**
* Add a keyword to the buffer.
*/
Buffer.prototype.keyword = function keyword(name) {
this.push(name);
this.space();
};
/**
* Add a space to the buffer unless it is compact (override with force).
*/
Buffer.prototype.space = function space(force) {
if (!force && this.format.compact) return;
if (force || this.buf && !this.isLast(" ") && !this.isLast("\n")) {
this.push(" ");
}
};
/**
* Remove the last character.
*/
Buffer.prototype.removeLast = function removeLast(cha) {
if (this.format.compact) return;
if (!this.isLast(cha)) return;
this.buf = this.buf.substr(0, this.buf.length - 1);
this.position.unshift(cha);
};
/**
* Add a newline (or many newlines), maintaining formatting.
* Strips multiple newlines if removeLast is true.
*/
Buffer.prototype.newline = function newline(i, removeLast) {
if (this.format.compact || this.format.retainLines) return;
if (this.format.concise) {
this.space();
return;
}
removeLast = removeLast || false;
if (_lodashLangIsNumber2["default"](i)) {
i = Math.min(2, i);
if (this.endsWith("{\n") || this.endsWith(":\n")) i--;
if (i <= 0) return;
while (i > 0) {
this._newline(removeLast);
i--;
}
return;
}
if (_lodashLangIsBoolean2["default"](i)) {
removeLast = i;
}
this._newline(removeLast);
};
/**
* Adds a newline unless there is already two previous newlines.
*/
Buffer.prototype._newline = function _newline(removeLast) {
// never allow more than two lines
if (this.endsWith("\n\n")) return;
// remove the last newline
if (removeLast && this.isLast("\n")) this.removeLast("\n");
this.removeLast(" ");
this._removeSpacesAfterLastNewline();
this._push("\n");
};
/**
* If buffer ends with a newline and some spaces after it, trim those spaces.
*/
Buffer.prototype._removeSpacesAfterLastNewline = function _removeSpacesAfterLastNewline() {
var lastNewlineIndex = this.buf.lastIndexOf("\n");
if (lastNewlineIndex === -1) {
return;
}
var index = this.buf.length - 1;
while (index > lastNewlineIndex) {
if (this.buf[index] !== " ") {
break;
}
index--;
}
if (index === lastNewlineIndex) {
this.buf = this.buf.substring(0, index + 1);
}
};
/**
* Push a string to the buffer, maintaining indentation and newlines.
*/
Buffer.prototype.push = function push(str, noIndent) {
if (!this.format.compact && this._indent && !noIndent && str !== "\n") {
// we have an indent level and we aren't pushing a newline
var indent = this.getIndent();
// replace all newlines with newlines with the indentation
str = str.replace(/\n/g, "\n" + indent);
// we've got a newline before us so prepend on the indentation
if (this.isLast("\n")) this._push(indent);
}
this._push(str);
};
/**
* Push a string to the buffer.
*/
Buffer.prototype._push = function _push(str) {
this.position.push(str);
this.buf += str;
};
/**
* Test if the buffer ends with a string.
*/
Buffer.prototype.endsWith = function endsWith(str) {
var buf = arguments.length <= 1 || arguments[1] === undefined ? this.buf : arguments[1];
if (str.length === 1) {
return buf[buf.length - 1] === str;
} else {
return buf.slice(-str.length) === str;
}
};
/**
* Test if a character is last in the buffer.
*/
Buffer.prototype.isLast = function isLast(cha) {
if (this.format.compact) return false;
var buf = this.buf;
var last = buf[buf.length - 1];
if (Array.isArray(cha)) {
return _lodashCollectionIncludes2["default"](cha, last);
} else {
return cha === last;
}
};
return Buffer;
})();
exports["default"] = Buffer;
module.exports = exports["default"];

View File

@ -1,10 +0,0 @@
## Generators
Code generation in Babel is broken down into generators by node type, they all
live in this directory.
[TBD: To Be Documented:]
- How generators work
- How to print a node
- How generators related to one another

View File

@ -1,58 +0,0 @@
/* */
"format cjs";
"use strict";
var _toolsProtectJs2 = require("./../../tools/protect.js");
var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2);
exports.__esModule = true;
exports.File = File;
exports.Program = Program;
exports.BlockStatement = BlockStatement;
exports.Noop = Noop;
_toolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* Print File.program
*/
function File(node, print) {
print.plain(node.program);
}
/**
* Print all nodes in a Program.body.
*/
function Program(node, print) {
print.sequence(node.body);
}
/**
* Print BlockStatement, collapses empty blocks, prints body.
*/
function BlockStatement(node, print) {
if (node.body.length === 0) {
this.push("{}");
} else {
this.push("{");
this.newline();
print.sequence(node.body, { indent: true });
if (!this.format.retainLines) this.removeLast("\n");
this.rightBrace();
}
}
/**
* What is my purpose?
* Why am I here?
* Why are any of us here?
* Does any of this really matter?
*/
function Noop() {}

View File

@ -1,106 +0,0 @@
/* */
"format cjs";
"use strict";
var _toolsProtectJs2 = require("./../../tools/protect.js");
var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2);
exports.__esModule = true;
exports.ClassDeclaration = ClassDeclaration;
exports.ClassBody = ClassBody;
exports.ClassProperty = ClassProperty;
exports.MethodDefinition = MethodDefinition;
_toolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* Print ClassDeclaration, prints decorators, typeParameters, extends, implements, and body.
*/
function ClassDeclaration(node, print) {
print.list(node.decorators, { separator: "" });
this.push("class");
if (node.id) {
this.push(" ");
print.plain(node.id);
}
print.plain(node.typeParameters);
if (node.superClass) {
this.push(" extends ");
print.plain(node.superClass);
print.plain(node.superTypeParameters);
}
if (node["implements"]) {
this.push(" implements ");
print.join(node["implements"], { separator: ", " });
}
this.space();
print.plain(node.body);
}
/**
* Alias ClassDeclaration printer as ClassExpression.
*/
exports.ClassExpression = ClassDeclaration;
/**
* Print ClassBody, collapses empty blocks, prints body.
*/
function ClassBody(node, print) {
if (node.body.length === 0) {
this.push("{}");
} else {
this.push("{");
this.newline();
this.indent();
print.sequence(node.body);
this.dedent();
this.rightBrace();
}
}
/**
* Print ClassProperty, prints decorators, static, key, typeAnnotation, and value.
* Also: semicolons, deal with it.
*/
function ClassProperty(node, print) {
print.list(node.decorators, { separator: "" });
if (node["static"]) this.push("static ");
print.plain(node.key);
print.plain(node.typeAnnotation);
if (node.value) {
this.space();
this.push("=");
this.space();
print.plain(node.value);
}
this.semicolon();
}
/**
* Print MethodDefinition, prints decorations, static, and method.
*/
function MethodDefinition(node, print) {
print.list(node.decorators, { separator: "" });
if (node["static"]) {
this.push("static ");
}
this._method(node, print);
}

View File

@ -1,51 +0,0 @@
/* */
"format cjs";
"use strict";
var _toolsProtectJs2 = require("./../../tools/protect.js");
var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2);
exports.__esModule = true;
exports.ComprehensionBlock = ComprehensionBlock;
exports.ComprehensionExpression = ComprehensionExpression;
_toolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* Prints ComprehensionBlock, prints left and right.
*/
function ComprehensionBlock(node, print) {
this.keyword("for");
this.push("(");
print.plain(node.left);
this.push(" of ");
print.plain(node.right);
this.push(")");
}
/**
* Prints ComprehensionExpression, prints blocks, filter, and body. Handles generators.
*/
function ComprehensionExpression(node, print) {
this.push(node.generator ? "(" : "[");
print.join(node.blocks, { separator: " " });
this.space();
if (node.filter) {
this.keyword("if");
this.push("(");
print.plain(node.filter);
this.push(")");
this.space();
}
print.plain(node.body);
this.push(node.generator ? ")" : "]");
}

View File

@ -1,322 +0,0 @@
/* */
"format cjs";
"use strict";
var _toolsProtectJs2 = require("./../../tools/protect.js");
var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2);
exports.__esModule = true;
exports.UnaryExpression = UnaryExpression;
exports.DoExpression = DoExpression;
exports.ParenthesizedExpression = ParenthesizedExpression;
exports.UpdateExpression = UpdateExpression;
exports.ConditionalExpression = ConditionalExpression;
exports.NewExpression = NewExpression;
exports.SequenceExpression = SequenceExpression;
exports.ThisExpression = ThisExpression;
exports.Super = Super;
exports.Decorator = Decorator;
exports.CallExpression = CallExpression;
exports.EmptyStatement = EmptyStatement;
exports.ExpressionStatement = ExpressionStatement;
exports.AssignmentPattern = AssignmentPattern;
exports.AssignmentExpression = AssignmentExpression;
exports.BindExpression = BindExpression;
exports.MemberExpression = MemberExpression;
exports.MetaProperty = MetaProperty;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } }
var _lodashLangIsNumber = require("lodash/lang/isNumber");
var _lodashLangIsNumber2 = _interopRequireDefault(_lodashLangIsNumber);
var _types = require("../../types");
var t = _interopRequireWildcard(_types);
_toolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* Prints UnaryExpression, prints operator and argument.
*/
function UnaryExpression(node, print) {
var needsSpace = /[a-z]$/.test(node.operator);
var arg = node.argument;
if (t.isUpdateExpression(arg) || t.isUnaryExpression(arg)) {
needsSpace = true;
}
if (t.isUnaryExpression(arg) && arg.operator === "!") {
needsSpace = false;
}
this.push(node.operator);
if (needsSpace) this.push(" ");
print.plain(node.argument);
}
/**
* Prints DoExpression, prints body.
*/
function DoExpression(node, print) {
this.push("do");
this.space();
print.plain(node.body);
}
/**
* Prints ParenthesizedExpression, prints expression.
*/
function ParenthesizedExpression(node, print) {
this.push("(");
print.plain(node.expression);
this.push(")");
}
/**
* Prints UpdateExpression, prints operator and argument.
*/
function UpdateExpression(node, print) {
if (node.prefix) {
this.push(node.operator);
print.plain(node.argument);
} else {
print.plain(node.argument);
this.push(node.operator);
}
}
/**
* Prints ConditionalExpression, prints test, consequent, and alternate.
*/
function ConditionalExpression(node, print) {
print.plain(node.test);
this.space();
this.push("?");
this.space();
print.plain(node.consequent);
this.space();
this.push(":");
this.space();
print.plain(node.alternate);
}
/**
* Prints NewExpression, prints callee and arguments.
*/
function NewExpression(node, print) {
this.push("new ");
print.plain(node.callee);
this.push("(");
print.list(node.arguments);
this.push(")");
}
/**
* Prints SequenceExpression.expressions.
*/
function SequenceExpression(node, print) {
print.list(node.expressions);
}
/**
* Prints ThisExpression.
*/
function ThisExpression() {
this.push("this");
}
/**
* Prints Super.
*/
function Super() {
this.push("super");
}
/**
* Prints Decorator, prints expression.
*/
function Decorator(node, print) {
this.push("@");
print.plain(node.expression);
this.newline();
}
/**
* Prints CallExpression, prints callee and arguments.
*/
function CallExpression(node, print) {
print.plain(node.callee);
this.push("(");
var isPrettyCall = node._prettyCall && !this.format.retainLines && !this.format.compact;
var separator;
if (isPrettyCall) {
separator = ",\n";
this.newline();
this.indent();
}
print.list(node.arguments, { separator: separator });
if (isPrettyCall) {
this.newline();
this.dedent();
}
this.push(")");
}
/**
* Builds yield or await expression printer.
* Prints delegate, all, and argument.
*/
var buildYieldAwait = function buildYieldAwait(keyword) {
return function (node, print) {
this.push(keyword);
if (node.delegate || node.all) {
this.push("*");
}
if (node.argument) {
this.push(" ");
print.plain(node.argument);
}
};
};
/**
* Create YieldExpression and AwaitExpression printers.
*/
var YieldExpression = buildYieldAwait("yield");
exports.YieldExpression = YieldExpression;
var AwaitExpression = buildYieldAwait("await");
exports.AwaitExpression = AwaitExpression;
/**
* Prints EmptyStatement.
*/
function EmptyStatement() {
this.semicolon();
}
/**
* Prints ExpressionStatement, prints expression.
*/
function ExpressionStatement(node, print) {
print.plain(node.expression);
this.semicolon();
}
/**
* Prints AssignmentPattern, prints left and right.
*/
function AssignmentPattern(node, print) {
print.plain(node.left);
this.push(" = ");
print.plain(node.right);
}
/**
* Prints AssignmentExpression, prints left, operator, and right.
*/
function AssignmentExpression(node, print) {
// todo: add cases where the spaces can be dropped when in compact mode
print.plain(node.left);
var spaces = node.operator === "in" || node.operator === "instanceof";
spaces = true; // todo: https://github.com/babel/babel/issues/1835
this.space(spaces);
this.push(node.operator);
if (!spaces) {
// space is mandatory to avoid outputting <!--
// http://javascript.spec.whatwg.org/#comment-syntax
spaces = node.operator === "<" && t.isUnaryExpression(node.right, { prefix: true, operator: "!" }) && t.isUnaryExpression(node.right.argument, { prefix: true, operator: "--" });
}
this.space(spaces);
print.plain(node.right);
}
/**
* Prints BindExpression, prints object and callee.
*/
function BindExpression(node, print) {
print.plain(node.object);
this.push("::");
print.plain(node.callee);
}
/**
* Alias ClassDeclaration printer as ClassExpression,
* and AssignmentExpression printer as LogicalExpression.
*/
exports.BinaryExpression = AssignmentExpression;
exports.LogicalExpression = AssignmentExpression;
/**
* Print MemberExpression, prints object, property, and value. Handles computed.
*/
function MemberExpression(node, print) {
var obj = node.object;
print.plain(obj);
if (!node.computed && t.isMemberExpression(node.property)) {
throw new TypeError("Got a MemberExpression for MemberExpression property");
}
var computed = node.computed;
if (t.isLiteral(node.property) && _lodashLangIsNumber2["default"](node.property.value)) {
computed = true;
}
if (computed) {
this.push("[");
print.plain(node.property);
this.push("]");
} else {
this.push(".");
print.plain(node.property);
}
}
/**
* Print MetaProperty, prints meta and property.
*/
function MetaProperty(node, print) {
print.plain(node.meta);
this.push(".");
print.plain(node.property);
}

View File

@ -1,421 +0,0 @@
/* */
"format cjs";
"use strict";
var _toolsProtectJs2 = require("./../../tools/protect.js");
var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2);
exports.__esModule = true;
exports.AnyTypeAnnotation = AnyTypeAnnotation;
exports.ArrayTypeAnnotation = ArrayTypeAnnotation;
exports.BooleanTypeAnnotation = BooleanTypeAnnotation;
exports.DeclareClass = DeclareClass;
exports.DeclareFunction = DeclareFunction;
exports.DeclareModule = DeclareModule;
exports.DeclareVariable = DeclareVariable;
exports.FunctionTypeAnnotation = FunctionTypeAnnotation;
exports.FunctionTypeParam = FunctionTypeParam;
exports.InterfaceExtends = InterfaceExtends;
exports._interfaceish = _interfaceish;
exports.InterfaceDeclaration = InterfaceDeclaration;
exports.IntersectionTypeAnnotation = IntersectionTypeAnnotation;
exports.MixedTypeAnnotation = MixedTypeAnnotation;
exports.NullableTypeAnnotation = NullableTypeAnnotation;
exports.NumberTypeAnnotation = NumberTypeAnnotation;
exports.StringLiteralTypeAnnotation = StringLiteralTypeAnnotation;
exports.StringTypeAnnotation = StringTypeAnnotation;
exports.TupleTypeAnnotation = TupleTypeAnnotation;
exports.TypeofTypeAnnotation = TypeofTypeAnnotation;
exports.TypeAlias = TypeAlias;
exports.TypeAnnotation = TypeAnnotation;
exports.TypeParameterInstantiation = TypeParameterInstantiation;
exports.ObjectTypeAnnotation = ObjectTypeAnnotation;
exports.ObjectTypeCallProperty = ObjectTypeCallProperty;
exports.ObjectTypeIndexer = ObjectTypeIndexer;
exports.ObjectTypeProperty = ObjectTypeProperty;
exports.QualifiedTypeIdentifier = QualifiedTypeIdentifier;
exports.UnionTypeAnnotation = UnionTypeAnnotation;
exports.TypeCastExpression = TypeCastExpression;
exports.VoidTypeAnnotation = VoidTypeAnnotation;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } }
var _types = require("../../types");
var t = _interopRequireWildcard(_types);
_toolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* Prints AnyTypeAnnotation.
*/
function AnyTypeAnnotation() {
this.push("any");
}
/**
* Prints ArrayTypeAnnotation, prints elementType.
*/
function ArrayTypeAnnotation(node, print) {
print.plain(node.elementType);
this.push("[");
this.push("]");
}
/**
* Prints BooleanTypeAnnotation.
*/
function BooleanTypeAnnotation(node) {
this.push("bool");
}
/**
* Prints DeclareClass, prints node.
*/
function DeclareClass(node, print) {
this.push("declare class ");
this._interfaceish(node, print);
}
/**
* Prints DeclareFunction, prints id and id.typeAnnotation.
*/
function DeclareFunction(node, print) {
this.push("declare function ");
print.plain(node.id);
print.plain(node.id.typeAnnotation.typeAnnotation);
this.semicolon();
}
/**
* Prints DeclareModule, prints id and body.
*/
function DeclareModule(node, print) {
this.push("declare module ");
print.plain(node.id);
this.space();
print.plain(node.body);
}
/**
* Prints DeclareVariable, prints id and id.typeAnnotation.
*/
function DeclareVariable(node, print) {
this.push("declare var ");
print.plain(node.id);
print.plain(node.id.typeAnnotation);
this.semicolon();
}
/**
* Prints FunctionTypeAnnotation, prints typeParameters, params, and rest.
*/
function FunctionTypeAnnotation(node, print, parent) {
print.plain(node.typeParameters);
this.push("(");
print.list(node.params);
if (node.rest) {
if (node.params.length) {
this.push(",");
this.space();
}
this.push("...");
print.plain(node.rest);
}
this.push(")");
// this node type is overloaded, not sure why but it makes it EXTREMELY annoying
if (parent.type === "ObjectTypeProperty" || parent.type === "ObjectTypeCallProperty" || parent.type === "DeclareFunction") {
this.push(":");
} else {
this.space();
this.push("=>");
}
this.space();
print.plain(node.returnType);
}
/**
* Prints FunctionTypeParam, prints name and typeAnnotation, handles optional.
*/
function FunctionTypeParam(node, print) {
print.plain(node.name);
if (node.optional) this.push("?");
this.push(":");
this.space();
print.plain(node.typeAnnotation);
}
/**
* Prints InterfaceExtends, prints id and typeParameters.
*/
function InterfaceExtends(node, print) {
print.plain(node.id);
print.plain(node.typeParameters);
}
/**
* Alias InterfaceExtends printer as ClassImplements,
* and InterfaceExtends printer as GenericTypeAnnotation.
*/
exports.ClassImplements = InterfaceExtends;
exports.GenericTypeAnnotation = InterfaceExtends;
/**
* Prints interface-like node, prints id, typeParameters, extends, and body.
*/
function _interfaceish(node, print) {
print.plain(node.id);
print.plain(node.typeParameters);
if (node["extends"].length) {
this.push(" extends ");
print.join(node["extends"], { separator: ", " });
}
this.space();
print.plain(node.body);
}
/**
* Prints InterfaceDeclaration, prints node.
*/
function InterfaceDeclaration(node, print) {
this.push("interface ");
this._interfaceish(node, print);
}
/**
* Prints IntersectionTypeAnnotation, prints types.
*/
function IntersectionTypeAnnotation(node, print) {
print.join(node.types, { separator: " & " });
}
/**
* Prints MixedTypeAnnotation.
*/
function MixedTypeAnnotation() {
this.push("mixed");
}
/**
* Prints NullableTypeAnnotation, prints typeAnnotation.
*/
function NullableTypeAnnotation(node, print) {
this.push("?");
print.plain(node.typeAnnotation);
}
/**
* Prints NumberTypeAnnotation.
*/
function NumberTypeAnnotation() {
this.push("number");
}
/**
* Prints StringLiteralTypeAnnotation, prints value.
*/
function StringLiteralTypeAnnotation(node) {
this._stringLiteral(node.value);
}
/**
* Prints StringTypeAnnotation.
*/
function StringTypeAnnotation() {
this.push("string");
}
/**
* Prints TupleTypeAnnotation, prints types.
*/
function TupleTypeAnnotation(node, print) {
this.push("[");
print.join(node.types, { separator: ", " });
this.push("]");
}
/**
* Prints TypeofTypeAnnotation, prints argument.
*/
function TypeofTypeAnnotation(node, print) {
this.push("typeof ");
print.plain(node.argument);
}
/**
* Prints TypeAlias, prints id, typeParameters, and right.
*/
function TypeAlias(node, print) {
this.push("type ");
print.plain(node.id);
print.plain(node.typeParameters);
this.space();
this.push("=");
this.space();
print.plain(node.right);
this.semicolon();
}
/**
* Prints TypeAnnotation, prints typeAnnotation, handles optional.
*/
function TypeAnnotation(node, print) {
this.push(":");
this.space();
if (node.optional) this.push("?");
print.plain(node.typeAnnotation);
}
/**
* Prints TypeParameterInstantiation, prints params.
*/
function TypeParameterInstantiation(node, print) {
this.push("<");
print.join(node.params, { separator: ", " });
this.push(">");
}
/**
* Alias TypeParameterInstantiation printer as TypeParameterDeclaration
*/
exports.TypeParameterDeclaration = TypeParameterInstantiation;
/**
* Prints ObjectTypeAnnotation, prints properties, callProperties, and indexers.
*/
function ObjectTypeAnnotation(node, print) {
var _this = this;
this.push("{");
var props = node.properties.concat(node.callProperties, node.indexers);
if (props.length) {
this.space();
print.list(props, {
separator: false,
indent: true,
iterator: function iterator() {
if (props.length !== 1) {
_this.semicolon();
_this.space();
}
}
});
this.space();
}
this.push("}");
}
/**
* Prints ObjectTypeCallProperty, prints value, handles static.
*/
function ObjectTypeCallProperty(node, print) {
if (node["static"]) this.push("static ");
print.plain(node.value);
}
/**
* Prints ObjectTypeIndexer, prints id, key, and value, handles static.
*/
function ObjectTypeIndexer(node, print) {
if (node["static"]) this.push("static ");
this.push("[");
print.plain(node.id);
this.push(":");
this.space();
print.plain(node.key);
this.push("]");
this.push(":");
this.space();
print.plain(node.value);
}
/**
* Prints ObjectTypeProperty, prints static, key, and value.
*/
function ObjectTypeProperty(node, print) {
if (node["static"]) this.push("static ");
print.plain(node.key);
if (node.optional) this.push("?");
if (!t.isFunctionTypeAnnotation(node.value)) {
this.push(":");
this.space();
}
print.plain(node.value);
}
/**
* Prints QualifiedTypeIdentifier, prints qualification and id.
*/
function QualifiedTypeIdentifier(node, print) {
print.plain(node.qualification);
this.push(".");
print.plain(node.id);
}
/**
* Prints UnionTypeAnnotation, prints types.
*/
function UnionTypeAnnotation(node, print) {
print.join(node.types, { separator: " | " });
}
/**
* Prints TypeCastExpression, prints expression and typeAnnotation.
*/
function TypeCastExpression(node, print) {
this.push("(");
print.plain(node.expression);
print.plain(node.typeAnnotation);
this.push(")");
}
/**
* Prints VoidTypeAnnotation.
*/
function VoidTypeAnnotation(node) {
this.push("void");
}

View File

@ -1,143 +0,0 @@
/* */
"format cjs";
"use strict";
var _toolsProtectJs2 = require("./../../tools/protect.js");
var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2);
exports.__esModule = true;
exports.JSXAttribute = JSXAttribute;
exports.JSXIdentifier = JSXIdentifier;
exports.JSXNamespacedName = JSXNamespacedName;
exports.JSXMemberExpression = JSXMemberExpression;
exports.JSXSpreadAttribute = JSXSpreadAttribute;
exports.JSXExpressionContainer = JSXExpressionContainer;
exports.JSXElement = JSXElement;
exports.JSXOpeningElement = JSXOpeningElement;
exports.JSXClosingElement = JSXClosingElement;
exports.JSXEmptyExpression = JSXEmptyExpression;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } }
var _types = require("../../types");
var t = _interopRequireWildcard(_types);
_toolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* Prints JSXAttribute, prints name and value.
*/
function JSXAttribute(node, print) {
print.plain(node.name);
if (node.value) {
this.push("=");
print.plain(node.value);
}
}
/**
* Prints JSXIdentifier, prints name.
*/
function JSXIdentifier(node) {
this.push(node.name);
}
/**
* Prints JSXNamespacedName, prints namespace and name.
*/
function JSXNamespacedName(node, print) {
print.plain(node.namespace);
this.push(":");
print.plain(node.name);
}
/**
* Prints JSXMemberExpression, prints object and property.
*/
function JSXMemberExpression(node, print) {
print.plain(node.object);
this.push(".");
print.plain(node.property);
}
/**
* Prints JSXSpreadAttribute, prints argument.
*/
function JSXSpreadAttribute(node, print) {
this.push("{...");
print.plain(node.argument);
this.push("}");
}
/**
* Prints JSXExpressionContainer, prints expression.
*/
function JSXExpressionContainer(node, print) {
this.push("{");
print.plain(node.expression);
this.push("}");
}
/**
* Prints JSXElement, prints openingElement, children, and closingElement.
*/
function JSXElement(node, print) {
var open = node.openingElement;
print.plain(open);
if (open.selfClosing) return;
this.indent();
var _arr = node.children;
for (var _i = 0; _i < _arr.length; _i++) {
var child = _arr[_i];
if (t.isLiteral(child)) {
this.push(child.value, true);
} else {
print.plain(child);
}
}
this.dedent();
print.plain(node.closingElement);
}
/**
* Prints JSXOpeningElement, prints name and attributes, handles selfClosing.
*/
function JSXOpeningElement(node, print) {
this.push("<");
print.plain(node.name);
if (node.attributes.length > 0) {
this.push(" ");
print.join(node.attributes, { separator: " " });
}
this.push(node.selfClosing ? " />" : ">");
}
/**
* Prints JSXClosingElement, prints name.
*/
function JSXClosingElement(node, print) {
this.push("</");
print.plain(node.name);
this.push(">");
}
/**
* Prints JSXEmptyExpression.
*/
function JSXEmptyExpression() {}

View File

@ -1,135 +0,0 @@
/* */
"format cjs";
"use strict";
var _toolsProtectJs2 = require("./../../tools/protect.js");
var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2);
exports.__esModule = true;
exports._params = _params;
exports._method = _method;
exports.FunctionExpression = FunctionExpression;
exports.ArrowFunctionExpression = ArrowFunctionExpression;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } }
var _types = require("../../types");
var t = _interopRequireWildcard(_types);
_toolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* Prints nodes with params, prints typeParameters, params, and returnType, handles optional params.
*/
function _params(node, print) {
var _this = this;
print.plain(node.typeParameters);
this.push("(");
print.list(node.params, {
iterator: function iterator(node) {
if (node.optional) _this.push("?");
print.plain(node.typeAnnotation);
}
});
this.push(")");
if (node.returnType) {
print.plain(node.returnType);
}
}
/**
* Prints method-like nodes, prints key, value, and body, handles async, generator, computed, and get or set.
*/
function _method(node, print) {
var value = node.value;
var kind = node.kind;
var key = node.key;
if (kind === "method" || kind === "init") {
if (value.generator) {
this.push("*");
}
}
if (kind === "get" || kind === "set") {
this.push(kind + " ");
}
if (value.async) this.push("async ");
if (node.computed) {
this.push("[");
print.plain(key);
this.push("]");
} else {
print.plain(key);
}
this._params(value, print);
this.space();
print.plain(value.body);
}
/**
* Prints FunctionExpression, prints id and body, handles async and generator.
*/
function FunctionExpression(node, print) {
if (node.async) this.push("async ");
this.push("function");
if (node.generator) this.push("*");
if (node.id) {
this.push(" ");
print.plain(node.id);
} else {
this.space();
}
this._params(node, print);
this.space();
print.plain(node.body);
}
/**
* Alias FunctionExpression printer as FunctionDeclaration.
*/
exports.FunctionDeclaration = FunctionExpression;
/**
* Prints ArrowFunctionExpression, prints params and body, handles async.
* Leaves out parentheses when single param.
*/
function ArrowFunctionExpression(node, print) {
if (node.async) this.push("async ");
if (node.params.length === 1 && t.isIdentifier(node.params[0])) {
print.plain(node.params[0]);
} else {
this._params(node, print);
}
this.push(" => ");
var bodyNeedsParens = t.isObjectExpression(node.body);
if (bodyNeedsParens) {
this.push("(");
}
print.plain(node.body);
if (bodyNeedsParens) {
this.push(")");
}
}

View File

@ -1,197 +0,0 @@
/* */
"format cjs";
"use strict";
var _toolsProtectJs2 = require("./../../tools/protect.js");
var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2);
exports.__esModule = true;
exports.ImportSpecifier = ImportSpecifier;
exports.ImportDefaultSpecifier = ImportDefaultSpecifier;
exports.ExportDefaultSpecifier = ExportDefaultSpecifier;
exports.ExportSpecifier = ExportSpecifier;
exports.ExportNamespaceSpecifier = ExportNamespaceSpecifier;
exports.ExportAllDeclaration = ExportAllDeclaration;
exports.ExportNamedDeclaration = ExportNamedDeclaration;
exports.ExportDefaultDeclaration = ExportDefaultDeclaration;
exports.ImportDeclaration = ImportDeclaration;
exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } }
var _types = require("../../types");
var t = _interopRequireWildcard(_types);
_toolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* Prints ImportSpecifier, prints imported and local.
*/
function ImportSpecifier(node, print) {
print.plain(node.imported);
if (node.local && node.local.name !== node.imported.name) {
this.push(" as ");
print.plain(node.local);
}
}
/**
* Prints ImportDefaultSpecifier, prints local.
*/
function ImportDefaultSpecifier(node, print) {
print.plain(node.local);
}
/**
* Prints ExportDefaultSpecifier, prints exported.
*/
function ExportDefaultSpecifier(node, print) {
print.plain(node.exported);
}
/**
* Prints ExportSpecifier, prints local and exported.
*/
function ExportSpecifier(node, print) {
print.plain(node.local);
if (node.exported && node.local.name !== node.exported.name) {
this.push(" as ");
print.plain(node.exported);
}
}
/**
* Prints ExportNamespaceSpecifier, prints exported.
*/
function ExportNamespaceSpecifier(node, print) {
this.push("* as ");
print.plain(node.exported);
}
/**
* Prints ExportAllDeclaration, prints exported and source.
*/
function ExportAllDeclaration(node, print) {
this.push("export *");
if (node.exported) {
this.push(" as ");
print.plain(node.exported);
}
this.push(" from ");
print.plain(node.source);
this.semicolon();
}
/**
* Prints ExportNamedDeclaration, delegates to ExportDeclaration.
*/
function ExportNamedDeclaration(node, print) {
this.push("export ");
ExportDeclaration.call(this, node, print);
}
/**
* Prints ExportDefaultDeclaration, delegates to ExportDeclaration.
*/
function ExportDefaultDeclaration(node, print) {
this.push("export default ");
ExportDeclaration.call(this, node, print);
}
/**
* Prints ExportDeclaration, prints specifiers, declration, and source.
*/
function ExportDeclaration(node, print) {
var specifiers = node.specifiers;
if (node.declaration) {
var declar = node.declaration;
print.plain(declar);
if (t.isStatement(declar) || t.isFunction(declar) || t.isClass(declar)) return;
} else {
var first = specifiers[0];
var hasSpecial = false;
if (t.isExportDefaultSpecifier(first) || t.isExportNamespaceSpecifier(first)) {
hasSpecial = true;
print.plain(specifiers.shift());
if (specifiers.length) {
this.push(", ");
}
}
if (specifiers.length || !specifiers.length && !hasSpecial) {
this.push("{");
if (specifiers.length) {
this.space();
print.join(specifiers, { separator: ", " });
this.space();
}
this.push("}");
}
if (node.source) {
this.push(" from ");
print.plain(node.source);
}
}
this.ensureSemicolon();
}
/**
* Prints ImportDeclaration, prints specifiers and source, handles isType.
*/
function ImportDeclaration(node, print) {
this.push("import ");
if (node.importKind === "type" || node.importKind === "typeof") {
this.push(node.importKind + " ");
}
var specfiers = node.specifiers;
if (specfiers && specfiers.length) {
var first = node.specifiers[0];
if (t.isImportDefaultSpecifier(first) || t.isImportNamespaceSpecifier(first)) {
print.plain(node.specifiers.shift());
if (node.specifiers.length) {
this.push(", ");
}
}
if (node.specifiers.length) {
this.push("{");
this.space();
print.join(node.specifiers, { separator: ", " });
this.space();
this.push("}");
}
this.push(" from ");
}
print.plain(node.source);
this.semicolon();
}
/**
* Prints ImportNamespaceSpecifier, prints local.
*/
function ImportNamespaceSpecifier(node, print) {
this.push("* as ");
print.plain(node.local);
}

View File

@ -1,348 +0,0 @@
/* */
"format cjs";
"use strict";
var _toolsProtectJs2 = require("./../../tools/protect.js");
var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2);
exports.__esModule = true;
exports.WithStatement = WithStatement;
exports.IfStatement = IfStatement;
exports.ForStatement = ForStatement;
exports.WhileStatement = WhileStatement;
exports.DoWhileStatement = DoWhileStatement;
exports.LabeledStatement = LabeledStatement;
exports.TryStatement = TryStatement;
exports.CatchClause = CatchClause;
exports.ThrowStatement = ThrowStatement;
exports.SwitchStatement = SwitchStatement;
exports.SwitchCase = SwitchCase;
exports.DebuggerStatement = DebuggerStatement;
exports.VariableDeclaration = VariableDeclaration;
exports.VariableDeclarator = VariableDeclarator;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } }
var _repeating = require("repeating");
var _repeating2 = _interopRequireDefault(_repeating);
var _types = require("../../types");
var t = _interopRequireWildcard(_types);
_toolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* Prints WithStatement, prints object and body.
*/
function WithStatement(node, print) {
this.keyword("with");
this.push("(");
print.plain(node.object);
this.push(")");
print.block(node.body);
}
/**
* Prints IfStatement, prints test, consequent, and alternate.
*/
function IfStatement(node, print) {
this.keyword("if");
this.push("(");
print.plain(node.test);
this.push(")");
this.space();
print.indentOnComments(node.consequent);
if (node.alternate) {
if (this.isLast("}")) this.space();
this.push("else ");
print.indentOnComments(node.alternate);
}
}
/**
* Prints ForStatement, prints init, test, update, and body.
*/
function ForStatement(node, print) {
this.keyword("for");
this.push("(");
print.plain(node.init);
this.push(";");
if (node.test) {
this.space();
print.plain(node.test);
}
this.push(";");
if (node.update) {
this.space();
print.plain(node.update);
}
this.push(")");
print.block(node.body);
}
/**
* Prints WhileStatement, prints test and body.
*/
function WhileStatement(node, print) {
this.keyword("while");
this.push("(");
print.plain(node.test);
this.push(")");
print.block(node.body);
}
/**
* Builds ForIn or ForOf statement printers.
* Prints left, right, and body.
*/
var buildForXStatement = function buildForXStatement(op) {
return function (node, print) {
this.keyword("for");
this.push("(");
print.plain(node.left);
this.push(" " + op + " ");
print.plain(node.right);
this.push(")");
print.block(node.body);
};
};
/**
* Create ForInStatement and ForOfStatement printers.
*/
var ForInStatement = buildForXStatement("in");
exports.ForInStatement = ForInStatement;
var ForOfStatement = buildForXStatement("of");
exports.ForOfStatement = ForOfStatement;
/**
* Prints DoWhileStatement, prints body and test.
*/
function DoWhileStatement(node, print) {
this.push("do ");
print.plain(node.body);
this.space();
this.keyword("while");
this.push("(");
print.plain(node.test);
this.push(");");
}
/**
* Builds continue, return, or break statement printers.
* Prints label (or key).
*/
var buildLabelStatement = function buildLabelStatement(prefix, key) {
return function (node, print) {
this.push(prefix);
var label = node[key || "label"];
if (label) {
this.push(" ");
print.plain(label);
}
this.semicolon();
};
};
/**
* Create ContinueStatement, ReturnStatement, and BreakStatement printers.
*/
var ContinueStatement = buildLabelStatement("continue");
exports.ContinueStatement = ContinueStatement;
var ReturnStatement = buildLabelStatement("return", "argument");
exports.ReturnStatement = ReturnStatement;
var BreakStatement = buildLabelStatement("break");
exports.BreakStatement = BreakStatement;
/**
* Prints LabeledStatement, prints label and body.
*/
function LabeledStatement(node, print) {
print.plain(node.label);
this.push(": ");
print.plain(node.body);
}
/**
* Prints TryStatement, prints block, handlers, and finalizer.
*/
function TryStatement(node, print) {
this.keyword("try");
print.plain(node.block);
this.space();
// Esprima bug puts the catch clause in a `handlers` array.
// see https://code.google.com/p/esprima/issues/detail?id=433
// We run into this from regenerator generated ast.
if (node.handlers) {
print.plain(node.handlers[0]);
} else {
print.plain(node.handler);
}
if (node.finalizer) {
this.space();
this.push("finally ");
print.plain(node.finalizer);
}
}
/**
* Prints CatchClause, prints param and body.
*/
function CatchClause(node, print) {
this.keyword("catch");
this.push("(");
print.plain(node.param);
this.push(") ");
print.plain(node.body);
}
/**
* Prints ThrowStatement, prints argument.
*/
function ThrowStatement(node, print) {
this.push("throw ");
print.plain(node.argument);
this.semicolon();
}
/**
* Prints SwitchStatement, prints discriminant and cases.
*/
function SwitchStatement(node, print) {
this.keyword("switch");
this.push("(");
print.plain(node.discriminant);
this.push(")");
this.space();
this.push("{");
print.sequence(node.cases, {
indent: true,
addNewlines: function addNewlines(leading, cas) {
if (!leading && node.cases[node.cases.length - 1] === cas) return -1;
}
});
this.push("}");
}
/**
* Prints SwitchCase, prints test and consequent.
*/
function SwitchCase(node, print) {
if (node.test) {
this.push("case ");
print.plain(node.test);
this.push(":");
} else {
this.push("default:");
}
if (node.consequent.length) {
this.newline();
print.sequence(node.consequent, { indent: true });
}
}
/**
* Prints DebuggerStatement.
*/
function DebuggerStatement() {
this.push("debugger;");
}
/**
* Prints VariableDeclaration, prints declarations, handles kind and format.
*/
function VariableDeclaration(node, print, parent) {
this.push(node.kind + " ");
var hasInits = false;
// don't add whitespace to loop heads
if (!t.isFor(parent)) {
var _arr = node.declarations;
for (var _i = 0; _i < _arr.length; _i++) {
var declar = _arr[_i];
if (declar.init) {
// has an init so let's split it up over multiple lines
hasInits = true;
}
}
}
//
// use a pretty separator when we aren't in compact mode, have initializers and don't have retainLines on
// this will format declarations like:
//
// var foo = "bar", bar = "foo";
//
// into
//
// var foo = "bar",
// bar = "foo";
//
var sep;
if (!this.format.compact && !this.format.concise && hasInits && !this.format.retainLines) {
sep = ",\n" + _repeating2["default"](" ", node.kind.length + 1);
}
//
print.list(node.declarations, { separator: sep });
if (t.isFor(parent)) {
// don't give semicolons to these nodes since they'll be inserted in the parent generator
if (parent.left === node || parent.init === node) return;
}
this.semicolon();
}
/**
* Prints VariableDeclarator, handles id, id.typeAnnotation, and init.
*/
function VariableDeclarator(node, print) {
print.plain(node.id);
print.plain(node.id.typeAnnotation);
if (node.init) {
this.space();
this.push("=");
this.space();
print.plain(node.init);
}
}

View File

@ -1,56 +0,0 @@
/* */
"format cjs";
"use strict";
var _toolsProtectJs2 = require("./../../tools/protect.js");
var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2);
exports.__esModule = true;
exports.TaggedTemplateExpression = TaggedTemplateExpression;
exports.TemplateElement = TemplateElement;
exports.TemplateLiteral = TemplateLiteral;
_toolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* Prints TaggedTemplateExpression, prints tag and quasi.
*/
function TaggedTemplateExpression(node, print) {
print.plain(node.tag);
print.plain(node.quasi);
}
/**
* Prints TemplateElement, prints value.
*/
function TemplateElement(node) {
this._push(node.value.raw);
}
/**
* Prints TemplateLiteral, prints quasis, and expressions.
*/
function TemplateLiteral(node, print) {
this.push("`");
var quasis = node.quasis;
var len = quasis.length;
for (var i = 0; i < len; i++) {
print.plain(quasis[i]);
if (i + 1 < len) {
this.push("${ ");
print.plain(node.expressions[i]);
this.push(" }");
}
}
this._push("`");
}

View File

@ -1,222 +0,0 @@
/* */
"format cjs";
"use strict";
var _toolsProtectJs2 = require("./../../tools/protect.js");
var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2);
exports.__esModule = true;
exports.Identifier = Identifier;
exports.RestElement = RestElement;
exports.ObjectExpression = ObjectExpression;
exports.Property = Property;
exports.ArrayExpression = ArrayExpression;
exports.Literal = Literal;
exports._stringLiteral = _stringLiteral;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } }
/* eslint quotes: 0 */
var _isInteger = require("is-integer");
var _isInteger2 = _interopRequireDefault(_isInteger);
var _types = require("../../types");
var t = _interopRequireWildcard(_types);
_toolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* Prints Identifier, prints name.
*/
function Identifier(node) {
this.push(node.name);
}
/**
* Prints RestElement, prints argument.
*/
function RestElement(node, print) {
this.push("...");
print.plain(node.argument);
}
/**
* Alias RestElement printer as SpreadElement,
* and RestElement printer as SpreadProperty.
*/
exports.SpreadElement = RestElement;
exports.SpreadProperty = RestElement;
/**
* Prints ObjectExpression, prints properties.
*/
function ObjectExpression(node, print) {
var props = node.properties;
if (props.length) {
this.push("{");
this.space();
print.list(props, { indent: true });
this.space();
this.push("}");
} else {
this.push("{}");
}
}
/**
* Alias ObjectExpression printer as ObjectPattern.
*/
exports.ObjectPattern = ObjectExpression;
/**
* Prints Property, prints decorators, key, and value, handles kind, computed, and shorthand.
*/
function Property(node, print) {
print.list(node.decorators, { separator: "" });
if (node.method || node.kind === "get" || node.kind === "set") {
this._method(node, print);
} else {
if (node.computed) {
this.push("[");
print.plain(node.key);
this.push("]");
} else {
// print `({ foo: foo = 5 } = {})` as `({ foo = 5 } = {});`
if (t.isAssignmentPattern(node.value) && t.isIdentifier(node.key) && node.key.name === node.value.left.name) {
print.plain(node.value);
return;
}
print.plain(node.key);
// shorthand!
if (node.shorthand && (t.isIdentifier(node.key) && t.isIdentifier(node.value) && node.key.name === node.value.name)) {
return;
}
}
this.push(":");
this.space();
print.plain(node.value);
}
}
/**
* Prints ArrayExpression, prints elements.
*/
function ArrayExpression(node, print) {
var elems = node.elements;
var len = elems.length;
this.push("[");
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
if (!elem) {
// If the array expression ends with a hole, that hole
// will be ignored by the interpreter, but if it ends with
// two (or more) holes, we need to write out two (or more)
// commas so that the resulting code is interpreted with
// both (all) of the holes.
this.push(",");
} else {
if (i > 0) this.space();
print.plain(elem);
if (i < len - 1) this.push(",");
}
}
this.push("]");
}
/**
* Alias ArrayExpression printer as ArrayPattern.
*/
exports.ArrayPattern = ArrayExpression;
/**
* RegExp for testing scientific notation in literals.
*/
var SCIENTIFIC_NOTATION = /e/i;
/**
* Prints Literal, prints value, regex, raw, handles val type.
*/
function Literal(node, print, parent) {
var val = node.value;
var type = typeof val;
if (type === "string") {
this._stringLiteral(val);
} else if (type === "number") {
// check to see if this is the same number as the raw one in the original source as asm.js uses
// numbers in the form 5.0 for type hinting
var raw = node.raw;
if (val === +raw && raw[raw.length - 1] !== "." && !/^0[bo]/i.test(raw)) {
val = raw;
}
val = val + "";
if (_isInteger2["default"](+val) && t.isMemberExpression(parent, { object: node }) && !SCIENTIFIC_NOTATION.test(val)) {
val += ".";
}
this.push(val);
} else if (type === "boolean") {
this.push(val ? "true" : "false");
} else if (node.regex) {
this.push("/" + node.regex.pattern + "/" + node.regex.flags);
} else if (val === null) {
this.push("null");
}
}
/**
* Prints string literals, handles format.
*/
function _stringLiteral(val) {
val = JSON.stringify(val);
// escape illegal js but valid json unicode characters
val = val.replace(/[\u000A\u000D\u2028\u2029]/g, function (c) {
return "\\u" + ("0000" + c.charCodeAt(0).toString(16)).slice(-4);
});
if (this.format.quotes === "single") {
// remove double quotes
val = val.slice(1, -1);
// unescape double quotes
val = val.replace(/\\"/g, "\"");
// escape single quotes
val = val.replace(/'/g, "\\'");
// add single quotes
val = "'" + val + "'";
}
this.push(val);
}

View File

@ -1,555 +0,0 @@
/* */
"format cjs";
"use strict";
var _toolsProtectJs2 = require("./../tools/protect.js");
var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2);
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 _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var _detectIndent = require("detect-indent");
var _detectIndent2 = _interopRequireDefault(_detectIndent);
var _whitespace = require("./whitespace");
var _whitespace2 = _interopRequireDefault(_whitespace);
var _nodePrinter = require("./node/printer");
var _nodePrinter2 = _interopRequireDefault(_nodePrinter);
var _repeating = require("repeating");
var _repeating2 = _interopRequireDefault(_repeating);
var _sourceMap = require("./source-map");
var _sourceMap2 = _interopRequireDefault(_sourceMap);
var _position = require("./position");
var _position2 = _interopRequireDefault(_position);
var _messages = require("../messages");
var messages = _interopRequireWildcard(_messages);
var _buffer = require("./buffer");
var _buffer2 = _interopRequireDefault(_buffer);
var _lodashObjectExtend = require("lodash/object/extend");
var _lodashObjectExtend2 = _interopRequireDefault(_lodashObjectExtend);
var _lodashCollectionEach = require("lodash/collection/each");
var _lodashCollectionEach2 = _interopRequireDefault(_lodashCollectionEach);
var _node2 = require("./node");
var _node3 = _interopRequireDefault(_node2);
var _types = require("../types");
var t = _interopRequireWildcard(_types);
_toolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* Babel's code generator, turns an ast into code, maintaining sourcemaps,
* user preferences, and valid output.
*/
var CodeGenerator = (function () {
function CodeGenerator(ast, opts, code) {
_classCallCheck(this, CodeGenerator);
opts = opts || {};
this.comments = ast.comments || [];
this.tokens = ast.tokens || [];
this.format = CodeGenerator.normalizeOptions(code, opts, this.tokens);
this.opts = opts;
this.ast = ast;
this.whitespace = new _whitespace2["default"](this.tokens);
this.position = new _position2["default"]();
this.map = new _sourceMap2["default"](this.position, opts, code);
this.buffer = new _buffer2["default"](this.position, this.format);
}
/**
* Normalize generator options, setting defaults.
*
* - Detects code indentation.
* - If `opts.compact = "auto"` and the code is over 100KB, `compact` will be set to `true`.
*/
CodeGenerator.normalizeOptions = function normalizeOptions(code, opts, tokens) {
var style = " ";
if (code) {
var indent = _detectIndent2["default"](code).indent;
if (indent && indent !== " ") style = indent;
}
var format = {
retainLines: opts.retainLines,
comments: opts.comments == null || opts.comments,
compact: opts.compact,
quotes: CodeGenerator.findCommonStringDelimiter(code, tokens),
indent: {
adjustMultilineComment: true,
style: style,
base: 0
}
};
if (format.compact === "auto") {
format.compact = code.length > 100000; // 100KB
if (format.compact) {
console.error("[BABEL] " + messages.get("codeGeneratorDeopt", opts.filename, "100KB"));
}
}
return format;
};
/**
* Determine if input code uses more single or double quotes.
*/
CodeGenerator.findCommonStringDelimiter = function findCommonStringDelimiter(code, tokens) {
var occurences = {
single: 0,
double: 0
};
var checked = 0;
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (token.type.label !== "string") continue;
var raw = code.slice(token.start, token.end);
if (raw[0] === "'") {
occurences.single++;
} else {
occurences.double++;
}
checked++;
if (checked >= 3) break;
}
if (occurences.single > occurences.double) {
return "single";
} else {
return "double";
}
};
/**
* Generate code and sourcemap from ast.
*
* Appends comments that weren't attached to any node to the end of the generated output.
*/
CodeGenerator.prototype.generate = function generate() {
var ast = this.ast;
this.print(ast);
if (ast.comments) {
var comments = [];
var _arr = ast.comments;
for (var _i = 0; _i < _arr.length; _i++) {
var comment = _arr[_i];
if (!comment._displayed) comments.push(comment);
}
this._printComments(comments);
}
return {
map: this.map.get(),
code: this.buffer.get()
};
};
/**
* Build NodePrinter.
*/
CodeGenerator.prototype.buildPrint = function buildPrint(parent) {
return new _nodePrinter2["default"](this, parent);
};
/**
* [Please add a description.]
*/
CodeGenerator.prototype.catchUp = function catchUp(node, parent, leftParenPrinted) {
// catch up to this nodes newline if we're behind
if (node.loc && this.format.retainLines && this.buffer.buf) {
var needsParens = false;
if (!leftParenPrinted && parent && this.position.line < node.loc.start.line && t.isTerminatorless(parent)) {
needsParens = true;
this._push("(");
}
while (this.position.line < node.loc.start.line) {
this._push("\n");
}
return needsParens;
}
return false;
};
/**
* [Please add a description.]
*/
CodeGenerator.prototype._printNewline = function _printNewline(leading, node, parent, opts) {
if (!opts.statement && !_node3["default"].isUserWhitespacable(node, parent)) {
return;
}
var lines = 0;
if (node.start != null && !node._ignoreUserWhitespace) {
// user node
if (leading) {
lines = this.whitespace.getNewlinesBefore(node);
} else {
lines = this.whitespace.getNewlinesAfter(node);
}
} else {
// generated node
if (!leading) lines++; // always include at least a single line after
if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0;
var needs = _node3["default"].needsWhitespaceAfter;
if (leading) needs = _node3["default"].needsWhitespaceBefore;
if (needs(node, parent)) lines++;
// generated nodes can't add starting file whitespace
if (!this.buffer.buf) lines = 0;
}
this.newline(lines);
};
/**
* [Please add a description.]
*/
CodeGenerator.prototype.print = function print(node, parent) {
var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
if (!node) return;
if (parent && parent._compact) {
node._compact = true;
}
var oldConcise = this.format.concise;
if (node._compact) {
this.format.concise = true;
}
if (this[node.type]) {
var needsNoLineTermParens = _node3["default"].needsParensNoLineTerminator(node, parent);
var needsParens = needsNoLineTermParens || _node3["default"].needsParens(node, parent);
if (needsParens) this.push("(");
if (needsNoLineTermParens) this.indent();
this.printLeadingComments(node, parent);
var needsParensFromCatchup = this.catchUp(node, parent, needsParens);
this._printNewline(true, node, parent, opts);
if (opts.before) opts.before();
this.map.mark(node, "start");
this[node.type](node, this.buildPrint(node), parent);
if (needsNoLineTermParens) {
this.newline();
this.dedent();
}
if (needsParens || needsParensFromCatchup) this.push(")");
this.map.mark(node, "end");
if (opts.after) opts.after();
this.format.concise = oldConcise;
this._printNewline(false, node, parent, opts);
this.printTrailingComments(node, parent);
} else {
throw new ReferenceError("unknown node of type " + JSON.stringify(node.type) + " with constructor " + JSON.stringify(node && node.constructor.name));
}
};
/**
* [Please add a description.]
*/
CodeGenerator.prototype.printJoin = function printJoin(print, nodes) {
var _this = this;
var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
if (!nodes || !nodes.length) return;
var len = nodes.length;
if (opts.indent) this.indent();
var printOpts = {
statement: opts.statement,
addNewlines: opts.addNewlines,
after: function after() {
if (opts.iterator) {
opts.iterator(node, i);
}
if (opts.separator && i < len - 1) {
_this.push(opts.separator);
}
}
};
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
print.plain(node, printOpts);
}
if (opts.indent) this.dedent();
};
/**
* [Please add a description.]
*/
CodeGenerator.prototype.printAndIndentOnComments = function printAndIndentOnComments(print, node) {
var indent = !!node.leadingComments;
if (indent) this.indent();
print.plain(node);
if (indent) this.dedent();
};
/**
* [Please add a description.]
*/
CodeGenerator.prototype.printBlock = function printBlock(print, node) {
if (t.isEmptyStatement(node)) {
this.semicolon();
} else {
this.push(" ");
print.plain(node);
}
};
/**
* [Please add a description.]
*/
CodeGenerator.prototype.generateComment = function generateComment(comment) {
var val = comment.value;
if (comment.type === "CommentLine") {
val = "//" + val;
} else {
val = "/*" + val + "*/";
}
return val;
};
/**
* [Please add a description.]
*/
CodeGenerator.prototype.printTrailingComments = function printTrailingComments(node, parent) {
this._printComments(this.getComments("trailingComments", node, parent));
};
/**
* [Please add a description.]
*/
CodeGenerator.prototype.printLeadingComments = function printLeadingComments(node, parent) {
this._printComments(this.getComments("leadingComments", node, parent));
};
/**
* [Please add a description.]
*/
CodeGenerator.prototype.getComments = function getComments(key, node, parent) {
if (t.isExpressionStatement(parent)) {
return [];
}
var comments = [];
var nodes = [node];
if (t.isExpressionStatement(node)) {
nodes.push(node.argument);
}
var _arr2 = nodes;
for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
var _node = _arr2[_i2];
comments = comments.concat(this._getComments(key, _node));
}
return comments;
};
/**
* [Please add a description.]
*/
CodeGenerator.prototype._getComments = function _getComments(key, node) {
return node && node[key] || [];
};
/**
* [Please add a description.]
*/
CodeGenerator.prototype._printComments = function _printComments(comments) {
if (this.format.compact) return;
if (!this.format.comments) return;
if (!comments || !comments.length) return;
var _arr3 = comments;
for (var _i3 = 0; _i3 < _arr3.length; _i3++) {
var comment = _arr3[_i3];
var skip = false;
if (this.ast.comments) {
// find the original comment in the ast and set it as displayed
var _arr4 = this.ast.comments;
for (var _i4 = 0; _i4 < _arr4.length; _i4++) {
var origComment = _arr4[_i4];
if (origComment.start === comment.start) {
// comment has already been output
if (origComment._displayed) skip = true;
origComment._displayed = true;
break;
}
}
}
if (skip) return;
this.catchUp(comment);
// whitespace before
this.newline(this.whitespace.getNewlinesBefore(comment));
var column = this.position.column;
var val = this.generateComment(comment);
if (column && !this.isLast(["\n", " ", "[", "{"])) {
this._push(" ");
column++;
}
//
if (comment.type === "CommentBlock" && this.format.indent.adjustMultilineComment) {
var offset = comment.loc && comment.loc.start.column;
if (offset) {
var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
val = val.replace(newlineRegex, "\n");
}
var indent = Math.max(this.indentSize(), column);
val = val.replace(/\n/g, "\n" + _repeating2["default"](" ", indent));
}
if (column === 0) {
val = this.getIndent() + val;
}
// force a newline for line comments when retainLines is set in case the next printed node
// doesn't catch up
if (this.format.retainLines && comment.type === "CommentLine") {
val += "\n";
}
//
this._push(val);
// whitespace after
this.newline(this.whitespace.getNewlinesAfter(comment));
}
};
_createClass(CodeGenerator, null, [{
key: "generators",
/**
* All node generators.
*/
value: {
templateLiterals: require("./generators/template-literals"),
comprehensions: require("./generators/comprehensions"),
expressions: require("./generators/expressions"),
statements: require("./generators/statements"),
classes: require("./generators/classes"),
methods: require("./generators/methods"),
modules: require("./generators/modules"),
types: require("./generators/types"),
flow: require("./generators/flow"),
base: require("./generators/base"),
jsx: require("./generators/jsx")
},
enumerable: true
}]);
return CodeGenerator;
})();
/**
* [Please add a description.]
*/
_lodashCollectionEach2["default"](_buffer2["default"].prototype, function (fn, key) {
CodeGenerator.prototype[key] = function () {
return fn.apply(this.buffer, arguments);
};
});
/**
* [Please add a description.]
*/
_lodashCollectionEach2["default"](CodeGenerator.generators, function (generator) {
_lodashObjectExtend2["default"](CodeGenerator.prototype, generator);
});
/**
* [Please add a description.]
*/
module.exports = function (ast, opts, code) {
var gen = new CodeGenerator(ast, opts, code);
return gen.generate();
};
module.exports.CodeGenerator = CodeGenerator;

View File

@ -1,187 +0,0 @@
/* */
"format cjs";
"use strict";
var _toolsProtectJs2 = require("./../../tools/protect.js");
var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2);
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var _whitespace = require("./whitespace");
var _whitespace2 = _interopRequireDefault(_whitespace);
var _parentheses = require("./parentheses");
var parens = _interopRequireWildcard(_parentheses);
var _lodashCollectionEach = require("lodash/collection/each");
var _lodashCollectionEach2 = _interopRequireDefault(_lodashCollectionEach);
var _lodashCollectionSome = require("lodash/collection/some");
var _lodashCollectionSome2 = _interopRequireDefault(_lodashCollectionSome);
var _types = require("../../types");
var t = _interopRequireWildcard(_types);
_toolsProtectJs3["default"](module);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* Test if node matches a set of type-matcher pairs.
* @example
* find({
* VariableDeclaration(node, parent) {
* return true;
* }
* }, node, parent);
*/
var find = function find(obj, node, parent) {
if (!obj) return;
var result;
var types = Object.keys(obj);
for (var i = 0; i < types.length; i++) {
var type = types[i];
if (t.is(type, node)) {
var fn = obj[type];
result = fn(node, parent);
if (result != null) break;
}
}
return result;
};
/**
* Whitespace and Parenthesis related methods for nodes.
*/
var Node = (function () {
function Node(node, parent) {
_classCallCheck(this, Node);
this.parent = parent;
this.node = node;
}
/**
* Test if `node` can have whitespace set by the user.
*/
Node.isUserWhitespacable = function isUserWhitespacable(node) {
return t.isUserWhitespacable(node);
};
/**
* Test if a `node` requires whitespace.
*/
Node.needsWhitespace = function needsWhitespace(node, parent, type) {
if (!node) return 0;
if (t.isExpressionStatement(node)) {
node = node.expression;
}
var linesInfo = find(_whitespace2["default"].nodes, node, parent);
if (!linesInfo) {
var items = find(_whitespace2["default"].list, node, parent);
if (items) {
for (var i = 0; i < items.length; i++) {
linesInfo = Node.needsWhitespace(items[i], node, type);
if (linesInfo) break;
}
}
}
return linesInfo && linesInfo[type] || 0;
};
/**
* Test if a `node` requires whitespace before it.
*/
Node.needsWhitespaceBefore = function needsWhitespaceBefore(node, parent) {
return Node.needsWhitespace(node, parent, "before");
};
/**
* Test if a `note` requires whitespace after it.
*/
Node.needsWhitespaceAfter = function needsWhitespaceAfter(node, parent) {
return Node.needsWhitespace(node, parent, "after");
};
/**
* Test if a `node` needs parentheses around it.
*/
Node.needsParens = function needsParens(node, parent) {
if (!parent) return false;
if (t.isNewExpression(parent) && parent.callee === node) {
if (t.isCallExpression(node)) return true;
var hasCall = _lodashCollectionSome2["default"](node, function (val) {
return t.isCallExpression(val);
});
if (hasCall) return true;
}
return find(parens, node, parent);
};
/**
* [Please add a description.]
*/
Node.needsParensNoLineTerminator = function needsParensNoLineTerminator(node, parent) {
if (!parent) return false;
// no comments
if (!node.leadingComments || !node.leadingComments.length) {
return false;
}
return t.isTerminatorless(parent);
};
return Node;
})();
exports["default"] = Node;
/**
* Add all static methods from `Node` to `Node.prototype`.
*/
_lodashCollectionEach2["default"](Node, function (fn, key) {
Node.prototype[key] = function () {
// Avoid leaking arguments to prevent deoptimization
var args = new Array(arguments.length + 2);
args[0] = this.node;
args[1] = this.parent;
for (var i = 0; i < args.length; i++) {
args[i + 2] = arguments[i];
}
return Node[key].apply(null, args);
};
});
module.exports = exports["default"];

Some files were not shown because too many files have changed in this diff Show More