diff options
Diffstat (limited to 'node_modules/babylon/lib/parser')
-rw-r--r-- | node_modules/babylon/lib/parser/comments.js | 163 | ||||
-rw-r--r-- | node_modules/babylon/lib/parser/expression.js | 1096 | ||||
-rw-r--r-- | node_modules/babylon/lib/parser/index.js | 102 | ||||
-rw-r--r-- | node_modules/babylon/lib/parser/location.js | 26 | ||||
-rw-r--r-- | node_modules/babylon/lib/parser/lval.js | 315 | ||||
-rw-r--r-- | node_modules/babylon/lib/parser/node.js | 70 | ||||
-rw-r--r-- | node_modules/babylon/lib/parser/statement.js | 1107 | ||||
-rw-r--r-- | node_modules/babylon/lib/parser/util.js | 92 |
8 files changed, 2971 insertions, 0 deletions
diff --git a/node_modules/babylon/lib/parser/comments.js b/node_modules/babylon/lib/parser/comments.js new file mode 100644 index 000000000..577e1c251 --- /dev/null +++ b/node_modules/babylon/lib/parser/comments.js @@ -0,0 +1,163 @@ +"use strict"; + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function last(stack) { + return stack[stack.length - 1]; +} /* eslint max-len: 0 */ + +/** + * Based on the comment attachment algorithm used in espree and estraverse. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +var pp = _index2.default.prototype; + +pp.addComment = function (comment) { + if (this.filename) comment.loc.filename = this.filename; + this.state.trailingComments.push(comment); + this.state.leadingComments.push(comment); +}; + +pp.processComment = function (node) { + if (node.type === "Program" && node.body.length > 0) return; + + var stack = this.state.commentStack; + + var lastChild = void 0, + trailingComments = void 0, + i = void 0, + j = void 0; + + if (this.state.trailingComments.length > 0) { + // If the first comment in trailingComments comes after the + // current node, then we're good - all comments in the array will + // come after the node and so it's safe to add them as official + // trailingComments. + if (this.state.trailingComments[0].start >= node.end) { + trailingComments = this.state.trailingComments; + this.state.trailingComments = []; + } else { + // Otherwise, if the first comment doesn't come after the + // current node, that means we have a mix of leading and trailing + // comments in the array and that leadingComments contains the + // same items as trailingComments. Reset trailingComments to + // zero items and we'll handle this by evaluating leadingComments + // later. + this.state.trailingComments.length = 0; + } + } else { + var lastInStack = last(stack); + if (stack.length > 0 && lastInStack.trailingComments && lastInStack.trailingComments[0].start >= node.end) { + trailingComments = lastInStack.trailingComments; + lastInStack.trailingComments = null; + } + } + + // Eating the stack. + while (stack.length > 0 && last(stack).start >= node.start) { + lastChild = stack.pop(); + } + + if (lastChild) { + if (lastChild.leadingComments) { + if (lastChild !== node && last(lastChild.leadingComments).end <= node.start) { + node.leadingComments = lastChild.leadingComments; + lastChild.leadingComments = null; + } else { + // A leading comment for an anonymous class had been stolen by its first ClassMethod, + // so this takes back the leading comment. + // See also: https://github.com/eslint/espree/issues/158 + for (i = lastChild.leadingComments.length - 2; i >= 0; --i) { + if (lastChild.leadingComments[i].end <= node.start) { + node.leadingComments = lastChild.leadingComments.splice(0, i + 1); + break; + } + } + } + } + } else if (this.state.leadingComments.length > 0) { + if (last(this.state.leadingComments).end <= node.start) { + if (this.state.commentPreviousNode) { + for (j = 0; j < this.state.leadingComments.length; j++) { + if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) { + this.state.leadingComments.splice(j, 1); + j--; + } + } + } + if (this.state.leadingComments.length > 0) { + node.leadingComments = this.state.leadingComments; + this.state.leadingComments = []; + } + } else { + // https://github.com/eslint/espree/issues/2 + // + // In special cases, such as return (without a value) and + // debugger, all comments will end up as leadingComments and + // will otherwise be eliminated. This step runs when the + // commentStack is empty and there are comments left + // in leadingComments. + // + // This loop figures out the stopping point between the actual + // leading and trailing comments by finding the location of the + // first comment that comes after the given node. + for (i = 0; i < this.state.leadingComments.length; i++) { + if (this.state.leadingComments[i].end > node.start) { + break; + } + } + + // Split the array based on the location of the first comment + // that comes after the node. Keep in mind that this could + // result in an empty array, and if so, the array must be + // deleted. + node.leadingComments = this.state.leadingComments.slice(0, i); + if (node.leadingComments.length === 0) { + node.leadingComments = null; + } + + // Similarly, trailing comments are attached later. The variable + // must be reset to null if there are no trailing comments. + trailingComments = this.state.leadingComments.slice(i); + if (trailingComments.length === 0) { + trailingComments = null; + } + } + } + + this.state.commentPreviousNode = node; + + if (trailingComments) { + if (trailingComments.length && trailingComments[0].start >= node.start && last(trailingComments).end <= node.end) { + node.innerComments = trailingComments; + } else { + node.trailingComments = trailingComments; + } + } + + stack.push(node); +};
\ No newline at end of file diff --git a/node_modules/babylon/lib/parser/expression.js b/node_modules/babylon/lib/parser/expression.js new file mode 100644 index 000000000..ec437b9dc --- /dev/null +++ b/node_modules/babylon/lib/parser/expression.js @@ -0,0 +1,1096 @@ +"use strict"; + +var _types = require("../tokenizer/types"); + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +var _identifier = require("../util/identifier"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var pp = _index2.default.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. + +/* eslint indent: 0 */ +/* eslint max-len: 0 */ + +// 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 + +pp.checkPropClash = function (prop, propHash) { + if (prop.computed) return; + + var key = prop.key; + var name = void 0; + switch (key.type) { + case "Identifier": + name = key.name; + break; + + case "StringLiteral": + case "NumericLiteral": + name = String(key.value); + break; + + default: + return; + } + + if (name === "__proto__" && prop.kind === "init") { + if (propHash.proto) this.raise(key.start, "Redefinition of __proto__ property"); + propHash.proto = 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 startPos = this.state.start, + startLoc = this.state.startLoc; + var expr = this.parseMaybeAssign(noIn, refShorthandDefaultPos); + if (this.match(_types.types.comma)) { + var node = this.startNodeAt(startPos, startLoc); + node.expressions = [expr]; + while (this.eat(_types.types.comma)) { + node.expressions.push(this.parseMaybeAssign(noIn, refShorthandDefaultPos)); + } + this.toReferencedList(node.expressions); + return this.finishNode(node, "SequenceExpression"); + } + return expr; +}; + +// Parse an assignment expression. This includes applications of +// operators like `+=`. + +pp.parseMaybeAssign = function (noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos) { + if (this.match(_types.types._yield) && this.state.inGenerator) { + return this.parseYield(); + } + + var failOnShorthandAssign = void 0; + if (refShorthandDefaultPos) { + failOnShorthandAssign = false; + } else { + refShorthandDefaultPos = { start: 0 }; + failOnShorthandAssign = true; + } + + var startPos = this.state.start; + var startLoc = this.state.startLoc; + + if (this.match(_types.types.parenL) || this.match(_types.types.name)) { + this.state.potentialArrowAt = this.state.start; + } + + var left = this.parseMaybeConditional(noIn, refShorthandDefaultPos, refNeedsArrowPos); + if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc); + if (this.state.type.isAssign) { + var node = this.startNodeAt(startPos, startLoc); + node.operator = this.state.value; + node.left = this.match(_types.types.eq) ? this.toAssignable(left, undefined, "assignment expression") : left; + refShorthandDefaultPos.start = 0; // reset because shorthand default was used correctly + + this.checkLVal(left, undefined, undefined, "assignment expression"); + + if (left.extra && left.extra.parenthesized) { + var errorMsg = void 0; + 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, refNeedsArrowPos) { + var startPos = this.state.start, + startLoc = this.state.startLoc; + var expr = this.parseExprOps(noIn, refShorthandDefaultPos); + if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr; + + return this.parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos); +}; + +pp.parseConditional = function (expr, noIn, startPos, startLoc) { + if (this.eat(_types.types.question)) { + var node = this.startNodeAt(startPos, startLoc); + node.test = expr; + node.consequent = this.parseMaybeAssign(); + this.expect(_types.types.colon); + node.alternate = this.parseMaybeAssign(noIn); + return this.finishNode(node, "ConditionalExpression"); + } + return expr; +}; + +// Start the precedence parser. + +pp.parseExprOps = function (noIn, refShorthandDefaultPos) { + var startPos = this.state.start, + startLoc = this.state.startLoc; + var expr = this.parseMaybeUnary(refShorthandDefaultPos); + if (refShorthandDefaultPos && refShorthandDefaultPos.start) { + return expr; + } else { + return this.parseExprOp(expr, startPos, startLoc, -1, noIn); + } +}; + +// Parse binary operators with the operator precedence parsing +// algorithm. `left` is the left-hand side of the operator. +// `minPrec` provides context that allows the function to stop and +// defer further parser to one of its callers when it encounters an +// operator that has a lower precedence than the set it is parsing. + +pp.parseExprOp = function (left, leftStartPos, leftStartLoc, minPrec, noIn) { + var prec = this.state.type.binop; + if (prec != null && (!noIn || !this.match(_types.types._in))) { + if (prec > minPrec) { + var node = this.startNodeAt(leftStartPos, leftStartLoc); + node.left = left; + node.operator = this.state.value; + + if (node.operator === "**" && left.type === "UnaryExpression" && left.extra && !left.extra.parenthesizedArgument && !left.extra.parenthesized) { + this.raise(left.argument.start, "Illegal expression. Wrap left hand side or entire exponentiation in parentheses."); + } + + var op = this.state.type; + this.next(); + + var startPos = this.state.start; + var startLoc = this.state.startLoc; + node.right = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec, noIn); + + this.finishNode(node, op === _types.types.logicalOR || op === _types.types.logicalAND ? "LogicalExpression" : "BinaryExpression"); + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn); + } + } + return left; +}; + +// Parse unary operators, both prefix and postfix. + +pp.parseMaybeUnary = function (refShorthandDefaultPos) { + if (this.state.type.prefix) { + var node = this.startNode(); + var update = this.match(_types.types.incDec); + node.operator = this.state.value; + node.prefix = true; + this.next(); + + var argType = this.state.type; + node.argument = this.parseMaybeUnary(); + + this.addExtra(node, "parenthesizedArgument", argType === _types.types.parenL && (!node.argument.extra || !node.argument.extra.parenthesized)); + + if (refShorthandDefaultPos && refShorthandDefaultPos.start) { + this.unexpected(refShorthandDefaultPos.start); + } + + if (update) { + this.checkLVal(node.argument, undefined, undefined, "prefix operation"); + } else if (this.state.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 startPos = this.state.start, + startLoc = this.state.startLoc; + var expr = this.parseExprSubscripts(refShorthandDefaultPos); + if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr; + while (this.state.type.postfix && !this.canInsertSemicolon()) { + var _node = this.startNodeAt(startPos, startLoc); + _node.operator = this.state.value; + _node.prefix = false; + _node.argument = expr; + this.checkLVal(expr, undefined, undefined, "postfix operation"); + this.next(); + expr = this.finishNode(_node, "UpdateExpression"); + } + return expr; +}; + +// Parse call, dot, and `[]`-subscript expressions. + +pp.parseExprSubscripts = function (refShorthandDefaultPos) { + var startPos = this.state.start, + startLoc = this.state.startLoc; + var potentialArrowAt = this.state.potentialArrowAt; + var expr = this.parseExprAtom(refShorthandDefaultPos); + + if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) { + return expr; + } + + if (refShorthandDefaultPos && refShorthandDefaultPos.start) { + return expr; + } + + return this.parseSubscripts(expr, startPos, startLoc); +}; + +pp.parseSubscripts = function (base, startPos, startLoc, noCalls) { + for (;;) { + if (!noCalls && this.eat(_types.types.doubleColon)) { + var node = this.startNodeAt(startPos, startLoc); + node.object = base; + node.callee = this.parseNoCallExpr(); + return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls); + } else if (this.eat(_types.types.dot)) { + var _node2 = this.startNodeAt(startPos, startLoc); + _node2.object = base; + _node2.property = this.parseIdentifier(true); + _node2.computed = false; + base = this.finishNode(_node2, "MemberExpression"); + } else if (this.eat(_types.types.bracketL)) { + var _node3 = this.startNodeAt(startPos, startLoc); + _node3.object = base; + _node3.property = this.parseExpression(); + _node3.computed = true; + this.expect(_types.types.bracketR); + base = this.finishNode(_node3, "MemberExpression"); + } else if (!noCalls && this.match(_types.types.parenL)) { + var possibleAsync = this.state.potentialArrowAt === base.start && base.type === "Identifier" && base.name === "async" && !this.canInsertSemicolon(); + this.next(); + + var _node4 = this.startNodeAt(startPos, startLoc); + _node4.callee = base; + _node4.arguments = this.parseCallExpressionArguments(_types.types.parenR, possibleAsync); + base = this.finishNode(_node4, "CallExpression"); + + if (possibleAsync && this.shouldParseAsyncArrow()) { + return this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), _node4); + } else { + this.toReferencedList(_node4.arguments); + } + } else if (this.match(_types.types.backQuote)) { + var _node5 = this.startNodeAt(startPos, startLoc); + _node5.tag = base; + _node5.quasi = this.parseTemplate(); + base = this.finishNode(_node5, "TaggedTemplateExpression"); + } else { + return base; + } + } +}; + +pp.parseCallExpressionArguments = function (close, possibleAsyncArrow) { + var innerParenStart = void 0; + + var elts = [], + first = true; + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(_types.types.comma); + if (this.eat(close)) break; + } + + // we need to make sure that if this is an async arrow functions, that we don't allow inner parens inside the params + if (this.match(_types.types.parenL) && !innerParenStart) { + innerParenStart = this.state.start; + } + + elts.push(this.parseExprListItem(undefined, possibleAsyncArrow ? { start: 0 } : undefined)); + } + + // we found an async arrow function so let's not allow any inner parens + if (possibleAsyncArrow && innerParenStart && this.shouldParseAsyncArrow()) { + this.unexpected(); + } + + return elts; +}; + +pp.shouldParseAsyncArrow = function () { + return this.match(_types.types.arrow); +}; + +pp.parseAsyncArrowFromCallExpression = function (node, call) { + this.expect(_types.types.arrow); + return this.parseArrowExpression(node, call.arguments, true); +}; + +// Parse a no-call expression (like argument of `new` or `::` operators). + +pp.parseNoCallExpr = function () { + var startPos = this.state.start, + startLoc = this.state.startLoc; + return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, 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 = void 0, + canBeArrow = this.state.potentialArrowAt === this.state.start; + switch (this.state.type) { + case _types.types._super: + if (!this.state.inMethod && !this.options.allowSuperOutsideMethod) { + this.raise(this.state.start, "'super' outside of function or class"); + } + + node = this.startNode(); + this.next(); + if (!this.match(_types.types.parenL) && !this.match(_types.types.bracketL) && !this.match(_types.types.dot)) { + this.unexpected(); + } + if (this.match(_types.types.parenL) && this.state.inMethod !== "constructor" && !this.options.allowSuperOutsideMethod) { + this.raise(node.start, "super() outside of class constructor"); + } + return this.finishNode(node, "Super"); + + case _types.types._this: + node = this.startNode(); + this.next(); + return this.finishNode(node, "ThisExpression"); + + case _types.types._yield: + if (this.state.inGenerator) this.unexpected(); + + case _types.types.name: + node = this.startNode(); + var allowAwait = this.state.value === "await" && this.state.inAsync; + var allowYield = this.shouldAllowYieldIdentifier(); + var id = this.parseIdentifier(allowAwait || allowYield); + + if (id.name === "await") { + if (this.state.inAsync || this.inModule) { + return this.parseAwait(node); + } + } else if (id.name === "async" && this.match(_types.types._function) && !this.canInsertSemicolon()) { + this.next(); + return this.parseFunction(node, false, false, true); + } else if (canBeArrow && id.name === "async" && this.match(_types.types.name)) { + var params = [this.parseIdentifier()]; + this.expect(_types.types.arrow); + // let foo = bar => {}; + return this.parseArrowExpression(node, params, true); + } + + if (canBeArrow && !this.canInsertSemicolon() && this.eat(_types.types.arrow)) { + return this.parseArrowExpression(node, [id]); + } + + return id; + + case _types.types._do: + if (this.hasPlugin("doExpressions")) { + var _node6 = this.startNode(); + this.next(); + var oldInFunction = this.state.inFunction; + var oldLabels = this.state.labels; + this.state.labels = []; + this.state.inFunction = false; + _node6.body = this.parseBlock(false, true); + this.state.inFunction = oldInFunction; + this.state.labels = oldLabels; + return this.finishNode(_node6, "DoExpression"); + } + + case _types.types.regexp: + var value = this.state.value; + node = this.parseLiteral(value.value, "RegExpLiteral"); + node.pattern = value.pattern; + node.flags = value.flags; + return node; + + case _types.types.num: + return this.parseLiteral(this.state.value, "NumericLiteral"); + + case _types.types.string: + return this.parseLiteral(this.state.value, "StringLiteral"); + + case _types.types._null: + node = this.startNode(); + this.next(); + return this.finishNode(node, "NullLiteral"); + + case _types.types._true:case _types.types._false: + node = this.startNode(); + node.value = this.match(_types.types._true); + this.next(); + return this.finishNode(node, "BooleanLiteral"); + + case _types.types.parenL: + return this.parseParenAndDistinguishExpression(null, null, canBeArrow); + + case _types.types.bracketL: + node = this.startNode(); + this.next(); + node.elements = this.parseExprList(_types.types.bracketR, true, refShorthandDefaultPos); + this.toReferencedList(node.elements); + return this.finishNode(node, "ArrayExpression"); + + case _types.types.braceL: + return this.parseObj(false, refShorthandDefaultPos); + + case _types.types._function: + return this.parseFunctionExpression(); + + case _types.types.at: + this.parseDecorators(); + + case _types.types._class: + node = this.startNode(); + this.takeDecorators(node); + return this.parseClass(node, false); + + case _types.types._new: + return this.parseNew(); + + case _types.types.backQuote: + return this.parseTemplate(); + + case _types.types.doubleColon: + node = this.startNode(); + this.next(); + node.object = null; + var callee = node.callee = this.parseNoCallExpr(); + if (callee.type === "MemberExpression") { + return this.finishNode(node, "BindExpression"); + } else { + this.raise(callee.start, "Binding should be performed on object property."); + } + + default: + this.unexpected(); + } +}; + +pp.parseFunctionExpression = function () { + var node = this.startNode(); + var meta = this.parseIdentifier(true); + if (this.state.inGenerator && this.eat(_types.types.dot) && this.hasPlugin("functionSent")) { + return this.parseMetaProperty(node, meta, "sent"); + } else { + return this.parseFunction(node, false); + } +}; + +pp.parseMetaProperty = function (node, meta, propertyName) { + node.meta = meta; + node.property = this.parseIdentifier(true); + + if (node.property.name !== propertyName) { + this.raise(node.property.start, "The only valid meta property for new is " + meta.name + "." + propertyName); + } + + return this.finishNode(node, "MetaProperty"); +}; + +pp.parseLiteral = function (value, type) { + var node = this.startNode(); + this.addExtra(node, "rawValue", value); + this.addExtra(node, "raw", this.input.slice(this.state.start, this.state.end)); + node.value = value; + this.next(); + return this.finishNode(node, type); +}; + +pp.parseParenExpression = function () { + this.expect(_types.types.parenL); + var val = this.parseExpression(); + this.expect(_types.types.parenR); + return val; +}; + +pp.parseParenAndDistinguishExpression = function (startPos, startLoc, canBeArrow, isAsync) { + startPos = startPos || this.state.start; + startLoc = startLoc || this.state.startLoc; + + var val = void 0; + this.expect(_types.types.parenL); + + var innerStartPos = this.state.start, + innerStartLoc = this.state.startLoc; + var exprList = [], + first = true; + var refShorthandDefaultPos = { start: 0 }, + spreadStart = void 0, + optionalCommaStart = void 0; + var refNeedsArrowPos = { start: 0 }; + while (!this.match(_types.types.parenR)) { + if (first) { + first = false; + } else { + this.expect(_types.types.comma, refNeedsArrowPos.start || null); + if (this.match(_types.types.parenR)) { + optionalCommaStart = this.state.start; + break; + } + } + + if (this.match(_types.types.ellipsis)) { + var spreadNodeStartPos = this.state.start, + spreadNodeStartLoc = this.state.startLoc; + spreadStart = this.state.start; + exprList.push(this.parseParenItem(this.parseRest(), spreadNodeStartLoc, spreadNodeStartPos)); + break; + } else { + exprList.push(this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem, refNeedsArrowPos)); + } + } + + var innerEndPos = this.state.start; + var innerEndLoc = this.state.startLoc; + this.expect(_types.types.parenR); + + var arrowNode = this.startNodeAt(startPos, startLoc); + if (canBeArrow && this.shouldParseArrow() && (arrowNode = this.parseArrow(arrowNode))) { + for (var _iterator = exprList, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var param = _ref; + + if (param.extra && param.extra.parenthesized) this.unexpected(param.extra.parenStart); + } + + return this.parseArrowExpression(arrowNode, exprList, isAsync); + } + + if (!exprList.length) { + if (isAsync) { + return; + } else { + this.unexpected(this.state.lastTokStart); + } + } + if (optionalCommaStart) this.unexpected(optionalCommaStart); + if (spreadStart) this.unexpected(spreadStart); + if (refShorthandDefaultPos.start) this.unexpected(refShorthandDefaultPos.start); + if (refNeedsArrowPos.start) this.unexpected(refNeedsArrowPos.start); + + if (exprList.length > 1) { + val = this.startNodeAt(innerStartPos, innerStartLoc); + val.expressions = exprList; + this.toReferencedList(val.expressions); + this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); + } else { + val = exprList[0]; + } + + this.addExtra(val, "parenthesized", true); + this.addExtra(val, "parenStart", startPos); + + return val; +}; + +pp.shouldParseArrow = function () { + return !this.canInsertSemicolon(); +}; + +pp.parseArrow = function (node) { + if (this.eat(_types.types.arrow)) { + return node; + } +}; + +pp.parseParenItem = function (node) { + 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 + +pp.parseNew = function () { + var node = this.startNode(); + var meta = this.parseIdentifier(true); + + if (this.eat(_types.types.dot)) { + return this.parseMetaProperty(node, meta, "target"); + } + + node.callee = this.parseNoCallExpr(); + + if (this.eat(_types.types.parenL)) { + node.arguments = this.parseExprList(_types.types.parenR); + this.toReferencedList(node.arguments); + } else { + node.arguments = []; + } + + return this.finishNode(node, "NewExpression"); +}; + +// Parse template expression. + +pp.parseTemplateElement = function () { + var elem = this.startNode(); + elem.value = { + raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"), + cooked: this.state.value + }; + this.next(); + elem.tail = this.match(_types.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(_types.types.dollarBraceL); + node.expressions.push(this.parseExpression()); + this.expect(_types.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 decorators = []; + var propHash = Object.create(null); + var first = true; + var node = this.startNode(); + + node.properties = []; + this.next(); + + var firstRestLocation = null; + + while (!this.eat(_types.types.braceR)) { + if (first) { + first = false; + } else { + this.expect(_types.types.comma); + if (this.eat(_types.types.braceR)) break; + } + + while (this.match(_types.types.at)) { + decorators.push(this.parseDecorator()); + } + + var prop = this.startNode(), + isGenerator = false, + isAsync = false, + startPos = void 0, + startLoc = void 0; + if (decorators.length) { + prop.decorators = decorators; + decorators = []; + } + + if (this.hasPlugin("objectRestSpread") && this.match(_types.types.ellipsis)) { + prop = this.parseSpread(); + prop.type = isPattern ? "RestProperty" : "SpreadProperty"; + node.properties.push(prop); + if (isPattern) { + var position = this.state.start; + if (firstRestLocation !== null) { + this.unexpected(firstRestLocation, "Cannot have multiple rest elements when destructuring"); + } else if (this.eat(_types.types.braceR)) { + break; + } else if (this.match(_types.types.comma) && this.lookahead().type === _types.types.braceR) { + // TODO: temporary rollback + // this.unexpected(position, "A trailing comma is not permitted after the rest element"); + continue; + } else { + firstRestLocation = position; + continue; + } + } else { + continue; + } + } + + prop.method = false; + prop.shorthand = false; + + if (isPattern || refShorthandDefaultPos) { + startPos = this.state.start; + startLoc = this.state.startLoc; + } + + if (!isPattern) { + isGenerator = this.eat(_types.types.star); + } + + if (!isPattern && this.isContextual("async")) { + if (isGenerator) this.unexpected(); + + var asyncId = this.parseIdentifier(); + if (this.match(_types.types.colon) || this.match(_types.types.parenL) || this.match(_types.types.braceR)) { + prop.key = asyncId; + } else { + isAsync = true; + if (this.hasPlugin("asyncGenerators")) isGenerator = this.eat(_types.types.star); + this.parsePropertyName(prop); + } + } else { + this.parsePropertyName(prop); + } + + this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos); + this.checkPropClash(prop, propHash); + + if (prop.shorthand) { + this.addExtra(prop, "shorthand", true); + } + + node.properties.push(prop); + } + + if (firstRestLocation !== null) { + this.unexpected(firstRestLocation, "The rest element has to be the last element when destructuring"); + } + + if (decorators.length) { + this.raise(this.state.start, "You have trailing decorators with no property"); + } + + return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression"); +}; + +pp.parseObjPropValue = function (prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos) { + if (isAsync || isGenerator || this.match(_types.types.parenL)) { + if (isPattern) this.unexpected(); + prop.kind = "method"; + prop.method = true; + this.parseMethod(prop, isGenerator, isAsync); + return this.finishNode(prop, "ObjectMethod"); + } + + if (this.eat(_types.types.colon)) { + prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssign(false, refShorthandDefaultPos); + return this.finishNode(prop, "ObjectProperty"); + } + + if (!isPattern && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && !this.match(_types.types.comma) && !this.match(_types.types.braceR)) { + if (isGenerator || isAsync) this.unexpected(); + prop.kind = prop.key.name; + this.parsePropertyName(prop); + this.parseMethod(prop, false); + var paramCount = prop.kind === "get" ? 0 : 1; + if (prop.params.length !== paramCount) { + var start = prop.start; + if (prop.kind === "get") { + this.raise(start, "getter should have no params"); + } else { + this.raise(start, "setter should have exactly one param"); + } + } + return this.finishNode(prop, "ObjectMethod"); + } + + if (!prop.computed && prop.key.type === "Identifier") { + if (isPattern) { + var illegalBinding = this.isKeyword(prop.key.name); + if (!illegalBinding && this.state.strict) { + illegalBinding = _identifier.reservedWords.strictBind(prop.key.name) || _identifier.reservedWords.strict(prop.key.name); + } + if (illegalBinding) { + this.raise(prop.key.start, "Binding " + prop.key.name); + } + prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone()); + } else if (this.match(_types.types.eq) && refShorthandDefaultPos) { + if (!refShorthandDefaultPos.start) { + refShorthandDefaultPos.start = this.state.start; + } + prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone()); + } else { + prop.value = prop.key.__clone(); + } + prop.shorthand = true; + return this.finishNode(prop, "ObjectProperty"); + } + + this.unexpected(); +}; + +pp.parsePropertyName = function (prop) { + if (this.eat(_types.types.bracketL)) { + prop.computed = true; + prop.key = this.parseMaybeAssign(); + this.expect(_types.types.bracketR); + return prop.key; + } else { + prop.computed = false; + return prop.key = this.match(_types.types.num) || this.match(_types.types.string) ? this.parseExprAtom() : this.parseIdentifier(true); + } +}; + +// Initialize empty function node. + +pp.initFunction = function (node, isAsync) { + node.id = null; + node.generator = false; + node.expression = false; + node.async = !!isAsync; +}; + +// Parse object or class method. + +pp.parseMethod = function (node, isGenerator, isAsync) { + var oldInMethod = this.state.inMethod; + this.state.inMethod = node.kind || true; + this.initFunction(node, isAsync); + this.expect(_types.types.parenL); + node.params = this.parseBindingList(_types.types.parenR); + node.generator = isGenerator; + this.parseFunctionBody(node); + this.state.inMethod = oldInMethod; + return node; +}; + +// Parse arrow function expression with given parameters. + +pp.parseArrowExpression = function (node, params, isAsync) { + this.initFunction(node, isAsync); + node.params = this.toAssignableList(params, true, "arrow function parameters"); + this.parseFunctionBody(node, true); + return this.finishNode(node, "ArrowFunctionExpression"); +}; + +// Parse function body and check parameters. + +pp.parseFunctionBody = function (node, allowExpression) { + var isExpression = allowExpression && !this.match(_types.types.braceL); + + var oldInAsync = this.state.inAsync; + this.state.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.state.inFunction, + oldInGen = this.state.inGenerator, + oldLabels = this.state.labels; + this.state.inFunction = true;this.state.inGenerator = node.generator;this.state.labels = []; + node.body = this.parseBlock(true); + node.expression = false; + this.state.inFunction = oldInFunc;this.state.inGenerator = oldInGen;this.state.labels = oldLabels; + } + this.state.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`. + var checkLVal = this.state.strict; + var isStrict = false; + + // arrow function + if (allowExpression) checkLVal = true; + + // normal function + if (!isExpression && node.body.directives.length) { + for (var _iterator2 = node.body.directives, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var directive = _ref2; + + if (directive.value.value === "use strict") { + isStrict = true; + checkLVal = true; + break; + } + } + } + + // + if (isStrict && node.id && node.id.type === "Identifier" && node.id.name === "yield") { + this.raise(node.id.start, "Binding yield in strict mode"); + } + + if (checkLVal) { + var nameHash = Object.create(null); + var oldStrict = this.state.strict; + if (isStrict) this.state.strict = true; + if (node.id) { + this.checkLVal(node.id, true, undefined, "function name"); + } + for (var _iterator3 = node.params, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) { + var _ref3; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } + + var param = _ref3; + + if (isStrict && param.type !== "Identifier") { + this.raise(param.start, "Non-simple parameter in strict mode"); + } + this.checkLVal(param, true, nameHash, "function parameter list"); + } + this.state.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, allowEmpty, refShorthandDefaultPos) { + var elts = [], + first = true; + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(_types.types.comma); + if (this.eat(close)) break; + } + + elts.push(this.parseExprListItem(allowEmpty, refShorthandDefaultPos)); + } + return elts; +}; + +pp.parseExprListItem = function (allowEmpty, refShorthandDefaultPos) { + var elt = void 0; + if (allowEmpty && this.match(_types.types.comma)) { + elt = null; + } else if (this.match(_types.types.ellipsis)) { + elt = this.parseSpread(refShorthandDefaultPos); + } else { + elt = this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem); + } + return elt; +}; + +// Parse the next token as an identifier. If `liberal` is true (used +// when parsing properties), it will also convert keywords into +// identifiers. + +pp.parseIdentifier = function (liberal) { + var node = this.startNode(); + + if (this.match(_types.types.name)) { + if (!liberal && this.state.strict && _identifier.reservedWords.strict(this.state.value)) { + this.raise(this.state.start, "The keyword '" + this.state.value + "' is reserved"); + } + + node.name = this.state.value; + } else if (liberal && this.state.type.keyword) { + node.name = this.state.type.keyword; + } else { + this.unexpected(); + } + + if (!liberal && node.name === "await" && this.state.inAsync) { + this.raise(node.start, "invalid use of await inside of an async function"); + } + + node.loc.identifierName = node.name; + + this.next(); + return this.finishNode(node, "Identifier"); +}; + +// Parses await expression inside async function. + +pp.parseAwait = function (node) { + if (!this.state.inAsync) { + this.unexpected(); + } + if (this.match(_types.types.star)) { + this.raise(node.start, "await* has been removed from the async functions proposal. Use Promise.all() instead."); + } + 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.match(_types.types.semi) || this.canInsertSemicolon() || !this.match(_types.types.star) && !this.state.type.startsExpr) { + node.delegate = false; + node.argument = null; + } else { + node.delegate = this.eat(_types.types.star); + node.argument = this.parseMaybeAssign(); + } + return this.finishNode(node, "YieldExpression"); +};
\ No newline at end of file diff --git a/node_modules/babylon/lib/parser/index.js b/node_modules/babylon/lib/parser/index.js new file mode 100644 index 000000000..e8398929d --- /dev/null +++ b/node_modules/babylon/lib/parser/index.js @@ -0,0 +1,102 @@ +"use strict"; + +exports.__esModule = true; +exports.plugins = undefined; + +var _identifier = require("../util/identifier"); + +var _options = require("../options"); + +var _tokenizer = require("../tokenizer"); + +var _tokenizer2 = _interopRequireDefault(_tokenizer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var plugins = exports.plugins = {}; + +var Parser = function (_Tokenizer) { + _inherits(Parser, _Tokenizer); + + function Parser(options, input) { + _classCallCheck(this, Parser); + + options = (0, _options.getOptions)(options); + + var _this = _possibleConstructorReturn(this, _Tokenizer.call(this, options, input)); + + _this.options = options; + _this.inModule = _this.options.sourceType === "module"; + _this.isReservedWord = _identifier.reservedWords[6]; + _this.input = input; + _this.plugins = _this.loadPlugins(_this.options.plugins); + _this.filename = options.sourceFilename; + + // If enabled, skip leading hashbang line. + if (_this.state.pos === 0 && _this.input[0] === "#" && _this.input[1] === "!") { + _this.skipLineComment(2); + } + return _this; + } + + Parser.prototype.hasPlugin = function hasPlugin(name) { + return !!(this.plugins["*"] || this.plugins[name]); + }; + + Parser.prototype.extend = function extend(name, f) { + this[name] = f(this[name]); + }; + + Parser.prototype.loadPlugins = function loadPlugins(plugins) { + var pluginMap = {}; + + if (plugins.indexOf("flow") >= 0) { + // ensure flow plugin loads last + plugins = plugins.filter(function (plugin) { + return plugin !== "flow"; + }); + plugins.push("flow"); + } + + for (var _iterator = plugins, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var name = _ref; + + if (!pluginMap[name]) { + pluginMap[name] = true; + + var plugin = exports.plugins[name]; + if (plugin) plugin(this); + } + } + + return pluginMap; + }; + + Parser.prototype.parse = function parse() { + var file = this.startNode(); + var program = this.startNode(); + this.nextToken(); + return this.parseTopLevel(file, program); + }; + + return Parser; +}(_tokenizer2.default); + +exports.default = Parser;
\ No newline at end of file diff --git a/node_modules/babylon/lib/parser/location.js b/node_modules/babylon/lib/parser/location.js new file mode 100644 index 000000000..61a9a27cc --- /dev/null +++ b/node_modules/babylon/lib/parser/location.js @@ -0,0 +1,26 @@ +"use strict"; + +var _location = require("../util/location"); + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var pp = _index2.default.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 = (0, _location.getLineInfo)(this.input, pos); + message += " (" + loc.line + ":" + loc.column + ")"; + var err = new SyntaxError(message); + err.pos = pos; + err.loc = loc; + throw err; +};
\ No newline at end of file diff --git a/node_modules/babylon/lib/parser/lval.js b/node_modules/babylon/lib/parser/lval.js new file mode 100644 index 000000000..1bdbfa1f0 --- /dev/null +++ b/node_modules/babylon/lib/parser/lval.js @@ -0,0 +1,315 @@ +"use strict"; + +var _types = require("../tokenizer/types"); + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +var _identifier = require("../util/identifier"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var pp = _index2.default.prototype; + +// Convert existing expression atom to assignable pattern +// if possible. + +/* eslint indent: 0 */ + +pp.toAssignable = function (node, isBinding, contextDescription) { + if (node) { + switch (node.type) { + case "Identifier": + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + break; + + case "ObjectExpression": + node.type = "ObjectPattern"; + for (var _iterator = node.properties, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var prop = _ref; + + if (prop.type === "ObjectMethod") { + if (prop.kind === "get" || prop.kind === "set") { + this.raise(prop.key.start, "Object pattern can't contain getter or setter"); + } else { + this.raise(prop.key.start, "Object pattern can't contain methods"); + } + } else { + this.toAssignable(prop, isBinding, "object destructuring pattern"); + } + } + break; + + case "ObjectProperty": + this.toAssignable(node.value, isBinding, contextDescription); + break; + + case "SpreadProperty": + node.type = "RestProperty"; + break; + + case "ArrayExpression": + node.type = "ArrayPattern"; + this.toAssignableList(node.elements, isBinding, contextDescription); + 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: + { + var message = "Invalid left-hand side" + (contextDescription ? " in " + contextDescription : /* istanbul ignore next */"expression"); + this.raise(node.start, message); + } + } + } + return node; +}; + +// Convert list of expression atoms to binding list. + +pp.toAssignableList = function (exprList, isBinding, contextDescription) { + 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, contextDescription); + 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, contextDescription); + } + return exprList; +}; + +// Convert list of expression atoms to a list of + +pp.toReferencedList = function (exprList) { + return exprList; +}; + +// Parses spread element. + +pp.parseSpread = function (refShorthandDefaultPos) { + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeAssign(false, refShorthandDefaultPos); + return this.finishNode(node, "SpreadElement"); +}; + +pp.parseRest = function () { + var node = this.startNode(); + this.next(); + node.argument = this.parseBindingIdentifier(); + return this.finishNode(node, "RestElement"); +}; + +pp.shouldAllowYieldIdentifier = function () { + return this.match(_types.types._yield) && !this.state.strict && !this.state.inGenerator; +}; + +pp.parseBindingIdentifier = function () { + return this.parseIdentifier(this.shouldAllowYieldIdentifier()); +}; + +// Parses lvalue (assignable) atom. + +pp.parseBindingAtom = function () { + switch (this.state.type) { + case _types.types._yield: + if (this.state.strict || this.state.inGenerator) this.unexpected(); + // fall-through + case _types.types.name: + return this.parseIdentifier(true); + + case _types.types.bracketL: + var node = this.startNode(); + this.next(); + node.elements = this.parseBindingList(_types.types.bracketR, true); + return this.finishNode(node, "ArrayPattern"); + + case _types.types.braceL: + return this.parseObj(true); + + default: + this.unexpected(); + } +}; + +pp.parseBindingList = function (close, allowEmpty) { + var elts = []; + var first = true; + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(_types.types.comma); + } + if (allowEmpty && this.match(_types.types.comma)) { + elts.push(null); + } else if (this.eat(close)) { + break; + } else if (this.match(_types.types.ellipsis)) { + elts.push(this.parseAssignableListItemTypes(this.parseRest())); + this.expect(close); + break; + } else { + var decorators = []; + while (this.match(_types.types.at)) { + decorators.push(this.parseDecorator()); + } + var left = this.parseMaybeDefault(); + if (decorators.length) { + left.decorators = decorators; + } + this.parseAssignableListItemTypes(left); + elts.push(this.parseMaybeDefault(left.start, left.loc.start, left)); + } + } + return elts; +}; + +pp.parseAssignableListItemTypes = function (param) { + return param; +}; + +// Parses assignment pattern around given atom if possible. + +pp.parseMaybeDefault = function (startPos, startLoc, left) { + startLoc = startLoc || this.state.startLoc; + startPos = startPos || this.state.start; + left = left || this.parseBindingAtom(); + if (!this.eat(_types.types.eq)) return left; + + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.right = this.parseMaybeAssign(); + return this.finishNode(node, "AssignmentPattern"); +}; + +// Verify that a node is an lval — something that can be assigned +// to. + +pp.checkLVal = function (expr, isBinding, checkClashes, contextDescription) { + switch (expr.type) { + case "Identifier": + if (this.state.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) { + // we need to prefix this with an underscore for the cases where we have a key of + // `__proto__`. there's a bug in old V8 where the following wouldn't work: + // + // > var obj = Object.create(null); + // undefined + // > obj.__proto__ + // null + // > obj.__proto__ = true; + // true + // > obj.__proto__ + // null + var key = "_" + expr.name; + + if (checkClashes[key]) { + this.raise(expr.start, "Argument name clash in strict mode"); + } else { + checkClashes[key] = true; + } + } + break; + + case "MemberExpression": + if (isBinding) this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " member expression"); + break; + + case "ObjectPattern": + for (var _iterator2 = expr.properties, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var prop = _ref2; + + if (prop.type === "ObjectProperty") prop = prop.value; + this.checkLVal(prop, isBinding, checkClashes, "object destructuring pattern"); + } + break; + + case "ArrayPattern": + for (var _iterator3 = expr.elements, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) { + var _ref3; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } + + var elem = _ref3; + + if (elem) this.checkLVal(elem, isBinding, checkClashes, "array destructuring pattern"); + } + break; + + case "AssignmentPattern": + this.checkLVal(expr.left, isBinding, checkClashes, "assignment pattern"); + break; + + case "RestProperty": + this.checkLVal(expr.argument, isBinding, checkClashes, "rest property"); + break; + + case "RestElement": + this.checkLVal(expr.argument, isBinding, checkClashes, "rest element"); + break; + + default: + { + var message = (isBinding ? /* istanbul ignore next */"Binding invalid" : "Invalid") + " left-hand side" + (contextDescription ? " in " + contextDescription : /* istanbul ignore next */"expression"); + this.raise(expr.start, message); + } + } +};
\ No newline at end of file diff --git a/node_modules/babylon/lib/parser/node.js b/node_modules/babylon/lib/parser/node.js new file mode 100644 index 000000000..a9bbe4e53 --- /dev/null +++ b/node_modules/babylon/lib/parser/node.js @@ -0,0 +1,70 @@ +"use strict"; + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +var _location = require("../util/location"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// Start an AST node, attaching a start offset. + +var pp = _index2.default.prototype; +var commentKeys = ["leadingComments", "trailingComments", "innerComments"]; + +var Node = function () { + function Node(pos, loc, filename) { + _classCallCheck(this, Node); + + this.type = ""; + this.start = pos; + this.end = 0; + this.loc = new _location.SourceLocation(loc); + if (filename) this.loc.filename = filename; + } + + Node.prototype.__clone = function __clone() { + var node2 = new Node(); + for (var key in this) { + // Do not clone comments that are already attached to the node + if (commentKeys.indexOf(key) < 0) { + node2[key] = this[key]; + } + } + + return node2; + }; + + return Node; +}(); + +pp.startNode = function () { + return new Node(this.state.start, this.state.startLoc, this.filename); +}; + +pp.startNodeAt = function (pos, loc) { + return new Node(pos, loc, this.filename); +}; + +function finishNodeAt(node, type, pos, loc) { + node.type = type; + node.end = pos; + node.loc.end = loc; + this.processComment(node); + return node; +} + +// Finish an AST node, adding `type` and `end` properties. + +pp.finishNode = function (node, type) { + return finishNodeAt.call(this, node, type, this.state.lastTokEnd, this.state.lastTokEndLoc); +}; + +// Finish node at given position + +pp.finishNodeAt = function (node, type, pos, loc) { + return finishNodeAt.call(this, node, type, pos, loc); +};
\ No newline at end of file diff --git a/node_modules/babylon/lib/parser/statement.js b/node_modules/babylon/lib/parser/statement.js new file mode 100644 index 000000000..3aa2f7882 --- /dev/null +++ b/node_modules/babylon/lib/parser/statement.js @@ -0,0 +1,1107 @@ +"use strict"; + +var _types = require("../tokenizer/types"); + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +var _whitespace = require("../util/whitespace"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var pp = _index2.default.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. + +/* eslint indent: 0 */ +/* eslint max-len: 0 */ + +pp.parseTopLevel = function (file, program) { + program.sourceType = this.options.sourceType; + + this.parseBlockBody(program, true, true, _types.types.eof); + + file.program = this.finishNode(program, "Program"); + file.comments = this.state.comments; + file.tokens = this.state.tokens; + + return this.finishNode(file, "File"); +}; + +var loopLabel = { kind: "loop" }, + switchLabel = { kind: "switch" }; + +// TODO + +pp.stmtToDirective = function (stmt) { + var expr = stmt.expression; + + var directiveLiteral = this.startNodeAt(expr.start, expr.loc.start); + var directive = this.startNodeAt(stmt.start, stmt.loc.start); + + var raw = this.input.slice(expr.start, expr.end); + var val = directiveLiteral.value = raw.slice(1, -1); // remove quotes + + this.addExtra(directiveLiteral, "raw", raw); + this.addExtra(directiveLiteral, "rawValue", val); + + directive.value = this.finishNodeAt(directiveLiteral, "DirectiveLiteral", expr.end, expr.loc.end); + + return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end); +}; + +// 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.match(_types.types.at)) { + this.parseDecorators(true); + } + + var starttype = this.state.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 _types.types._break:case _types.types._continue: + return this.parseBreakContinueStatement(node, starttype.keyword); + case _types.types._debugger: + return this.parseDebuggerStatement(node); + case _types.types._do: + return this.parseDoStatement(node); + case _types.types._for: + return this.parseForStatement(node); + case _types.types._function: + if (!declaration) this.unexpected(); + return this.parseFunctionStatement(node); + + case _types.types._class: + if (!declaration) this.unexpected(); + this.takeDecorators(node); + return this.parseClass(node, true); + + case _types.types._if: + return this.parseIfStatement(node); + case _types.types._return: + return this.parseReturnStatement(node); + case _types.types._switch: + return this.parseSwitchStatement(node); + case _types.types._throw: + return this.parseThrowStatement(node); + case _types.types._try: + return this.parseTryStatement(node); + + case _types.types._let: + case _types.types._const: + if (!declaration) this.unexpected(); // NOTE: falls through to _var + + case _types.types._var: + return this.parseVarStatement(node, starttype); + + case _types.types._while: + return this.parseWhileStatement(node); + case _types.types._with: + return this.parseWithStatement(node); + case _types.types.braceL: + return this.parseBlock(); + case _types.types.semi: + return this.parseEmptyStatement(node); + case _types.types._export: + case _types.types._import: + if (!this.options.allowImportExportEverywhere) { + if (!topLevel) { + this.raise(this.state.start, "'import' and 'export' may only appear at the top level"); + } + + if (!this.inModule) { + this.raise(this.state.start, "'import' and 'export' may appear only with 'sourceType: module'"); + } + } + return starttype === _types.types._import ? this.parseImport(node) : this.parseExport(node); + + case _types.types.name: + if (this.state.value === "async") { + // peek ahead and see if next token is a function + var state = this.state.clone(); + this.next(); + if (this.match(_types.types._function) && !this.canInsertSemicolon()) { + this.expect(_types.types._function); + return this.parseFunction(node, true, false, true); + } else { + this.state = state; + } + } + } + + // 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. + var maybeName = this.state.value; + var expr = this.parseExpression(); + + if (starttype === _types.types.name && expr.type === "Identifier" && this.eat(_types.types.colon)) { + return this.parseLabeledStatement(node, maybeName, expr); + } else { + return this.parseExpressionStatement(node, expr); + } +}; + +pp.takeDecorators = function (node) { + if (this.state.decorators.length) { + node.decorators = this.state.decorators; + this.state.decorators = []; + } +}; + +pp.parseDecorators = function (allowExport) { + while (this.match(_types.types.at)) { + this.state.decorators.push(this.parseDecorator()); + } + + if (allowExport && this.match(_types.types._export)) { + return; + } + + if (!this.match(_types.types._class)) { + this.raise(this.state.start, "Leading decorators must be attached to a class declaration"); + } +}; + +pp.parseDecorator = function () { + if (!this.hasPlugin("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.isLineTerminator()) { + node.label = null; + } else if (!this.match(_types.types.name)) { + this.unexpected(); + } else { + node.label = this.parseIdentifier(); + this.semicolon(); + } + + // Verify that there is an actual destination to break or + // continue to. + var i = void 0; + for (i = 0; i < this.state.labels.length; ++i) { + var lab = this.state.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.state.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) { + this.next(); + this.state.labels.push(loopLabel); + node.body = this.parseStatement(false); + this.state.labels.pop(); + this.expect(_types.types._while); + node.test = this.parseParenExpression(); + this.eat(_types.types.semi); + 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.state.labels.push(loopLabel); + + var forAwait = false; + if (this.hasPlugin("asyncGenerators") && this.state.inAsync && this.isContextual("await")) { + forAwait = true; + this.next(); + } + this.expect(_types.types.parenL); + + if (this.match(_types.types.semi)) { + if (forAwait) { + this.unexpected(); + } + return this.parseFor(node, null); + } + + if (this.match(_types.types._var) || this.match(_types.types._let) || this.match(_types.types._const)) { + var _init = this.startNode(), + varKind = this.state.type; + this.next(); + this.parseVar(_init, true, varKind); + this.finishNode(_init, "VariableDeclaration"); + + if (this.match(_types.types._in) || this.isContextual("of")) { + if (_init.declarations.length === 1 && !_init.declarations[0].init) { + return this.parseForIn(node, _init, forAwait); + } + } + if (forAwait) { + this.unexpected(); + } + return this.parseFor(node, _init); + } + + var refShorthandDefaultPos = { start: 0 }; + var init = this.parseExpression(true, refShorthandDefaultPos); + if (this.match(_types.types._in) || this.isContextual("of")) { + var description = this.isContextual("of") ? "for-of statement" : "for-in statement"; + this.toAssignable(init, undefined, description); + this.checkLVal(init, undefined, undefined, description); + return this.parseForIn(node, init, forAwait); + } else if (refShorthandDefaultPos.start) { + this.unexpected(refShorthandDefaultPos.start); + } + if (forAwait) { + this.unexpected(); + } + 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(_types.types._else) ? this.parseStatement(false) : null; + return this.finishNode(node, "IfStatement"); +}; + +pp.parseReturnStatement = function (node) { + if (!this.state.inFunction && !this.options.allowReturnOutsideFunction) { + this.raise(this.state.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.isLineTerminator()) { + 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(_types.types.braceL); + this.state.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. + + var cur = void 0; + for (var sawDefault; !this.match(_types.types.braceR);) { + if (this.match(_types.types._case) || this.match(_types.types._default)) { + var isCase = this.match(_types.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.state.lastTokStart, "Multiple default clauses"); + sawDefault = true; + cur.test = null; + } + this.expect(_types.types.colon); + } else { + if (cur) { + cur.consequent.push(this.parseStatement(true)); + } else { + this.unexpected(); + } + } + } + if (cur) this.finishNode(cur, "SwitchCase"); + this.next(); // Closing brace + this.state.labels.pop(); + return this.finishNode(node, "SwitchStatement"); +}; + +pp.parseThrowStatement = function (node) { + this.next(); + if (_whitespace.lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start))) this.raise(this.state.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.match(_types.types._catch)) { + var clause = this.startNode(); + this.next(); + + this.expect(_types.types.parenL); + clause.param = this.parseBindingAtom(); + this.checkLVal(clause.param, true, Object.create(null), "catch clause"); + this.expect(_types.types.parenR); + + clause.body = this.parseBlock(); + node.handler = this.finishNode(clause, "CatchClause"); + } + + node.guardedHandlers = empty; + node.finalizer = this.eat(_types.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.state.labels.push(loopLabel); + node.body = this.parseStatement(false); + this.state.labels.pop(); + return this.finishNode(node, "WhileStatement"); +}; + +pp.parseWithStatement = function (node) { + if (this.state.strict) this.raise(this.state.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 _iterator = this.state.labels, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var _label = _ref; + + if (_label.name === maybeName) { + this.raise(expr.start, "Label '" + maybeName + "' is already declared"); + } + } + + var kind = this.state.type.isLoop ? "loop" : this.match(_types.types._switch) ? "switch" : null; + for (var i = this.state.labels.length - 1; i >= 0; i--) { + var label = this.state.labels[i]; + if (label.statementStart === node.start) { + label.statementStart = this.state.start; + label.kind = kind; + } else { + break; + } + } + + this.state.labels.push({ name: maybeName, kind: kind, statementStart: this.state.start }); + node.body = this.parseStatement(true); + this.state.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 (allowDirectives) { + var node = this.startNode(); + this.expect(_types.types.braceL); + this.parseBlockBody(node, allowDirectives, false, _types.types.braceR); + return this.finishNode(node, "BlockStatement"); +}; + +// TODO + +pp.parseBlockBody = function (node, allowDirectives, topLevel, end) { + node.body = []; + node.directives = []; + + var parsedNonDirective = false; + var oldStrict = void 0; + var octalPosition = void 0; + + while (!this.eat(end)) { + if (!parsedNonDirective && this.state.containsOctal && !octalPosition) { + octalPosition = this.state.octalPosition; + } + + var stmt = this.parseStatement(true, topLevel); + + if (allowDirectives && !parsedNonDirective && stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized) { + var directive = this.stmtToDirective(stmt); + node.directives.push(directive); + + if (oldStrict === undefined && directive.value.value === "use strict") { + oldStrict = this.state.strict; + this.setStrict(true); + + if (octalPosition) { + this.raise(octalPosition, "Octal literal in strict mode"); + } + } + + continue; + } + + parsedNonDirective = true; + node.body.push(stmt); + } + + if (oldStrict === false) { + this.setStrict(false); + } +}; + +// 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(_types.types.semi); + node.test = this.match(_types.types.semi) ? null : this.parseExpression(); + this.expect(_types.types.semi); + node.update = this.match(_types.types.parenR) ? null : this.parseExpression(); + this.expect(_types.types.parenR); + node.body = this.parseStatement(false); + this.state.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, forAwait) { + var type = void 0; + if (forAwait) { + this.eatContextual("of"); + type = "ForAwaitStatement"; + } else { + type = this.match(_types.types._in) ? "ForInStatement" : "ForOfStatement"; + this.next(); + } + node.left = init; + node.right = this.parseExpression(); + this.expect(_types.types.parenR); + node.body = this.parseStatement(false); + this.state.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(_types.types.eq)) { + decl.init = this.parseMaybeAssign(isFor); + } else if (kind === _types.types._const && !(this.match(_types.types._in) || this.isContextual("of"))) { + this.unexpected(); + } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(_types.types._in) || this.isContextual("of")))) { + this.raise(this.state.lastTokEnd, "Complex binding patterns require an initialization value"); + } else { + decl.init = null; + } + node.declarations.push(this.finishNode(decl, "VariableDeclarator")); + if (!this.eat(_types.types.comma)) break; + } + return node; +}; + +pp.parseVarHead = function (decl) { + decl.id = this.parseBindingAtom(); + this.checkLVal(decl.id, true, undefined, "variable declaration"); +}; + +// Parse a function declaration or literal (depending on the +// `isStatement` parameter). + +pp.parseFunction = function (node, isStatement, allowExpressionBody, isAsync, optionalId) { + var oldInMethod = this.state.inMethod; + this.state.inMethod = false; + + this.initFunction(node, isAsync); + + if (this.match(_types.types.star)) { + if (node.async && !this.hasPlugin("asyncGenerators")) { + this.unexpected(); + } else { + node.generator = true; + this.next(); + } + } + + if (isStatement && !optionalId && !this.match(_types.types.name) && !this.match(_types.types._yield)) { + this.unexpected(); + } + + if (this.match(_types.types.name) || this.match(_types.types._yield)) { + node.id = this.parseBindingIdentifier(); + } + + this.parseFunctionParams(node); + this.parseFunctionBody(node, allowExpressionBody); + + this.state.inMethod = oldInMethod; + + return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression"); +}; + +pp.parseFunctionParams = function (node) { + this.expect(_types.types.parenL); + node.params = this.parseBindingList(_types.types.parenR); +}; + +// Parse a class declaration or literal (depending on the +// `isStatement` parameter). + +pp.parseClass = function (node, isStatement, optionalId) { + this.next(); + this.parseClassId(node, isStatement, optionalId); + this.parseClassSuper(node); + this.parseClassBody(node); + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression"); +}; + +pp.isClassProperty = function () { + return this.match(_types.types.eq) || this.isLineTerminator(); +}; + +pp.isClassMutatorStarter = function () { + return false; +}; + +pp.parseClassBody = function (node) { + // class bodies are implicitly strict + var oldStrict = this.state.strict; + this.state.strict = true; + + var hadConstructorCall = false; + var hadConstructor = false; + var decorators = []; + var classBody = this.startNode(); + + classBody.body = []; + + this.expect(_types.types.braceL); + + while (!this.eat(_types.types.braceR)) { + if (this.eat(_types.types.semi)) { + continue; + } + + if (this.match(_types.types.at)) { + decorators.push(this.parseDecorator()); + continue; + } + + var method = this.startNode(); + + // steal the decorators if there are any + if (decorators.length) { + method.decorators = decorators; + decorators = []; + } + + var isConstructorCall = false; + var isMaybeStatic = this.match(_types.types.name) && this.state.value === "static"; + var isGenerator = this.eat(_types.types.star); + var isGetSet = false; + var isAsync = false; + + this.parsePropertyName(method); + + method.static = isMaybeStatic && !this.match(_types.types.parenL); + if (method.static) { + if (isGenerator) this.unexpected(); + isGenerator = this.eat(_types.types.star); + this.parsePropertyName(method); + } + + if (!isGenerator) { + if (this.isClassProperty()) { + classBody.body.push(this.parseClassProperty(method)); + continue; + } + + if (method.key.type === "Identifier" && !method.computed && this.hasPlugin("classConstructorCall") && method.key.name === "call" && this.match(_types.types.name) && this.state.value === "constructor") { + isConstructorCall = true; + this.parsePropertyName(method); + } + } + + var isAsyncMethod = !this.match(_types.types.parenL) && !method.computed && method.key.type === "Identifier" && method.key.name === "async"; + if (isAsyncMethod) { + if (this.hasPlugin("asyncGenerators") && this.eat(_types.types.star)) isGenerator = true; + isAsync = true; + this.parsePropertyName(method); + } + + method.kind = "method"; + + if (!method.computed) { + var key = method.key; + + // handle get/set methods + // eg. class Foo { get bar() {} set bar() {} } + + if (!isAsync && !isGenerator && !this.isClassMutatorStarter() && key.type === "Identifier" && !this.match(_types.types.parenL) && (key.name === "get" || key.name === "set")) { + isGetSet = true; + method.kind = key.name; + key = this.parsePropertyName(method); + } + + // disallow invalid constructors + var isConstructor = !isConstructorCall && !method.static && (key.type === "Identifier" && key.name === "constructor" || key.type === "StringLiteral" && key.value === "constructor"); + if (isConstructor) { + 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; + } + + // disallow static prototype method + var isStaticPrototype = method.static && (key.type === "Identifier" && key.name === "prototype" || key.type === "StringLiteral" && key.value === "prototype"); + if (isStaticPrototype) { + this.raise(key.start, "Classes may not have static property named prototype"); + } + } + + // convert constructor to a constructor call + if (isConstructorCall) { + if (hadConstructorCall) this.raise(method.start, "Duplicate constructor call in the same class"); + method.kind = "constructorCall"; + hadConstructorCall = true; + } + + // disallow decorators on class constructors + if ((method.kind === "constructor" || method.kind === "constructorCall") && method.decorators) { + this.raise(method.start, "You can't attach decorators to a class constructor"); + } + + this.parseClassMethod(classBody, method, isGenerator, isAsync); + + // get methods aren't allowed to have any parameters + // set methods must have exactly 1 parameter + if (isGetSet) { + var paramCount = method.kind === "get" ? 0 : 1; + if (method.params.length !== paramCount) { + var start = method.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.state.start, "You have trailing decorators with no method"); + } + + node.body = this.finishNode(classBody, "ClassBody"); + + this.state.strict = oldStrict; +}; + +pp.parseClassProperty = function (node) { + if (this.match(_types.types.eq)) { + if (!this.hasPlugin("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) { + this.parseMethod(method, isGenerator, isAsync); + classBody.body.push(this.finishNode(method, "ClassMethod")); +}; + +pp.parseClassId = function (node, isStatement, optionalId) { + if (this.match(_types.types.name)) { + node.id = this.parseIdentifier(); + } else { + if (optionalId || !isStatement) { + node.id = null; + } else { + this.unexpected(); + } + } +}; + +pp.parseClassSuper = function (node) { + node.superClass = this.eat(_types.types._extends) ? this.parseExprSubscripts() : null; +}; + +// Parses module export declaration. + +pp.parseExport = function (node) { + this.next(); + // export * from '...' + if (this.match(_types.types.star)) { + var specifier = this.startNode(); + this.next(); + if (this.hasPlugin("exportExtensions") && this.eatContextual("as")) { + specifier.exported = this.parseIdentifier(); + node.specifiers = [this.finishNode(specifier, "ExportNamespaceSpecifier")]; + this.parseExportSpecifiersMaybe(node); + this.parseExportFrom(node, true); + } else { + this.parseExportFrom(node, true); + return this.finishNode(node, "ExportAllDeclaration"); + } + } else if (this.hasPlugin("exportExtensions") && this.isExportDefaultSpecifier()) { + var _specifier = this.startNode(); + _specifier.exported = this.parseIdentifier(true); + node.specifiers = [this.finishNode(_specifier, "ExportDefaultSpecifier")]; + if (this.match(_types.types.comma) && this.lookahead().type === _types.types.star) { + this.expect(_types.types.comma); + var _specifier2 = this.startNode(); + this.expect(_types.types.star); + this.expectContextual("as"); + _specifier2.exported = this.parseIdentifier(); + node.specifiers.push(this.finishNode(_specifier2, "ExportNamespaceSpecifier")); + } else { + this.parseExportSpecifiersMaybe(node); + } + this.parseExportFrom(node, true); + } else if (this.eat(_types.types._default)) { + // export default ... + var expr = this.startNode(); + var needsSemi = false; + if (this.eat(_types.types._function)) { + expr = this.parseFunction(expr, true, false, false, true); + } else if (this.match(_types.types._class)) { + expr = this.parseClass(expr, true, true); + } else { + needsSemi = true; + expr = this.parseMaybeAssign(); + } + node.declaration = expr; + if (needsSemi) this.semicolon(); + this.checkExport(node, true, true); + return this.finishNode(node, "ExportDefaultDeclaration"); + } else if (this.state.type.keyword || this.shouldParseExportDeclaration()) { + node.specifiers = []; + node.source = null; + node.declaration = this.parseExportDeclaration(node); + } else { + // export { x, y as z } [from '...'] + node.declaration = null; + node.specifiers = this.parseExportSpecifiers(); + this.parseExportFrom(node); + } + this.checkExport(node, true); + return this.finishNode(node, "ExportNamedDeclaration"); +}; + +pp.parseExportDeclaration = function () { + return this.parseStatement(true); +}; + +pp.isExportDefaultSpecifier = function () { + if (this.match(_types.types.name)) { + return this.state.value !== "type" && this.state.value !== "async" && this.state.value !== "interface"; + } + + if (!this.match(_types.types._default)) { + return false; + } + + var lookahead = this.lookahead(); + return lookahead.type === _types.types.comma || lookahead.type === _types.types.name && lookahead.value === "from"; +}; + +pp.parseExportSpecifiersMaybe = function (node) { + if (this.eat(_types.types.comma)) { + node.specifiers = node.specifiers.concat(this.parseExportSpecifiers()); + } +}; + +pp.parseExportFrom = function (node, expect) { + if (this.eatContextual("from")) { + node.source = this.match(_types.types.string) ? this.parseExprAtom() : this.unexpected(); + this.checkExport(node); + } else { + if (expect) { + this.unexpected(); + } else { + node.source = null; + } + } + + this.semicolon(); +}; + +pp.shouldParseExportDeclaration = function () { + return this.isContextual("async"); +}; + +pp.checkExport = function (node, checkNames, isDefault) { + if (checkNames) { + // Check for duplicate exports + if (isDefault) { + // Default exports + this.checkDuplicateExports(node, "default", isDefault); + } else if (node.specifiers && node.specifiers.length) { + // Named exports + for (var _iterator2 = node.specifiers, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var specifier = _ref2; + + var name = specifier.exported.name; + if (name === "default") isDefault = true; + this.checkDuplicateExports(specifier, name, isDefault); + } + } else if (node.declaration) { + // Exported declarations + if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") { + this.checkDuplicateExports(node, node.declaration.id.name, isDefault); + } else if (node.declaration.type === "VariableDeclaration") { + for (var _iterator3 = node.declaration.declarations, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) { + var _ref3; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } + + var declaration = _ref3; + + if (declaration.id.name) { + this.checkDuplicateExports(declaration, declaration.id.name, isDefault); + } + } + } + } + } + + if (this.state.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); + } +}; + +pp.checkDuplicateExports = function (node, name, isDefault) { + if (this.state.exportedIdentifiers.indexOf(name) > -1) { + this.raiseDuplicateExportError(node, name, isDefault); + } + this.state.exportedIdentifiers.push(name); +}; + +pp.raiseDuplicateExportError = function (node, name, isDefault) { + this.raise(node.start, isDefault ? "Only one default export allowed per module." : "`" + name + "` has already been exported. Exported identifiers must be unique."); +}; + +// Parses a comma-separated list of module exports. + +pp.parseExportSpecifiers = function () { + var nodes = []; + var first = true; + var needsFrom = void 0; + + // export { x, y as z } [from '...'] + this.expect(_types.types.braceL); + + while (!this.eat(_types.types.braceR)) { + if (first) { + first = false; + } else { + this.expect(_types.types.comma); + if (this.eat(_types.types.braceR)) break; + } + + var isDefault = this.match(_types.types._default); + if (isDefault && !needsFrom) needsFrom = true; + + var node = this.startNode(); + node.local = this.parseIdentifier(isDefault); + node.exported = this.eatContextual("as") ? this.parseIdentifier(true) : node.local.__clone(); + nodes.push(this.finishNode(node, "ExportSpecifier")); + } + + // https://github.com/ember-cli/ember-cli/pull/3739 + if (needsFrom && !this.isContextual("from")) { + this.unexpected(); + } + + return nodes; +}; + +// Parses import declaration. + +pp.parseImport = function (node) { + this.next(); + + // import '...' + if (this.match(_types.types.string)) { + node.specifiers = []; + node.source = this.parseExprAtom(); + } else { + node.specifiers = []; + this.parseImportSpecifiers(node); + this.expectContextual("from"); + node.source = this.match(_types.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.match(_types.types.name)) { + // import defaultObj, { x, y as z } from '...' + var startPos = this.state.start, + startLoc = this.state.startLoc; + node.specifiers.push(this.parseImportSpecifierDefault(this.parseIdentifier(), startPos, startLoc)); + if (!this.eat(_types.types.comma)) return; + } + + if (this.match(_types.types.star)) { + var specifier = this.startNode(); + this.next(); + this.expectContextual("as"); + specifier.local = this.parseIdentifier(); + this.checkLVal(specifier.local, true, undefined, "import namespace specifier"); + node.specifiers.push(this.finishNode(specifier, "ImportNamespaceSpecifier")); + return; + } + + this.expect(_types.types.braceL); + while (!this.eat(_types.types.braceR)) { + if (first) { + first = false; + } else { + this.expect(_types.types.comma); + if (this.eat(_types.types.braceR)) break; + } + + var _specifier3 = this.startNode(); + _specifier3.imported = this.parseIdentifier(true); + _specifier3.local = this.eatContextual("as") ? this.parseIdentifier() : _specifier3.imported.__clone(); + this.checkLVal(_specifier3.local, true, undefined, "import specifier"); + node.specifiers.push(this.finishNode(_specifier3, "ImportSpecifier")); + } +}; + +pp.parseImportSpecifierDefault = function (id, startPos, startLoc) { + var node = this.startNodeAt(startPos, startLoc); + node.local = id; + this.checkLVal(node.local, true, undefined, "default import specifier"); + return this.finishNode(node, "ImportDefaultSpecifier"); +};
\ No newline at end of file diff --git a/node_modules/babylon/lib/parser/util.js b/node_modules/babylon/lib/parser/util.js new file mode 100644 index 000000000..f092721a4 --- /dev/null +++ b/node_modules/babylon/lib/parser/util.js @@ -0,0 +1,92 @@ +"use strict"; + +var _types = require("../tokenizer/types"); + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +var _whitespace = require("../util/whitespace"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var pp = _index2.default.prototype; + +// ## Parser utilities + +// TODO + +pp.addExtra = function (node, key, val) { + if (!node) return; + + var extra = node.extra = node.extra || {}; + extra[key] = val; +}; + +// TODO + +pp.isRelational = function (op) { + return this.match(_types.types.relational) && this.state.value === op; +}; + +// TODO + +pp.expectRelational = function (op) { + if (this.isRelational(op)) { + this.next(); + } else { + this.unexpected(); + } +}; + +// Tests whether parsed token is a contextual keyword. + +pp.isContextual = function (name) { + return this.match(_types.types.name) && this.state.value === name; +}; + +// Consumes contextual keyword if possible. + +pp.eatContextual = function (name) { + return this.state.value === name && this.eat(_types.types.name); +}; + +// Asserts that following token is given contextual keyword. + +pp.expectContextual = function (name, message) { + if (!this.eatContextual(name)) this.unexpected(null, message); +}; + +// Test whether a semicolon can be inserted at the current position. + +pp.canInsertSemicolon = function () { + return this.match(_types.types.eof) || this.match(_types.types.braceR) || _whitespace.lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start)); +}; + +// TODO + +pp.isLineTerminator = function () { + return this.eat(_types.types.semi) || this.canInsertSemicolon(); +}; + +// 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.isLineTerminator()) this.unexpected(); +}; + +// Expect a token of a given type. If found, consume it, otherwise, +// raise an unexpected token error at given pos. + +pp.expect = function (type, pos) { + return this.eat(type) || this.unexpected(pos); +}; + +// Raise an unexpected token error. + +pp.unexpected = function (pos) { + var message = arguments.length <= 1 || arguments[1] === undefined ? "Unexpected token" : arguments[1]; + + this.raise(pos != null ? pos : this.state.start, message); +};
\ No newline at end of file |