boa_parser 0.21.1

ECMAScript parser for the Boa JavaScript engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
//! Object initializer parsing.
//!
//! More information:
//!  - [MDN documentation][mdn]
//!  - [ECMAScript specification][spec]
//!
//! [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer
//! [spec]: https://tc39.es/ecma262/#sec-object-initializer

#[cfg(test)]
mod tests;

use crate::{
    Error,
    lexer::{
        Error as LexError, InputElement, TokenKind,
        token::{ContainsEscapeSequence, Numeric},
    },
    parser::{
        AllowAwait, AllowIn, AllowYield, Cursor, OrAbrupt, ParseResult, TokenParser,
        expression::{AssignmentExpression, identifiers::IdentifierReference},
        function::{FormalParameter, FormalParameters, FunctionBody, UniqueFormalParameters},
        name_in_lexically_declared_names,
    },
    source::ReadChar,
};
use boa_ast::{
    Expression, Keyword, Punctuator, Span, Spanned,
    expression::{
        Identifier,
        literal::{
            self, Literal, ObjectMethodDefinition, PropertyDefinition as PropertyDefinitionNode,
        },
    },
    function::{
        ClassElementName as ClassElementNameNode, FormalParameterList,
        FunctionBody as FunctionBodyAst, PrivateName,
    },
    operations::{
        ContainsSymbol, bound_names, contains, has_direct_super_new, lexically_declared_names,
    },
    property::{MethodDefinitionKind, PropertyName as PropertyNameNode},
};
use boa_interner::{Interner, Sym};

/// Parses an object literal.
///
/// More information:
///  - [MDN documentation][mdn]
///  - [ECMAScript specification][spec]
///
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer
/// [spec]: https://tc39.es/ecma262/#prod-ObjectLiteral
#[derive(Debug, Clone, Copy)]
pub(super) struct ObjectLiteral {
    allow_yield: AllowYield,
    allow_await: AllowAwait,
}

impl ObjectLiteral {
    /// Creates a new `ObjectLiteral` parser.
    pub(super) fn new<Y, A>(allow_yield: Y, allow_await: A) -> Self
    where
        Y: Into<AllowYield>,
        A: Into<AllowAwait>,
    {
        Self {
            allow_yield: allow_yield.into(),
            allow_await: allow_await.into(),
        }
    }
}

impl<R> TokenParser<R> for ObjectLiteral
where
    R: ReadChar,
{
    type Output = literal::ObjectLiteral;

    fn parse(self, cursor: &mut Cursor<R>, interner: &mut Interner) -> ParseResult<Self::Output> {
        let open_block_token = cursor.expect(Punctuator::OpenBlock, "object parsing", interner)?;
        cursor.set_goal(InputElement::RegExp);

        let mut elements = Vec::new();

        let mut has_proto = false;
        let mut duplicate_proto_position = None;

        let end = loop {
            if let Some(token) = cursor.next_if(Punctuator::CloseBlock, interner)? {
                break token.span().end();
            }

            let position = cursor.peek(0, interner).or_abrupt()?.span().start();

            let property = PropertyDefinition::new(self.allow_yield, self.allow_await)
                .parse(cursor, interner)?;

            if let PropertyDefinitionNode::Property(PropertyNameNode::Literal(ident), _) = property
                && ident.sym() == Sym::__PROTO__
            {
                if has_proto && duplicate_proto_position.is_none() {
                    duplicate_proto_position = Some(position);
                } else {
                    has_proto = true;
                }
            }

            elements.push(property);

            if let Some(token) = cursor.next_if(Punctuator::CloseBlock, interner)? {
                break token.span().end();
            }

            if cursor.next_if(Punctuator::Comma, interner)?.is_none() {
                let next_token = cursor.next(interner).or_abrupt()?;
                return Err(Error::expected(
                    [",".to_owned(), "}".to_owned()],
                    next_token.to_string(interner),
                    next_token.span(),
                    "object literal",
                ));
            }
        };

        if let Some(position) = duplicate_proto_position
            && !cursor.json_parse()
            && cursor
                .peek(0, interner)?
                .is_none_or(|token| token.kind() != &TokenKind::Punctuator(Punctuator::Assign))
        {
            return Err(Error::general(
                "Duplicate __proto__ fields are not allowed in object literals.",
                position,
            ));
        }

        let start = open_block_token.span().start();
        Ok(literal::ObjectLiteral::new(elements, Span::new(start, end)))
    }
}

