Debian Codegraph @

benchmark/babel-core/real-case-preset-env-flow/babel-parser-expression.txt

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 import {
22 tokenCanStartExpression,
23 tokenIsAssignment,
24 tokenIsIdentifier,
25 tokenIsKeyword,
26 tokenIsKeywordOrIdentifier,
27 tokenIsOperator,
28 tokenIsPostfix,
29 tokenIsPrefix,
30 tokenIsRightAssociative,
31 tokenLabelName,
32 tokenOperatorPrecedence,
33 tt,
34 type TokenType,
35 } from "../tokenizer/types";
36 import * as N from "../types";
37 import LValParser from "./lval";
38 import {
39 isKeyword,
40 isReservedWord,
41 isStrictReservedWord,
42 isStrictBindReservedWord,
43 isIdentifierStart,
44 canBeReservedWord,
45 } from "../util/identifier";
46 import { Position } from "../util/location";
47 import * as charCodes from "charcodes";
48 import {
49 BIND_OUTSIDE,
50 BIND_VAR,
51 SCOPE_ARROW,
52 SCOPE_CLASS,
53 SCOPE_DIRECT_SUPER,
54 SCOPE_FUNCTION,
55 SCOPE_SUPER,
56 } from "../util/scopeflags";
57 import { ExpressionErrors } from "./util";
58 import {
59 PARAM_AWAIT,
60 PARAM_IN,
61 PARAM_RETURN,
62 functionFlags,
63 } from "../util/production-parameter";
64 import {
65 newArrowHeadScope,
66 newAsyncArrowScope,
67 newExpressionScope,
68 } from "../util/expression-scope";
69 import { Errors, SourceTypeModuleErrors } from "./error";
70 import type { ParsingError } from "./error";
71 import { setInnerComments } from "./comments";
72 import { cloneIdentifier } from "./node";
73
74 /*::
75 import type { SourceType } from "../options";
76 */
77
78 const invalidHackPipeBodies = new Map([
79 ["ArrowFunctionExpression", "arrow function"],
80 ["AssignmentExpression", "assignment"],
81 ["ConditionalExpression", "conditional"],
82 ["YieldExpression", "yield"],
83 ]);
84
85 export default class ExpressionParser extends LValParser {
86 // Forward-declaration: defined in statement.js
87 /*::
88 +parseBlock: (
89 allowDirectives?: boolean,
90 createNewLexicalScope?: boolean,
91 afterBlockParse?: (hasStrictModeDirective: boolean) => void,
92 ) => N.BlockStatement;
93 +parseClass: (
94 node: N.Class,
95 isStatement: boolean,
96 optionalId?: boolean,
97 ) => N.Class;
98 +parseDecorators: (allowExport?: boolean) => void;
99 +parseFunction: <T: N.NormalFunction>(
100 node: T,
101 statement?: number,
102 allowExpressionBody?: boolean,
103 isAsync?: boolean,
104 ) => T;
105 +parseFunctionParams: (node: N.Function, allowModifiers?: boolean) => void;
106 +takeDecorators: (node: N.HasDecorators) => void;
107 +parseBlockOrModuleBlockBody: (
108 body: N.Statement[],
109 directives: ?(N.Directive[]),
110 topLevel: boolean,
111 end: TokenType,
112 afterBlockParse?: (hasStrictModeDirective: boolean) => void
113 ) => void
114 +parseProgram: (
115 program: N.Program, end: TokenType, sourceType?: SourceType
116 ) => N.Program
117 */
118
119 // For object literal, check if property __proto__ has been used more than once.
120 // If the expression is a destructuring assignment, then __proto__ may appear
121 // multiple times. Otherwise, __proto__ is a duplicated key.
122
123 // For record expression, check if property __proto__ exists
124
125 checkProto(
126 prop: N.ObjectMember | N.SpreadElement,
127 isRecord: boolean,
128 protoRef: { used: boolean },
129 refExpressionErrors: ?ExpressionErrors
130 ): void {
131 if (
132 prop.type === "SpreadElement" ||
133 this.isObjectMethod(prop) ||
134 prop.computed ||
135 // $FlowIgnore
136 prop.shorthand
137 ) {
138 return;
139 }
140
141 const key = prop.key;
142 // It is either an Identifier or a String/NumericLiteral
143 const name = key.type === "Identifier" ? key.name : key.value;
144
145 if (name === "__proto__") {
146 if (isRecord) {
147 this.raise(key.start, Errors.RecordNoProto);
148 return;
149 }
150 if (protoRef.used) {
151 if (refExpressionErrors) {
152 // Store the first redefinition's position, otherwise ignore because
153 // we are parsing ambiguous pattern
154 if (refExpressionErrors.doubleProto === -1) {
155 refExpressionErrors.doubleProto = key.start;
156 }
157 } else {
158 this.raise(key.start, Errors.DuplicateProto);
159 }
160 }
161
162 protoRef.used = true;
163 }
164 }
165
166 shouldExitDescending(expr: N.Expression, potentialArrowAt: number): boolean {
167 return (
168 expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt
169 );
170 }
171
172 // Convenience method to parse an Expression only
173 getExpression(): N.Expression & N.ParserOutput {
174 this.enterInitialScopes();
175 this.nextToken();
176 const expr = this.parseExpression();
177 if (!this.match(tt.eof)) {
178 this.unexpected();
179 }
180 // Unlike parseTopLevel, we need to drain remaining commentStacks
181 // because the top level node is _not_ Program.
182 this.finalizeRemainingComments();
183 expr.comments = this.state.comments;
184 expr.errors = this.state.errors;
185 if (this.options.tokens) {
186 expr.tokens = this.tokens;
187 }
188 return expr;
189 }
190
191 // ### Expression parsing
192
193 // These nest, from the most general expression type at the top to
194 // 'atomic', nondivisible expression types at the bottom. Most of
195 // the functions will simply let the function (s) below them parse,
196 // and, *if* the syntactic construct they handle is present, wrap
197 // the AST node that the inner parser gave them in another node.
198
199 // Parse a full expression.
200 // - `disallowIn`
201 // is used to forbid the `in` operator (in for loops initialization expressions)
202 // When `disallowIn` is true, the production parameter [In] is not present.
203
204 // - `refExpressionErrors `
205 // provides reference for storing '=' operator inside shorthand
206 // property assignment in contexts where both object expression
207 // and object pattern might appear (so it's possible to raise
208 // delayed syntax error at correct position).
209
210 parseExpression(
211 disallowIn?: boolean,
212 refExpressionErrors?: ExpressionErrors
213 ): N.Expression {
214 if (disallowIn) {
215 return this.disallowInAnd(() =>
216 this.parseExpressionBase(refExpressionErrors)
217 );
218 }
219 return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors));
220 }
221
222 // https://tc39.es/ecma262/#prod-Expression
223 parseExpressionBase(refExpressionErrors?: ExpressionErrors): N.Expression {
224 const startPos = this.state.start;
225 const startLoc = this.state.startLoc;
226 const expr = this.parseMaybeAssign(refExpressionErrors);
227 if (this.match(tt.comma)) {
228 const node = this.startNodeAt(startPos, startLoc);
229 node.expressions = [expr];
230 while (this.eat(tt.comma)) {
231 node.expressions.push(this.parseMaybeAssign(refExpressionErrors));
232 }
233 this.toReferencedList(node.expressions);
234 return this.finishNode(node, "SequenceExpression");
235 }
236 return expr;
237 }
238
239 // Set [~In] parameter for assignment expression
240 parseMaybeAssignDisallowIn(
241 refExpressionErrors?: ?ExpressionErrors,
242 afterLeftParse?: Function
243 ) {
244 return this.disallowInAnd(() =>
245 this.parseMaybeAssign(refExpressionErrors, afterLeftParse)
246 );
247 }
248
249 // Set [+In] parameter for assignment expression
250 parseMaybeAssignAllowIn(
251 refExpressionErrors?: ?ExpressionErrors,
252 afterLeftParse?: Function
253 ) {
254 return this.allowInAnd(() =>
255 this.parseMaybeAssign(refExpressionErrors, afterLeftParse)
256 );
257 }
258
259 // This method is only used by
260 // the typescript and flow plugins.
261 setOptionalParametersError(
262 refExpressionErrors: ExpressionErrors,
263 resultError?: ParsingError
264 ) {
265 refExpressionErrors.optionalParameters =
266 resultError?.pos ?? this.state.start;
267 }
268
269 // Parse an assignment expression. This includes applications of
270 // operators like `+=`.
271 // https://tc39.es/ecma262/#prod-AssignmentExpression
272 parseMaybeAssign(
273 refExpressionErrors?: ?ExpressionErrors,
274 afterLeftParse?: Function
275 ): N.Expression {
276 const startPos = this.state.start;
277 const startLoc = this.state.startLoc;
278 if (this.isContextual(tt._yield)) {
279 if (this.prodParam.hasYield) {
280 let left = this.parseYield();
281 if (afterLeftParse) {
282 left = afterLeftParse.call(this, left, startPos, startLoc);
283 }
284 return left;
285 }
286 }
287
288 let ownExpressionErrors;
289 if (refExpressionErrors) {
290 ownExpressionErrors = false;
291 } else {
292 refExpressionErrors = new ExpressionErrors();
293 ownExpressionErrors = true;
294 }
295 const { type } = this.state;
296
297 if (type === tt.parenL || tokenIsIdentifier(type)) {
298 this.state.potentialArrowAt = this.state.start;
299 }
300
301 let left = this.parseMaybeConditional(refExpressionErrors);
302 if (afterLeftParse) {
303 left = afterLeftParse.call(this, left, startPos, startLoc);
304 }
305 if (tokenIsAssignment(this.state.type)) {
306 const node = this.startNodeAt(startPos, startLoc);
307 const operator = this.state.value;
308 node.operator = operator;
309
310 if (this.match(tt.eq)) {
311 node.left = this.toAssignable(left, /* isLHS */ true);
312 refExpressionErrors.doubleProto = -1; // reset because double __proto__ is valid in assignment expression
313 } else {
314 node.left = left;
315 }
316
317 if (refExpressionErrors.shorthandAssign >= node.left.start) {
318 refExpressionErrors.shorthandAssign = -1; // reset because shorthand default was used correctly
319 }
320
321 this.checkLVal(left, "assignment expression");
322
323 this.next();
324 node.right = this.parseMaybeAssign();
325 return this.finishNode(node, "AssignmentExpression");
326 } else if (ownExpressionErrors) {
327 this.checkExpressionErrors(refExpressionErrors, true);
328 }
329
330 return left;
331 }
332
333 // Parse a ternary conditional (`?:`) operator.
334 // https://tc39.es/ecma262/#prod-ConditionalExpression
335
336 parseMaybeConditional(refExpressionErrors: ExpressionErrors): N.Expression {
337 const startPos = this.state.start;
338 const startLoc = this.state.startLoc;
339 const potentialArrowAt = this.state.potentialArrowAt;
340 const expr = this.parseExprOps(refExpressionErrors);
341
342 if (this.shouldExitDescending(expr, potentialArrowAt)) {
343 return expr;
344 }
345
346 return this.parseConditional(expr, startPos, startLoc, refExpressionErrors);
347 }
348
349 parseConditional(
350 expr: N.Expression,
351 startPos: number,
352 startLoc: Position,
353 // eslint-disable-next-line no-unused-vars
354 refExpressionErrors?: ?ExpressionErrors
355 ): N.Expression {
356 if (this.eat(tt.question)) {
357 const node = this.startNodeAt(startPos, startLoc);
358 node.test = expr;
359 node.consequent = this.parseMaybeAssignAllowIn();
360 this.expect(tt.colon);
361 node.alternate = this.parseMaybeAssign();
362 return this.finishNode(node, "ConditionalExpression");
363 }
364 return expr;
365 }
366
367 parseMaybeUnaryOrPrivate(
368 refExpressionErrors?: ExpressionErrors
369 ): N.Expression | N.PrivateName {
370 return this.match(tt.privateName)
371 ? this.parsePrivateName()
372 : this.parseMaybeUnary(refExpressionErrors);
373 }
374
375 // Start the precedence parser.
376 // https://tc39.es/ecma262/#prod-ShortCircuitExpression
377
378 parseExprOps(refExpressionErrors: ExpressionErrors): N.Expression {
379 const startPos = this.state.start;
380 const startLoc = this.state.startLoc;
381 const potentialArrowAt = this.state.potentialArrowAt;
382 const expr = this.parseMaybeUnaryOrPrivate(refExpressionErrors);
383
384 if (this.shouldExitDescending(expr, potentialArrowAt)) {
385 return expr;
386 }
387
388 return this.parseExprOp(expr, startPos, startLoc, -1);
389 }
390
391 // Parse binary operators with the operator precedence parsing
392 // algorithm. `left` is the left-hand side of the operator.
393 // `minPrec` provides context that allows the function to stop and
394 // defer further parser to one of its callers when it encounters an
395 // operator that has a lower precedence than the set it is parsing.
396
397 parseExprOp(
398 left: N.Expression | N.PrivateName,
399 leftStartPos: number,
400 leftStartLoc: Position,
401 minPrec: number
402 ): N.Expression {
403 if (this.isPrivateName(left)) {
404 // https://tc39.es/proposal-private-fields-in-in
405 // RelationalExpression [In, Yield, Await]
406 // [+In] PrivateIdentifier in ShiftExpression[?Yield, ?Await]
407
408 const value = this.getPrivateNameSV(left);
409 const { start } = left;
410
411 if (
412 minPrec >= tokenOperatorPrecedence(tt._in) ||
413 !this.prodParam.hasIn ||
414 !this.match(tt._in)
415 ) {
416 this.raise(start, Errors.PrivateInExpectedIn, value);
417 }
418
419 this.classScope.usePrivateName(value, start);
420 }
421
422 const op = this.state.type;
423 if (tokenIsOperator(op) && (this.prodParam.hasIn || !this.match(tt._in))) {
424 let prec = tokenOperatorPrecedence(op);
425 if (prec > minPrec) {
426 if (op === tt.pipeline) {
427 this.expectPlugin("pipelineOperator");
428 if (this.state.inFSharpPipelineDirectBody) {
429 return left;
430 }
431 this.checkPipelineAtInfixOperator(left, leftStartPos);
432 }
433 const node = this.startNodeAt(leftStartPos, leftStartLoc);
434 node.left = left;
435 node.operator = this.state.value;
436
437 const logical = op === tt.logicalOR || op === tt.logicalAND;
438 const coalesce = op === tt.nullishCoalescing;
439
440 if (coalesce) {
441 // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
442 // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
443 prec = tokenOperatorPrecedence(tt.logicalAND);
444 }
445
446 this.next();
447
448 if (
449 op === tt.pipeline &&
450 this.getPluginOption("pipelineOperator", "proposal") === "minimal"
451 ) {
452 if (this.state.type === tt._await && this.prodParam.hasAwait) {
453 throw this.raise(
454 this.state.start,
455 Errors.UnexpectedAwaitAfterPipelineBody
456 );
457 }
458 }
459
460 node.right = this.parseExprOpRightExpr(op, prec);
461 this.finishNode(
462 node,
463 logical || coalesce ? "LogicalExpression" : "BinaryExpression"
464 );
465 /* this check is for all ?? operators
466 * a ?? b && c for this example
467 * when op is coalesce and nextOp is logical (&&), throw at the pos of nextOp that it can not be mixed.
468 * Symmetrically it also throws when op is logical and nextOp is coalesce
469 */
470 const nextOp = this.state.type;
471 if (
472 (coalesce && (nextOp === tt.logicalOR || nextOp === tt.logicalAND)) ||
473 (logical && nextOp === tt.nullishCoalescing)
474 ) {
475 throw this.raise(this.state.start, Errors.MixingCoalesceWithLogical);
476 }
477
478 return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
479 }
480 }
481 return left;
482 }
483
484 // Helper function for `parseExprOp`. Parse the right-hand side of binary-
485 // operator expressions, then apply any operator-specific functions.
486
487 parseExprOpRightExpr(op: TokenType, prec: number): N.Expression {
488 const startPos = this.state.start;
489 const startLoc = this.state.startLoc;
490 switch (op) {
491 case tt.pipeline:
492 switch (this.getPluginOption("pipelineOperator", "proposal")) {
493 case "hack":
494 return this.withTopicBindingContext(() => {
495 return this.parseHackPipeBody();
496 });
497
498 case "smart":
499 return this.withTopicBindingContext(() => {
500 if (this.prodParam.hasYield && this.isContextual(tt._yield)) {
501 throw this.raise(
502 this.state.start,
503 Errors.PipeBodyIsTighter,
504 this.state.value
505 );
506 }
507 return this.parseSmartPipelineBodyInStyle(
508 this.parseExprOpBaseRightExpr(op, prec),
509 startPos,
510 startLoc
511 );
512 });
513
514 case "fsharp":
515 return this.withSoloAwaitPermittingContext(() => {
516 return this.parseFSharpPipelineBody(prec);
517 });
518 }
519
520 // Falls through.
521 default:
522 return this.parseExprOpBaseRightExpr(op, prec);
523 }
524 }
525
526 // Helper function for `parseExprOpRightExpr`. Parse the right-hand side of
527 // binary-operator expressions without applying any operator-specific functions.
528
529 parseExprOpBaseRightExpr(op: TokenType, prec: number): N.Expression {
530 const startPos = this.state.start;
531 const startLoc = this.state.startLoc;
532
533 return this.parseExprOp(
534 this.parseMaybeUnaryOrPrivate(),
535 startPos,
536 startLoc,
537 tokenIsRightAssociative(op) ? prec - 1 : prec
538 );
539 }
540
541 parseHackPipeBody(): N.Expression {
542 const { start } = this.state;
543
544 const body = this.parseMaybeAssign();
545
546 // TODO: Check how to handle type casts in Flow and TS once they are supported
547 if (invalidHackPipeBodies.has(body.type) && !body.extra?.parenthesized) {
548 this.raise(
549 start,
550 Errors.PipeUnparenthesizedBody,
551 invalidHackPipeBodies.get(body.type)
552 );
553 }
554 if (!this.topicReferenceWasUsedInCurrentContext()) {
555 // A Hack pipe body must use the topic reference at least once.
556 this.raise(start, Errors.PipeTopicUnused);
557 }
558
559 return body;
560 }
561
562 checkExponentialAfterUnary(node: N.AwaitExpression | N.UnaryExpression) {
563 if (this.match(tt.exponent)) {
564 this.raise(
565 node.argument.start,
566 Errors.UnexpectedTokenUnaryExponentiation
567 );
568 }
569 }
570
571 // Parse unary operators, both prefix and postfix.
572 // https://tc39.es/ecma262/#prod-UnaryExpression
573 parseMaybeUnary(
574 refExpressionErrors: ?ExpressionErrors,
575 sawUnary?: boolean
576 ): N.Expression {
577 const startPos = this.state.start;
578 const startLoc = this.state.startLoc;
579 const isAwait = this.isContextual(tt._await);
580
581 if (isAwait && this.isAwaitAllowed()) {
582 this.next();
583 const expr = this.parseAwait(startPos, startLoc);
584 if (!sawUnary) this.checkExponentialAfterUnary(expr);
585 return expr;
586 }
587 const update = this.match(tt.incDec);
588 const node = this.startNode();
589 if (tokenIsPrefix(this.state.type)) {
590 node.operator = this.state.value;
591 node.prefix = true;
592
593 if (this.match(tt._throw)) {
594 this.expectPlugin("throwExpressions");
595 }
596 const isDelete = this.match(tt._delete);
597 this.next();
598
599 node.argument = this.parseMaybeUnary(null, true);
600
601 this.checkExpressionErrors(refExpressionErrors, true);
602
603 if (this.state.strict && isDelete) {
604 const arg = node.argument;
605
606 if (arg.type === "Identifier") {
607 this.raise(node.start, Errors.StrictDelete);
608 } else if (this.hasPropertyAsPrivateName(arg)) {
609 this.raise(node.start, Errors.DeletePrivateField);
610 }
611 }
612
613 if (!update) {
614 if (!sawUnary) this.checkExponentialAfterUnary(node);
615 return this.finishNode(node, "UnaryExpression");
616 }
617 }
618
619 const expr = this.parseUpdate(node, update, refExpressionErrors);
620
621 if (isAwait) {
622 const { type } = this.state;
623 const startsExpr = this.hasPlugin("v8intrinsic")
624 ? tokenCanStartExpression(type)
625 : tokenCanStartExpression(type) && !this.match(tt.modulo);
626 if (startsExpr && !this.isAmbiguousAwait()) {
627 this.raiseOverwrite(startPos, Errors.AwaitNotInAsyncContext);
628 return this.parseAwait(startPos, startLoc);
629 }
630 }
631
632 return expr;
633 }
634
635 // https://tc39.es/ecma262/#prod-UpdateExpression
636 parseUpdate(
637 node: N.Expression,
638 update: boolean,
639 refExpressionErrors: ?ExpressionErrors
640 ): N.Expression {
641 if (update) {
642 this.checkLVal(node.argument, "prefix operation");
643 return this.finishNode(node, "UpdateExpression");
644 }
645
646 const startPos = this.state.start;
647 const startLoc = this.state.startLoc;
648 let expr = this.parseExprSubscripts(refExpressionErrors);
649 if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
650 while (tokenIsPostfix(this.state.type) && !this.canInsertSemicolon()) {
651 const node = this.startNodeAt(startPos, startLoc);
652 node.operator = this.state.value;
653 node.prefix = false;
654 node.argument = expr;
655 this.checkLVal(expr, "postfix operation");
656 this.next();
657 expr = this.finishNode(node, "UpdateExpression");
658 }
659 return expr;
660 }
661
662 // Parse call, dot, and `[]`-subscript expressions.
663 // https://tc39.es/ecma262/#prod-LeftHandSideExpression
664 parseExprSubscripts(refExpressionErrors: ?ExpressionErrors): N.Expression {
665 const startPos = this.state.start;
666 const startLoc = this.state.startLoc;
667 const potentialArrowAt = this.state.potentialArrowAt;
668 const expr = this.parseExprAtom(refExpressionErrors);
669
670 if (this.shouldExitDescending(expr, potentialArrowAt)) {
671 return expr;
672 }
673
674 return this.parseSubscripts(expr, startPos, startLoc);
675 }
676
677 parseSubscripts(
678 base: N.Expression,
679 startPos: number,
680 startLoc: Position,
681 noCalls?: ?boolean
682 ): N.Expression {
683 const state = {
684 optionalChainMember: false,
685 maybeAsyncArrow: this.atPossibleAsyncArrow(base),
686 stop: false,
687 };
688 do {
689 base = this.parseSubscript(base, startPos, startLoc, noCalls, state);
690
691 // After parsing a subscript, this isn't "async" for sure.
692 state.maybeAsyncArrow = false;
693 } while (!state.stop);
694 return base;
695 }
696
697 /**
698 * @param state Set 'state.stop = true' to indicate that we should stop parsing subscripts.
699 * state.optionalChainMember to indicate that the member is currently in OptionalChain
700 */
701 parseSubscript(
702 base: N.Expression,
703 startPos: number,
704 startLoc: Position,
705 noCalls: ?boolean,
706 state: N.ParseSubscriptState
707 ): N.Expression {
708 if (!noCalls && this.eat(tt.doubleColon)) {
709 return this.parseBind(base, startPos, startLoc, noCalls, state);
710 } else if (this.match(tt.backQuote)) {
711 return this.parseTaggedTemplateExpression(
712 base,
713 startPos,
714 startLoc,
715 state
716 );
717 }
718
719 let optional = false;
720
721 if (this.match(tt.questionDot)) {
722 if (noCalls && this.lookaheadCharCode() === charCodes.leftParenthesis) {
723 // stop at `?.` when parsing `new a?.()`
724 state.stop = true;
725 return base;
726 }
727 state.optionalChainMember = optional = true;
728 this.next();
729 }
730
731 if (!noCalls && this.match(tt.parenL)) {
732 return this.parseCoverCallAndAsyncArrowHead(
733 base,
734 startPos,
735 startLoc,
736 state,
737 optional
738 );
739 } else {
740 const computed = this.eat(tt.bracketL);
741 if (computed || optional || this.eat(tt.dot)) {
742 return this.parseMember(
743 base,
744 startPos,
745 startLoc,
746 state,
747 computed,
748 optional
749 );
750 } else {
751 state.stop = true;
752 return base;
753 }
754 }
755 }
756
757 // base[?Yield, ?Await] [ Expression[+In, ?Yield, ?Await] ]
758 // base[?Yield, ?Await] . IdentifierName
759 // base[?Yield, ?Await] . PrivateIdentifier
760 // where `base` is one of CallExpression, MemberExpression and OptionalChain
761 parseMember(
762 base: N.Expression,
763 startPos: number,
764 startLoc: Position,
765 state: N.ParseSubscriptState,
766 computed: boolean,
767 optional: boolean
768 ): N.OptionalMemberExpression | N.MemberExpression {
769 const node = this.startNodeAt(startPos, startLoc);
770 node.object = base;
771 node.computed = computed;
772 const privateName =
773 !computed && this.match(tt.privateName) && this.state.value;
774 const property = computed
775 ? this.parseExpression()
776 : privateName
777 ? this.parsePrivateName()
778 : this.parseIdentifier(true);
779
780 if (privateName !== false) {
781 if (node.object.type === "Super") {
782 this.raise(startPos, Errors.SuperPrivateField);
783 }
784 this.classScope.usePrivateName(privateName, property.start);
785 }
786 node.property = property;
787
788 if (computed) {
789 this.expect(tt.bracketR);
790 }
791
792 if (state.optionalChainMember) {
793 node.optional = optional;
794 return this.finishNode(node, "OptionalMemberExpression");
795 } else {
796 return this.finishNode(node, "MemberExpression");
797 }
798 }
799
800 // https://github.com/tc39/proposal-bind-operator#syntax
801 parseBind(
802 base: N.Expression,
803 startPos: number,
804 startLoc: Position,
805 noCalls: ?boolean,
806 state: N.ParseSubscriptState
807 ): N.Expression {
808 const node = this.startNodeAt(startPos, startLoc);
809 node.object = base;
810 node.callee = this.parseNoCallExpr();
811 state.stop = true;
812 return this.parseSubscripts(
813 this.finishNode(node, "BindExpression"),
814 startPos,
815 startLoc,
816 noCalls
817 );
818 }
819
820 // https://tc39.es/ecma262/#prod-CoverCallExpressionAndAsyncArrowHead
821 // CoverCallExpressionAndAsyncArrowHead
822 // CallExpression[?Yield, ?Await] Arguments[?Yield, ?Await]
823 // OptionalChain[?Yield, ?Await] Arguments[?Yield, ?Await]
824 parseCoverCallAndAsyncArrowHead(
825 base: N.Expression,
826 startPos: number,
827 startLoc: Position,
828 state: N.ParseSubscriptState,
829 optional: boolean
830 ): N.Expression {
831 const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
832 let refExpressionErrors = null;
833
834 this.state.maybeInArrowParameters = true;
835 this.next(); // eat `(`
836
837 let node = this.startNodeAt(startPos, startLoc);
838 node.callee = base;
839
840 if (state.maybeAsyncArrow) {
841 this.expressionScope.enter(newAsyncArrowScope());
842 refExpressionErrors = new ExpressionErrors();
843 }
844
845 if (state.optionalChainMember) {
846 node.optional = optional;
847 }
848
849 if (optional) {
850 node.arguments = this.parseCallExpressionArguments(tt.parenR);
851 } else {
852 node.arguments = this.parseCallExpressionArguments(
853 tt.parenR,
854 base.type === "Import",
855 base.type !== "Super",
856 node,
857 refExpressionErrors
858 );
859 }
860 this.finishCallExpression(node, state.optionalChainMember);
861
862 if (state.maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
863 state.stop = true;
864 this.expressionScope.validateAsPattern();
865 this.expressionScope.exit();
866 node = this.parseAsyncArrowFromCallExpression(
867 this.startNodeAt(startPos, startLoc),
868 node
869 );
870 } else {
871 if (state.maybeAsyncArrow) {
872 this.checkExpressionErrors(refExpressionErrors, true);
873 this.expressionScope.exit();
874 }
875 this.toReferencedArguments(node);
876 }
877
878 this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
879
880 return node;
881 }
882
883 toReferencedArguments(
884 node: N.CallExpression | N.OptionalCallExpression,
885 isParenthesizedExpr?: boolean
886 ) {
887 this.toReferencedListDeep(node.arguments, isParenthesizedExpr);
888 }
889
890 // MemberExpression [?Yield, ?Await] TemplateLiteral[?Yield, ?Await, +Tagged]
891 // CallExpression [?Yield, ?Await] TemplateLiteral[?Yield, ?Await, +Tagged]
892 parseTaggedTemplateExpression(
893 base: N.Expression,
894 startPos: number,
895 startLoc: Position,
896 state: N.ParseSubscriptState
897 ): N.TaggedTemplateExpression {
898 const node: N.TaggedTemplateExpression = this.startNodeAt(
899 startPos,
900 startLoc
901 );
902 node.tag = base;
903 node.quasi = this.parseTemplate(true);
904 if (state.optionalChainMember) {
905 this.raise(startPos, Errors.OptionalChainingNoTemplate);
906 }
907 return this.finishNode(node, "TaggedTemplateExpression");
908 }
909
910 atPossibleAsyncArrow(base: N.Expression): boolean {
911 return (
912 base.type === "Identifier" &&
913 base.name === "async" &&
914 this.state.lastTokEnd === base.end &&
915 !this.canInsertSemicolon() &&
916 // check there are no escape sequences, such as \u{61}sync
917 base.end - base.start === 5 &&
918 base.start === this.state.potentialArrowAt
919 );
920 }
921
922 finishCallExpression<T: N.CallExpression | N.OptionalCallExpression>(
923 node: T,
924 optional: boolean
925 ): N.Expression {
926 if (node.callee.type === "Import") {
927 if (node.arguments.length === 2) {
928 if (process.env.BABEL_8_BREAKING) {
929 this.expectPlugin("importAssertions");
930 } else {
931 if (!this.hasPlugin("moduleAttributes")) {
932 this.expectPlugin("importAssertions");
933 }
934 }
935 }
936 if (node.arguments.length === 0 || node.arguments.length > 2) {
937 this.raise(
938 node.start,
939 Errors.ImportCallArity,
940 this.hasPlugin("importAssertions") ||
941 this.hasPlugin("moduleAttributes")
942 ? "one or two arguments"
943 : "one argument"
944 );
945 } else {
946 for (const arg of node.arguments) {
947 if (arg.type === "SpreadElement") {
948 this.raise(arg.start, Errors.ImportCallSpreadArgument);
949 }
950 }
951 }
952 }
953 return this.finishNode(
954 node,
955 optional ? "OptionalCallExpression" : "CallExpression"
956 );
957 }
958
959 parseCallExpressionArguments(
960 close: TokenType,
961 dynamicImport?: boolean,
962 allowPlaceholder?: boolean,
963 nodeForExtra?: ?N.Node,
964 refExpressionErrors?: ?ExpressionErrors
965 ): $ReadOnlyArray<?N.Expression> {
966 const elts = [];
967 let first = true;
968 const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
969 this.state.inFSharpPipelineDirectBody = false;
970
971 while (!this.eat(close)) {
972 if (first) {
973 first = false;
974 } else {
975 this.expect(tt.comma);
976 if (this.match(close)) {
977 if (
978 dynamicImport &&
979 !this.hasPlugin("importAssertions") &&
980 !this.hasPlugin("moduleAttributes")
981 ) {
982 this.raise(
983 this.state.lastTokStart,
984 Errors.ImportCallArgumentTrailingComma
985 );
986 }
987 if (nodeForExtra) {
988 this.addExtra(
989 nodeForExtra,
990 "trailingComma",
991 this.state.lastTokStart
992 );
993 }
994 this.next();
995 break;
996 }
997 }
998
999 elts.push(
1000 this.parseExprListItem(false, refExpressionErrors, allowPlaceholder)
1001 );
1002 }
1003
1004 this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
1005
1006 return elts;
1007 }
1008
1009 shouldParseAsyncArrow(): boolean {
1010 return this.match(tt.arrow) && !this.canInsertSemicolon();
1011 }
1012
1013 parseAsyncArrowFromCallExpression(
1014 node: N.ArrowFunctionExpression,
1015 call: N.CallExpression
1016 ): N.ArrowFunctionExpression {
1017 this.resetPreviousNodeTrailingComments(call);
1018 this.expect(tt.arrow);
1019 this.parseArrowExpression(
1020 node,
1021 call.arguments,
1022 true,
1023 call.extra?.trailingComma
1024 );
1025 // mark inner comments of `async()` as inner comments of `async () =>`
1026 setInnerComments(node, call.innerComments);
1027 // mark trailing comments of `async` to be inner comments
1028 setInnerComments(node, call.callee.trailingComments);
1029 return node;
1030 }
1031
1032 // Parse a no-call expression (like argument of `new` or `::` operators).
1033 // https://tc39.es/ecma262/#prod-MemberExpression
1034 parseNoCallExpr(): N.Expression {
1035 const startPos = this.state.start;
1036 const startLoc = this.state.startLoc;
1037 return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
1038 }
1039
1040 // Parse an atomic expression — either a single token that is an
1041 // expression, an expression started by a keyword like `function` or
1042 // `new`, or an expression wrapped in punctuation like `()`, `[]`,
1043 // or `{}`.
1044
1045 // https://tc39.es/ecma262/#prod-PrimaryExpression
1046 // https://tc39.es/ecma262/#prod-AsyncArrowFunction
1047 // PrimaryExpression
1048 // Super
1049 // Import
1050 // AsyncArrowFunction
1051
1052 parseExprAtom(refExpressionErrors?: ?ExpressionErrors): N.Expression {
1053 let node;
1054
1055 const { type } = this.state;
1056 switch (type) {
1057 case tt._super:
1058 return this.parseSuper();
1059
1060 case tt._import:
1061 node = this.startNode();
1062 this.next();
1063
1064 if (this.match(tt.dot)) {
1065 return this.parseImportMetaProperty(node);
1066 }
1067
1068 if (!this.match(tt.parenL)) {
1069 this.raise(this.state.lastTokStart, Errors.UnsupportedImport);
1070 }
1071 return this.finishNode(node, "Import");
1072 case tt._this:
1073 node = this.startNode();
1074 this.next();
1075 return this.finishNode(node, "ThisExpression");
1076
1077 case tt._do: {
1078 return this.parseDo(this.startNode(), false);
1079 }
1080
1081 case tt.slash:
1082 case tt.slashAssign: {
1083 this.readRegexp();
1084 return this.parseRegExpLiteral(this.state.value);
1085 }
1086
1087 case tt.num:
1088 return this.parseNumericLiteral(this.state.value);
1089
1090 case tt.bigint:
1091 return this.parseBigIntLiteral(this.state.value);
1092
1093 case tt.decimal:
1094 return this.parseDecimalLiteral(this.state.value);
1095
1096 case tt.string:
1097 return this.parseStringLiteral(this.state.value);
1098
1099 case tt._null:
1100 return this.parseNullLiteral();
1101
1102 case tt._true:
1103 return this.parseBooleanLiteral(true);
1104 case tt._false:
1105 return this.parseBooleanLiteral(false);
1106
1107 case tt.parenL: {
1108 const canBeArrow = this.state.potentialArrowAt === this.state.start;
1109 return this.parseParenAndDistinguishExpression(canBeArrow);
1110 }
1111
1112 case tt.bracketBarL:
1113 case tt.bracketHashL: {
1114 return this.parseArrayLike(
1115 this.state.type === tt.bracketBarL ? tt.bracketBarR : tt.bracketR,
1116 /* canBePattern */ false,
1117 /* isTuple */ true,
1118 refExpressionErrors
1119 );
1120 }
1121 case tt.bracketL: {
1122 return this.parseArrayLike(
1123 tt.bracketR,
1124 /* canBePattern */ true,
1125 /* isTuple */ false,
1126 refExpressionErrors
1127 );
1128 }
1129 case tt.braceBarL:
1130 case tt.braceHashL: {
1131 return this.parseObjectLike(
1132 this.state.type === tt.braceBarL ? tt.braceBarR : tt.braceR,
1133 /* isPattern */ false,
1134 /* isRecord */ true,
1135 refExpressionErrors
1136 );
1137 }
1138 case tt.braceL: {
1139 return this.parseObjectLike(
1140 tt.braceR,
1141 /* isPattern */ false,
1142 /* isRecord */ false,
1143 refExpressionErrors
1144 );
1145 }
1146 case tt._function:
1147 return this.parseFunctionOrFunctionSent();
1148
1149 case tt.at:
1150 this.parseDecorators();
1151 // fall through
1152 case tt._class:
1153 node = this.startNode();
1154 this.takeDecorators(node);
1155 return this.parseClass(node, false);
1156
1157 case tt._new:
1158 return this.parseNewOrNewTarget();
1159
1160 case tt.backQuote:
1161 return this.parseTemplate(false);
1162
1163 // BindExpression[Yield]
1164 // :: MemberExpression[?Yield]
1165 case tt.doubleColon: {
1166 node = this.startNode();
1167 this.next();
1168 node.object = null;
1169 const callee = (node.callee = this.parseNoCallExpr());
1170 if (callee.type === "MemberExpression") {
1171 return this.finishNode(node, "BindExpression");
1172 } else {
1173 throw this.raise(callee.start, Errors.UnsupportedBind);
1174 }
1175 }
1176
1177 case tt.privateName: {
1178 // Standalone private names are only allowed in "#x in obj"
1179 // expressions, and they are directly handled by callers of
1180 // parseExprOp. If we reach this, the input is always invalid.
1181 // We can throw a better error message and recover, rather than
1182 // just throwing "Unexpected token" (which is the default
1183 // behavior of this big switch statement).
1184 this.raise(
1185 this.state.start,
1186 Errors.PrivateInExpectedIn,
1187 this.state.value
1188 );
1189 return this.parsePrivateName();
1190 }
1191
1192 case tt.moduloAssign:
1193 if (
1194 this.getPluginOption("pipelineOperator", "proposal") === "hack" &&
1195 this.getPluginOption("pipelineOperator", "topicToken") === "%"
1196 ) {
1197 // If we find %= in an expression position, and the Hack-pipes proposal is active,
1198 // then the % could be the topic token (e.g., in x |> %==y or x |> %===y), and so we
1199 // reparse it as %.
1200 // The next readToken() call will start parsing from =.
1201
1202 this.state.value = "%";
1203 this.state.type = tt.modulo;
1204 this.state.pos--;
1205 this.state.end--;
1206 this.state.endLoc.column--;
1207 } else {
1208 throw this.unexpected();
1209 }
1210
1211 // falls through
1212 case tt.modulo:
1213 case tt.hash: {
1214 const pipeProposal = this.getPluginOption(
1215 "pipelineOperator",
1216 "proposal"
1217 );
1218
1219 if (pipeProposal) {
1220 // A pipe-operator proposal is active,
1221 // although its configuration might not match the current token’s type.
1222 node = this.startNode();
1223 const start = this.state.start;
1224 const tokenType = this.state.type;
1225
1226 // Consume the current token.
1227 this.next();
1228
1229 // If the pipe-operator plugin’s configuration matches the current token’s type,
1230 // then this will return `node`, will have been finished as a topic reference.
1231 // Otherwise, this will throw a `PipeTopicUnconfiguredToken` error.
1232 return this.finishTopicReference(
1233 node,
1234 start,
1235 pipeProposal,
1236 tokenType
1237 );
1238 }
1239 }
1240
1241 // fall through
1242 case tt.relational: {
1243 if (this.state.value === "<") {
1244 const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
1245 if (
1246 isIdentifierStart(lookaheadCh) || // Element/Type Parameter <foo>
1247 lookaheadCh === charCodes.greaterThan // Fragment <>
1248 ) {
1249 this.expectOnePlugin(["jsx", "flow", "typescript"]);
1250 }
1251 }
1252 }
1253
1254 // fall through
1255 default:
1256 if (tokenIsIdentifier(type)) {
1257 if (
1258 this.isContextual(tt._module) &&
1259 this.lookaheadCharCode() === charCodes.leftCurlyBrace &&
1260 !this.hasFollowingLineBreak()
1261 ) {
1262 return this.parseModuleExpression();
1263 }
1264 const canBeArrow = this.state.potentialArrowAt === this.state.start;
1265 const containsEsc = this.state.containsEsc;
1266 const id = this.parseIdentifier();
1267
1268 if (
1269 !containsEsc &&
1270 id.name === "async" &&
1271 !this.canInsertSemicolon()
1272 ) {
1273 const { type } = this.state;
1274 if (type === tt._function) {
1275 this.resetPreviousNodeTrailingComments(id);
1276 this.next();
1277 return this.parseFunction(
1278 this.startNodeAtNode(id),
1279 undefined,
1280 true
1281 );
1282 } else if (tokenIsIdentifier(type)) {
1283 // If the next token begins with "=", commit to parsing an async
1284 // arrow function. (Peeking ahead for "=" lets us avoid a more
1285 // expensive full-token lookahead on this common path.)
1286 if (this.lookaheadCharCode() === charCodes.equalsTo) {
1287 // although `id` is not used in async arrow unary function,
1288 // we don't need to reset `async`'s trailing comments because
1289 // it will be attached to the upcoming async arrow binding identifier
1290 return this.parseAsyncArrowUnaryFunction(
1291 this.startNodeAtNode(id)
1292 );
1293 } else {
1294 // Otherwise, treat "async" as an identifier and let calling code
1295 // deal with the current tt.name token.
1296 return id;
1297 }
1298 } else if (type === tt._do) {
1299 this.resetPreviousNodeTrailingComments(id);
1300 return this.parseDo(this.startNodeAtNode(id), true);
1301 }
1302 }
1303
1304 if (
1305 canBeArrow &&
1306 this.match(tt.arrow) &&
1307 !this.canInsertSemicolon()
1308 ) {
1309 this.next();
1310 return this.parseArrowExpression(
1311 this.startNodeAtNode(id),
1312 [id],
1313 false
1314 );
1315 }
1316
1317 return id;
1318 } else {
1319 throw this.unexpected();
1320 }
1321 }
1322 }
1323
1324 // This helper method attempts to finish the given `node`
1325 // into a topic-reference node for the given `pipeProposal`.
1326 // See <https://github.com/js-choi/proposal-hack-pipes>.
1327 //
1328 // The method assumes that any topic token was consumed before it was called.
1329 //
1330 // If the `pipelineOperator` plugin is active,
1331 // and if the given `tokenType` matches the plugin’s configuration,
1332 // then this method will return the finished `node`.
1333 //
1334 // If the `pipelineOperator` plugin is active,
1335 // but if the given `tokenType` does not match the plugin’s configuration,
1336 // then this method will throw a `PipeTopicUnconfiguredToken` error.
1337 finishTopicReference(
1338 node: N.Node,
1339 start: number,
1340 pipeProposal: string,
1341 tokenType: TokenType
1342 ): N.Expression {
1343 if (this.testTopicReferenceConfiguration(pipeProposal, start, tokenType)) {
1344 // The token matches the plugin’s configuration.
1345 // The token is therefore a topic reference.
1346
1347 // Determine the node type for the topic reference
1348 // that is appropriate for the active pipe-operator proposal.
1349 let nodeType;
1350 if (pipeProposal === "smart") {
1351 nodeType = "PipelinePrimaryTopicReference";
1352 } else {
1353 // The proposal must otherwise be "hack",
1354 // as enforced by testTopicReferenceConfiguration.
1355 nodeType = "TopicReference";
1356 }
1357
1358 if (!this.topicReferenceIsAllowedInCurrentContext()) {
1359 // The topic reference is not allowed in the current context:
1360 // it is outside of a pipe body.
1361 // Raise recoverable errors.
1362 if (pipeProposal === "smart") {
1363 this.raise(start, Errors.PrimaryTopicNotAllowed);
1364 } else {
1365 // In this case, `pipeProposal === "hack"` is true.
1366 this.raise(start, Errors.PipeTopicUnbound);
1367 }
1368 }
1369
1370 // Register the topic reference so that its pipe body knows
1371 // that its topic was used at least once.
1372 this.registerTopicReference();
1373
1374 return this.finishNode(node, nodeType);
1375 } else {
1376 // The token does not match the plugin’s configuration.
1377 throw this.raise(
1378 start,
1379 Errors.PipeTopicUnconfiguredToken,
1380 tokenLabelName(tokenType)
1381 );
1382 }
1383 }
1384
1385 // This helper method tests whether the given token type
1386 // matches the pipelineOperator parser plugin’s configuration.
1387 // If the active pipe proposal is Hack style,
1388 // and if the given token is the same as the plugin configuration’s `topicToken`,
1389 // then this is a valid topic reference.
1390 // If the active pipe proposal is smart mix,
1391 // then the topic token must always be `#`.
1392 // If the active pipe proposal is neither (e.g., "minimal" or "fsharp"),
1393 // then an error is thrown.
1394 testTopicReferenceConfiguration(
1395 pipeProposal: string,
1396 start: number,
1397 tokenType: TokenType
1398 ): boolean {
1399 switch (pipeProposal) {
1400 case "hack": {
1401 const pluginTopicToken = this.getPluginOption(
1402 "pipelineOperator",
1403 "topicToken"
1404 );
1405 return tokenLabelName(tokenType) === pluginTopicToken;
1406 }
1407 case "smart":
1408 return tokenType === tt.hash;
1409 default:
1410 throw this.raise(start, Errors.PipeTopicRequiresHackPipes);
1411 }
1412 }
1413
1414 // async [no LineTerminator here] AsyncArrowBindingIdentifier[?Yield] [no LineTerminator here] => AsyncConciseBody[?In]
1415 parseAsyncArrowUnaryFunction(node: N.Node): N.ArrowFunctionExpression {
1416 // We don't need to push a new ParameterDeclarationScope here since we are sure
1417 // 1) it is an async arrow, 2) no biding pattern is allowed in params
1418 this.prodParam.enter(functionFlags(true, this.prodParam.hasYield));
1419 const params = [this.parseIdentifier()];
1420 this.prodParam.exit();
1421 if (this.hasPrecedingLineBreak()) {
1422 this.raise(this.state.pos, Errors.LineTerminatorBeforeArrow);
1423 }
1424 this.expect(tt.arrow);
1425 // let foo = async bar => {};
1426 this.parseArrowExpression(node, params, true);
1427 return node;
1428 }
1429
1430 // https://github.com/tc39/proposal-do-expressions
1431 // https://github.com/tc39/proposal-async-do-expressions
1432 parseDo(node: N.Node, isAsync: boolean): N.DoExpression {
1433 this.expectPlugin("doExpressions");
1434 if (isAsync) {
1435 this.expectPlugin("asyncDoExpressions");
1436 }
1437 node.async = isAsync;
1438 this.next(); // eat `do`
1439 const oldLabels = this.state.labels;
1440 this.state.labels = [];
1441 if (isAsync) {
1442 // AsyncDoExpression :
1443 // async [no LineTerminator here] do Block[~Yield, +Await, ~Return]
1444 this.prodParam.enter(PARAM_AWAIT);
1445 node.body = this.parseBlock();
1446 this.prodParam.exit();
1447 } else {
1448 node.body = this.parseBlock();
1449 }
1450
1451 this.state.labels = oldLabels;
1452 return this.finishNode(node, "DoExpression");
1453 }
1454
1455 // Parse the `super` keyword
1456 parseSuper(): N.Super {
1457 const node = this.startNode();
1458 this.next(); // eat `super`
1459 if (
1460 this.match(tt.parenL) &&
1461 !this.scope.allowDirectSuper &&
1462 !this.options.allowSuperOutsideMethod
1463 ) {
1464 this.raise(node.start, Errors.SuperNotAllowed);
1465 } else if (
1466 !this.scope.allowSuper &&
1467 !this.options.allowSuperOutsideMethod
1468 ) {
1469 this.raise(node.start, Errors.UnexpectedSuper);
1470 }
1471
1472 if (
1473 !this.match(tt.parenL) &&
1474 !this.match(tt.bracketL) &&
1475 !this.match(tt.dot)
1476 ) {
1477 this.raise(node.start, Errors.UnsupportedSuper);
1478 }
1479
1480 return this.finishNode(node, "Super");
1481 }
1482
1483 parseMaybePrivateName(
1484 isPrivateNameAllowed: boolean
1485 ): N.PrivateName | N.Identifier {
1486 const isPrivate = this.match(tt.privateName);
1487
1488 if (isPrivate) {
1489 if (!isPrivateNameAllowed) {
1490 this.raise(this.state.start + 1, Errors.UnexpectedPrivateField);
1491 }
1492 return this.parsePrivateName();
1493 } else {
1494 return this.parseIdentifier(true);
1495 }
1496 }
1497
1498 parsePrivateName(): N.PrivateName {
1499 const node = this.startNode();
1500 const id = this.startNodeAt(
1501 this.state.start + 1,
1502 // The position is hardcoded because we merge `#` and name into a single
1503 // tt.privateName token
1504 new Position(
1505 this.state.curLine,
1506 this.state.start + 1 - this.state.lineStart
1507 )
1508 );
1509 const name = this.state.value;
1510 this.next(); // eat #name;
1511 node.id = this.createIdentifier(id, name);
1512 return this.finishNode(node, "PrivateName");
1513 }
1514
1515 parseFunctionOrFunctionSent(): N.FunctionExpression | N.MetaProperty {
1516 const node = this.startNode();
1517
1518 // We do not do parseIdentifier here because when parseFunctionOrFunctionSent
1519 // is called we already know that the current token is a "name" with the value "function"
1520 // This will improve perf a tiny little bit as we do not do validation but more importantly
1521 // here is that parseIdentifier will remove an item from the expression stack
1522 // if "function" or "class" is parsed as identifier (in objects e.g.), which should not happen here.
1523 this.next(); // eat `function`
1524
1525 if (this.prodParam.hasYield && this.match(tt.dot)) {
1526 const meta = this.createIdentifier(
1527 this.startNodeAtNode(node),
1528 "function"
1529 );
1530 this.next(); // eat `.`
1531 // https://github.com/tc39/proposal-function.sent#syntax-1
1532 if (this.match(tt._sent)) {
1533 this.expectPlugin("functionSent");
1534 } else if (!this.hasPlugin("functionSent")) {
1535 // The code wasn't `function.sent` but just `function.`, so a simple error is less confusing.
1536 this.unexpected();
1537 }
1538 return this.parseMetaProperty(node, meta, "sent");
1539 }
1540 return this.parseFunction(node);
1541 }
1542
1543 parseMetaProperty(
1544 node: N.MetaProperty,
1545 meta: N.Identifier,
1546 propertyName: string
1547 ): N.MetaProperty {
1548 node.meta = meta;
1549
1550 const containsEsc = this.state.containsEsc;
1551
1552 node.property = this.parseIdentifier(true);
1553
1554 if (node.property.name !== propertyName || containsEsc) {
1555 this.raise(
1556 node.property.start,
1557 Errors.UnsupportedMetaProperty,
1558 meta.name,
1559 propertyName
1560 );
1561 }
1562
1563 return this.finishNode(node, "MetaProperty");
1564 }
1565
1566 // https://tc39.es/ecma262/#prod-ImportMeta
1567 parseImportMetaProperty(node: N.MetaProperty): N.MetaProperty {
1568 const id = this.createIdentifier(this.startNodeAtNode(node), "import");
1569 this.next(); // eat `.`
1570
1571 if (this.isContextual(tt._meta)) {
1572 if (!this.inModule) {
1573 this.raise(id.start, SourceTypeModuleErrors.ImportMetaOutsideModule);
1574 }
1575 this.sawUnambiguousESM = true;
1576 }
1577
1578 return this.parseMetaProperty(node, id, "meta");
1579 }
1580
1581 parseLiteralAtNode<T: N.Node>(
1582 value: any,
1583 type: $ElementType<T, "type">,
1584 node: any
1585 ): T {
1586 this.addExtra(node, "rawValue", value);
1587 this.addExtra(node, "raw", this.input.slice(node.start, this.state.end));
1588 node.value = value;
1589 this.next();
1590 return this.finishNode<T>(node, type);
1591 }
1592
1593 parseLiteral<T: N.Node>(value: any, type: $ElementType<T, "type">): T {
1594 const node = this.startNode();
1595 return this.parseLiteralAtNode(value, type, node);
1596 }
1597
1598 parseStringLiteral(value: any) {
1599 return this.parseLiteral<N.StringLiteral>(value, "StringLiteral");
1600 }
1601
1602 parseNumericLiteral(value: any) {
1603 return this.parseLiteral<N.NumericLiteral>(value, "NumericLiteral");
1604 }
1605
1606 parseBigIntLiteral(value: any) {
1607 return this.parseLiteral<N.BigIntLiteral>(value, "BigIntLiteral");
1608 }
1609
1610 parseDecimalLiteral(value: any) {
1611 return this.parseLiteral<N.DecimalLiteral>(value, "DecimalLiteral");
1612 }
1613
1614 parseRegExpLiteral(value: { value: any, pattern: string, flags: string }) {
1615 const node = this.parseLiteral<N.RegExpLiteral>(
1616 value.value,
1617 "RegExpLiteral"
1618 );
1619 node.pattern = value.pattern;
1620 node.flags = value.flags;
1621 return node;
1622 }
1623
1624 parseBooleanLiteral(value: boolean) {
1625 const node = this.startNode();
1626 node.value = value;
1627 this.next();
1628 return this.finishNode<N.BooleanLiteral>(node, "BooleanLiteral");
1629 }
1630
1631 parseNullLiteral() {
1632 const node = this.startNode();
1633 this.next();
1634 return this.finishNode<N.NullLiteral>(node, "NullLiteral");
1635 }
1636
1637 // https://tc39.es/ecma262/#prod-CoverParenthesizedExpressionAndArrowParameterList
1638 parseParenAndDistinguishExpression(canBeArrow: boolean): N.Expression {
1639 const startPos = this.state.start;
1640 const startLoc = this.state.startLoc;
1641
1642 let val;
1643 this.next(); // eat `(`
1644 this.expressionScope.enter(newArrowHeadScope());
1645
1646 const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
1647 const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
1648 this.state.maybeInArrowParameters = true;
1649 this.state.inFSharpPipelineDirectBody = false;
1650
1651 const innerStartPos = this.state.start;
1652 const innerStartLoc = this.state.startLoc;
1653 const exprList = [];
1654 const refExpressionErrors = new ExpressionErrors();
1655 let first = true;
1656 let spreadStart;
1657 let optionalCommaStart;
1658
1659 while (!this.match(tt.parenR)) {
1660 if (first) {
1661 first = false;
1662 } else {
1663 this.expect(
1664 tt.comma,
1665 refExpressionErrors.optionalParameters === -1
1666 ? null
1667 : refExpressionErrors.optionalParameters
1668 );
1669 if (this.match(tt.parenR)) {
1670 optionalCommaStart = this.state.start;
1671 break;
1672 }
1673 }
1674
1675 if (this.match(tt.ellipsis)) {
1676 const spreadNodeStartPos = this.state.start;
1677 const spreadNodeStartLoc = this.state.startLoc;
1678 spreadStart = this.state.start;
1679 exprList.push(
1680 this.parseParenItem(
1681 this.parseRestBinding(),
1682 spreadNodeStartPos,
1683 spreadNodeStartLoc
1684 )
1685 );
1686
1687 this.checkCommaAfterRest(charCodes.rightParenthesis);
1688
1689 break;
1690 } else {
1691 exprList.push(
1692 this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem)
1693 );
1694 }
1695 }
1696
1697 const innerEndPos = this.state.lastTokEnd;
1698 const innerEndLoc = this.state.lastTokEndLoc;
1699 this.expect(tt.parenR);
1700
1701 this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
1702 this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
1703
1704 let arrowNode = this.startNodeAt(startPos, startLoc);
1705 if (
1706 canBeArrow &&
1707 this.shouldParseArrow(exprList) &&
1708 (arrowNode = this.parseArrow(arrowNode))
1709 ) {
1710 this.expressionScope.validateAsPattern();
1711 this.expressionScope.exit();
1712 this.parseArrowExpression(arrowNode, exprList, false);
1713 return arrowNode;
1714 }
1715 this.expressionScope.exit();
1716
1717 if (!exprList.length) {
1718 this.unexpected(this.state.lastTokStart);
1719 }
1720 if (optionalCommaStart) this.unexpected(optionalCommaStart);
1721 if (spreadStart) this.unexpected(spreadStart);
1722 this.checkExpressionErrors(refExpressionErrors, true);
1723
1724 this.toReferencedListDeep(exprList, /* isParenthesizedExpr */ true);
1725 if (exprList.length > 1) {
1726 val = this.startNodeAt(innerStartPos, innerStartLoc);
1727 val.expressions = exprList;
1728 // finish node at current location so it can pick up comments after `)`
1729 this.finishNode(val, "SequenceExpression");
1730 this.resetEndLocation(val, innerEndPos, innerEndLoc);
1731 } else {
1732 val = exprList[0];
1733 }
1734
1735 if (!this.options.createParenthesizedExpressions) {
1736 this.addExtra(val, "parenthesized", true);
1737 this.addExtra(val, "parenStart", startPos);
1738 return val;
1739 }
1740
1741 const parenExpression = this.startNodeAt(startPos, startLoc);
1742 parenExpression.expression = val;
1743 this.finishNode(parenExpression, "ParenthesizedExpression");
1744 return parenExpression;
1745 }
1746
1747 // eslint-disable-next-line no-unused-vars -- `params` is used in typescript plugin
1748 shouldParseArrow(params: Array<N.Node>): boolean {
1749 return !this.canInsertSemicolon();
1750 }
1751
1752 parseArrow(node: N.ArrowFunctionExpression): ?N.ArrowFunctionExpression {
1753 if (this.eat(tt.arrow)) {
1754 return node;
1755 }
1756 }
1757
1758 parseParenItem(
1759 node: N.Expression,
1760 startPos: number, // eslint-disable-line no-unused-vars
1761 startLoc: Position // eslint-disable-line no-unused-vars
1762 ): N.Expression {
1763 return node;
1764 }
1765
1766 parseNewOrNewTarget(): N.NewExpression | N.MetaProperty {
1767 const node = this.startNode();
1768 this.next();
1769 if (this.match(tt.dot)) {
1770 // https://tc39.es/ecma262/#prod-NewTarget
1771 const meta = this.createIdentifier(this.startNodeAtNode(node), "new");
1772 this.next();
1773 const metaProp = this.parseMetaProperty(node, meta, "target");
1774
1775 if (!this.scope.inNonArrowFunction && !this.scope.inClass) {
1776 this.raise(metaProp.start, Errors.UnexpectedNewTarget);
1777 }
1778
1779 return metaProp;
1780 }
1781
1782 return this.parseNew(node);
1783 }
1784
1785 // New's precedence is slightly tricky. It must allow its argument to
1786 // be a `[]` or dot subscript expression, but not a call — at least,
1787 // not without wrapping it in parentheses. Thus, it uses the noCalls
1788 // argument to parseSubscripts to prevent it from consuming the
1789 // argument list.
1790 // https://tc39.es/ecma262/#prod-NewExpression
1791 parseNew(node: N.Expression): N.NewExpression {
1792 node.callee = this.parseNoCallExpr();
1793 if (node.callee.type === "Import") {
1794 this.raise(node.callee.start, Errors.ImportCallNotNewExpression);
1795 } else if (this.isOptionalChain(node.callee)) {
1796 this.raise(this.state.lastTokEnd, Errors.OptionalChainingNoNew);
1797 } else if (this.eat(tt.questionDot)) {
1798 this.raise(this.state.start, Errors.OptionalChainingNoNew);
1799 }
1800
1801 this.parseNewArguments(node);
1802 return this.finishNode(node, "NewExpression");
1803 }
1804
1805 parseNewArguments(node: N.NewExpression): void {
1806 if (this.eat(tt.parenL)) {
1807 const args = this.parseExprList(tt.parenR);
1808 this.toReferencedList(args);
1809 // $FlowFixMe (parseExprList should be all non-null in this case)
1810 node.arguments = args;
1811 } else {
1812 node.arguments = [];
1813 }
1814 }
1815
1816 // Parse template expression.
1817
1818 parseTemplateElement(isTagged: boolean): N.TemplateElement {
1819 const elem = this.startNode();
1820 if (this.state.value === null) {
1821 if (!isTagged) {
1822 this.raise(this.state.start + 1, Errors.InvalidEscapeSequenceTemplate);
1823 }
1824 }
1825 elem.value = {
1826 raw: this.input
1827 .slice(this.state.start, this.state.end)
1828 .replace(/\r\n?/g, "\n"),
1829 cooked: this.state.value,
1830 };
1831 this.next();
1832 elem.tail = this.match(tt.backQuote);
1833 return this.finishNode(elem, "TemplateElement");
1834 }
1835
1836 // https://tc39.es/ecma262/#prod-TemplateLiteral
1837 parseTemplate(isTagged: boolean): N.TemplateLiteral {
1838 const node = this.startNode();
1839 this.next();
1840 node.expressions = [];
1841 let curElt = this.parseTemplateElement(isTagged);
1842 node.quasis = [curElt];
1843 while (!curElt.tail) {
1844 this.expect(tt.dollarBraceL);
1845 node.expressions.push(this.parseTemplateSubstitution());
1846 this.expect(tt.braceR);
1847 node.quasis.push((curElt = this.parseTemplateElement(isTagged)));
1848 }
1849 this.next();
1850 return this.finishNode(node, "TemplateLiteral");
1851 }
1852
1853 // This is overwritten by the TypeScript plugin to parse template types
1854 parseTemplateSubstitution(): N.Expression {
1855 return this.parseExpression();
1856 }
1857
1858 // Parse an object literal, binding pattern, or record.
1859
1860 parseObjectLike<T: N.ObjectPattern | N.ObjectExpression>(
1861 close: TokenType,
1862 isPattern: boolean,
1863 isRecord?: ?boolean,
1864 refExpressionErrors?: ?ExpressionErrors
1865 ): T {
1866 if (isRecord) {
1867 this.expectPlugin("recordAndTuple");
1868 }
1869 const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
1870 this.state.inFSharpPipelineDirectBody = false;
1871 const propHash: any = Object.create(null);
1872 let first = true;
1873 const node = this.startNode();
1874
1875 node.properties = [];
1876 this.next();
1877
1878 while (!this.match(close)) {
1879 if (first) {
1880 first = false;
1881 } else {
1882 this.expect(tt.comma);
1883 if (this.match(close)) {
1884 this.addExtra(node, "trailingComma", this.state.lastTokStart);
1885 break;
1886 }
1887 }
1888
1889 const prop = this.parsePropertyDefinition(isPattern, refExpressionErrors);
1890 if (!isPattern) {
1891 // $FlowIgnore RestElement will never be returned if !isPattern
1892 this.checkProto(prop, isRecord, propHash, refExpressionErrors);
1893 }
1894
1895 if (
1896 isRecord &&
1897 !this.isObjectProperty(prop) &&
1898 prop.type !== "SpreadElement"
1899 ) {
1900 this.raise(prop.start, Errors.InvalidRecordProperty);
1901 }
1902
1903 // $FlowIgnore
1904 if (prop.shorthand) {
1905 this.addExtra(prop, "shorthand", true);
1906 }
1907
1908 node.properties.push(prop);
1909 }
1910
1911 this.next();
1912
1913 this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
1914 let type = "ObjectExpression";
1915 if (isPattern) {
1916 type = "ObjectPattern";
1917 } else if (isRecord) {
1918 type = "RecordExpression";
1919 }
1920 return this.finishNode(node, type);
1921 }
1922
1923 // Check grammar production:
1924 // IdentifierName *_opt PropertyName
1925 // It is used in `parsePropertyDefinition` to detect AsyncMethod and Accessors
1926 maybeAsyncOrAccessorProp(prop: N.ObjectProperty): boolean {
1927 return (
1928 !prop.computed &&
1929 prop.key.type === "Identifier" &&
1930 (this.isLiteralPropertyName() ||
1931 this.match(tt.bracketL) ||
1932 this.match(tt.star))
1933 );
1934 }
1935
1936 // https://tc39.es/ecma262/#prod-PropertyDefinition
1937 parsePropertyDefinition(
1938 isPattern: boolean,
1939 refExpressionErrors?: ?ExpressionErrors
1940 ): N.ObjectMember | N.SpreadElement | N.RestElement {
1941 let decorators = [];
1942 if (this.match(tt.at)) {
1943 if (this.hasPlugin("decorators")) {
1944 this.raise(this.state.start, Errors.UnsupportedPropertyDecorator);
1945 }
1946
1947 // we needn't check if decorators (stage 0) plugin is enabled since it's checked by
1948 // the call to this.parseDecorator
1949 while (this.match(tt.at)) {
1950 decorators.push(this.parseDecorator());
1951 }
1952 }
1953
1954 const prop = this.startNode();
1955 let isGenerator = false;
1956 let isAsync = false;
1957 let isAccessor = false;
1958 let startPos;
1959 let startLoc;
1960
1961 if (this.match(tt.ellipsis)) {
1962 if (decorators.length) this.unexpected();
1963 if (isPattern) {
1964 this.next();
1965 // Don't use parseRestBinding() as we only allow Identifier here.
1966 prop.argument = this.parseIdentifier();
1967 this.checkCommaAfterRest(charCodes.rightCurlyBrace);
1968 return this.finishNode(prop, "RestElement");
1969 }
1970
1971 return this.parseSpread();
1972 }
1973
1974 if (decorators.length) {
1975 prop.decorators = decorators;
1976 decorators = [];
1977 }
1978
1979 prop.method = false;
1980
1981 if (isPattern || refExpressionErrors) {
1982 startPos = this.state.start;
1983 startLoc = this.state.startLoc;
1984 }
1985
1986 if (!isPattern) {
1987 isGenerator = this.eat(tt.star);
1988 }
1989
1990 const containsEsc = this.state.containsEsc;
1991 const key = this.parsePropertyName(prop, /* isPrivateNameAllowed */ false);
1992
1993 if (
1994 !isPattern &&
1995 !isGenerator &&
1996 !containsEsc &&
1997 this.maybeAsyncOrAccessorProp(prop)
1998 ) {
1999 const keyName = key.name;
2000 // https://tc39.es/ecma262/#prod-AsyncMethod
2001 // https://tc39.es/ecma262/#prod-AsyncGeneratorMethod
2002 if (keyName === "async" && !this.hasPrecedingLineBreak()) {
2003 isAsync = true;
2004 this.resetPreviousNodeTrailingComments(key);
2005 isGenerator = this.eat(tt.star);
2006 this.parsePropertyName(prop, /* isPrivateNameAllowed */ false);
2007 }
2008 // get PropertyName[?Yield, ?Await] () { FunctionBody[~Yield, ~Await] }
2009 // set PropertyName[?Yield, ?Await] ( PropertySetParameterList ) { FunctionBody[~Yield, ~Await] }
2010 if (keyName === "get" || keyName === "set") {
2011 isAccessor = true;
2012 this.resetPreviousNodeTrailingComments(key);
2013 prop.kind = keyName;
2014 if (this.match(tt.star)) {
2015 isGenerator = true;
2016 this.raise(this.state.pos, Errors.AccessorIsGenerator, keyName);
2017 this.next();
2018 }
2019 this.parsePropertyName(prop, /* isPrivateNameAllowed */ false);
2020 }
2021 }
2022
2023 this.parseObjPropValue(
2024 prop,
2025 startPos,
2026 startLoc,
2027 isGenerator,
2028 isAsync,
2029 isPattern,
2030 isAccessor,
2031 refExpressionErrors
2032 );
2033
2034 return prop;
2035 }
2036
2037 getGetterSetterExpectedParamCount(
2038 method: N.ObjectMethod | N.ClassMethod
2039 ): number {
2040 return method.kind === "get" ? 0 : 1;
2041 }
2042
2043 // This exists so we can override within the ESTree plugin
2044 getObjectOrClassMethodParams(method: N.ObjectMethod | N.ClassMethod) {
2045 return method.params;
2046 }
2047
2048 // get methods aren't allowed to have any parameters
2049 // set methods must have exactly 1 parameter which is not a rest parameter
2050 checkGetterSetterParams(method: N.ObjectMethod | N.ClassMethod): void {
2051 const paramCount = this.getGetterSetterExpectedParamCount(method);
2052 const params = this.getObjectOrClassMethodParams(method);
2053
2054 const start = method.start;
2055
2056 if (params.length !== paramCount) {
2057 if (method.kind === "get") {
2058 this.raise(start, Errors.BadGetterArity);
2059 } else {
2060 this.raise(start, Errors.BadSetterArity);
2061 }
2062 }
2063
2064 if (
2065 method.kind === "set" &&
2066 params[params.length - 1]?.type === "RestElement"
2067 ) {
2068 this.raise(start, Errors.BadSetterRestParameter);
2069 }
2070 }
2071
2072 // https://tc39.es/ecma262/#prod-MethodDefinition
2073 parseObjectMethod(
2074 prop: N.ObjectMethod,
2075 isGenerator: boolean,
2076 isAsync: boolean,
2077 isPattern: boolean,
2078 isAccessor: boolean
2079 ): ?N.ObjectMethod {
2080 if (isAccessor) {
2081 // isAccessor implies isAsync: false, isPattern: false, isGenerator: false
2082 this.parseMethod(
2083 prop,
2084 // This _should_ be false, but with error recovery, we allow it to be
2085 // set for informational purposes
2086 isGenerator,
2087 /* isAsync */ false,
2088 /* isConstructor */ false,
2089 false,
2090 "ObjectMethod"
2091 );
2092 this.checkGetterSetterParams(prop);
2093 return prop;
2094 }
2095
2096 if (isAsync || isGenerator || this.match(tt.parenL)) {
2097 if (isPattern) this.unexpected();
2098 prop.kind = "method";
2099 prop.method = true;
2100 return this.parseMethod(
2101 prop,
2102 isGenerator,
2103 isAsync,
2104 /* isConstructor */ false,
2105 false,
2106 "ObjectMethod"
2107 );
2108 }
2109 }
2110
2111 // if `isPattern` is true, parse https://tc39.es/ecma262/#prod-BindingProperty
2112 // else https://tc39.es/ecma262/#prod-PropertyDefinition
2113 parseObjectProperty(
2114 prop: N.ObjectProperty,
2115 startPos: ?number,
2116 startLoc: ?Position,
2117 isPattern: boolean,
2118 refExpressionErrors: ?ExpressionErrors
2119 ): ?N.ObjectProperty {
2120 prop.shorthand = false;
2121
2122 if (this.eat(tt.colon)) {
2123 prop.value = isPattern
2124 ? this.parseMaybeDefault(this.state.start, this.state.startLoc)
2125 : this.parseMaybeAssignAllowIn(refExpressionErrors);
2126
2127 return this.finishNode(prop, "ObjectProperty");
2128 }
2129
2130 if (!prop.computed && prop.key.type === "Identifier") {
2131 // PropertyDefinition:
2132 // IdentifierReference
2133 // CoveredInitializedName
2134 // Note: `{ eval } = {}` will be checked in `checkLVal` later.
2135 this.checkReservedWord(prop.key.name, prop.key.start, true, false);
2136
2137 if (isPattern) {
2138 prop.value = this.parseMaybeDefault(
2139 startPos,
2140 startLoc,
2141 cloneIdentifier(prop.key)
2142 );
2143 } else if (this.match(tt.eq) && refExpressionErrors) {
2144 if (refExpressionErrors.shorthandAssign === -1) {
2145 refExpressionErrors.shorthandAssign = this.state.start;
2146 }
2147 prop.value = this.parseMaybeDefault(
2148 startPos,
2149 startLoc,
2150 cloneIdentifier(prop.key)
2151 );
2152 } else {
2153 prop.value = cloneIdentifier(prop.key);
2154 }
2155 prop.shorthand = true;
2156
2157 return this.finishNode(prop, "ObjectProperty");
2158 }
2159 }
2160
2161 parseObjPropValue(
2162 prop: any,
2163 startPos: ?number,
2164 startLoc: ?Position,
2165 isGenerator: boolean,
2166 isAsync: boolean,
2167 isPattern: boolean,
2168 isAccessor: boolean,
2169 refExpressionErrors?: ?ExpressionErrors
2170 ): void {
2171 const node =
2172 this.parseObjectMethod(
2173 prop,
2174 isGenerator,
2175 isAsync,
2176 isPattern,
2177 isAccessor
2178 ) ||
2179 this.parseObjectProperty(
2180 prop,
2181 startPos,
2182 startLoc,
2183 isPattern,
2184 refExpressionErrors
2185 );
2186
2187 if (!node) this.unexpected();
2188
2189 // $FlowFixMe
2190 return node;
2191 }
2192
2193 parsePropertyName(
2194 prop: N.ObjectOrClassMember | N.ClassMember | N.TsNamedTypeElementBase,
2195 isPrivateNameAllowed: boolean
2196 ): N.Expression | N.Identifier {
2197 if (this.eat(tt.bracketL)) {
2198 (prop: $FlowSubtype<N.ObjectOrClassMember>).computed = true;
2199 prop.key = this.parseMaybeAssignAllowIn();
2200 this.expect(tt.bracketR);
2201 } else {
2202 const oldInPropertyName = this.state.inPropertyName;
2203 this.state.inPropertyName = true;
2204 // We check if it's valid for it to be a private name when we push it.
2205 const type = this.state.type;
2206 (prop: $FlowFixMe).key =
2207 type === tt.num ||
2208 type === tt.string ||
2209 type === tt.bigint ||
2210 type === tt.decimal
2211 ? this.parseExprAtom()
2212 : this.parseMaybePrivateName(isPrivateNameAllowed);
2213
2214 if (type !== tt.privateName) {
2215 // ClassPrivateProperty is never computed, so we don't assign in that case.
2216 prop.computed = false;
2217 }
2218
2219 this.state.inPropertyName = oldInPropertyName;
2220 }
2221
2222 return prop.key;
2223 }
2224
2225 // Initialize empty function node.
2226
2227 initFunction(node: N.BodilessFunctionOrMethodBase, isAsync: ?boolean): void {
2228 node.id = null;
2229 node.generator = false;
2230 node.async = !!isAsync;
2231 }
2232
2233 // Parse object or class method.
2234
2235 parseMethod<T: N.MethodLike>(
2236 node: T,
2237 isGenerator: boolean,
2238 isAsync: boolean,
2239 isConstructor: boolean,
2240 allowDirectSuper: boolean,
2241 type: string,
2242 inClassScope: boolean = false
2243 ): T {
2244 this.initFunction(node, isAsync);
2245 node.generator = !!isGenerator;
2246 const allowModifiers = isConstructor; // For TypeScript parameter properties
2247 this.scope.enter(
2248 SCOPE_FUNCTION |
2249 SCOPE_SUPER |
2250 (inClassScope ? SCOPE_CLASS : 0) |
2251 (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)
2252 );
2253 this.prodParam.enter(functionFlags(isAsync, node.generator));
2254 this.parseFunctionParams((node: any), allowModifiers);
2255 this.parseFunctionBodyAndFinish(node, type, true);
2256 this.prodParam.exit();
2257 this.scope.exit();
2258
2259 return node;
2260 }
2261
2262 // parse an array literal or tuple literal
2263 // https://tc39.es/ecma262/#prod-ArrayLiteral
2264 // https://tc39.es/proposal-record-tuple/#prod-TupleLiteral
2265 parseArrayLike(
2266 close: TokenType,
2267 canBePattern: boolean,
2268 isTuple: boolean,
2269 refExpressionErrors: ?ExpressionErrors
2270 ): N.ArrayExpression | N.TupleExpression {
2271 if (isTuple) {
2272 this.expectPlugin("recordAndTuple");
2273 }
2274 const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
2275 this.state.inFSharpPipelineDirectBody = false;
2276 const node = this.startNode();
2277 this.next();
2278 node.elements = this.parseExprList(
2279 close,
2280 /* allowEmpty */ !isTuple,
2281 refExpressionErrors,
2282 node
2283 );
2284 this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
2285 return this.finishNode(
2286 node,
2287 isTuple ? "TupleExpression" : "ArrayExpression"
2288 );
2289 }
2290
2291 // Parse arrow function expression.
2292 // If the parameters are provided, they will be converted to an
2293 // assignable list.
2294 parseArrowExpression(
2295 node: N.ArrowFunctionExpression,
2296 params: ?(N.Expression[]),
2297 isAsync: boolean,
2298 trailingCommaPos: ?number
2299 ): N.ArrowFunctionExpression {
2300 this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
2301 let flags = functionFlags(isAsync, false);
2302 // ConciseBody and AsyncConciseBody inherit [In]
2303 if (!this.match(tt.bracketL) && this.prodParam.hasIn) {
2304 flags |= PARAM_IN;
2305 }
2306 this.prodParam.enter(flags);
2307 this.initFunction(node, isAsync);
2308 const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
2309
2310 if (params) {
2311 this.state.maybeInArrowParameters = true;
2312 this.setArrowFunctionParameters(node, params, trailingCommaPos);
2313 }
2314 this.state.maybeInArrowParameters = false;
2315 this.parseFunctionBody(node, true);
2316
2317 this.prodParam.exit();
2318 this.scope.exit();
2319 this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
2320
2321 return this.finishNode(node, "ArrowFunctionExpression");
2322 }
2323
2324 setArrowFunctionParameters(
2325 node: N.ArrowFunctionExpression,
2326 params: N.Expression[],
2327 trailingCommaPos: ?number
2328 ): void {
2329 node.params = this.toAssignableList(params, trailingCommaPos, false);
2330 }
2331
2332 parseFunctionBodyAndFinish(
2333 node: N.BodilessFunctionOrMethodBase,
2334 type: string,
2335 isMethod?: boolean = false
2336 ): void {
2337 // $FlowIgnore (node is not bodiless if we get here)
2338 this.parseFunctionBody(node, false, isMethod);
2339 this.finishNode(node, type);
2340 }
2341
2342 // Parse function body and check parameters.
2343 parseFunctionBody(
2344 node: N.Function,
2345 allowExpression: ?boolean,
2346 isMethod?: boolean = false
2347 ): void {
2348 const isExpression = allowExpression && !this.match(tt.braceL);
2349 this.expressionScope.enter(newExpressionScope());
2350
2351 if (isExpression) {
2352 // https://tc39.es/ecma262/#prod-ExpressionBody
2353 node.body = this.parseMaybeAssign();
2354 this.checkParams(node, false, allowExpression, false);
2355 } else {
2356 const oldStrict = this.state.strict;
2357 // Start a new scope with regard to labels
2358 // flag (restore them to their old value afterwards).
2359 const oldLabels = this.state.labels;
2360 this.state.labels = [];
2361
2362 // FunctionBody[Yield, Await]:
2363 // StatementList[?Yield, ?Await, +Return] opt
2364 this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN);
2365 node.body = this.parseBlock(
2366 true,
2367 false,
2368 // Strict mode function checks after we parse the statements in the function body.
2369 (hasStrictModeDirective: boolean) => {
2370 const nonSimple = !this.isSimpleParamList(node.params);
2371
2372 if (hasStrictModeDirective && nonSimple) {
2373 // This logic is here to align the error location with the ESTree plugin.
2374 const errorPos =
2375 // $FlowIgnore
2376 (node.kind === "method" || node.kind === "constructor") &&
2377 // $FlowIgnore
2378 !!node.key
2379 ? node.key.end
2380 : node.start;
2381 this.raise(errorPos, Errors.IllegalLanguageModeDirective);
2382 }
2383
2384 const strictModeChanged = !oldStrict && this.state.strict;
2385
2386 // Add the params to varDeclaredNames to ensure that an error is thrown
2387 // if a let/const declaration in the function clashes with one of the params.
2388 this.checkParams(
2389 node,
2390 !this.state.strict && !allowExpression && !isMethod && !nonSimple,
2391 allowExpression,
2392 strictModeChanged
2393 );
2394
2395 // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
2396 if (this.state.strict && node.id) {
2397 this.checkLVal(
2398 node.id,
2399 "function name",
2400 BIND_OUTSIDE,
2401 undefined,
2402 undefined,
2403 strictModeChanged
2404 );
2405 }
2406 }
2407 );
2408 this.prodParam.exit();
2409 this.expressionScope.exit();
2410 this.state.labels = oldLabels;
2411 }
2412 }
2413
2414 isSimpleParamList(
2415 params: $ReadOnlyArray<N.Pattern | N.TSParameterProperty>
2416 ): boolean {
2417 for (let i = 0, len = params.length; i < len; i++) {
2418 if (params[i].type !== "Identifier") return false;
2419 }
2420 return true;
2421 }
2422
2423 checkParams(
2424 node: N.Function,
2425 allowDuplicates: boolean,
2426 // eslint-disable-next-line no-unused-vars
2427 isArrowFunction: ?boolean,
2428 strictModeChanged?: boolean = true
2429 ): void {
2430 const checkClashes = new Set();
2431 for (const param of node.params) {
2432 this.checkLVal(
2433 param,
2434 "function parameter list",
2435 BIND_VAR,
2436 allowDuplicates ? null : checkClashes,
2437 undefined,
2438 strictModeChanged
2439 );
2440 }
2441 }
2442
2443 // Parses a comma-separated list of expressions, and returns them as
2444 // an array. `close` is the token type that ends the list, and
2445 // `allowEmpty` can be turned on to allow subsequent commas with
2446 // nothing in between them to be parsed as `null` (which is needed
2447 // for array literals).
2448
2449 parseExprList(
2450 close: TokenType,
2451 allowEmpty?: boolean,
2452 refExpressionErrors?: ?ExpressionErrors,
2453 nodeForExtra?: ?N.Node
2454 ): $ReadOnlyArray<?N.Expression> {
2455 const elts = [];
2456 let first = true;
2457
2458 while (!this.eat(close)) {
2459 if (first) {
2460 first = false;
2461 } else {
2462 this.expect(tt.comma);
2463 if (this.match(close)) {
2464 if (nodeForExtra) {
2465 this.addExtra(
2466 nodeForExtra,
2467 "trailingComma",
2468 this.state.lastTokStart
2469 );
2470 }
2471 this.next();
2472 break;
2473 }
2474 }
2475
2476 elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
2477 }
2478 return elts;
2479 }
2480
2481 parseExprListItem(
2482 allowEmpty: ?boolean,
2483 refExpressionErrors?: ?ExpressionErrors,
2484 allowPlaceholder: ?boolean
2485 ): ?N.Expression {
2486 let elt;
2487 if (this.match(tt.comma)) {
2488 if (!allowEmpty) {
2489 this.raise(this.state.pos, Errors.UnexpectedToken, ",");
2490 }
2491 elt = null;
2492 } else if (this.match(tt.ellipsis)) {
2493 const spreadNodeStartPos = this.state.start;
2494 const spreadNodeStartLoc = this.state.startLoc;
2495
2496 elt = this.parseParenItem(
2497 this.parseSpread(refExpressionErrors),
2498 spreadNodeStartPos,
2499 spreadNodeStartLoc
2500 );
2501 } else if (this.match(tt.question)) {
2502 this.expectPlugin("partialApplication");
2503 if (!allowPlaceholder) {
2504 this.raise(this.state.start, Errors.UnexpectedArgumentPlaceholder);
2505 }
2506 const node = this.startNode();
2507 this.next();
2508 elt = this.finishNode(node, "ArgumentPlaceholder");
2509 } else {
2510 elt = this.parseMaybeAssignAllowIn(
2511 refExpressionErrors,
2512 this.parseParenItem
2513 );
2514 }
2515 return elt;
2516 }
2517
2518 // Parse the next token as an identifier. If `liberal` is true (used
2519 // when parsing properties), it will also convert keywords into
2520 // identifiers.
2521 // This shouldn't be used to parse the keywords of meta properties, since they
2522 // are not identifiers and cannot contain escape sequences.
2523
2524 parseIdentifier(liberal?: boolean): N.Identifier {
2525 const node = this.startNode();
2526 const name = this.parseIdentifierName(node.start, liberal);
2527
2528 return this.createIdentifier(node, name);
2529 }
2530
2531 createIdentifier(node: N.Identifier, name: string): N.Identifier {
2532 node.name = name;
2533 node.loc.identifierName = name;
2534
2535 return this.finishNode(node, "Identifier");
2536 }
2537
2538 parseIdentifierName(pos: number, liberal?: boolean): string {
2539 let name: string;
2540
2541 const { start, type } = this.state;
2542
2543 if (tokenIsKeywordOrIdentifier(type)) {
2544 name = this.state.value;
2545 } else {
2546 throw this.unexpected();
2547 }
2548
2549 if (liberal) {
2550 // If the current token is not used as a keyword, set its type to "tt.name".
2551 // This will prevent this.next() from throwing about unexpected escapes.
2552 this.state.type = tt.name;
2553 } else {
2554 this.checkReservedWord(name, start, tokenIsKeyword(type), false);
2555 }
2556
2557 this.next();
2558
2559 return name;
2560 }
2561
2562 checkReservedWord(
2563 word: string,
2564 startLoc: number,
2565 checkKeywords: boolean,
2566 isBinding: boolean
2567 ): void {
2568 // Every JavaScript reserved word is 10 characters or less.
2569 if (word.length > 10) {
2570 return;
2571 }
2572 // Most identifiers are not reservedWord-like, they don't need special
2573 // treatments afterward, which very likely ends up throwing errors
2574 if (!canBeReservedWord(word)) {
2575 return;
2576 }
2577
2578 if (word === "yield") {
2579 if (this.prodParam.hasYield) {
2580 this.raise(startLoc, Errors.YieldBindingIdentifier);
2581 return;
2582 }
2583 } else if (word === "await") {
2584 if (this.prodParam.hasAwait) {
2585 this.raise(startLoc, Errors.AwaitBindingIdentifier);
2586 return;
2587 } else if (this.scope.inStaticBlock) {
2588 this.raise(startLoc, Errors.AwaitBindingIdentifierInStaticBlock);
2589 return;
2590 } else {
2591 this.expressionScope.recordAsyncArrowParametersError(
2592 startLoc,
2593 Errors.AwaitBindingIdentifier
2594 );
2595 }
2596 } else if (word === "arguments") {
2597 if (this.scope.inClassAndNotInNonArrowFunction) {
2598 this.raise(startLoc, Errors.ArgumentsInClass);
2599 return;
2600 }
2601 }
2602
2603 if (checkKeywords && isKeyword(word)) {
2604 this.raise(startLoc, Errors.UnexpectedKeyword, word);
2605 return;
2606 }
2607
2608 const reservedTest = !this.state.strict
2609 ? isReservedWord
2610 : isBinding
2611 ? isStrictBindReservedWord
2612 : isStrictReservedWord;
2613
2614 if (reservedTest(word, this.inModule)) {
2615 this.raise(startLoc, Errors.UnexpectedReservedWord, word);
2616 }
2617 }
2618
2619 isAwaitAllowed(): boolean {
2620 if (this.prodParam.hasAwait) return true;
2621 if (this.options.allowAwaitOutsideFunction && !this.scope.inFunction) {
2622 return true;
2623 }
2624 return false;
2625 }
2626
2627 // Parses await expression inside async function.
2628
2629 parseAwait(startPos: number, startLoc: Position): N.AwaitExpression {
2630 const node = this.startNodeAt(startPos, startLoc);
2631
2632 this.expressionScope.recordParameterInitializerError(
2633 node.start,
2634 Errors.AwaitExpressionFormalParameter
2635 );
2636
2637 if (this.eat(tt.star)) {
2638 this.raise(node.start, Errors.ObsoleteAwaitStar);
2639 }
2640
2641 if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
2642 if (this.isAmbiguousAwait()) {
2643 this.ambiguousScriptDifferentAst = true;
2644 } else {
2645 this.sawUnambiguousESM = true;
2646 }
2647 }
2648
2649 if (!this.state.soloAwait) {
2650 node.argument = this.parseMaybeUnary(null, true);
2651 }
2652
2653 return this.finishNode(node, "AwaitExpression");
2654 }
2655
2656 isAmbiguousAwait(): boolean {
2657 return (
2658 this.hasPrecedingLineBreak() ||
2659 // All the following expressions are ambiguous:
2660 // await + 0, await - 0, await ( 0 ), await [ 0 ], await / 0 /u, await ``
2661 this.match(tt.plusMin) ||
2662 this.match(tt.parenL) ||
2663 this.match(tt.bracketL) ||
2664 this.match(tt.backQuote) ||
2665 // Sometimes the tokenizer generates tt.slash for regexps, and this is
2666 // handler by parseExprAtom
2667 this.match(tt.regexp) ||
2668 this.match(tt.slash) ||
2669 // This code could be parsed both as a modulo operator or as an intrinsic:
2670 // await %x(0)
2671 (this.hasPlugin("v8intrinsic") && this.match(tt.modulo))
2672 );
2673 }
2674
2675 // Parses yield expression inside generator.
2676
2677 parseYield(): N.YieldExpression {
2678 const node = this.startNode();
2679
2680 this.expressionScope.recordParameterInitializerError(
2681 node.start,
2682 Errors.YieldInParameter
2683 );
2684
2685 this.next();
2686 let delegating = false;
2687 let argument = null;
2688 if (!this.hasPrecedingLineBreak()) {
2689 delegating = this.eat(tt.star);
2690 switch (this.state.type) {
2691 case tt.semi:
2692 case tt.eof:
2693 case tt.braceR:
2694 case tt.parenR:
2695 case tt.bracketR:
2696 case tt.braceBarR:
2697 case tt.colon:
2698 case tt.comma:
2699 // The above is the complete set of tokens that can
2700 // follow an AssignmentExpression, and none of them
2701 // can start an AssignmentExpression
2702 if (!delegating) break;
2703 /* fallthrough */
2704 default:
2705 argument = this.parseMaybeAssign();
2706 }
2707 }
2708 node.delegate = delegating;
2709 node.argument = argument;
2710 return this.finishNode(node, "YieldExpression");
2711 }
2712
2713 // Validates a pipeline (for any of the pipeline Babylon plugins) at the point
2714 // of the infix operator `|>`.
2715
2716 checkPipelineAtInfixOperator(left: N.Expression, leftStartPos: number) {
2717 if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
2718 if (left.type === "SequenceExpression") {
2719 // Ensure that the pipeline head is not a comma-delimited
2720 // sequence expression.
2721 this.raise(leftStartPos, Errors.PipelineHeadSequenceExpression);
2722 }
2723 }
2724 }
2725
2726 // This helper method is to be called immediately
2727 // after a Hack-style pipe body is parsed.
2728 // The `startPos` is the starting position of the pipe body.
2729
2730 checkHackPipeBodyEarlyErrors(startPos: number): void {
2731 if (!this.topicReferenceWasUsedInCurrentContext()) {
2732 // A Hack pipe body must use the topic reference at least once.
2733 this.raise(startPos, Errors.PipeTopicUnused);
2734 }
2735 }
2736
2737 parseSmartPipelineBodyInStyle(
2738 childExpr: N.Expression,
2739 startPos: number,
2740 startLoc: Position
2741 ): N.PipelineBody {
2742 const bodyNode = this.startNodeAt(startPos, startLoc);
2743 if (this.isSimpleReference(childExpr)) {
2744 bodyNode.callee = childExpr;
2745 return this.finishNode(bodyNode, "PipelineBareFunction");
2746 } else {
2747 this.checkSmartPipeTopicBodyEarlyErrors(startPos);
2748 bodyNode.expression = childExpr;
2749 return this.finishNode(bodyNode, "PipelineTopicExpression");
2750 }
2751 }
2752
2753 isSimpleReference(expression: N.Expression): boolean {
2754 switch (expression.type) {
2755 case "MemberExpression":
2756 return (
2757 !expression.computed && this.isSimpleReference(expression.object)
2758 );
2759 case "Identifier":
2760 return true;
2761 default:
2762 return false;
2763 }
2764 }
2765
2766 // This helper method is to be called immediately
2767 // after a topic-style smart-mix pipe body is parsed.
2768 // The `startPos` is the starting position of the pipe body.
2769
2770 checkSmartPipeTopicBodyEarlyErrors(startPos: number): void {
2771 // If the following token is invalidly `=>`, then throw a human-friendly error
2772 // instead of something like 'Unexpected token, expected ";"'.
2773 // For example, `x => x |> y => #` (assuming `#` is the topic reference)
2774 // groups into `x => (x |> y) => #`,
2775 // and `(x |> y) => #` is an invalid arrow function.
2776 // This is because smart-mix `|>` has tighter precedence than `=>`.
2777 if (this.match(tt.arrow)) {
2778 throw this.raise(this.state.start, Errors.PipelineBodyNoArrow);
2779 }
2780
2781 // A topic-style smart-mix pipe body must use the topic reference at least once.
2782 else if (!this.topicReferenceWasUsedInCurrentContext()) {
2783 this.raise(startPos, Errors.PipelineTopicUnused);
2784 }
2785 }
2786
2787 // Enable topic references from outer contexts within Hack-style pipe bodies.
2788 // The function modifies the parser's topic-context state to enable or disable
2789 // the use of topic references.
2790 // The function then calls a callback, then resets the parser
2791 // to the old topic-context state that it had before the function was called.
2792
2793 withTopicBindingContext<T>(callback: () => T): T {
2794 const outerContextTopicState = this.state.topicContext;
2795 this.state.topicContext = {
2796 // Enable the use of the primary topic reference.
2797 maxNumOfResolvableTopics: 1,
2798 // Hide the use of any topic references from outer contexts.
2799 maxTopicIndex: null,
2800 };
2801
2802 try {
2803 return callback();
2804 } finally {
2805 this.state.topicContext = outerContextTopicState;
2806 }
2807 }
2808
2809 // This helper method is used only with the deprecated smart-mix pipe proposal.
2810 // Disables topic references from outer contexts within syntax constructs
2811 // such as the bodies of iteration statements.
2812 // The function modifies the parser's topic-context state to enable or disable
2813 // the use of topic references with the smartPipelines plugin. They then run a
2814 // callback, then they reset the parser to the old topic-context state that it
2815 // had before the function was called.
2816
2817 withSmartMixTopicForbiddingContext<T>(callback: () => T): T {
2818 const proposal = this.getPluginOption("pipelineOperator", "proposal");
2819 if (proposal === "smart") {
2820 // Reset the parser’s topic context only if the smart-mix pipe proposal is active.
2821 const outerContextTopicState = this.state.topicContext;
2822 this.state.topicContext = {
2823 // Disable the use of the primary topic reference.
2824 maxNumOfResolvableTopics: 0,
2825 // Hide the use of any topic references from outer contexts.
2826 maxTopicIndex: null,
2827 };
2828
2829 try {
2830 return callback();
2831 } finally {
2832 this.state.topicContext = outerContextTopicState;
2833 }
2834 } else {
2835 // If the pipe proposal is "minimal", "fsharp", or "hack",
2836 // or if no pipe proposal is active,
2837 // then the callback result is returned
2838 // without touching any extra parser state.
2839 return callback();
2840 }
2841 }
2842
2843 withSoloAwaitPermittingContext<T>(callback: () => T): T {
2844 const outerContextSoloAwaitState = this.state.soloAwait;
2845 this.state.soloAwait = true;
2846
2847 try {
2848 return callback();
2849 } finally {
2850 this.state.soloAwait = outerContextSoloAwaitState;
2851 }
2852 }
2853
2854 allowInAnd<T>(callback: () => T): T {
2855 const flags = this.prodParam.currentFlags();
2856 const prodParamToSet = PARAM_IN & ~flags;
2857 if (prodParamToSet) {
2858 this.prodParam.enter(flags | PARAM_IN);
2859 try {
2860 return callback();
2861 } finally {
2862 this.prodParam.exit();
2863 }
2864 }
2865 return callback();
2866 }
2867
2868 disallowInAnd<T>(callback: () => T): T {
2869 const flags = this.prodParam.currentFlags();
2870 const prodParamToClear = PARAM_IN & flags;
2871 if (prodParamToClear) {
2872 this.prodParam.enter(flags & ~PARAM_IN);
2873 try {
2874 return callback();
2875 } finally {
2876 this.prodParam.exit();
2877 }
2878 }
2879 return callback();
2880 }
2881
2882 // Register the use of a topic reference within the current
2883 // topic-binding context.
2884 registerTopicReference(): void {
2885 this.state.topicContext.maxTopicIndex = 0;
2886 }
2887
2888 topicReferenceIsAllowedInCurrentContext(): boolean {
2889 return this.state.topicContext.maxNumOfResolvableTopics >= 1;
2890 }
2891
2892 topicReferenceWasUsedInCurrentContext(): boolean {
2893 return (
2894 this.state.topicContext.maxTopicIndex != null &&
2895 this.state.topicContext.maxTopicIndex >= 0
2896 );
2897 }
2898
2899 parseFSharpPipelineBody(prec: number): N.Expression {
2900 const startPos = this.state.start;
2901 const startLoc = this.state.startLoc;
2902
2903 this.state.potentialArrowAt = this.state.start;
2904 const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
2905 this.state.inFSharpPipelineDirectBody = true;
2906
2907 const ret = this.parseExprOp(
2908 this.parseMaybeUnaryOrPrivate(),
2909 startPos,
2910 startLoc,
2911 prec
2912 );
2913
2914 this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
2915
2916 return ret;
2917 }
2918
2919 // https://github.com/tc39/proposal-js-module-blocks
2920 parseModuleExpression(): N.ModuleExpression {
2921 this.expectPlugin("moduleBlocks");
2922 const node = this.startNode<N.ModuleExpression>();
2923 this.next(); // eat "module"
2924 this.eat(tt.braceL);
2925
2926 const revertScopes = this.initializeScopes(/** inModule */ true);
2927 this.enterInitialScopes();
2928
2929 const program = this.startNode<N.Program>();
2930 try {
2931 node.body = this.parseProgram(program, tt.braceR, "module");
2932 } finally {
2933 revertScopes();
2934 }
2935 this.eat(tt.braceR);
2936 return this.finishNode<N.ModuleExpression>(node, "ModuleExpression");
2937 }
2938 }