UNPKG

35.2 kBJavaScriptView Raw
1/* @flow */
2
3// A recursive descent parser operates by defining functions for all
4// syntactic elements, and recursively calling those, each function
5// advancing the input stream and returning an AST node. Precedence
6// of constructs (for example, the fact that `!x[1]` means `!(x[1])`
7// instead of `(!x)[1]` is handled by the fact that the parser
8// function that parses unary prefix operators is called first, and
9// in turn calls the function that parses `[]` subscripts — that
10// way, it'll receive the node for `x[1]` already parsed, and wraps
11// *that* in the unary operator node.
12//
13// Acorn uses an [operator precedence parser][opp] to handle binary
14// operator precedence, because it is much more compact than using
15// the technique outlined above, which uses different, nesting
16// functions to specify precedence, for all of the ten binary
17// precedence levels that JavaScript defines.
18//
19// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
20
21"use strict";
22
23var _Object$create = require("babel-runtime/core-js/object/create")["default"];
24
25var _getIterator = require("babel-runtime/core-js/get-iterator")["default"];
26
27var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
28
29var _tokenizerTypes = require("../tokenizer/types");
30
31var _index = require("./index");
32
33var _index2 = _interopRequireDefault(_index);
34
35var _utilIdentifier = require("../util/identifier");
36
37var pp = _index2["default"].prototype;
38
39// Check if property name clashes with already added.
40// Object/class getters and setters are not allowed to clash —
41// either with each other or with an init property — and in
42// strict mode, init properties are also not allowed to be repeated.
43
44pp.checkPropClash = function (prop, propHash) {
45 if (prop.computed || prop.method) return;
46
47 var key = prop.key;
48 var name = undefined;
49 switch (key.type) {
50 case "Identifier":
51 name = key.name;
52 break;
53
54 case "StringLiteral":
55 case "NumericLiteral":
56 name = String(key.value);
57 break;
58
59 default:
60 return;
61 }
62
63 if (name === "__proto__" && prop.kind === "init") {
64 if (propHash.proto) this.raise(key.start, "Redefinition of __proto__ property");
65 propHash.proto = true;
66 }
67};
68
69// ### Expression parsing
70
71// These nest, from the most general expression type at the top to
72// 'atomic', nondivisible expression types at the bottom. Most of
73// the functions will simply let the function (s) below them parse,
74// and, *if* the syntactic construct they handle is present, wrap
75// the AST node that the inner parser gave them in another node.
76
77// Parse a full expression. The optional arguments are used to
78// forbid the `in` operator (in for loops initalization expressions)
79// and provide reference for storing '=' operator inside shorthand
80// property assignment in contexts where both object expression
81// and object pattern might appear (so it's possible to raise
82// delayed syntax error at correct position).
83
84pp.parseExpression = function (noIn, refShorthandDefaultPos) {
85 var startPos = this.state.start,
86 startLoc = this.state.startLoc;
87 var expr = this.parseMaybeAssign(noIn, refShorthandDefaultPos);
88 if (this.match(_tokenizerTypes.types.comma)) {
89 var node = this.startNodeAt(startPos, startLoc);
90 node.expressions = [expr];
91 while (this.eat(_tokenizerTypes.types.comma)) {
92 node.expressions.push(this.parseMaybeAssign(noIn, refShorthandDefaultPos));
93 }
94 this.toReferencedList(node.expressions);
95 return this.finishNode(node, "SequenceExpression");
96 }
97 return expr;
98};
99
100// Parse an assignment expression. This includes applications of
101// operators like `+=`.
102
103pp.parseMaybeAssign = function (noIn, refShorthandDefaultPos, afterLeftParse) {
104 if (this.match(_tokenizerTypes.types._yield) && this.state.inGenerator) {
105 return this.parseYield();
106 }
107
108 var failOnShorthandAssign = undefined;
109 if (!refShorthandDefaultPos) {
110 refShorthandDefaultPos = { start: 0 };
111 failOnShorthandAssign = true;
112 } else {
113 failOnShorthandAssign = false;
114 }
115 var startPos = this.state.start,
116 startLoc = this.state.startLoc;
117 if (this.match(_tokenizerTypes.types.parenL) || this.match(_tokenizerTypes.types.name)) {
118 this.state.potentialArrowAt = this.state.start;
119 }
120 var left = this.parseMaybeConditional(noIn, refShorthandDefaultPos);
121 if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc);
122 if (this.state.type.isAssign) {
123 var node = this.startNodeAt(startPos, startLoc);
124 node.operator = this.state.value;
125 node.left = this.match(_tokenizerTypes.types.eq) ? this.toAssignable(left) : left;
126 refShorthandDefaultPos.start = 0; // reset because shorthand default was used correctly
127 this.checkLVal(left);
128 if (left.extra && left.extra.parenthesized) {
129 var errorMsg = undefined;
130 if (left.type === "ObjectPattern") {
131 errorMsg = "`({a}) = 0` use `({a} = 0)`";
132 } else if (left.type === "ArrayPattern") {
133 errorMsg = "`([a]) = 0` use `([a] = 0)`";
134 }
135 if (errorMsg) {
136 this.raise(left.start, "You're trying to assign to a parenthesized expression, eg. instead of " + errorMsg);
137 }
138 }
139 this.next();
140 node.right = this.parseMaybeAssign(noIn);
141 return this.finishNode(node, "AssignmentExpression");
142 } else if (failOnShorthandAssign && refShorthandDefaultPos.start) {
143 this.unexpected(refShorthandDefaultPos.start);
144 }
145 return left;
146};
147
148// Parse a ternary conditional (`?:`) operator.
149
150pp.parseMaybeConditional = function (noIn, refShorthandDefaultPos) {
151 var startPos = this.state.start,
152 startLoc = this.state.startLoc;
153 var expr = this.parseExprOps(noIn, refShorthandDefaultPos);
154 if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
155 if (this.eat(_tokenizerTypes.types.question)) {
156 var node = this.startNodeAt(startPos, startLoc);
157 node.test = expr;
158 node.consequent = this.parseMaybeAssign();
159 this.expect(_tokenizerTypes.types.colon);
160 node.alternate = this.parseMaybeAssign(noIn);
161 return this.finishNode(node, "ConditionalExpression");
162 }
163 return expr;
164};
165
166// Start the precedence parser.
167
168pp.parseExprOps = function (noIn, refShorthandDefaultPos) {
169 var startPos = this.state.start,
170 startLoc = this.state.startLoc;
171 var expr = this.parseMaybeUnary(refShorthandDefaultPos);
172 if (refShorthandDefaultPos && refShorthandDefaultPos.start) {
173 return expr;
174 } else {
175 return this.parseExprOp(expr, startPos, startLoc, -1, noIn);
176 }
177};
178
179// Parse binary operators with the operator precedence parsing
180// algorithm. `left` is the left-hand side of the operator.
181// `minPrec` provides context that allows the function to stop and
182// defer further parser to one of its callers when it encounters an
183// operator that has a lower precedence than the set it is parsing.
184
185pp.parseExprOp = function (left, leftStartPos, leftStartLoc, minPrec, noIn) {
186 var prec = this.state.type.binop;
187 if (prec != null && (!noIn || !this.match(_tokenizerTypes.types._in))) {
188 if (prec > minPrec) {
189 var node = this.startNodeAt(leftStartPos, leftStartLoc);
190 node.left = left;
191 node.operator = this.state.value;
192
193 if (node.operator === "**" && left.type === "UnaryExpression" && left.extra && !left.extra.parenthesizedArgument) {
194 this.raise(left.argument.start, "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.");
195 }
196
197 var op = this.state.type;
198 this.next();
199
200 var startPos = this.state.start;
201 var startLoc = this.state.startLoc;
202 node.right = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec, noIn);
203
204 this.finishNode(node, op === _tokenizerTypes.types.logicalOR || op === _tokenizerTypes.types.logicalAND ? "LogicalExpression" : "BinaryExpression");
205 return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
206 }
207 }
208 return left;
209};
210
211// Parse unary operators, both prefix and postfix.
212
213pp.parseMaybeUnary = function (refShorthandDefaultPos) {
214 if (this.state.type.prefix) {
215 var node = this.startNode();
216 var update = this.match(_tokenizerTypes.types.incDec);
217 node.operator = this.state.value;
218 node.prefix = true;
219 this.next();
220
221 var argType = this.state.type;
222 this.addExtra(node, "parenthesizedArgument", argType === _tokenizerTypes.types.parenL);
223 node.argument = this.parseMaybeUnary();
224
225 if (refShorthandDefaultPos && refShorthandDefaultPos.start) {
226 this.unexpected(refShorthandDefaultPos.start);
227 }
228
229 if (update) {
230 this.checkLVal(node.argument);
231 } else if (this.state.strict && node.operator === "delete" && node.argument.type === "Identifier") {
232 this.raise(node.start, "Deleting local variable in strict mode");
233 }
234
235 return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
236 }
237
238 var startPos = this.state.start,
239 startLoc = this.state.startLoc;
240 var expr = this.parseExprSubscripts(refShorthandDefaultPos);
241 if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
242 while (this.state.type.postfix && !this.canInsertSemicolon()) {
243 var node = this.startNodeAt(startPos, startLoc);
244 node.operator = this.state.value;
245 node.prefix = false;
246 node.argument = expr;
247 this.checkLVal(expr);
248 this.next();
249 expr = this.finishNode(node, "UpdateExpression");
250 }
251 return expr;
252};
253
254// Parse call, dot, and `[]`-subscript expressions.
255
256pp.parseExprSubscripts = function (refShorthandDefaultPos) {
257 var startPos = this.state.start,
258 startLoc = this.state.startLoc;
259 var potentialArrowAt = this.state.potentialArrowAt;
260 var expr = this.parseExprAtom(refShorthandDefaultPos);
261
262 if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) {
263 return expr;
264 }
265
266 if (refShorthandDefaultPos && refShorthandDefaultPos.start) {
267 return expr;
268 }
269
270 return this.parseSubscripts(expr, startPos, startLoc);
271};
272
273pp.parseSubscripts = function (base, startPos, startLoc, noCalls) {
274 for (;;) {
275 if (!noCalls && this.eat(_tokenizerTypes.types.doubleColon)) {
276 var node = this.startNodeAt(startPos, startLoc);
277 node.object = base;
278 node.callee = this.parseNoCallExpr();
279 return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls);
280 } else if (this.eat(_tokenizerTypes.types.dot)) {
281 var node = this.startNodeAt(startPos, startLoc);
282 node.object = base;
283 node.property = this.parseIdentifier(true);
284 node.computed = false;
285 base = this.finishNode(node, "MemberExpression");
286 } else if (this.eat(_tokenizerTypes.types.bracketL)) {
287 var node = this.startNodeAt(startPos, startLoc);
288 node.object = base;
289 node.property = this.parseExpression();
290 node.computed = true;
291 this.expect(_tokenizerTypes.types.bracketR);
292 base = this.finishNode(node, "MemberExpression");
293 } else if (!noCalls && this.match(_tokenizerTypes.types.parenL)) {
294 var possibleAsync = this.state.potentialArrowAt === base.start && base.type === "Identifier" && base.name === "async" && !this.canInsertSemicolon();
295 this.next();
296
297 var node = this.startNodeAt(startPos, startLoc);
298 node.callee = base;
299 node.arguments = this.parseCallExpressionArguments(_tokenizerTypes.types.parenR, this.hasPlugin("trailingFunctionCommas"), possibleAsync);
300 base = this.finishNode(node, "CallExpression");
301
302 if (possibleAsync && this.shouldParseAsyncArrow()) {
303 return this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node);
304 } else {
305 this.toReferencedList(node.arguments);
306 }
307 } else if (this.match(_tokenizerTypes.types.backQuote)) {
308 var node = this.startNodeAt(startPos, startLoc);
309 node.tag = base;
310 node.quasi = this.parseTemplate();
311 base = this.finishNode(node, "TaggedTemplateExpression");
312 } else {
313 return base;
314 }
315 }
316};
317
318pp.parseCallExpressionArguments = function (close, allowTrailingComma, possibleAsyncArrow) {
319 var innerParenStart = undefined;
320
321 var elts = [],
322 first = true;
323 while (!this.eat(close)) {
324 if (first) {
325 first = false;
326 } else {
327 this.expect(_tokenizerTypes.types.comma);
328 if (allowTrailingComma && this.eat(close)) break;
329 }
330
331 // we need to make sure that if this is an async arrow functions, that we don't allow inner parens inside the params
332 if (this.match(_tokenizerTypes.types.parenL) && !innerParenStart) {
333 innerParenStart = this.state.start;
334 }
335
336 elts.push(this.parseExprListItem());
337 }
338
339 // we found an async arrow function so let's not allow any inner parens
340 if (possibleAsyncArrow && innerParenStart && this.shouldParseAsyncArrow()) {
341 this.unexpected();
342 }
343
344 return elts;
345};
346
347pp.shouldParseAsyncArrow = function () {
348 return this.match(_tokenizerTypes.types.arrow);
349};
350
351pp.parseAsyncArrowFromCallExpression = function (node, call) {
352 if (!this.hasPlugin("asyncFunctions")) this.unexpected();
353 this.expect(_tokenizerTypes.types.arrow);
354 return this.parseArrowExpression(node, call.arguments, true);
355};
356
357// Parse a no-call expression (like argument of `new` or `::` operators).
358
359pp.parseNoCallExpr = function () {
360 var startPos = this.state.start,
361 startLoc = this.state.startLoc;
362 return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
363};
364
365// Parse an atomic expression — either a single token that is an
366// expression, an expression started by a keyword like `function` or
367// `new`, or an expression wrapped in punctuation like `()`, `[]`,
368// or `{}`.
369
370pp.parseExprAtom = function (refShorthandDefaultPos) {
371 var node = undefined,
372 canBeArrow = this.state.potentialArrowAt === this.state.start;
373 switch (this.state.type) {
374 case _tokenizerTypes.types._super:
375 if (!this.state.inMethod && !this.options.allowSuperOutsideMethod) {
376 this.raise(this.state.start, "'super' outside of function or class");
377 }
378
379 node = this.startNode();
380 this.next();
381 if (!this.match(_tokenizerTypes.types.parenL) && !this.match(_tokenizerTypes.types.bracketL) && !this.match(_tokenizerTypes.types.dot)) {
382 this.unexpected();
383 }
384 if (this.match(_tokenizerTypes.types.parenL) && this.state.inMethod !== "constructor" && !this.options.allowSuperOutsideMethod) {
385 this.raise(node.start, "super() outside of class constructor");
386 }
387 return this.finishNode(node, "Super");
388
389 case _tokenizerTypes.types._this:
390 node = this.startNode();
391 this.next();
392 return this.finishNode(node, "ThisExpression");
393
394 case _tokenizerTypes.types._yield:
395 if (this.state.inGenerator) this.unexpected();
396
397 case _tokenizerTypes.types.name:
398 node = this.startNode();
399 var allowAwait = this.hasPlugin("asyncFunctions") && this.state.value === "await" && this.state.inAsync;
400 var allowYield = this.shouldAllowYieldIdentifier();
401 var id = this.parseIdentifier(allowAwait || allowYield);
402
403 if (this.hasPlugin("asyncFunctions")) {
404 if (id.name === "await") {
405 if (this.state.inAsync || this.inModule) {
406 return this.parseAwait(node);
407 }
408 } else if (id.name === "async" && this.match(_tokenizerTypes.types._function) && !this.canInsertSemicolon()) {
409 this.next();
410 return this.parseFunction(node, false, false, true);
411 } else if (canBeArrow && id.name === "async" && this.match(_tokenizerTypes.types.name)) {
412 var params = [this.parseIdentifier()];
413 this.expect(_tokenizerTypes.types.arrow);
414 // let foo = bar => {};
415 return this.parseArrowExpression(node, params, true);
416 }
417 }
418
419 if (canBeArrow && !this.canInsertSemicolon() && this.eat(_tokenizerTypes.types.arrow)) {
420 return this.parseArrowExpression(node, [id]);
421 }
422
423 return id;
424
425 case _tokenizerTypes.types._do:
426 if (this.hasPlugin("doExpressions")) {
427 var _node = this.startNode();
428 this.next();
429 var oldInFunction = this.state.inFunction;
430 var oldLabels = this.state.labels;
431 this.state.labels = [];
432 this.state.inFunction = false;
433 _node.body = this.parseBlock(false, true);
434 this.state.inFunction = oldInFunction;
435 this.state.labels = oldLabels;
436 return this.finishNode(_node, "DoExpression");
437 }
438
439 case _tokenizerTypes.types.regexp:
440 var value = this.state.value;
441 node = this.parseLiteral(value.value, "RegExpLiteral");
442 node.pattern = value.pattern;
443 node.flags = value.flags;
444 return node;
445
446 case _tokenizerTypes.types.num:
447 return this.parseLiteral(this.state.value, "NumericLiteral");
448
449 case _tokenizerTypes.types.string:
450 return this.parseLiteral(this.state.value, "StringLiteral");
451
452 case _tokenizerTypes.types._null:
453 node = this.startNode();
454 this.next();
455 return this.finishNode(node, "NullLiteral");
456
457 case _tokenizerTypes.types._true:case _tokenizerTypes.types._false:
458 node = this.startNode();
459 node.value = this.match(_tokenizerTypes.types._true);
460 this.next();
461 return this.finishNode(node, "BooleanLiteral");
462
463 case _tokenizerTypes.types.parenL:
464 return this.parseParenAndDistinguishExpression(null, null, canBeArrow);
465
466 case _tokenizerTypes.types.bracketL:
467 node = this.startNode();
468 this.next();
469 node.elements = this.parseExprList(_tokenizerTypes.types.bracketR, true, true, refShorthandDefaultPos);
470 this.toReferencedList(node.elements);
471 return this.finishNode(node, "ArrayExpression");
472
473 case _tokenizerTypes.types.braceL:
474 return this.parseObj(false, refShorthandDefaultPos);
475
476 case _tokenizerTypes.types._function:
477 node = this.startNode();
478 this.next();
479 return this.parseFunction(node, false);
480
481 case _tokenizerTypes.types.at:
482 this.parseDecorators();
483
484 case _tokenizerTypes.types._class:
485 node = this.startNode();
486 this.takeDecorators(node);
487 return this.parseClass(node, false);
488
489 case _tokenizerTypes.types._new:
490 return this.parseNew();
491
492 case _tokenizerTypes.types.backQuote:
493 return this.parseTemplate();
494
495 case _tokenizerTypes.types.doubleColon:
496 node = this.startNode();
497 this.next();
498 node.object = null;
499 var callee = node.callee = this.parseNoCallExpr();
500 if (callee.type === "MemberExpression") {
501 return this.finishNode(node, "BindExpression");
502 } else {
503 this.raise(callee.start, "Binding should be performed on object property.");
504 }
505
506 default:
507 this.unexpected();
508 }
509};
510
511pp.parseLiteral = function (value, type) {
512 var node = this.startNode();
513 this.addExtra(node, "rawValue", value);
514 this.addExtra(node, "raw", this.input.slice(this.state.start, this.state.end));
515 node.value = value;
516 this.next();
517 return this.finishNode(node, type);
518};
519
520pp.parseParenExpression = function () {
521 this.expect(_tokenizerTypes.types.parenL);
522 var val = this.parseExpression();
523 this.expect(_tokenizerTypes.types.parenR);
524 return val;
525};
526
527pp.parseParenAndDistinguishExpression = function (startPos, startLoc, canBeArrow, isAsync) {
528 startPos = startPos || this.state.start;
529 startLoc = startLoc || this.state.startLoc;
530 var val = undefined;
531 this.next();
532
533 var innerStartPos = this.state.start,
534 innerStartLoc = this.state.startLoc;
535 var exprList = [],
536 first = true;
537 var refShorthandDefaultPos = { start: 0 },
538 spreadStart = undefined,
539 innerParenStart = undefined,
540 optionalCommaStart = undefined;
541 while (!this.match(_tokenizerTypes.types.parenR)) {
542 if (first) {
543 first = false;
544 } else {
545 this.expect(_tokenizerTypes.types.comma);
546 if (this.match(_tokenizerTypes.types.parenR) && this.hasPlugin("trailingFunctionCommas")) {
547 optionalCommaStart = this.state.start;
548 break;
549 }
550 }
551
552 if (this.match(_tokenizerTypes.types.ellipsis)) {
553 var spreadNodeStartPos = this.state.start,
554 spreadNodeStartLoc = this.state.startLoc;
555 spreadStart = this.state.start;
556 exprList.push(this.parseParenItem(this.parseRest(), spreadNodeStartLoc, spreadNodeStartPos));
557 break;
558 } else {
559 if (this.match(_tokenizerTypes.types.parenL) && !innerParenStart) {
560 innerParenStart = this.state.start;
561 }
562 exprList.push(this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem));
563 }
564 }
565
566 var innerEndPos = this.state.start;
567 var innerEndLoc = this.state.startLoc;
568 this.expect(_tokenizerTypes.types.parenR);
569
570 if (canBeArrow && !this.canInsertSemicolon() && this.eat(_tokenizerTypes.types.arrow)) {
571 if (innerParenStart) this.unexpected(innerParenStart);
572 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, isAsync);
573 }
574
575 if (!exprList.length) {
576 if (isAsync) {
577 return;
578 } else {
579 this.unexpected(this.state.lastTokStart);
580 }
581 }
582 if (optionalCommaStart) this.unexpected(optionalCommaStart);
583 if (spreadStart) this.unexpected(spreadStart);
584 if (refShorthandDefaultPos.start) this.unexpected(refShorthandDefaultPos.start);
585
586 if (exprList.length > 1) {
587 val = this.startNodeAt(innerStartPos, innerStartLoc);
588 val.expressions = exprList;
589 this.toReferencedList(val.expressions);
590 this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
591 } else {
592 val = exprList[0];
593 }
594 this.addExtra(val, "parenthesized", true);
595 return val;
596};
597
598pp.parseParenItem = function (node) {
599 return node;
600};
601
602// New's precedence is slightly tricky. It must allow its argument
603// to be a `[]` or dot subscript expression, but not a call — at
604// least, not without wrapping it in parentheses. Thus, it uses the
605
606pp.parseNew = function () {
607 var node = this.startNode();
608 var meta = this.parseIdentifier(true);
609
610 if (this.eat(_tokenizerTypes.types.dot)) {
611 node.meta = meta;
612 node.property = this.parseIdentifier(true);
613
614 if (node.property.name !== "target") {
615 this.raise(node.property.start, "The only valid meta property for new is new.target");
616 }
617
618 return this.finishNode(node, "MetaProperty");
619 }
620
621 node.callee = this.parseNoCallExpr();
622
623 if (this.eat(_tokenizerTypes.types.parenL)) {
624 node.arguments = this.parseExprList(_tokenizerTypes.types.parenR, this.hasPlugin("trailingFunctionCommas"));
625 this.toReferencedList(node.arguments);
626 } else {
627 node.arguments = [];
628 }
629
630 return this.finishNode(node, "NewExpression");
631};
632
633// Parse template expression.
634
635pp.parseTemplateElement = function () {
636 var elem = this.startNode();
637 elem.value = {
638 raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"),
639 cooked: this.state.value
640 };
641 this.next();
642 elem.tail = this.match(_tokenizerTypes.types.backQuote);
643 return this.finishNode(elem, "TemplateElement");
644};
645
646pp.parseTemplate = function () {
647 var node = this.startNode();
648 this.next();
649 node.expressions = [];
650 var curElt = this.parseTemplateElement();
651 node.quasis = [curElt];
652 while (!curElt.tail) {
653 this.expect(_tokenizerTypes.types.dollarBraceL);
654 node.expressions.push(this.parseExpression());
655 this.expect(_tokenizerTypes.types.braceR);
656 node.quasis.push(curElt = this.parseTemplateElement());
657 }
658 this.next();
659 return this.finishNode(node, "TemplateLiteral");
660};
661
662// Parse an object literal or binding pattern.
663
664pp.parseObj = function (isPattern, refShorthandDefaultPos) {
665 var decorators = [];
666 var propHash = _Object$create(null);
667 var first = true;
668 var node = this.startNode();
669
670 node.properties = [];
671 this.next();
672
673 while (!this.eat(_tokenizerTypes.types.braceR)) {
674 if (first) {
675 first = false;
676 } else {
677 this.expect(_tokenizerTypes.types.comma);
678 if (this.eat(_tokenizerTypes.types.braceR)) break;
679 }
680
681 while (this.match(_tokenizerTypes.types.at)) {
682 decorators.push(this.parseDecorator());
683 }
684
685 var prop = this.startNode(),
686 isGenerator = false,
687 isAsync = false,
688 startPos = undefined,
689 startLoc = undefined;
690 if (decorators.length) {
691 prop.decorators = decorators;
692 decorators = [];
693 }
694
695 if (this.hasPlugin("objectRestSpread") && this.match(_tokenizerTypes.types.ellipsis)) {
696 prop = this.parseSpread();
697 prop.type = isPattern ? "RestProperty" : "SpreadProperty";
698 node.properties.push(prop);
699 continue;
700 }
701
702 prop.method = false;
703 prop.shorthand = false;
704
705 if (isPattern || refShorthandDefaultPos) {
706 startPos = this.state.start;
707 startLoc = this.state.startLoc;
708 }
709
710 if (!isPattern) {
711 isGenerator = this.eat(_tokenizerTypes.types.star);
712 }
713
714 if (!isPattern && this.hasPlugin("asyncFunctions") && this.isContextual("async")) {
715 if (isGenerator) this.unexpected();
716
717 var asyncId = this.parseIdentifier();
718 if (this.match(_tokenizerTypes.types.colon) || this.match(_tokenizerTypes.types.parenL) || this.match(_tokenizerTypes.types.braceR)) {
719 prop.key = asyncId;
720 } else {
721 isAsync = true;
722 this.parsePropertyName(prop);
723 }
724 } else {
725 this.parsePropertyName(prop);
726 }
727
728 this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos);
729 this.checkPropClash(prop, propHash);
730
731 if (prop.shorthand) {
732 this.addExtra(prop, "shorthand", true);
733 }
734
735 node.properties.push(prop);
736 }
737
738 if (decorators.length) {
739 this.raise(this.state.start, "You have trailing decorators with no property");
740 }
741
742 return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression");
743};
744
745pp.parseObjPropValue = function (prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos) {
746 if (isAsync || isGenerator || this.match(_tokenizerTypes.types.parenL)) {
747 if (isPattern) this.unexpected();
748 prop.kind = "method";
749 prop.method = true;
750 this.parseMethod(prop, isGenerator, isAsync);
751 return this.finishNode(prop, "ObjectMethod");
752 }
753
754 if (this.eat(_tokenizerTypes.types.colon)) {
755 prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssign(false, refShorthandDefaultPos);
756 return this.finishNode(prop, "ObjectProperty");
757 }
758
759 if (!prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && !this.match(_tokenizerTypes.types.comma) && !this.match(_tokenizerTypes.types.braceR)) {
760 if (isGenerator || isAsync || isPattern) this.unexpected();
761 prop.kind = prop.key.name;
762 this.parsePropertyName(prop);
763 this.parseMethod(prop, false);
764 var paramCount = prop.kind === "get" ? 0 : 1;
765 if (prop.params.length !== paramCount) {
766 var start = prop.start;
767 if (prop.kind === "get") {
768 this.raise(start, "getter should have no params");
769 } else {
770 this.raise(start, "setter should have exactly one param");
771 }
772 }
773 return this.finishNode(prop, "ObjectMethod");
774 }
775
776 if (!prop.computed && prop.key.type === "Identifier") {
777 if (isPattern) {
778 var illegalBinding = this.isKeyword(prop.key.name);
779 if (!illegalBinding && this.state.strict) {
780 illegalBinding = _utilIdentifier.reservedWords.strictBind(prop.key.name) || _utilIdentifier.reservedWords.strict(prop.key.name);
781 }
782 if (illegalBinding) {
783 this.raise(prop.key.start, "Binding " + prop.key.name);
784 }
785 prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
786 } else if (this.match(_tokenizerTypes.types.eq) && refShorthandDefaultPos) {
787 if (!refShorthandDefaultPos.start) {
788 refShorthandDefaultPos.start = this.state.start;
789 }
790 prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
791 } else {
792 prop.value = prop.key.__clone();
793 }
794 prop.shorthand = true;
795 return this.finishNode(prop, "ObjectProperty");
796 }
797
798 this.unexpected();
799};
800
801pp.parsePropertyName = function (prop) {
802 if (this.eat(_tokenizerTypes.types.bracketL)) {
803 prop.computed = true;
804 prop.key = this.parseMaybeAssign();
805 this.expect(_tokenizerTypes.types.bracketR);
806 return prop.key;
807 } else {
808 prop.computed = false;
809 return prop.key = this.match(_tokenizerTypes.types.num) || this.match(_tokenizerTypes.types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
810 }
811};
812
813// Initialize empty function node.
814
815pp.initFunction = function (node, isAsync) {
816 node.id = null;
817 node.generator = false;
818 node.expression = false;
819 if (this.hasPlugin("asyncFunctions")) {
820 node.async = !!isAsync;
821 }
822};
823
824// Parse object or class method.
825
826pp.parseMethod = function (node, isGenerator, isAsync) {
827 var oldInMethod = this.state.inMethod;
828 this.state.inMethod = node.kind || true;
829 this.initFunction(node, isAsync);
830 this.expect(_tokenizerTypes.types.parenL);
831 node.params = this.parseBindingList(_tokenizerTypes.types.parenR, false, this.hasPlugin("trailingFunctionCommas"));
832 node.generator = isGenerator;
833 this.parseFunctionBody(node);
834 this.state.inMethod = oldInMethod;
835 return node;
836};
837
838// Parse arrow function expression with given parameters.
839
840pp.parseArrowExpression = function (node, params, isAsync) {
841 this.initFunction(node, isAsync);
842 node.params = this.toAssignableList(params, true);
843 this.parseFunctionBody(node, true);
844 return this.finishNode(node, "ArrowFunctionExpression");
845};
846
847// Parse function body and check parameters.
848
849pp.parseFunctionBody = function (node, allowExpression) {
850 var isExpression = allowExpression && !this.match(_tokenizerTypes.types.braceL);
851
852 var oldInAsync = this.state.inAsync;
853 this.state.inAsync = node.async;
854 if (isExpression) {
855 node.body = this.parseMaybeAssign();
856 node.expression = true;
857 } else {
858 // Start a new scope with regard to labels and the `inFunction`
859 // flag (restore them to their old value afterwards).
860 var oldInFunc = this.state.inFunction,
861 oldInGen = this.state.inGenerator,
862 oldLabels = this.state.labels;
863 this.state.inFunction = true;this.state.inGenerator = node.generator;this.state.labels = [];
864 node.body = this.parseBlock(true);
865 node.expression = false;
866 this.state.inFunction = oldInFunc;this.state.inGenerator = oldInGen;this.state.labels = oldLabels;
867 }
868 this.state.inAsync = oldInAsync;
869
870 // If this is a strict mode function, verify that argument names
871 // are not repeated, and it does not try to bind the words `eval`
872 // or `arguments`.
873 var checkLVal = this.state.strict;
874 var checkLValStrict = false;
875 var isStrict = false;
876
877 // arrow function
878 if (allowExpression) checkLVal = true;
879
880 // normal function
881 if (!isExpression && node.body.directives.length) {
882 for (var _iterator = (node.body.directives /*: Array<Object>*/), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _getIterator(_iterator);;) {
883 var _ref;
884
885 if (_isArray) {
886 if (_i >= _iterator.length) break;
887 _ref = _iterator[_i++];
888 } else {
889 _i = _iterator.next();
890 if (_i.done) break;
891 _ref = _i.value;
892 }
893
894 var directive = _ref;
895
896 if (directive.value.value === "use strict") {
897 isStrict = true;
898 checkLVal = true;
899 checkLValStrict = true;
900 break;
901 }
902 }
903 }
904
905 //
906 if (isStrict && node.id && node.id.type === "Identifier" && node.id.name === "yield") {
907 this.raise(node.id.start, "Binding yield in strict mode");
908 }
909
910 if (checkLVal) {
911 var nameHash = _Object$create(null);
912 var oldStrict = this.state.strict;
913 if (checkLValStrict) this.state.strict = true;
914 if (node.id) {
915 this.checkLVal(node.id, true);
916 }
917 for (var _iterator2 = (node.params /*: Array<Object>*/), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _getIterator(_iterator2);;) {
918 var _ref2;
919
920 if (_isArray2) {
921 if (_i2 >= _iterator2.length) break;
922 _ref2 = _iterator2[_i2++];
923 } else {
924 _i2 = _iterator2.next();
925 if (_i2.done) break;
926 _ref2 = _i2.value;
927 }
928
929 var param = _ref2;
930
931 this.checkLVal(param, true, nameHash);
932 }
933 this.state.strict = oldStrict;
934 }
935};
936
937// Parses a comma-separated list of expressions, and returns them as
938// an array. `close` is the token type that ends the list, and
939// `allowEmpty` can be turned on to allow subsequent commas with
940// nothing in between them to be parsed as `null` (which is needed
941// for array literals).
942
943pp.parseExprList = function (close, allowTrailingComma, allowEmpty, refShorthandDefaultPos) {
944 var elts = [],
945 first = true;
946 while (!this.eat(close)) {
947 if (first) {
948 first = false;
949 } else {
950 this.expect(_tokenizerTypes.types.comma);
951 if (allowTrailingComma && this.eat(close)) break;
952 }
953
954 elts.push(this.parseExprListItem(allowEmpty, refShorthandDefaultPos));
955 }
956 return elts;
957};
958
959pp.parseExprListItem = function (allowEmpty, refShorthandDefaultPos) {
960 var elt = undefined;
961 if (allowEmpty && this.match(_tokenizerTypes.types.comma)) {
962 elt = null;
963 } else if (this.match(_tokenizerTypes.types.ellipsis)) {
964 elt = this.parseSpread(refShorthandDefaultPos);
965 } else {
966 elt = this.parseMaybeAssign(false, refShorthandDefaultPos);
967 }
968 return elt;
969};
970
971// Parse the next token as an identifier. If `liberal` is true (used
972// when parsing properties), it will also convert keywords into
973// identifiers.
974
975pp.parseIdentifier = function (liberal) {
976 var node = this.startNode();
977
978 if (this.match(_tokenizerTypes.types.name)) {
979 if (!liberal && this.state.strict && _utilIdentifier.reservedWords.strict(this.state.value)) {
980 this.raise(this.state.start, "The keyword '" + this.state.value + "' is reserved");
981 }
982
983 node.name = this.state.value;
984 } else if (liberal && this.state.type.keyword) {
985 node.name = this.state.type.keyword;
986 } else {
987 this.unexpected();
988 }
989
990 if (!liberal && node.name === "await" && this.state.inAsync) {
991 this.raise(node.start, "invalid use of await inside of an async function");
992 }
993
994 this.next();
995 return this.finishNode(node, "Identifier");
996};
997
998// Parses await expression inside async function.
999
1000pp.parseAwait = function (node) {
1001 if (!this.state.inAsync) {
1002 this.unexpected();
1003 }
1004 if (this.isLineTerminator()) {
1005 this.unexpected();
1006 }
1007 node.all = this.eat(_tokenizerTypes.types.star);
1008 node.argument = this.parseMaybeUnary();
1009 return this.finishNode(node, "AwaitExpression");
1010};
1011
1012// Parses yield expression inside generator.
1013
1014pp.parseYield = function () {
1015 var node = this.startNode();
1016 this.next();
1017 if (this.match(_tokenizerTypes.types.semi) || this.canInsertSemicolon() || !this.match(_tokenizerTypes.types.star) && !this.state.type.startsExpr) {
1018 node.delegate = false;
1019 node.argument = null;
1020 } else {
1021 node.delegate = this.eat(_tokenizerTypes.types.star);
1022 node.argument = this.parseMaybeAssign();
1023 }
1024 return this.finishNode(node, "YieldExpression");
1025};
\No newline at end of file