/// Parses a property definition.
///
/// More information:
///  - [ECMAScript specification][spec]
///
/// [spec]: https://tc39.es/ecma262/#prod-PropertyDefinition
#[derive(Debug, Clone, Copy)]
pub(in crate::parser) struct PropertyDefinition {
    allow_yield: AllowYield,
    allow_await: AllowAwait,
}

impl PropertyDefinition {
    /// Creates a new `PropertyDefinition` parser.
    pub(in crate::parser) fn new<Y, A>(allow_yield: Y, allow_await: A) -> Self
    where
        Y: Into<AllowYield>,
        A: Into<AllowAwait>,
    {
        Self {
            allow_yield: allow_yield.into(),
            allow_await: allow_await.into(),
        }
    }
}

impl<R> TokenParser<R> for PropertyDefinition
where
    R: ReadChar,
{
    type Output = PropertyDefinitionNode;

    fn parse(self, cursor: &mut Cursor<R>, interner: &mut Interner) -> ParseResult<Self::Output> {
        match cursor.peek(1, interner).or_abrupt()?.kind() {
            TokenKind::Punctuator(Punctuator::CloseBlock | Punctuator::Comma) => {
                let ident = IdentifierReference::new(self.allow_yield, self.allow_await)
                    .parse(cursor, interner)?;
                return Ok(PropertyDefinitionNode::IdentifierReference(ident));
            }
            TokenKind::Punctuator(Punctuator::Assign) => {
                return CoverInitializedName::new(self.allow_yield, self.allow_await)
                    .parse(cursor, interner);
            }
            _ => {}
        }

        //  ... AssignmentExpression[+In, ?Yield, ?Await]
        if cursor.next_if(Punctuator::Spread, interner)?.is_some() {
            let node = AssignmentExpression::new(true, self.allow_yield, self.allow_await)
                .parse(cursor, interner)?;
            return Ok(PropertyDefinitionNode::SpreadObject(node));
        }

        //Async [AsyncMethod, AsyncGeneratorMethod] object methods
        let is_keyword = !matches!(
            cursor.peek(1, interner).or_abrupt()?.kind(),
            TokenKind::Punctuator(Punctuator::OpenParen | Punctuator::Colon)
        );

        let token = cursor.peek(0, interner).or_abrupt()?;
        let start_linear_pos = token.linear_span().start();

        match token.kind() {
            TokenKind::Keyword((Keyword::Async, true)) if is_keyword => {
                return Err(Error::general(
                    "Keyword must not contain escaped characters",
                    token.span().start(),
                ));
            }
            TokenKind::Keyword((Keyword::Async, false)) if is_keyword => {
                cursor.advance(interner);
                cursor.peek_expect_no_lineterminator(0, "Async object methods", interner)?;

                let token = cursor.peek(0, interner).or_abrupt()?;
                let position = token.span().start();

                if token.kind() == &TokenKind::Punctuator(Punctuator::Mul) {
                    let (class_element_name, params, body) =
                        AsyncGeneratorMethod::new(self.allow_yield, self.allow_await)
                            .parse(cursor, interner)?;

                    let ClassElementNameNode::PropertyName(property_name) = class_element_name
                    else {
                        return Err(Error::general(
                            "private identifiers not allowed in object literal",
                            position,
                        ));
                    };

                    // Early Error: It is a Syntax Error if HasDirectSuper of MethodDefinition is true.
                    if has_direct_super_new(&params, &body) {
                        return Err(Error::lex(LexError::Syntax(
                            "invalid super call usage".into(),
                            position,
                        )));
                    }

                    return Ok(PropertyDefinitionNode::MethodDefinition(
                        ObjectMethodDefinition::new(
                            property_name,
                            params,
                            body,
                            MethodDefinitionKind::AsyncGenerator,
                            start_linear_pos,
                        ),
                    ));
                }
                let (class_element_name, params, body) =
                    AsyncMethod::new(self.allow_yield, self.allow_await).parse(cursor, interner)?;

                let ClassElementNameNode::PropertyName(property_name) = class_element_name else {
                    return Err(Error::general(
                        "private identifiers not allowed in object literal",
                        position,
                    ));
                };

                // Early Error: It is a Syntax Error if HasDirectSuper of MethodDefinition is true.
                if has_direct_super_new(&params, &body) {
                    return Err(Error::lex(LexError::Syntax(
                        "invalid super call usage".into(),
                        position,
                    )));
                }

                return Ok(PropertyDefinitionNode::MethodDefinition(
                    ObjectMethodDefinition::new(
                        property_name,
                        params,
                        body,
                        MethodDefinitionKind::Async,
                        start_linear_pos,
                    ),
                ));
            }
            _ => {}
        }

        let token = cursor.peek(0, interner).or_abrupt()?;
        let start_linear_pos = token.linear_span().start();

        if token.kind() == &TokenKind::Punctuator(Punctuator::Mul) {
            let position = cursor.peek(0, interner).or_abrupt()?.span().start();
            let (class_element_name, params, body) =
                GeneratorMethod::new(self.allow_yield, self.allow_await).parse(cursor, interner)?;

            let ClassElementNameNode::PropertyName(property_name) = class_element_name else {
                return Err(Error::general(
                    "private identifier not allowed in object literal",
                    position,
                ));
            };

            // Early Error: It is a Syntax Error if HasDirectSuper of MethodDefinition is true.
            if has_direct_super_new(&params, &body) {
                return Err(Error::lex(LexError::Syntax(
                    "invalid super call usage".into(),
                    position,
                )));
            }

            return Ok(PropertyDefinitionNode::MethodDefinition(
                ObjectMethodDefinition::new(
                    property_name,
                    params,
                    body,
                    MethodDefinitionKind::Generator,
                    start_linear_pos,
                ),
            ));
        }

        let set_or_get_escaped_position = match token.kind() {
            TokenKind::IdentifierName((Sym::GET | Sym::SET, ContainsEscapeSequence(true))) => {
                Some(token.span().start())
            }
            _ => None,
        };

        let mut property_name =
            PropertyName::new(self.allow_yield, self.allow_await).parse(cursor, interner)?;

        //  PropertyName[?Yield, ?Await] : AssignmentExpression[+In, ?Yield, ?Await]
        if cursor.next_if(Punctuator::Colon, interner)?.is_some() {
            let mut value = AssignmentExpression::new(true, self.allow_yield, self.allow_await)
                .parse(cursor, interner)?;

            if let Some(name) = property_name.literal()
                && name != Sym::__PROTO__
            {
                value.set_anonymous_function_definition_name(&name);
            }

            return Ok(PropertyDefinitionNode::Property(property_name, value));
        }

        let ordinary_method = cursor.peek(0, interner).or_abrupt()?.kind()
            == &TokenKind::Punctuator(Punctuator::OpenParen);

        match property_name {
            // MethodDefinition[?Yield, ?Await] -> get ClassElementName[?Yield, ?Await] ( ) { FunctionBody[~Yield, ~Await] }
            PropertyNameNode::Literal(str) if str == Sym::GET && !ordinary_method => {
                if let Some(position) = set_or_get_escaped_position {
                    return Err(Error::general(
                        "Keyword must not contain escaped characters",
                        position,
                    ));
                }

                let position = cursor.peek(0, interner).or_abrupt()?.span().start();

                property_name = PropertyName::new(self.allow_yield, self.allow_await)
                    .parse(cursor, interner)?;

                cursor.expect(
                    TokenKind::Punctuator(Punctuator::OpenParen),
                    "get method definition",
                    interner,
                )?;
                cursor.expect(
                    TokenKind::Punctuator(Punctuator::CloseParen),
                    "get method definition",
                    interner,
                )?;

                let body = FunctionBody::new(false, false, "get method definition")
                    .parse(cursor, interner)?;

                // Early Error: It is a Syntax Error if HasDirectSuper of MethodDefinition is true.
                if has_direct_super_new(&FormalParameterList::default(), &body) {
                    return Err(Error::lex(LexError::Syntax(
                        "invalid super call usage".into(),
                        position,
                    )));
                }

                Ok(PropertyDefinitionNode::MethodDefinition(
                    ObjectMethodDefinition::new(
                        property_name,
                        FormalParameterList::default(),
                        body,
                        MethodDefinitionKind::Get,
                        start_linear_pos,
                    ),
                ))
            }
            // MethodDefinition[?Yield, ?Await] -> set ClassElementName[?Yield, ?Await] ( PropertySetParameterList ) { FunctionBody[~Yield, ~Await] }
            PropertyNameNode::Literal(str) if str == Sym::SET && !ordinary_method => {
                if let Some(position) = set_or_get_escaped_position {
                    return Err(Error::general(
                        "Keyword must not contain escaped characters",
                        position,
                    ));
                }

                property_name = PropertyName::new(self.allow_yield, self.allow_await)
                    .parse(cursor, interner)?;

                let params_start_position = cursor
                    .expect(
                        TokenKind::Punctuator(Punctuator::OpenParen),
                        "set method definition",
                        interner,
                    )?
                    .span()
                    .end();
                let params: FormalParameterList = FormalParameter::new(false, false)
                    .parse(cursor, interner)?
                    .into();
                cursor.expect(
                    TokenKind::Punctuator(Punctuator::CloseParen),
                    "set method definition",
                    interner,
                )?;

                let body = FunctionBody::new(false, false, "set method definition")
                    .parse(cursor, interner)?;

                // Catch early error for BindingIdentifier.
                if body.strict() && contains(&params, ContainsSymbol::EvalOrArguments) {
                    return Err(Error::lex(LexError::Syntax(
                        "unexpected identifier 'eval' or 'arguments' in strict mode".into(),
                        params_start_position,
                    )));
                }

                // It is a Syntax Error if FunctionBodyContainsUseStrict of FunctionBody is true
                // and IsSimpleParameterList of PropertySetParameterList is false.
                // https://tc39.es/ecma262/#sec-method-definitions-static-semantics-early-errors
                if body.strict() && !params.is_simple() {
                    return Err(Error::lex(LexError::Syntax(
                        "Illegal 'use strict' directive in function with non-simple parameter list"
                            .into(),
                        params_start_position,
                    )));
                }

                // It is a Syntax Error if any element of the BoundNames of PropertySetParameterList also
                // occurs in the LexicallyDeclaredNames of FunctionBody.
                // https://tc39.es/ecma262/#sec-method-definitions-static-semantics-early-errors
                name_in_lexically_declared_names(
                    &bound_names(&params),
                    &lexically_declared_names(&body),
                    params_start_position,
                    interner,
                )?;

                // Early Error: It is a Syntax Error if HasDirectSuper of MethodDefinition is true.
                if has_direct_super_new(&params, &body) {
                    return Err(Error::lex(LexError::Syntax(
                        "invalid super call usage".into(),
                        params_start_position,
                    )));
                }

                Ok(PropertyDefinitionNode::MethodDefinition(
                    ObjectMethodDefinition::new(
                        property_name,
                        params,
                        body,
                        MethodDefinitionKind::Set,
                        start_linear_pos,
                    ),
                ))
            }
            // MethodDefinition[?Yield, ?Await] -> ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[~Yield, ~Await] ) { FunctionBody[~Yield, ~Await] }
            _ => {
                let params_start_position = cursor
                    .expect(
                        TokenKind::Punctuator(Punctuator::OpenParen),
                        "method definition",
                        interner,
                    )?
                    .span()
                    .end();
                let params = FormalParameters::new(false, false).parse(cursor, interner)?;
                cursor.expect(
                    TokenKind::Punctuator(Punctuator::CloseParen),
                    "method definition",
                    interner,
                )?;

                // Early Error: UniqueFormalParameters : FormalParameters
                if params.has_duplicates() {
                    return Err(Error::lex(LexError::Syntax(
                        "Duplicate parameter name not allowed in this context".into(),
                        params_start_position,
                    )));
                }

                let body =
                    FunctionBody::new(false, false, "method definition").parse(cursor, interner)?;

                // Early Error: It is a Syntax Error if FunctionBodyContainsUseStrict of FunctionBody is true
                // and IsSimpleParameterList of UniqueFormalParameters is false.
                if body.strict() && !params.is_simple() {
                    return Err(Error::lex(LexError::Syntax(
                        "Illegal 'use strict' directive in function with non-simple parameter list"
                            .into(),
                        params_start_position,
                    )));
                }

                // It is a Syntax Error if any element of the BoundNames of FormalParameters also occurs in the
                // LexicallyDeclaredNames of FunctionBody.
                name_in_lexically_declared_names(
                    &bound_names(&params),
                    &lexically_declared_names(&body),
                    params_start_position,
                    interner,
                )?;

                // Early Error: It is a Syntax Error if HasDirectSuper of MethodDefinition is true.
                if has_direct_super_new(&params, &body) {
                    return Err(Error::lex(LexError::Syntax(
                        "invalid super call usage".into(),
                        params_start_position,
                    )));
                }

                Ok(PropertyDefinitionNode::MethodDefinition(
                    ObjectMethodDefinition::new(
                        property_name,
                        params,
                        body,
                        MethodDefinitionKind::Ordinary,
                        start_linear_pos,
                    ),
                ))
            }
        }
    }
}

