UNPKG

babel-core

Version:

A compiler for writing next generation JavaScript

1,508 lines (1,282 loc) 2.14 MB
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.babel = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ "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); },{"./../babel/tools/protect.js":52,"./plugins/flow":2,"./src/index":5,"acorn-jsx/inject":182}],2:[function(require,module,exports){ "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); } }; }); }; },{"../src/index":5,"./../../babel/tools/protect.js":52}],3:[function(require,module,exports){ "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.va