UNPKG

26.1 kBJavaScriptView Raw
1/* eslint max-len: 0 */
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
21import {
22 flowParseArrow,
23 flowParseFunctionBodyAndFinish,
24 flowParseMaybeAssign,
25 flowParseSubscript,
26 flowParseSubscripts,
27 flowParseVariance,
28 flowStartParseAsyncArrowFromCallExpression,
29 flowStartParseNewArguments,
30 flowStartParseObjPropValue,
31} from "../plugins/flow";
32import {jsxParseElement} from "../plugins/jsx/index";
33import {typedParseConditional, typedParseParenItem} from "../plugins/types";
34import {
35 tsParseArrow,
36 tsParseFunctionBodyAndFinish,
37 tsParseMaybeAssign,
38 tsParseSubscript,
39 tsParseType,
40 tsParseTypeAssertion,
41 tsStartParseAsyncArrowFromCallExpression,
42 tsStartParseNewArguments,
43 tsStartParseObjPropValue,
44} from "../plugins/typescript";
45import {
46 eat,
47 IdentifierRole,
48 lookaheadType,
49 match,
50 next,
51 nextTemplateToken,
52 popTypeContext,
53 pushTypeContext,
54 retokenizeSlashAsRegex,
55} from "../tokenizer/index";
56import {ContextualKeyword} from "../tokenizer/keywords";
57import {Scope} from "../tokenizer/state";
58import {TokenType, TokenType as tt} from "../tokenizer/types";
59import {getNextContextId, isFlowEnabled, isJSXEnabled, isTypeScriptEnabled, state} from "./base";
60import {
61 markPriorBindingIdentifier,
62 parseBindingIdentifier,
63 parseMaybeDefault,
64 parseRest,
65 parseSpread,
66} from "./lval";
67import {
68 parseBlock,
69 parseClass,
70 parseDecorators,
71 parseFunction,
72 parseFunctionParams,
73} from "./statement";
74import {
75 canInsertSemicolon,
76 eatContextual,
77 expect,
78 hasPrecedingLineBreak,
79 isContextual,
80 unexpected,
81} from "./util";
82
83export class StopState {
84
85 constructor(stop) {
86 this.stop = stop;
87 }
88}
89
90// ### Expression parsing
91
92// These nest, from the most general expression type at the top to
93// 'atomic', nondivisible expression types at the bottom. Most of
94// the functions will simply let the function (s) below them parse,
95// and, *if* the syntactic construct they handle is present, wrap
96// the AST node that the inner parser gave them in another node.
97export function parseExpression(noIn = false) {
98 parseMaybeAssign(noIn);
99 if (match(tt.comma)) {
100 while (eat(tt.comma)) {
101 parseMaybeAssign(noIn);
102 }
103 }
104}
105
106/**
107 * noIn is used when parsing a for loop so that we don't interpret a following "in" as the binary
108 * operatior.
109 * isWithinParens is used to indicate that we're parsing something that might be a comma expression
110 * or might be an arrow function or might be a Flow type assertion (which requires explicit parens).
111 * In these cases, we should allow : and ?: after the initial "left" part.
112 */
113export function parseMaybeAssign(noIn = false, isWithinParens = false) {
114 if (isTypeScriptEnabled) {
115 return tsParseMaybeAssign(noIn, isWithinParens);
116 } else if (isFlowEnabled) {
117 return flowParseMaybeAssign(noIn, isWithinParens);
118 } else {
119 return baseParseMaybeAssign(noIn, isWithinParens);
120 }
121}
122
123// Parse an assignment expression. This includes applications of
124// operators like `+=`.
125// Returns true if the expression was an arrow function.
126export function baseParseMaybeAssign(noIn, isWithinParens) {
127 if (match(tt._yield)) {
128 parseYield();
129 return false;
130 }
131
132 if (match(tt.parenL) || match(tt.name) || match(tt._yield)) {
133 state.potentialArrowAt = state.start;
134 }
135
136 const wasArrow = parseMaybeConditional(noIn);
137 if (isWithinParens) {
138 parseParenItem();
139 }
140 if (state.type & TokenType.IS_ASSIGN) {
141 next();
142 parseMaybeAssign(noIn);
143 return false;
144 }
145 return wasArrow;
146}
147
148// Parse a ternary conditional (`?:`) operator.
149// Returns true if the expression was an arrow function.
150function parseMaybeConditional(noIn) {
151 const wasArrow = parseExprOps(noIn);
152 if (wasArrow) {
153 return true;
154 }
155 parseConditional(noIn);
156 return false;
157}
158
159function parseConditional(noIn) {
160 if (isTypeScriptEnabled || isFlowEnabled) {
161 typedParseConditional(noIn);
162 } else {
163 baseParseConditional(noIn);
164 }
165}
166
167export function baseParseConditional(noIn) {
168 if (eat(tt.question)) {
169 parseMaybeAssign();
170 expect(tt.colon);
171 parseMaybeAssign(noIn);
172 }
173}
174
175// Start the precedence parser.
176// Returns true if this was an arrow function
177function parseExprOps(noIn) {
178 const wasArrow = parseMaybeUnary();
179 if (wasArrow) {
180 return true;
181 }
182 parseExprOp(-1, noIn);
183 return false;
184}
185
186// Parse binary operators with the operator precedence parsing
187// algorithm. `left` is the left-hand side of the operator.
188// `minPrec` provides context that allows the function to stop and
189// defer further parser to one of its callers when it encounters an
190// operator that has a lower precedence than the set it is parsing.
191function parseExprOp(minPrec, noIn) {
192 if (
193 isTypeScriptEnabled &&
194 (tt._in & TokenType.PRECEDENCE_MASK) > minPrec &&
195 !hasPrecedingLineBreak() &&
196 eatContextual(ContextualKeyword._as)
197 ) {
198 state.tokens[state.tokens.length - 1].type = tt._as;
199 const oldIsType = pushTypeContext(1);
200 tsParseType();
201 popTypeContext(oldIsType);
202 parseExprOp(minPrec, noIn);
203 return;
204 }
205
206 const prec = state.type & TokenType.PRECEDENCE_MASK;
207 if (prec > 0 && (!noIn || !match(tt._in))) {
208 if (prec > minPrec) {
209 const op = state.type;
210 next();
211
212 parseMaybeUnary();
213 parseExprOp(op & TokenType.IS_RIGHT_ASSOCIATIVE ? prec - 1 : prec, noIn);
214 parseExprOp(minPrec, noIn);
215 }
216 }
217}
218
219// Parse unary operators, both prefix and postfix.
220// Returns true if this was an arrow function.
221export function parseMaybeUnary() {
222 if (isTypeScriptEnabled && !isJSXEnabled && eat(tt.lessThan)) {
223 tsParseTypeAssertion();
224 return false;
225 }
226
227 if (state.type & TokenType.IS_PREFIX) {
228 next();
229 parseMaybeUnary();
230 return false;
231 }
232
233 const wasArrow = parseExprSubscripts();
234 if (wasArrow) {
235 return true;
236 }
237 while (state.type & TokenType.IS_POSTFIX && !canInsertSemicolon()) {
238 // The tokenizer calls everything a preincrement, so make it a postincrement when
239 // we see it in that context.
240 if (state.type === tt.preIncDec) {
241 state.type = tt.postIncDec;
242 }
243 next();
244 }
245 return false;
246}
247
248// Parse call, dot, and `[]`-subscript expressions.
249// Returns true if this was an arrow function.
250export function parseExprSubscripts() {
251 const startPos = state.start;
252 const wasArrow = parseExprAtom();
253 if (wasArrow) {
254 return true;
255 }
256 parseSubscripts(startPos);
257 return false;
258}
259
260function parseSubscripts(startPos, noCalls = false) {
261 if (isFlowEnabled) {
262 flowParseSubscripts(startPos, noCalls);
263 } else {
264 baseParseSubscripts(startPos, noCalls);
265 }
266}
267
268export function baseParseSubscripts(startPos, noCalls = false) {
269 const stopState = new StopState(false);
270 do {
271 parseSubscript(startPos, noCalls, stopState);
272 } while (!stopState.stop && !state.error);
273}
274
275function parseSubscript(startPos, noCalls, stopState) {
276 if (isTypeScriptEnabled) {
277 tsParseSubscript(startPos, noCalls, stopState);
278 } else if (isFlowEnabled) {
279 flowParseSubscript(startPos, noCalls, stopState);
280 } else {
281 baseParseSubscript(startPos, noCalls, stopState);
282 }
283}
284
285/** Set 'state.stop = true' to indicate that we should stop parsing subscripts. */
286export function baseParseSubscript(startPos, noCalls, stopState) {
287 if (!noCalls && eat(tt.doubleColon)) {
288 parseNoCallExpr();
289 stopState.stop = true;
290 parseSubscripts(startPos, noCalls);
291 } else if (match(tt.questionDot)) {
292 if (noCalls && lookaheadType() === tt.parenL) {
293 stopState.stop = true;
294 return;
295 }
296 next();
297
298 if (eat(tt.bracketL)) {
299 parseExpression();
300 expect(tt.bracketR);
301 } else if (eat(tt.parenL)) {
302 parseCallExpressionArguments();
303 } else {
304 parseIdentifier();
305 }
306 } else if (eat(tt.dot)) {
307 parseMaybePrivateName();
308 } else if (eat(tt.bracketL)) {
309 parseExpression();
310 expect(tt.bracketR);
311 } else if (!noCalls && match(tt.parenL)) {
312 if (atPossibleAsync()) {
313 // We see "async", but it's possible it's a usage of the name "async". Parse as if it's a
314 // function call, and if we see an arrow later, backtrack and re-parse as a parameter list.
315 const snapshot = state.snapshot();
316 const startTokenIndex = state.tokens.length;
317 next();
318
319 const callContextId = getNextContextId();
320
321 state.tokens[state.tokens.length - 1].contextId = callContextId;
322 parseCallExpressionArguments();
323 state.tokens[state.tokens.length - 1].contextId = callContextId;
324
325 if (shouldParseAsyncArrow()) {
326 // We hit an arrow, so backtrack and start again parsing function parameters.
327 state.restoreFromSnapshot(snapshot);
328 stopState.stop = true;
329 state.scopeDepth++;
330
331 parseFunctionParams();
332 parseAsyncArrowFromCallExpression(startPos, startTokenIndex);
333 }
334 } else {
335 next();
336 const callContextId = getNextContextId();
337 state.tokens[state.tokens.length - 1].contextId = callContextId;
338 parseCallExpressionArguments();
339 state.tokens[state.tokens.length - 1].contextId = callContextId;
340 }
341 } else if (match(tt.backQuote)) {
342 // Tagged template expression.
343 parseTemplate();
344 } else {
345 stopState.stop = true;
346 }
347}
348
349export function atPossibleAsync() {
350 // This was made less strict than the original version to avoid passing around nodes, but it
351 // should be safe to have rare false positives here.
352 return (
353 state.tokens[state.tokens.length - 1].contextualKeyword === ContextualKeyword._async &&
354 !canInsertSemicolon()
355 );
356}
357
358export function parseCallExpressionArguments() {
359 let first = true;
360 while (!eat(tt.parenR) && !state.error) {
361 if (first) {
362 first = false;
363 } else {
364 expect(tt.comma);
365 if (eat(tt.parenR)) {
366 break;
367 }
368 }
369
370 parseExprListItem(false);
371 }
372}
373
374function shouldParseAsyncArrow() {
375 return match(tt.colon) || match(tt.arrow);
376}
377
378function parseAsyncArrowFromCallExpression(functionStart, startTokenIndex) {
379 if (isTypeScriptEnabled) {
380 tsStartParseAsyncArrowFromCallExpression();
381 } else if (isFlowEnabled) {
382 flowStartParseAsyncArrowFromCallExpression();
383 }
384 expect(tt.arrow);
385 parseArrowExpression(functionStart, startTokenIndex);
386}
387
388// Parse a no-call expression (like argument of `new` or `::` operators).
389
390function parseNoCallExpr() {
391 const startPos = state.start;
392 parseExprAtom();
393 parseSubscripts(startPos, true);
394}
395
396// Parse an atomic expression — either a single token that is an
397// expression, an expression started by a keyword like `function` or
398// `new`, or an expression wrapped in punctuation like `()`, `[]`,
399// or `{}`.
400// Returns true if the parsed expression was an arrow function.
401export function parseExprAtom() {
402 if (match(tt.jsxText)) {
403 parseLiteral();
404 return false;
405 } else if (match(tt.lessThan) && isJSXEnabled) {
406 state.type = tt.jsxTagStart;
407 jsxParseElement();
408 next();
409 return false;
410 }
411
412 const canBeArrow = state.potentialArrowAt === state.start;
413 switch (state.type) {
414 case tt.slash:
415 case tt.assign:
416 retokenizeSlashAsRegex();
417 // Fall through.
418
419 case tt._super:
420 case tt._this:
421 case tt.regexp:
422 case tt.num:
423 case tt.bigint:
424 case tt.string:
425 case tt._null:
426 case tt._true:
427 case tt._false:
428 next();
429 return false;
430
431 case tt._import:
432 if (lookaheadType() === tt.dot) {
433 parseImportMetaProperty();
434 return false;
435 }
436 next();
437 return false;
438
439 case tt.name: {
440 const startTokenIndex = state.tokens.length;
441 const functionStart = state.start;
442 const contextualKeyword = state.contextualKeyword;
443 parseIdentifier();
444 if (contextualKeyword === ContextualKeyword._await) {
445 parseAwait();
446 return false;
447 } else if (
448 contextualKeyword === ContextualKeyword._async &&
449 match(tt._function) &&
450 !canInsertSemicolon()
451 ) {
452 next();
453 parseFunction(functionStart, false, false);
454 return false;
455 } else if (
456 canBeArrow &&
457 !canInsertSemicolon() &&
458 contextualKeyword === ContextualKeyword._async &&
459 match(tt.name)
460 ) {
461 state.scopeDepth++;
462 parseBindingIdentifier(false);
463 expect(tt.arrow);
464 // let foo = async bar => {};
465 parseArrowExpression(functionStart, startTokenIndex);
466 return true;
467 }
468
469 if (canBeArrow && !canInsertSemicolon() && match(tt.arrow)) {
470 state.scopeDepth++;
471 markPriorBindingIdentifier(false);
472 expect(tt.arrow);
473 parseArrowExpression(functionStart, startTokenIndex);
474 return true;
475 }
476
477 state.tokens[state.tokens.length - 1].identifierRole = IdentifierRole.Access;
478 return false;
479 }
480
481 case tt._do: {
482 next();
483 parseBlock(false);
484 return false;
485 }
486
487 case tt.parenL: {
488 const wasArrow = parseParenAndDistinguishExpression(canBeArrow);
489 return wasArrow;
490 }
491
492 case tt.bracketL:
493 next();
494 parseExprList(tt.bracketR, true);
495 return false;
496
497 case tt.braceL:
498 parseObj(false, false);
499 return false;
500
501 case tt._function:
502 parseFunctionExpression();
503 return false;
504
505 case tt.at:
506 parseDecorators();
507 // Fall through.
508
509 case tt._class:
510 parseClass(false);
511 return false;
512
513 case tt._new:
514 parseNew();
515 return false;
516
517 case tt.backQuote:
518 parseTemplate();
519 return false;
520
521 case tt.doubleColon: {
522 next();
523 parseNoCallExpr();
524 return false;
525 }
526
527 default:
528 unexpected();
529 return false;
530 }
531}
532
533function parseMaybePrivateName() {
534 eat(tt.hash);
535 parseIdentifier();
536}
537
538function parseFunctionExpression() {
539 const functionStart = state.start;
540 parseIdentifier();
541 if (eat(tt.dot)) {
542 // function.sent
543 parseMetaProperty();
544 }
545 parseFunction(functionStart, false);
546}
547
548function parseMetaProperty() {
549 parseIdentifier();
550}
551
552function parseImportMetaProperty() {
553 parseIdentifier();
554 expect(tt.dot);
555 // import.meta
556 parseMetaProperty();
557}
558
559export function parseLiteral() {
560 next();
561}
562
563export function parseParenExpression() {
564 expect(tt.parenL);
565 parseExpression();
566 expect(tt.parenR);
567}
568
569// Returns true if this was an arrow expression.
570function parseParenAndDistinguishExpression(canBeArrow) {
571 // Assume this is a normal parenthesized expression, but if we see an arrow, we'll bail and
572 // start over as a parameter list.
573 const snapshot = state.snapshot();
574
575 const startTokenIndex = state.tokens.length;
576 expect(tt.parenL);
577
578 let first = true;
579
580 while (!match(tt.parenR) && !state.error) {
581 if (first) {
582 first = false;
583 } else {
584 expect(tt.comma);
585 if (match(tt.parenR)) {
586 break;
587 }
588 }
589
590 if (match(tt.ellipsis)) {
591 parseRest(false /* isBlockScope */);
592 parseParenItem();
593 break;
594 } else {
595 parseMaybeAssign(false, true);
596 }
597 }
598
599 expect(tt.parenR);
600
601 if (canBeArrow && shouldParseArrow()) {
602 const wasArrow = parseArrow();
603 if (wasArrow) {
604 // It was an arrow function this whole time, so start over and parse it as params so that we
605 // get proper token annotations.
606 state.restoreFromSnapshot(snapshot);
607 state.scopeDepth++;
608 // We don't need to worry about functionStart for arrow functions, so just use something.
609 const functionStart = state.start;
610 // Don't specify a context ID because arrow functions don't need a context ID.
611 parseFunctionParams();
612 parseArrow();
613 parseArrowExpression(functionStart, startTokenIndex);
614 return true;
615 }
616 }
617
618 return false;
619}
620
621function shouldParseArrow() {
622 return match(tt.colon) || !canInsertSemicolon();
623}
624
625// Returns whether there was an arrow token.
626export function parseArrow() {
627 if (isTypeScriptEnabled) {
628 return tsParseArrow();
629 } else if (isFlowEnabled) {
630 return flowParseArrow();
631 } else {
632 return eat(tt.arrow);
633 }
634}
635
636function parseParenItem() {
637 if (isTypeScriptEnabled || isFlowEnabled) {
638 typedParseParenItem();
639 }
640}
641
642// New's precedence is slightly tricky. It must allow its argument to
643// be a `[]` or dot subscript expression, but not a call — at least,
644// not without wrapping it in parentheses. Thus, it uses the noCalls
645// argument to parseSubscripts to prevent it from consuming the
646// argument list.
647function parseNew() {
648 expect(tt._new);
649 if (eat(tt.dot)) {
650 // new.target
651 parseMetaProperty();
652 return;
653 }
654 parseNoCallExpr();
655 eat(tt.questionDot);
656 parseNewArguments();
657}
658
659function parseNewArguments() {
660 if (isTypeScriptEnabled) {
661 tsStartParseNewArguments();
662 } else if (isFlowEnabled) {
663 flowStartParseNewArguments();
664 }
665 if (eat(tt.parenL)) {
666 parseExprList(tt.parenR);
667 }
668}
669
670export function parseTemplate() {
671 // Finish `, read quasi
672 nextTemplateToken();
673 // Finish quasi, read ${
674 nextTemplateToken();
675 while (!match(tt.backQuote) && !state.error) {
676 expect(tt.dollarBraceL);
677 parseExpression();
678 // Finish }, read quasi
679 nextTemplateToken();
680 // Finish quasi, read either ${ or `
681 nextTemplateToken();
682 }
683 next();
684}
685
686// Parse an object literal or binding pattern.
687export function parseObj(isPattern, isBlockScope) {
688 // Attach a context ID to the object open and close brace and each object key.
689 const contextId = getNextContextId();
690 let first = true;
691
692 next();
693 state.tokens[state.tokens.length - 1].contextId = contextId;
694
695 while (!eat(tt.braceR) && !state.error) {
696 if (first) {
697 first = false;
698 } else {
699 expect(tt.comma);
700 if (eat(tt.braceR)) {
701 break;
702 }
703 }
704
705 let isGenerator = false;
706 if (match(tt.ellipsis)) {
707 const previousIndex = state.tokens.length;
708 parseSpread();
709 if (isPattern) {
710 // Mark role when the only thing being spread over is an identifier.
711 if (state.tokens.length === previousIndex + 2) {
712 markPriorBindingIdentifier(isBlockScope);
713 }
714 if (eat(tt.braceR)) {
715 break;
716 }
717 }
718 continue;
719 }
720
721 if (!isPattern) {
722 isGenerator = eat(tt.star);
723 }
724
725 if (!isPattern && isContextual(ContextualKeyword._async)) {
726 if (isGenerator) unexpected();
727
728 parseIdentifier();
729 if (
730 match(tt.colon) ||
731 match(tt.parenL) ||
732 match(tt.braceR) ||
733 match(tt.eq) ||
734 match(tt.comma)
735 ) {
736 // This is a key called "async" rather than an async function.
737 } else {
738 if (match(tt.star)) {
739 next();
740 isGenerator = true;
741 }
742 parsePropertyName(contextId);
743 }
744 } else {
745 parsePropertyName(contextId);
746 }
747
748 parseObjPropValue(isGenerator, isPattern, isBlockScope, contextId);
749 }
750
751 state.tokens[state.tokens.length - 1].contextId = contextId;
752}
753
754function isGetterOrSetterMethod(isPattern) {
755 // We go off of the next and don't bother checking if the node key is actually "get" or "set".
756 // This lets us avoid generating a node, and should only make the validation worse.
757 return (
758 !isPattern &&
759 (match(tt.string) || // get "string"() {}
760 match(tt.num) || // get 1() {}
761 match(tt.bracketL) || // get ["string"]() {}
762 match(tt.name) || // get foo() {}
763 !!(state.type & TokenType.IS_KEYWORD)) // get debugger() {}
764 );
765}
766
767// Returns true if this was a method.
768function parseObjectMethod(
769 isGenerator,
770 isPattern,
771 objectContextId,
772) {
773 // We don't need to worry about modifiers because object methods can't have optional bodies, so
774 // the start will never be used.
775 const functionStart = state.start;
776 if (match(tt.parenL)) {
777 if (isPattern) unexpected();
778 parseMethod(functionStart, isGenerator, /* isConstructor */ false);
779 return true;
780 }
781
782 if (isGetterOrSetterMethod(isPattern)) {
783 parsePropertyName(objectContextId);
784 parseMethod(functionStart, /* isGenerator */ false, /* isConstructor */ false);
785 return true;
786 }
787 return false;
788}
789
790function parseObjectProperty(isPattern, isBlockScope) {
791 if (eat(tt.colon)) {
792 if (isPattern) {
793 parseMaybeDefault(isBlockScope);
794 } else {
795 parseMaybeAssign(false);
796 }
797 return;
798 }
799
800 // Since there's no colon, we assume this is an object shorthand.
801
802 // If we're in a destructuring, we've now discovered that the key was actually an assignee, so
803 // we need to tag it as a declaration with the appropriate scope. Otherwise, we might need to
804 // transform it on access, so mark it as a normal object shorthand.
805 if (isPattern) {
806 state.tokens[state.tokens.length - 1].identifierRole = isBlockScope
807 ? IdentifierRole.ObjectShorthandBlockScopedDeclaration
808 : IdentifierRole.ObjectShorthandFunctionScopedDeclaration;
809 } else {
810 state.tokens[state.tokens.length - 1].identifierRole = IdentifierRole.ObjectShorthand;
811 }
812
813 // Regardless of whether we know this to be a pattern or if we're in an ambiguous context, allow
814 // parsing as if there's a default value.
815 parseMaybeDefault(isBlockScope, true);
816}
817
818function parseObjPropValue(
819 isGenerator,
820 isPattern,
821 isBlockScope,
822 objectContextId,
823) {
824 if (isTypeScriptEnabled) {
825 tsStartParseObjPropValue();
826 } else if (isFlowEnabled) {
827 flowStartParseObjPropValue();
828 }
829 const wasMethod = parseObjectMethod(isGenerator, isPattern, objectContextId);
830 if (!wasMethod) {
831 parseObjectProperty(isPattern, isBlockScope);
832 }
833}
834
835export function parsePropertyName(objectContextId) {
836 if (isFlowEnabled) {
837 flowParseVariance();
838 }
839 if (eat(tt.bracketL)) {
840 state.tokens[state.tokens.length - 1].contextId = objectContextId;
841 parseMaybeAssign();
842 expect(tt.bracketR);
843 state.tokens[state.tokens.length - 1].contextId = objectContextId;
844 } else {
845 if (match(tt.num) || match(tt.string)) {
846 parseExprAtom();
847 } else {
848 parseMaybePrivateName();
849 }
850
851 state.tokens[state.tokens.length - 1].identifierRole = IdentifierRole.ObjectKey;
852 state.tokens[state.tokens.length - 1].contextId = objectContextId;
853 }
854}
855
856// Parse object or class method.
857export function parseMethod(
858 functionStart,
859 isGenerator,
860 isConstructor,
861) {
862 const funcContextId = getNextContextId();
863
864 state.scopeDepth++;
865 const startTokenIndex = state.tokens.length;
866 const allowModifiers = isConstructor; // For TypeScript parameter properties
867 parseFunctionParams(allowModifiers, funcContextId);
868 parseFunctionBodyAndFinish(
869 functionStart,
870 isGenerator,
871 false /* allowExpressionBody */,
872 funcContextId,
873 );
874 const endTokenIndex = state.tokens.length;
875 state.scopes.push(new Scope(startTokenIndex, endTokenIndex, true));
876 state.scopeDepth--;
877}
878
879// Parse arrow function expression.
880// If the parameters are provided, they will be converted to an
881// assignable list.
882export function parseArrowExpression(functionStart, startTokenIndex) {
883 parseFunctionBody(functionStart, false /* isGenerator */, true);
884 const endTokenIndex = state.tokens.length;
885 state.scopes.push(new Scope(startTokenIndex, endTokenIndex, true));
886 state.scopeDepth--;
887}
888
889export function parseFunctionBodyAndFinish(
890 functionStart,
891 isGenerator,
892 allowExpressionBody = false,
893 funcContextId = 0,
894) {
895 if (isTypeScriptEnabled) {
896 tsParseFunctionBodyAndFinish(functionStart, isGenerator, allowExpressionBody, funcContextId);
897 } else if (isFlowEnabled) {
898 flowParseFunctionBodyAndFinish(functionStart, isGenerator, allowExpressionBody, funcContextId);
899 } else {
900 parseFunctionBody(functionStart, isGenerator, allowExpressionBody, funcContextId);
901 }
902}
903
904// Parse function body and check parameters.
905export function parseFunctionBody(
906 functionStart,
907 isGenerator,
908 allowExpression,
909 funcContextId = 0,
910) {
911 const isExpression = allowExpression && !match(tt.braceL);
912
913 if (isExpression) {
914 parseMaybeAssign();
915 } else {
916 parseBlock(true /* allowDirectives */, true /* isFunctionScope */, funcContextId);
917 }
918}
919
920// Parses a comma-separated list of expressions, and returns them as
921// an array. `close` is the token type that ends the list, and
922// `allowEmpty` can be turned on to allow subsequent commas with
923// nothing in between them to be parsed as `null` (which is needed
924// for array literals).
925
926function parseExprList(close, allowEmpty = false) {
927 let first = true;
928 while (!eat(close) && !state.error) {
929 if (first) {
930 first = false;
931 } else {
932 expect(tt.comma);
933 if (eat(close)) break;
934 }
935 parseExprListItem(allowEmpty);
936 }
937}
938
939function parseExprListItem(allowEmpty) {
940 if (allowEmpty && match(tt.comma)) {
941 // Empty item; nothing more to parse for this item.
942 } else if (match(tt.ellipsis)) {
943 parseSpread();
944 parseParenItem();
945 } else {
946 parseMaybeAssign(false, true);
947 }
948}
949
950// Parse the next token as an identifier.
951export function parseIdentifier() {
952 next();
953 state.tokens[state.tokens.length - 1].type = tt.name;
954}
955
956// Parses await expression inside async function.
957function parseAwait() {
958 parseMaybeUnary();
959}
960
961// Parses yield expression inside generator.
962function parseYield() {
963 next();
964 if (!match(tt.semi) && !canInsertSemicolon()) {
965 eat(tt.star);
966 parseMaybeAssign();
967 }
968}