/// Parses a property name.
///
/// More information:
///  - [ECMAScript specification][spec]
///
/// [spec]: https://tc39.es/ecma262/#prod-PropertyName
#[derive(Debug, Clone)]
pub(in crate::parser) struct PropertyName {
    allow_yield: AllowYield,
    allow_await: AllowAwait,
}

impl PropertyName {
    /// Creates a new `PropertyName` parser.
    pub(in crate::parser) fn new<Y, A>(allow_yield: Y, allow_await: A) -> Self
    where
        Y: Into<AllowYield>,
        A: Into<AllowAwait>,
    {
        Self {
            allow_yield: allow_yield.into(),
            allow_await: allow_await.into(),
        }
    }
}

impl<R> TokenParser<R> for PropertyName
where
    R: ReadChar,
{
    type Output = PropertyNameNode;

    fn parse(self, cursor: &mut Cursor<R>, interner: &mut Interner) -> ParseResult<Self::Output> {
        let token = cursor.peek(0, interner).or_abrupt()?;
        let name: PropertyNameNode = match token.kind() {
            TokenKind::Punctuator(Punctuator::OpenBracket) => {
                cursor.advance(interner);
                let node = AssignmentExpression::new(true, self.allow_yield, self.allow_await)
                    .parse(cursor, interner)?;
                cursor.expect(Punctuator::CloseBracket, "expected token ']'", interner)?;
                return Ok(node.into());
            }
            TokenKind::IdentifierName((name, _)) | TokenKind::StringLiteral((name, _)) => {
                Identifier::new(*name, token.span()).into()
            }
            TokenKind::NumericLiteral(num) => match num {
                Numeric::Rational(num) => {
                    Expression::Literal(Literal::new(*num, token.span())).into()
                }
                Numeric::Integer(num) => {
                    Expression::Literal(Literal::new(*num, token.span())).into()
                }
                Numeric::BigInt(num) => {
                    Expression::Literal(Literal::new(num.clone(), token.span())).into()
                }
            },
            TokenKind::Keyword((word, _)) => {
                let (utf8, utf16) = word.as_str();
                let sym = interner.get_or_intern_static(utf8, utf16);
                Identifier::new(sym, token.span()).into()
            }
            TokenKind::NullLiteral(_) => Identifier::new(Sym::NULL, token.span()).into(),
            TokenKind::BooleanLiteral((bool, _)) => match bool {
                true => Identifier::new(Sym::TRUE, token.span()).into(),
                false => Identifier::new(Sym::FALSE, token.span()).into(),
            },
            _ => {
                return Err(Error::expected(
                    vec!["property name".to_owned()],
                    token.to_string(interner),
                    token.span(),
                    "property name",
                ));
            }
        };
        cursor.advance(interner);
        Ok(name)
    }
}

