UNPKG

25.9 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 next();
239 }
240 return false;
241}
242
243// Parse call, dot, and `[]`-subscript expressions.
244// Returns true if this was an arrow function.
245export function parseExprSubscripts() {
246 const startPos = state.start;
247 const wasArrow = parseExprAtom();
248 if (wasArrow) {
249 return true;
250 }
251 parseSubscripts(startPos);
252 return false;
253}
254
255function parseSubscripts(startPos, noCalls = false) {
256 if (isFlowEnabled) {
257 flowParseSubscripts(startPos, noCalls);
258 } else {
259 baseParseSubscripts(startPos, noCalls);
260 }
261}
262
263export function baseParseSubscripts(startPos, noCalls = false) {
264 const stopState = new StopState(false);
265 do {
266 parseSubscript(startPos, noCalls, stopState);
267 } while (!stopState.stop && !state.error);
268}
269
270function parseSubscript(startPos, noCalls, stopState) {
271 if (isTypeScriptEnabled) {
272 tsParseSubscript(startPos, noCalls, stopState);
273 } else if (isFlowEnabled) {
274 flowParseSubscript(startPos, noCalls, stopState);
275 } else {
276 baseParseSubscript(startPos, noCalls, stopState);
277 }
278}
279
280/** Set 'state.stop = true' to indicate that we should stop parsing subscripts. */
281export function baseParseSubscript(startPos, noCalls, stopState) {
282 if (!noCalls && eat(tt.doubleColon)) {
283 parseNoCallExpr();
284 stopState.stop = true;
285 parseSubscripts(startPos, noCalls);
286 } else if (match(tt.questionDot)) {
287 if (noCalls && lookaheadType() === tt.parenL) {
288 stopState.stop = true;
289 return;
290 }
291 next();
292
293 if (eat(tt.bracketL)) {
294 parseExpression();
295 expect(tt.bracketR);
296 } else if (eat(tt.parenL)) {
297 parseCallExpressionArguments();
298 } else {
299 parseIdentifier();
300 }
301 } else if (eat(tt.dot)) {
302 parseMaybePrivateName();
303 } else if (eat(tt.bracketL)) {
304 parseExpression();
305 expect(tt.bracketR);
306 } else if (!noCalls && match(tt.parenL)) {
307 if (atPossibleAsync()) {
308 // We see "async", but it's possible it's a usage of the name "async". Parse as if it's a
309 // function call, and if we see an arrow later, backtrack and re-parse as a parameter list.
310 const snapshot = state.snapshot();
311 const startTokenIndex = state.tokens.length;
312 next();
313
314 const callContextId = getNextContextId();
315
316 state.tokens[state.tokens.length - 1].contextId = callContextId;
317 parseCallExpressionArguments();
318 state.tokens[state.tokens.length - 1].contextId = callContextId;
319
320 if (shouldParseAsyncArrow()) {
321 // We hit an arrow, so backtrack and start again parsing function parameters.
322 state.restoreFromSnapshot(snapshot);
323 stopState.stop = true;
324 state.scopeDepth++;
325
326 parseFunctionParams();
327 parseAsyncArrowFromCallExpression(startPos, startTokenIndex);
328 }
329 } else {
330 next();
331 const callContextId = getNextContextId();
332 state.tokens[state.tokens.length - 1].contextId = callContextId;
333 parseCallExpressionArguments();
334 state.tokens[state.tokens.length - 1].contextId = callContextId;
335 }
336 } else if (match(tt.backQuote)) {
337 // Tagged template expression.
338 parseTemplate();
339 } else {
340 stopState.stop = true;
341 }
342}
343
344export function atPossibleAsync() {
345 // This was made less strict than the original version to avoid passing around nodes, but it
346 // should be safe to have rare false positives here.
347 return (
348 state.tokens[state.tokens.length - 1].contextualKeyword === ContextualKeyword._async &&
349 !canInsertSemicolon()
350 );
351}
352
353export function parseCallExpressionArguments() {
354 let first = true;
355 while (!eat(tt.parenR) && !state.error) {
356 if (first) {
357 first = false;
358 } else {
359 expect(tt.comma);
360 if (eat(tt.parenR)) {
361 break;
362 }
363 }
364
365 parseExprListItem(false);
366 }
367}
368
369function shouldParseAsyncArrow() {
370 return match(tt.colon) || match(tt.arrow);
371}
372
373function parseAsyncArrowFromCallExpression(functionStart, startTokenIndex) {
374 if (isTypeScriptEnabled) {
375 tsStartParseAsyncArrowFromCallExpression();
376 } else if (isFlowEnabled) {
377 flowStartParseAsyncArrowFromCallExpression();
378 }
379 expect(tt.arrow);
380 parseArrowExpression(functionStart, startTokenIndex);
381}
382
383// Parse a no-call expression (like argument of `new` or `::` operators).
384
385function parseNoCallExpr() {
386 const startPos = state.start;
387 parseExprAtom();
388 parseSubscripts(startPos, true);
389}
390
391// Parse an atomic expression — either a single token that is an
392// expression, an expression started by a keyword like `function` or
393// `new`, or an expression wrapped in punctuation like `()`, `[]`,
394// or `{}`.
395// Returns true if the parsed expression was an arrow function.
396export function parseExprAtom() {
397 if (match(tt.jsxText)) {
398 parseLiteral();
399 return false;
400 } else if (match(tt.lessThan) && isJSXEnabled) {
401 state.type = tt.jsxTagStart;
402 jsxParseElement();
403 next();
404 return false;
405 }
406
407 const canBeArrow = state.potentialArrowAt === state.start;
408 switch (state.type) {
409 case tt.slash:
410 case tt.assign:
411 retokenizeSlashAsRegex();
412 // Fall through.
413
414 case tt._super:
415 case tt._this:
416 case tt.regexp:
417 case tt.num:
418 case tt.bigint:
419 case tt.string:
420 case tt._null:
421 case tt._true:
422 case tt._false:
423 next();
424 return false;
425
426 case tt._import:
427 if (lookaheadType() === tt.dot) {
428 parseImportMetaProperty();
429 return false;
430 }
431 next();
432 return false;
433
434 case tt.name: {
435 const startTokenIndex = state.tokens.length;
436 const functionStart = state.start;
437 const contextualKeyword = state.contextualKeyword;
438 parseIdentifier();
439 if (contextualKeyword === ContextualKeyword._await) {
440 parseAwait();
441 return false;
442 } else if (
443 contextualKeyword === ContextualKeyword._async &&
444 match(tt._function) &&
445 !canInsertSemicolon()
446 ) {
447 next();
448 parseFunction(functionStart, false, false);
449 return false;
450 } else if (
451 canBeArrow &&
452 !canInsertSemicolon() &&
453 contextualKeyword === ContextualKeyword._async &&
454 match(tt.name)
455 ) {
456 state.scopeDepth++;
457 parseBindingIdentifier(false);
458 expect(tt.arrow);
459 // let foo = async bar => {};
460 parseArrowExpression(functionStart, startTokenIndex);
461 return true;
462 }
463
464 if (canBeArrow && !canInsertSemicolon() && match(tt.arrow)) {
465 state.scopeDepth++;
466 markPriorBindingIdentifier(false);
467 expect(tt.arrow);
468 parseArrowExpression(functionStart, startTokenIndex);
469 return true;
470 }
471
472 state.tokens[state.tokens.length - 1].identifierRole = IdentifierRole.Access;
473 return false;
474 }
475
476 case tt._do: {
477 next();
478 parseBlock(false);
479 return false;
480 }
481
482 case tt.parenL: {
483 const wasArrow = parseParenAndDistinguishExpression(canBeArrow);
484 return wasArrow;
485 }
486
487 case tt.bracketL:
488 next();
489 parseExprList(tt.bracketR, true);
490 return false;
491
492 case tt.braceL:
493 parseObj(false, false);
494 return false;
495
496 case tt._function:
497 parseFunctionExpression();
498 return false;
499
500 case tt.at:
501 parseDecorators();
502 // Fall through.
503
504 case tt._class:
505 parseClass(false);
506 return false;
507
508 case tt._new:
509 parseNew();
510 return false;
511
512 case tt.backQuote:
513 parseTemplate();
514 return false;
515
516 case tt.doubleColon: {
517 next();
518 parseNoCallExpr();
519 return false;
520 }
521
522 default:
523 unexpected();
524 return false;
525 }
526}
527
528function parseMaybePrivateName() {
529 eat(tt.hash);
530 parseIdentifier();
531}
532
533function parseFunctionExpression() {
534 const functionStart = state.start;
535 parseIdentifier();
536 if (eat(tt.dot)) {
537 // function.sent
538 parseMetaProperty();
539 }
540 parseFunction(functionStart, false);
541}
542
543function parseMetaProperty() {
544 parseIdentifier();
545}
546
547function parseImportMetaProperty() {
548 parseIdentifier();
549 expect(tt.dot);
550 // import.meta
551 parseMetaProperty();
552}
553
554export function parseLiteral() {
555 next();
556}
557
558export function parseParenExpression() {
559 expect(tt.parenL);
560 parseExpression();
561 expect(tt.parenR);
562}
563
564// Returns true if this was an arrow expression.
565function parseParenAndDistinguishExpression(canBeArrow) {
566 // Assume this is a normal parenthesized expression, but if we see an arrow, we'll bail and
567 // start over as a parameter list.
568 const snapshot = state.snapshot();
569
570 const startTokenIndex = state.tokens.length;
571 expect(tt.parenL);
572
573 let first = true;
574
575 while (!match(tt.parenR) && !state.error) {
576 if (first) {
577 first = false;
578 } else {
579 expect(tt.comma);
580 if (match(tt.parenR)) {
581 break;
582 }
583 }
584
585 if (match(tt.ellipsis)) {
586 parseRest(false /* isBlockScope */);
587 parseParenItem();
588 break;
589 } else {
590 parseMaybeAssign(false, true);
591 }
592 }
593
594 expect(tt.parenR);
595
596 if (canBeArrow && shouldParseArrow()) {
597 const wasArrow = parseArrow();
598 if (wasArrow) {
599 // It was an arrow function this whole time, so start over and parse it as params so that we
600 // get proper token annotations.
601 state.restoreFromSnapshot(snapshot);
602 state.scopeDepth++;
603 // We don't need to worry about functionStart for arrow functions, so just use something.
604 const functionStart = state.start;
605 // Don't specify a context ID because arrow functions don't need a context ID.
606 parseFunctionParams();
607 parseArrow();
608 parseArrowExpression(functionStart, startTokenIndex);
609 return true;
610 }
611 }
612
613 return false;
614}
615
616function shouldParseArrow() {
617 return match(tt.colon) || !canInsertSemicolon();
618}
619
620// Returns whether there was an arrow token.
621export function parseArrow() {
622 if (isTypeScriptEnabled) {
623 return tsParseArrow();
624 } else if (isFlowEnabled) {
625 return flowParseArrow();
626 } else {
627 return eat(tt.arrow);
628 }
629}
630
631function parseParenItem() {
632 if (isTypeScriptEnabled || isFlowEnabled) {
633 typedParseParenItem();
634 }
635}
636
637// New's precedence is slightly tricky. It must allow its argument to
638// be a `[]` or dot subscript expression, but not a call — at least,
639// not without wrapping it in parentheses. Thus, it uses the noCalls
640// argument to parseSubscripts to prevent it from consuming the
641// argument list.
642function parseNew() {
643 expect(tt._new);
644 if (eat(tt.dot)) {
645 // new.target
646 parseMetaProperty();
647 return;
648 }
649 parseNoCallExpr();
650 eat(tt.questionDot);
651 parseNewArguments();
652}
653
654function parseNewArguments() {
655 if (isTypeScriptEnabled) {
656 tsStartParseNewArguments();
657 } else if (isFlowEnabled) {
658 flowStartParseNewArguments();
659 }
660 if (eat(tt.parenL)) {
661 parseExprList(tt.parenR);
662 }
663}
664
665export function parseTemplate() {
666 // Finish `, read quasi
667 nextTemplateToken();
668 // Finish quasi, read ${
669 nextTemplateToken();
670 while (!match(tt.backQuote) && !state.error) {
671 expect(tt.dollarBraceL);
672 parseExpression();
673 // Finish }, read quasi
674 nextTemplateToken();
675 // Finish quasi, read either ${ or `
676 nextTemplateToken();
677 }
678 next();
679}
680
681// Parse an object literal or binding pattern.
682export function parseObj(isPattern, isBlockScope) {
683 // Attach a context ID to the object open and close brace and each object key.
684 const contextId = getNextContextId();
685 let first = true;
686
687 next();
688 state.tokens[state.tokens.length - 1].contextId = contextId;
689
690 while (!eat(tt.braceR) && !state.error) {
691 if (first) {
692 first = false;
693 } else {
694 expect(tt.comma);
695 if (eat(tt.braceR)) {
696 break;
697 }
698 }
699
700 let isGenerator = false;
701 if (match(tt.ellipsis)) {
702 const previousIndex = state.tokens.length;
703 parseSpread();
704 if (isPattern) {
705 // Mark role when the only thing being spread over is an identifier.
706 if (state.tokens.length === previousIndex + 2) {
707 markPriorBindingIdentifier(isBlockScope);
708 }
709 if (eat(tt.braceR)) {
710 break;
711 }
712 }
713 continue;
714 }
715
716 if (!isPattern) {
717 isGenerator = eat(tt.star);
718 }
719
720 if (!isPattern && isContextual(ContextualKeyword._async)) {
721 if (isGenerator) unexpected();
722
723 parseIdentifier();
724 if (
725 match(tt.colon) ||
726 match(tt.parenL) ||
727 match(tt.braceR) ||
728 match(tt.eq) ||
729 match(tt.comma)
730 ) {
731 // This is a key called "async" rather than an async function.
732 } else {
733 if (match(tt.star)) {
734 next();
735 isGenerator = true;
736 }
737 parsePropertyName(contextId);
738 }
739 } else {
740 parsePropertyName(contextId);
741 }
742
743 parseObjPropValue(isGenerator, isPattern, isBlockScope, contextId);
744 }
745
746 state.tokens[state.tokens.length - 1].contextId = contextId;
747}
748
749function isGetterOrSetterMethod(isPattern) {
750 // We go off of the next and don't bother checking if the node key is actually "get" or "set".
751 // This lets us avoid generating a node, and should only make the validation worse.
752 return (
753 !isPattern &&
754 (match(tt.string) || // get "string"() {}
755 match(tt.num) || // get 1() {}
756 match(tt.bracketL) || // get ["string"]() {}
757 match(tt.name) || // get foo() {}
758 !!(state.type & TokenType.IS_KEYWORD)) // get debugger() {}
759 );
760}
761
762// Returns true if this was a method.
763function parseObjectMethod(
764 isGenerator,
765 isPattern,
766 objectContextId,
767) {
768 // We don't need to worry about modifiers because object methods can't have optional bodies, so
769 // the start will never be used.
770 const functionStart = state.start;
771 if (match(tt.parenL)) {
772 if (isPattern) unexpected();
773 parseMethod(functionStart, isGenerator, /* isConstructor */ false);
774 return true;
775 }
776
777 if (isGetterOrSetterMethod(isPattern)) {
778 parsePropertyName(objectContextId);
779 parseMethod(functionStart, /* isGenerator */ false, /* isConstructor */ false);
780 return true;
781 }
782 return false;
783}
784
785function parseObjectProperty(isPattern, isBlockScope) {
786 if (eat(tt.colon)) {
787 if (isPattern) {
788 parseMaybeDefault(isBlockScope);
789 } else {
790 parseMaybeAssign(false);
791 }
792 return;
793 }
794
795 // Since there's no colon, we assume this is an object shorthand.
796
797 // If we're in a destructuring, we've now discovered that the key was actually an assignee, so
798 // we need to tag it as a declaration with the appropriate scope. Otherwise, we might need to
799 // transform it on access, so mark it as a normal object shorthand.
800 if (isPattern) {
801 state.tokens[state.tokens.length - 1].identifierRole = isBlockScope
802 ? IdentifierRole.ObjectShorthandBlockScopedDeclaration
803 : IdentifierRole.ObjectShorthandFunctionScopedDeclaration;
804 } else {
805 state.tokens[state.tokens.length - 1].identifierRole = IdentifierRole.ObjectShorthand;
806 }
807
808 // Regardless of whether we know this to be a pattern or if we're in an ambiguous context, allow
809 // parsing as if there's a default value.
810 parseMaybeDefault(isBlockScope, true);
811}
812
813function parseObjPropValue(
814 isGenerator,
815 isPattern,
816 isBlockScope,
817 objectContextId,
818) {
819 if (isTypeScriptEnabled) {
820 tsStartParseObjPropValue();
821 } else if (isFlowEnabled) {
822 flowStartParseObjPropValue();
823 }
824 const wasMethod = parseObjectMethod(isGenerator, isPattern, objectContextId);
825 if (!wasMethod) {
826 parseObjectProperty(isPattern, isBlockScope);
827 }
828}
829
830export function parsePropertyName(objectContextId) {
831 if (isFlowEnabled) {
832 flowParseVariance();
833 }
834 if (eat(tt.bracketL)) {
835 state.tokens[state.tokens.length - 1].contextId = objectContextId;
836 parseMaybeAssign();
837 expect(tt.bracketR);
838 state.tokens[state.tokens.length - 1].contextId = objectContextId;
839 } else {
840 if (match(tt.num) || match(tt.string)) {
841 parseExprAtom();
842 } else {
843 parseMaybePrivateName();
844 }
845
846 state.tokens[state.tokens.length - 1].identifierRole = IdentifierRole.ObjectKey;
847 state.tokens[state.tokens.length - 1].contextId = objectContextId;
848 }
849}
850
851// Parse object or class method.
852export function parseMethod(
853 functionStart,
854 isGenerator,
855 isConstructor,
856) {
857 const funcContextId = getNextContextId();
858
859 state.scopeDepth++;
860 const startTokenIndex = state.tokens.length;
861 const allowModifiers = isConstructor; // For TypeScript parameter properties
862 parseFunctionParams(allowModifiers, funcContextId);
863 parseFunctionBodyAndFinish(
864 functionStart,
865 isGenerator,
866 false /* allowExpressionBody */,
867 funcContextId,
868 );
869 const endTokenIndex = state.tokens.length;
870 state.scopes.push(new Scope(startTokenIndex, endTokenIndex, true));
871 state.scopeDepth--;
872}
873
874// Parse arrow function expression.
875// If the parameters are provided, they will be converted to an
876// assignable list.
877export function parseArrowExpression(functionStart, startTokenIndex) {
878 parseFunctionBody(functionStart, false /* isGenerator */, true);
879 const endTokenIndex = state.tokens.length;
880 state.scopes.push(new Scope(startTokenIndex, endTokenIndex, true));
881 state.scopeDepth--;
882}
883
884export function parseFunctionBodyAndFinish(
885 functionStart,
886 isGenerator,
887 allowExpressionBody = false,
888 funcContextId = 0,
889) {
890 if (isTypeScriptEnabled) {
891 tsParseFunctionBodyAndFinish(functionStart, isGenerator, allowExpressionBody, funcContextId);
892 } else if (isFlowEnabled) {
893 flowParseFunctionBodyAndFinish(functionStart, isGenerator, allowExpressionBody, funcContextId);
894 } else {
895 parseFunctionBody(functionStart, isGenerator, allowExpressionBody, funcContextId);
896 }
897}
898
899// Parse function body and check parameters.
900export function parseFunctionBody(
901 functionStart,
902 isGenerator,
903 allowExpression,
904 funcContextId = 0,
905) {
906 const isExpression = allowExpression && !match(tt.braceL);
907
908 if (isExpression) {
909 parseMaybeAssign();
910 } else {
911 parseBlock(true /* allowDirectives */, true /* isFunctionScope */, funcContextId);
912 }
913}
914
915// Parses a comma-separated list of expressions, and returns them as
916// an array. `close` is the token type that ends the list, and
917// `allowEmpty` can be turned on to allow subsequent commas with
918// nothing in between them to be parsed as `null` (which is needed
919// for array literals).
920
921function parseExprList(close, allowEmpty = false) {
922 let first = true;
923 while (!eat(close) && !state.error) {
924 if (first) {
925 first = false;
926 } else {
927 expect(tt.comma);
928 if (eat(close)) break;
929 }
930 parseExprListItem(allowEmpty);
931 }
932}
933
934function parseExprListItem(allowEmpty) {
935 if (allowEmpty && match(tt.comma)) {
936 // Empty item; nothing more to parse for this item.
937 } else if (match(tt.ellipsis)) {
938 parseSpread();
939 parseParenItem();
940 } else {
941 parseMaybeAssign(false, true);
942 }
943}
944
945// Parse the next token as an identifier.
946export function parseIdentifier() {
947 next();
948 state.tokens[state.tokens.length - 1].type = tt.name;
949}
950
951// Parses await expression inside async function.
952function parseAwait() {
953 parseMaybeUnary();
954}
955
956// Parses yield expression inside generator.
957function parseYield() {
958 next();
959 if (!match(tt.semi) && !canInsertSemicolon()) {
960 eat(tt.star);
961 parseMaybeAssign();
962 }
963}