/// `ClassElementName` can be either a property name or a private identifier.
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#prod-ClassElementName
#[derive(Debug, Clone)]
pub(in crate::parser) struct ClassElementName {
    allow_yield: AllowYield,
    allow_await: AllowAwait,
}

impl ClassElementName {
    /// Creates a new `ClassElementName` parser.
    pub(in crate::parser) fn new<Y, A>(allow_yield: Y, allow_await: A) -> Self
    where
        Y: Into<AllowYield>,
        A: Into<AllowAwait>,
    {
        Self {
            allow_yield: allow_yield.into(),
            allow_await: allow_await.into(),
        }
    }
}

impl<R> TokenParser<R> for ClassElementName
where
    R: ReadChar,
{
    type Output = ClassElementNameNode;

    fn parse(self, cursor: &mut Cursor<R>, interner: &mut Interner) -> ParseResult<Self::Output> {
        let token = cursor.peek(0, interner).or_abrupt()?;
        match token.kind() {
            TokenKind::PrivateIdentifier(ident) => {
                let ident = *ident;
                let span = token.span();
                cursor.advance(interner);
                Ok(ClassElementNameNode::PrivateName(PrivateName::new(
                    ident, span,
                )))
            }
            _ => Ok(ClassElementNameNode::PropertyName(
                PropertyName::new(self.allow_yield, self.allow_await).parse(cursor, interner)?,
            )),
        }
    }
}

/// Initializer parsing.
///
/// More information:
///  - [ECMAScript specification][spec]
///
/// [spec]: https://tc39.es/ecma262/#prod-Initializer
#[derive(Debug, Clone, Copy)]
pub(in crate::parser) struct Initializer {
    allow_in: AllowIn,
    allow_yield: AllowYield,
    allow_await: AllowAwait,
}

impl Initializer {
    /// Creates a new `Initializer` parser.
    pub(in crate::parser) fn new<I, Y, A>(allow_in: I, allow_yield: Y, allow_await: A) -> Self
    where
        I: Into<AllowIn>,
        Y: Into<AllowYield>,
        A: Into<AllowAwait>,
    {
        Self {
            allow_in: allow_in.into(),
            allow_yield: allow_yield.into(),
            allow_await: allow_await.into(),
        }
    }
}

impl<R> TokenParser<R> for Initializer
where
    R: ReadChar,
{
    type Output = Expression;

    fn parse(self, cursor: &mut Cursor<R>, interner: &mut Interner) -> ParseResult<Self::Output> {
        cursor.expect(Punctuator::Assign, "initializer", interner)?;
        AssignmentExpression::new(self.allow_in, self.allow_yield, self.allow_await)
            .parse(cursor, interner)
    }
}

/// `GeneratorMethod` parsing.
///
/// More information:
///  - [ECMAScript specification][spec]
///
/// [spec]: https://tc39.es/ecma262/#prod-GeneratorMethod
#[derive(Debug, Clone, Copy)]
pub(in crate::parser) struct GeneratorMethod {
    allow_yield: AllowYield,
    allow_await: AllowAwait,
}

impl GeneratorMethod {
    /// Creates a new `GeneratorMethod` parser.
    pub(in crate::parser) fn new<Y, A>(allow_yield: Y, allow_await: A) -> Self
    where
        Y: Into<AllowYield>,
        A: Into<AllowAwait>,
    {
        Self {
            allow_yield: allow_yield.into(),
            allow_await: allow_await.into(),
        }
    }
}

impl<R> TokenParser<R> for GeneratorMethod
where
    R: ReadChar,
{
    type Output = (ClassElementNameNode, FormalParameterList, FunctionBodyAst);

    fn parse(self, cursor: &mut Cursor<R>, interner: &mut Interner) -> ParseResult<Self::Output> {
        cursor.expect(Punctuator::Mul, "generator method definition", interner)?;

        let class_element_name =
            ClassElementName::new(self.allow_yield, self.allow_await).parse(cursor, interner)?;

        let params_start_position = cursor.peek(0, interner).or_abrupt()?.span().start();

        let params = UniqueFormalParameters::new(true, false).parse(cursor, interner)?;

        // It is a Syntax Error if UniqueFormalParameters Contains YieldExpression is true.
        if contains(&params, ContainsSymbol::YieldExpression) {
            return Err(Error::lex(LexError::Syntax(
                "yield expression not allowed in generator method definition parameters".into(),
                params_start_position,
            )));
        }

        let body = FunctionBody::new(true, false, "generator method definition")
            .parse(cursor, interner)?;

        let body_start = body.span().start();

        // Early Error: It is a Syntax Error if FunctionBodyContainsUseStrict of FunctionBody is true
        // and IsSimpleParameterList of UniqueFormalParameters is false.
        if body.strict() && !params.is_simple() {
            return Err(Error::lex(LexError::Syntax(
                "Illegal 'use strict' directive in function with non-simple parameter list".into(),
                body_start,
            )));
        }

        // Early Error: It is a Syntax Error if any element of the BoundNames of UniqueFormalParameters also
        // occurs in the LexicallyDeclaredNames of GeneratorBody.
        name_in_lexically_declared_names(
            &bound_names(&params),
            &lexically_declared_names(&body),
            params_start_position,
            interner,
        )?;

        // Early Error: It is a Syntax Error if HasDirectSuper of AsyncMethod is true.
        if has_direct_super_new(&params, &body) {
            return Err(Error::lex(LexError::Syntax(
                "invalid super call usage".into(),
                body_start,
            )));
        }

        Ok((class_element_name, params, body))
    }
}

/// `AsyncGeneratorMethod` parsing.
///
/// More information:
///  - [ECMAScript specification][spec]
///
/// [spec]: https://tc39.es/ecma262/#prod-AsyncGeneratorMethod
#[derive(Debug, Clone, Copy)]
pub(in crate::parser) struct AsyncGeneratorMethod {
    allow_yield: AllowYield,
    allow_await: AllowAwait,
}

impl AsyncGeneratorMethod {
    /// Creates a new `AsyncGeneratorMethod` parser.
    pub(in crate::parser) fn new<Y, A>(allow_yield: Y, allow_await: A) -> Self
    where
        Y: Into<AllowYield>,
        A: Into<AllowAwait>,
    {
        Self {
            allow_yield: allow_yield.into(),
            allow_await: allow_await.into(),
        }
    }
}

impl<R> TokenParser<R> for AsyncGeneratorMethod
where
    R: ReadChar,
{
    type Output = (ClassElementNameNode, FormalParameterList, FunctionBodyAst);

    fn parse(self, cursor: &mut Cursor<R>, interner: &mut Interner) -> ParseResult<Self::Output> {
        cursor.expect(
            Punctuator::Mul,
            "async generator method definition",
            interner,
        )?;

        let name =
            ClassElementName::new(self.allow_yield, self.allow_await).parse(cursor, interner)?;

        let params_start_position = cursor.peek(0, interner).or_abrupt()?.span().start();

        let params = UniqueFormalParameters::new(true, true).parse(cursor, interner)?;

        // Early Error: It is a Syntax Error if UniqueFormalParameters Contains YieldExpression is true.
        if contains(&params, ContainsSymbol::YieldExpression) {
            return Err(Error::lex(LexError::Syntax(
                "yield expression not allowed in async generator method definition parameters"
                    .into(),
                params_start_position,
            )));
        }

        // Early Error: It is a Syntax Error if UniqueFormalParameters Contains AwaitExpression is true.
        if contains(&params, ContainsSymbol::AwaitExpression) {
            return Err(Error::lex(LexError::Syntax(
                "await expression not allowed in async generator method definition parameters"
                    .into(),
                params_start_position,
            )));
        }

        let body = FunctionBody::new(true, true, "async generator method definition")
            .parse(cursor, interner)?;

        let body_start = body.span().start();

        // Early Error: It is a Syntax Error if FunctionBodyContainsUseStrict of FunctionBody is true
        // and IsSimpleParameterList of UniqueFormalParameters is false.
        if body.strict() && !params.is_simple() {
            return Err(Error::lex(LexError::Syntax(
                "Illegal 'use strict' directive in function with non-simple parameter list".into(),
                body_start,
            )));
        }

        // Early Error: It is a Syntax Error if any element of the BoundNames of UniqueFormalParameters
        // also occurs in the LexicallyDeclaredNames of AsyncGeneratorBody.
        name_in_lexically_declared_names(
            &bound_names(&params),
            &lexically_declared_names(&body),
            params_start_position,
            interner,
        )?;

        // Early Error: It is a Syntax Error if HasDirectSuper of AsyncMethod is true.
        if has_direct_super_new(&params, &body) {
            return Err(Error::lex(LexError::Syntax(
                "invalid super call usage".into(),
                body_start,
            )));
        }

        Ok((name, params, body))
    }
}

/// `AsyncMethod` parsing.
///
/// More information:
///  - [ECMAScript specification][spec]
///
/// [spec]: https://tc39.es/ecma262/#prod-AsyncMethod
#[derive(Debug, Clone, Copy)]
pub(in crate::parser) struct AsyncMethod {
    allow_yield: AllowYield,
    allow_await: AllowAwait,
}

impl AsyncMethod {
    /// Creates a new `AsyncMethod` parser.
    pub(in crate::parser) fn new<Y, A>(allow_yield: Y, allow_await: A) -> Self
    where
        Y: Into<AllowYield>,
        A: Into<AllowAwait>,
    {
        Self {
            allow_yield: allow_yield.into(),
            allow_await: allow_await.into(),
        }
    }
}

impl<R> TokenParser<R> for AsyncMethod
where
    R: ReadChar,
{
    type Output = (ClassElementNameNode, FormalParameterList, FunctionBodyAst);

    fn parse(self, cursor: &mut Cursor<R>, interner: &mut Interner) -> ParseResult<Self::Output> {
        let class_element_name =
            ClassElementName::new(self.allow_yield, self.allow_await).parse(cursor, interner)?;

        let params_start_position = cursor.peek(0, interner).or_abrupt()?.span().start();

        let params = UniqueFormalParameters::new(false, true).parse(cursor, interner)?;

        let body =
            FunctionBody::new(true, true, "async method definition").parse(cursor, interner)?;

        let body_start = body.span().start();

        // Early Error: It is a Syntax Error if FunctionBodyContainsUseStrict of AsyncFunctionBody
        // is true and IsSimpleParameterList of UniqueFormalParameters is false.
        if body.strict() && !params.is_simple() {
            return Err(Error::lex(LexError::Syntax(
                "Illegal 'use strict' directive in function with non-simple parameter list".into(),
                body_start,
            )));
        }

        // Early Error: It is a Syntax Error if any element of the BoundNames of UniqueFormalParameters
        // also occurs in the LexicallyDeclaredNames of AsyncFunctionBody.
        name_in_lexically_declared_names(
            &bound_names(&params),
            &lexically_declared_names(&body),
            params_start_position,
            interner,
        )?;

        // Early Error: It is a Syntax Error if HasDirectSuper of AsyncMethod is true.
        if has_direct_super_new(&params, &body) {
            return Err(Error::lex(LexError::Syntax(
                "invalid super call usage".into(),
                body_start,
            )));
        }

        Ok((class_element_name, params, body))
    }
}

/// `CoverInitializedName` parsing.
///
/// More information:
///  - [ECMAScript specification][spec]
///
/// [spec]: https://tc39.es/ecma262/#prod-CoverInitializedName
#[derive(Debug, Clone, Copy)]
pub(in crate::parser) struct CoverInitializedName {
    allow_yield: AllowYield,
    allow_await: AllowAwait,
}

impl CoverInitializedName {
    /// Creates a new `CoverInitializedName` parser.
    pub(in crate::parser) fn new<Y, A>(allow_yield: Y, allow_await: A) -> Self
    where
        Y: Into<AllowYield>,
        A: Into<AllowAwait>,
    {
        Self {
            allow_yield: allow_yield.into(),
            allow_await: allow_await.into(),
        }
    }
}

impl<R> TokenParser<R> for CoverInitializedName
where
    R: ReadChar,
{
    type Output = PropertyDefinitionNode;

    fn parse(self, cursor: &mut Cursor<R>, interner: &mut Interner) -> ParseResult<Self::Output> {
        let ident =
            IdentifierReference::new(self.allow_yield, self.allow_await).parse(cursor, interner)?;

        cursor.expect(Punctuator::Assign, "CoverInitializedName", interner)?;

        let expr = AssignmentExpression::new(true, self.allow_yield, self.allow_await)
            .parse(cursor, interner)?;

        Ok(PropertyDefinitionNode::CoverInitializedName(ident, expr))
    }
}