biome_js_parser 0.5.7

Biome's JavaScript parser
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
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
//! Expressions, these include `this`, identifiers, arrays, objects,
//! binary expressions, unary expressions, and more.
//!
//! See the [ECMAScript spec](https://www.ecma-international.org/ecma-262/5.1/#sec-11).

use super::typescript::*;
use crate::lexer::{JsLexContext, JsReLexContext};
use crate::parser::rewrite_parser::{RewriteMarker, RewriteParser};
use crate::parser::{JsParserCheckpoint, RecoveryResult};
use crate::prelude::*;
use crate::rewrite::rewrite_events;
use crate::rewrite::RewriteParseEvents;
use crate::syntax::assignment::parse_assignment;
use crate::syntax::assignment::AssignmentExprPrecedence;
use crate::syntax::assignment::{expression_to_assignment, expression_to_assignment_pattern};
use crate::syntax::class::{parse_class_expression, parse_decorators};
use crate::syntax::function::{
    is_at_async_function, parse_arrow_function_expression, parse_function_expression, LineBreak,
};
use crate::syntax::js_parse_error;
use crate::syntax::js_parse_error::{decorators_not_allowed, expected_simple_assignment_target};
use crate::syntax::js_parse_error::{
    expected_expression, expected_identifier, invalid_assignment_error,
    private_names_only_allowed_on_left_side_of_in_expression,
};
use crate::syntax::jsx::parse_jsx_tag_expression;
use crate::syntax::object::parse_object_expression;
use crate::syntax::stmt::{is_semi, STMT_RECOVERY_SET};
use crate::syntax::typescript::ts_parse_error::{expected_ts_type, ts_only_syntax_error};
use crate::JsSyntaxFeature::{Jsx, StrictMode, TypeScript};
use crate::ParsedSyntax::{Absent, Present};
use crate::{syntax, JsParser, ParseRecoveryTokenSet, ParsedSyntax};
use biome_js_syntax::{JsSyntaxKind::*, *};
use biome_parser::diagnostic::expected_token;
use biome_parser::parse_lists::ParseSeparatedList;
use biome_parser::ParserProgress;
use bitflags::bitflags;

pub const EXPR_RECOVERY_SET: TokenSet<JsSyntaxKind> =
    token_set![VAR_KW, R_PAREN, L_PAREN, L_BRACK, R_BRACK];

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub(crate) struct ExpressionContext(ExpressionContextFlags);

bitflags! {
    #[derive(Debug, Copy, Clone, Eq, PartialEq)]
    struct ExpressionContextFlags: u8 {
        /// Whether `in` should be counted in a binary expression.
        /// This is for `for...in` statements to prevent ambiguity.
        /// Corresponds to `[+In]` in the EcmaScript spec if true
        const INCLUDE_IN = 1 << 0;

        /// If false, object expressions are not allowed to be parsed
        /// inside an expression.
        ///
        /// Also applies for object patterns
        const ALLOW_OBJECT_EXPRESSION = 1 << 1;

        /// If `true` then, don't parse computed member expressions because they can as well indicate
        /// the start of a computed class member.
        const IN_DECORATOR = 1 << 2;

        /// If `true` allows a typescript type assertion.
        /// Currently disabled on "new" expressions.
        const ALLOW_TS_TYPE_ASSERTION = 1 << 3;
    }
}

impl ExpressionContext {
    pub(crate) fn and_include_in(self, include: bool) -> Self {
        self.and(ExpressionContextFlags::INCLUDE_IN, include)
    }

    pub(crate) fn and_object_expression_allowed(self, allowed: bool) -> Self {
        self.and(ExpressionContextFlags::ALLOW_OBJECT_EXPRESSION, allowed)
    }

    pub(crate) fn and_in_decorator(self, in_decorator: bool) -> Self {
        self.and(ExpressionContextFlags::IN_DECORATOR, in_decorator)
    }

    pub(crate) fn and_ts_type_assertion_allowed(self, allowed: bool) -> Self {
        self.and(ExpressionContextFlags::ALLOW_TS_TYPE_ASSERTION, allowed)
    }

    /// Returns true if object expressions or object patterns are valid in this context
    pub(crate) const fn is_object_expression_allowed(&self) -> bool {
        self.0
            .contains(ExpressionContextFlags::ALLOW_OBJECT_EXPRESSION)
    }

    /// Returns `true` if the expression parsing includes binary in expressions.
    pub(crate) const fn is_in_included(&self) -> bool {
        self.0.contains(ExpressionContextFlags::INCLUDE_IN)
    }

    /// Returns `true` if currently parsing a decorator expression `@<expr>`.
    pub(crate) const fn is_in_decorator(&self) -> bool {
        self.0.contains(ExpressionContextFlags::IN_DECORATOR)
    }

    /// Adds the `flag` if `set` is `true`, otherwise removes the `flag`
    fn and(self, flag: ExpressionContextFlags, set: bool) -> Self {
        ExpressionContext(if set { self.0 | flag } else { self.0 - flag })
    }
}

/// Sets the default flags for a context that parses a new root expression (for example, the condition of an if statement)
/// or sub-expression of another expression (the alternate branch of a condition expression).
impl Default for ExpressionContext {
    fn default() -> Self {
        ExpressionContext(
            ExpressionContextFlags::INCLUDE_IN
                | ExpressionContextFlags::ALLOW_OBJECT_EXPRESSION
                | ExpressionContextFlags::ALLOW_TS_TYPE_ASSERTION,
        )
    }
}

/// Parses an expression or recovers to the point of where the next statement starts
pub(crate) fn parse_expression_or_recover_to_next_statement(
    p: &mut JsParser,
    assign: bool,
    context: ExpressionContext,
) -> RecoveryResult {
    let func = if assign {
        syntax::expr::parse_assignment_expression_or_higher
    } else {
        syntax::expr::parse_expression
    };

    func(p, context).or_recover_with_token_set(
        p,
        &ParseRecoveryTokenSet::new(
            JsSyntaxKind::JS_BOGUS_EXPRESSION,
            STMT_RECOVERY_SET.union(token_set![T!['}']]),
        )
        .enable_recovery_on_line_break(),
        expected_expression,
    )
}

/// A literal expression.
///
/// `TRUE | FALSE | NUMBER | STRING | NULL`
// test js literals
// 5
// true
// false
// 5n
// "foo"
// 'bar'
// null
// 0, 0.0, 0n, 0e00
// "test\
// new-line";
// /^[يفمئامئ‍ئاسۆند]/i; //regex with unicode
// /[\p{Control}--[\t\n]]/v;
// /\’/; // regex with escaped non-ascii chars (issue #1941)

// test_err js literals
// 00, 012, 08, 091, 0789 // parser errors
// 01n, 0_0, 01.2 // lexer errors
// "test
// continues" // unterminated string literal

// test_err js regex
// /[\p{Control}--[\t\n]]/vv;
// /[\p{Control}--[\t\n]]/uv;
pub(super) fn parse_literal_expression(p: &mut JsParser) -> ParsedSyntax {
    let literal_kind = match p.cur() {
        JsSyntaxKind::JS_NUMBER_LITERAL => {
            return parse_number_literal_expression(p)
                .or_else(|| parse_big_int_literal_expression(p));
        }
        JsSyntaxKind::JS_STRING_LITERAL => JsSyntaxKind::JS_STRING_LITERAL_EXPRESSION,
        JsSyntaxKind::NULL_KW => JsSyntaxKind::JS_NULL_LITERAL_EXPRESSION,
        JsSyntaxKind::TRUE_KW | JsSyntaxKind::FALSE_KW => {
            JsSyntaxKind::JS_BOOLEAN_LITERAL_EXPRESSION
        }
        T![/] | T![/=] => {
            if p.re_lex(JsReLexContext::Regex) == JS_REGEX_LITERAL {
                JS_REGEX_LITERAL_EXPRESSION
            } else {
                return Absent;
            }
        }
        _ => return Absent,
    };

    let m = p.start();
    p.bump_any();
    Present(m.complete(p, literal_kind))
}

pub(crate) fn parse_big_int_literal_expression(p: &mut JsParser) -> ParsedSyntax {
    if !p.at(JS_NUMBER_LITERAL) || !p.cur_text().ends_with('n') {
        return Absent;
    }

    let m = p.start();
    p.bump_remap(JsSyntaxKind::JS_BIGINT_LITERAL);
    Present(m.complete(p, JS_BIGINT_LITERAL_EXPRESSION))
}

pub(crate) fn parse_number_literal_expression(p: &mut JsParser) -> ParsedSyntax {
    let cur_src = p.cur_text();
    if !p.at(JS_NUMBER_LITERAL) || cur_src.ends_with('n') {
        return Absent;
    }

    // Forbid legacy octal number in strict mode
    if p.state().strict().is_some()
        && cur_src.starts_with('0')
        && cur_src
            .chars()
            .nth(1)
            .filter(|c| c.is_ascii_digit())
            .is_some()
    {
        let err_msg = if cur_src.contains(['8', '9']) {
            "Decimals with leading zeros are not allowed in strict mode."
        } else {
            "\"0\"-prefixed octal literals are deprecated; use the \"0o\" prefix instead."
        };
        p.error(p.err_builder(err_msg, p.cur_range()));
    }

    let m = p.start();
    p.bump_any();
    Present(m.complete(p, JS_NUMBER_LITERAL_EXPRESSION))
}

/// Parses an assignment expression or any higher expression
/// https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#prod-AssignmentExpression
pub(crate) fn parse_assignment_expression_or_higher(
    p: &mut JsParser,
    context: ExpressionContext,
) -> ParsedSyntax {
    let arrow_expression = parse_arrow_function_expression(p);

    if arrow_expression.is_present() {
        return arrow_expression;
    }

    parse_assignment_expression_or_higher_base(p, context)
}

fn parse_assignment_expression_or_higher_base(
    p: &mut JsParser,
    context: ExpressionContext,
) -> ParsedSyntax {
    // test js reparse_yield_as_identifier
    // // SCRIPT
    // function foo() { yield *bar; }
    // function bar() { yield; }
    // function baz() { yield }
    if p.at(T![yield]) && (p.state().in_generator() || is_nth_at_expression(p, 1)) {
        return Present(parse_yield_expression(p, context));
    }

    let checkpoint = p.checkpoint();
    parse_conditional_expr(p, context)
        .and_then(|target| parse_assign_expr_recursive(p, target, checkpoint, context))
}

// test js assign_expr
// foo += bar = b ??= 3;
// foo -= bar;
// (foo = bar);
// [foo, bar] = baz;
// [foo, bar = "default", ...rest] = baz;
// [,,,foo,bar] = baz;
// ({ bar, baz } = {});
// ({ bar: [baz = "baz"], foo = "foo", ...rest } = {});

// test_err js assign_expr_right
// (foo = );

// test_err js assign_expr_left
// ( = foo);

// test js assign_eval_member_or_computed_expr
// eval.foo = 10
// arguments[1] = "baz"
// eval[2] = "Chungking Express"

// test_err js assign_eval_or_arguments
// eval = 0
// eval ??= 2
// eval *= 4
// arguments = "foo"
// arguments ||= "baz"
// ({ eval } = o)
// ({ foo: { eval }}) = o
fn parse_assign_expr_recursive(
    p: &mut JsParser,
    mut target: CompletedMarker,
    checkpoint: JsParserCheckpoint,
    context: ExpressionContext,
) -> ParsedSyntax {
    let assign_operator = p.cur();
    if is_assign_token(assign_operator) {
        let target = if matches!(
            target.kind(p),
            JS_BINARY_EXPRESSION | TS_TYPE_ASSERTION_EXPRESSION
        ) {
            // Special handling for binary expressions and type assertions to avoid having to deal with `a as string = ...`
            // inside of the `ReparseAssignment` implementation because not using parentheses is valid
            // in for heads `for (a as any in []) {}`
            p.error(invalid_assignment_error(p, target.range(p)));
            target.change_kind(p, JS_BOGUS_ASSIGNMENT);
            target
        } else {
            expression_to_assignment_pattern(p, target, checkpoint)
        };

        let m = target.precede(p);
        p.expect(assign_operator);

        parse_assignment_expression_or_higher(p, context.and_object_expression_allowed(true))
            .or_add_diagnostic(p, js_parse_error::expected_expression_assignment);
        Present(m.complete(p, JS_ASSIGNMENT_EXPRESSION))
    } else {
        Present(target)
    }
}

fn is_assign_token(kind: JsSyntaxKind) -> bool {
    matches!(
        kind,
        T![=]
            | T![+=]
            | T![-=]
            | T![*=]
            | T![/=]
            | T![%=]
            | T![<<=]
            | T![>>=]
            | T![>>>=]
            | T![&=]
            | T![|=]
            | T![^=]
            | T![&&=]
            | T![||=]
            | T![??=]
            | T![**=]
    )
}

// test js yield_expr
// function *foo() {
//  yield foo;
//  yield* foo;
//  yield;
//  yield
//  yield
// }
fn parse_yield_expression(p: &mut JsParser, context: ExpressionContext) -> CompletedMarker {
    let m = p.start();
    let yield_range = p.cur_range();
    p.expect(T![yield]);

    // test js yield_in_generator_function
    // function* foo() { yield 10; }
    // function* foo() { yield *bar; }
    // function* foo() { yield; }
    if !is_semi(p, 0) && (p.at(T![*]) || is_at_expression(p)) {
        let argument = p.start();
        p.eat(T![*]);
        parse_assignment_expression_or_higher(p, context.and_object_expression_allowed(true)).ok();
        argument.complete(p, JS_YIELD_ARGUMENT);
    }

    let mut yield_expr = m.complete(p, JS_YIELD_EXPRESSION);

    // test_err js yield_at_top_level_module
    // yield 10;

    // test_err js yield_at_top_level_script
    // // SCRIPT
    // yield 10;

    // test_err js yield_in_non_generator_function_script
    // // SCRIPT
    // function foo() { yield bar; }
    // function foo() { yield 10; }

    // test_err js yield_in_non_generator_function_module
    // function foo() { yield; }
    // function foo() { yield foo; }
    // function foo() { yield *foo; }
    if !(p.state().in_generator() && p.state().in_function()) {
        // test_err js yield_expr_in_parameter_initializer
        // function* test(a = yield "test") {}
        // function test2(a = yield "test") {}
        p.error(p.err_builder(
            "`yield` is only allowed within generator functions.",
            yield_range,
        ));
        yield_expr.change_to_bogus(p);
    }

    yield_expr
}

/// A conditional expression such as `foo ? bar : baz`
// test js conditional_expr
// foo ? bar : baz
// foo ? bar : baz ? bar : baz

pub(super) fn parse_conditional_expr(p: &mut JsParser, context: ExpressionContext) -> ParsedSyntax {
    // test_err js conditional_expr_err
    // foo ? bar baz
    // foo ? bar baz ? foo : bar
    // foo ? bar :
    let lhs = parse_binary_or_logical_expression(p, OperatorPrecedence::lowest(), context);

    if p.at(T![?]) {
        lhs.map(|marker| {
            let m = marker.precede(p);
            p.bump(T![?]);

            parse_conditional_expr_consequent(p, ExpressionContext::default())
                .or_add_diagnostic(p, js_parse_error::expected_expression_assignment);

            p.expect(T![:]);

            parse_assignment_expression_or_higher(p, context)
                .or_add_diagnostic(p, js_parse_error::expected_expression_assignment);
            m.complete(p, JS_CONDITIONAL_EXPRESSION)
        })
    } else {
        lhs
    }
}

/// Specialized version of [parse_assignment_expression_or_higher].
/// We need to make sure that on a successful arrow expression parse that
/// the next token is `:`.
// test js arrow_expr_in_alternate
// a ? (b) : a => {};

// test ts ts_arrow_exrp_in_alternate
// a ? (b) : a => {};

// test jsx jsx_arrow_exrp_in_alternate
// bar ? (foo) : (<a>{() => {}}</a>);
fn parse_conditional_expr_consequent(p: &mut JsParser, context: ExpressionContext) -> ParsedSyntax {
    let checkpoint = p.checkpoint();

    let arrow_expression = parse_arrow_function_expression(p);
    if arrow_expression.is_present() && p.at(T![:]) {
        return arrow_expression;
    }

    p.rewind(checkpoint);
    parse_assignment_expression_or_higher_base(p, context)
}

pub(crate) fn is_at_binary_operator(p: &JsParser, context: ExpressionContext) -> bool {
    let cur_kind = p.cur();

    match cur_kind {
        T![in] => context.is_in_included(),
        kind => OperatorPrecedence::try_from_binary_operator(kind).is_some(),
    }
}

/// A binary expression such as `2 + 2` or `foo * bar + 2` or a logical expression 'a || b'
fn parse_binary_or_logical_expression(
    p: &mut JsParser,
    left_precedence: OperatorPrecedence,
    context: ExpressionContext,
) -> ParsedSyntax {
    // test js private_name_presence_check
    // class A {
    // 	#prop;
    // 	test() {
    //    #prop in this
    //  }
    // }
    let left = parse_unary_expr(p, context).or_else(|| parse_private_name(p));

    parse_binary_or_logical_expression_recursive(p, left, left_precedence, context)
}

// test js binary_expressions
// 5 * 5
// 6 ** 6 ** 7
// 1 + 2 * 3
// (1 + 2) * 3
// 1 / 2
// 74 in foo
// foo instanceof Array
// foo ?? bar
// a >> b
// a >>> b
// 1 + 1 + 1 + 1
// 5 + 6 - 1 * 2 / 1 ** 6
// class Test { #name; test() { true && #name in {} } }

// test_err js binary_expressions_err
// foo(foo +);
// foo + * 2;
// !foo * bar;
fn parse_binary_or_logical_expression_recursive(
    p: &mut JsParser,
    mut left: ParsedSyntax,
    left_precedence: OperatorPrecedence,
    context: ExpressionContext,
) -> ParsedSyntax {
    // Use a loop to eat all binary expressions with the same precedence.
    // At first, the algorithm makes the impression that it recurse for every right-hand side expression.
    // This is true, but `parse_binary_or_logical_expression` immediately returns if the
    // current operator has the same or a lower precedence than the left-hand side expression. Thus,
    // the algorithm goes at most `count(OperatorPrecedence)` levels deep.
    loop {
        // test_err js js_right_shift_comments
        // 1 >> /* a comment */ > 2;
        let op = p.re_lex(JsReLexContext::BinaryOperator);

        if (op == T![as] && p.has_preceding_line_break())
            || (op == T![satisfies] && p.has_preceding_line_break())
            || (op == T![in] && !context.is_in_included())
        {
            break;
        }

        // This isn't spec compliant but improves error recovery in case the `}` is missing
        // inside of a JSX attribute expression value or an expression child.
        // Prevents that it parses `</` as less than followed by a RegEx if JSX is enabled and only if
        // there's no whitespace between the two tokens.
        // The downside of this is that `a </test/` will be incorrectly left unparsed. I think this is
        // a worth compromise and compatible with what TypeScript's doing.
        if Jsx.is_supported(p)
            && op == T![<]
            && p.nth_at(1, T![/])
            && !p.source_mut().has_next_preceding_trivia()
        {
            // test_err jsx jsx_child_expression_missing_r_curly
            // <test>{ 4 + 3</test>
            break;
        }

        let new_precedence = match OperatorPrecedence::try_from_binary_operator(op) {
            Some(precedence) => precedence,
            // Not a binary operator
            None => break,
        };

        let stop_at_current_operator = if new_precedence.is_right_to_left() {
            new_precedence < left_precedence
        } else {
            new_precedence <= left_precedence
        };

        if stop_at_current_operator {
            break;
        }

        let op_range = p.cur_range();

        let mut is_bogus = false;
        if let Present(left) = &mut left {
            // test js exponent_unary_parenthesized
            // (delete a.b) ** 2;
            // (void ident) ** 2;
            // (typeof ident) ** 2;
            // (-3) ** 2;
            // (+3) ** 2;
            // (~3) ** 2;
            // (!true) ** 2;

            // test_err js exponent_unary_unparenthesized
            // delete a.b ** 2;
            // void ident ** 2;
            // typeof ident ** 2;
            // -3 ** 2;
            // +3 ** 2;
            // ~3 ** 2;
            // !true ** 2;

            if op == T![**] && left.kind(p) == JS_UNARY_EXPRESSION {
                let err = p
					.err_builder(
						"unparenthesized unary expression can't appear on the left-hand side of '**'",
                        left.range(p)
					)
					.with_detail(op_range, "The operation")
					.with_detail(left.range(p), "The left-hand side");

                p.error(err);
                is_bogus = true;
            } else if op != T![in] && left.kind(p) == JS_PRIVATE_NAME {
                p.error(private_names_only_allowed_on_left_side_of_in_expression(
                    p,
                    left.range(p),
                ));
                left.change_kind(p, JS_BOGUS_EXPRESSION);
            }
        } else {
            let err = p
                .err_builder(
                    format!(
                        "Expected an expression for the left hand side of the `{}` operator.",
                        p.text(op_range),
                    ),
                    op_range,
                )
                .with_hint("This operator requires a left hand side value");
            p.error(err);
        }

        let m = left.precede(p);
        p.bump(op);

        // test ts ts_as_expression
        // let x: any = "string";
        // let y = x as string;
        // let z = x as const;
        // let not_an_as_expression = x
        // as;
        // let precedence = "hello" as const + 3 as number as number;
        if op == T![as] {
            parse_ts_type(p, TypeContext::default()).or_add_diagnostic(p, expected_ts_type);
            let mut as_expression = m.complete(p, TS_AS_EXPRESSION);

            if TypeScript.is_unsupported(p) {
                p.error(ts_only_syntax_error(
                    p,
                    "'as' expression",
                    as_expression.range(p),
                ));
                as_expression.change_to_bogus(p);
            }
            left = Present(as_expression);
            continue;
        }

        // test ts ts_satisfies_expression
        // interface A {
        //    a: string
        // };
        // let x = { a: 'test' } satisfies A;
        // let y = { a: 'test', b: 'test' } satisfies A;
        // const z = undefined satisfies 1;
        // let not_a_satisfies_expression = undefined
        // satisfies;
        // let precedence = "hello" satisfies string + 3 satisfies number satisfies number;

        // test_err js ts_satisfies_expression
        // let x = "hello" satisfies string;
        if op == T![satisfies] {
            parse_ts_type(p, TypeContext::default()).or_add_diagnostic(p, expected_ts_type);
            let mut satisfies_expression = m.complete(p, TS_SATISFIES_EXPRESSION);

            if TypeScript.is_unsupported(p) {
                p.error(ts_only_syntax_error(
                    p,
                    "'satisfies' expression",
                    satisfies_expression.range(p),
                ));
                satisfies_expression.change_to_bogus(p);
            }
            left = Present(satisfies_expression);
            continue;
        }

        parse_binary_or_logical_expression(p, new_precedence, context)
            .or_add_diagnostic(p, expected_expression);

        let expression_kind = if is_bogus {
            JS_BOGUS_EXPRESSION
        } else {
            match op {
                // test js logical_expressions
                // foo ?? bar
                // a || b
                // a && b
                //
                // test_err js logical_expressions_err
                // foo ?? * 2;
                // !foo && bar;
                // foo(foo ||)
                T![??] | T![||] | T![&&] => JS_LOGICAL_EXPRESSION,
                T![instanceof] => JS_INSTANCEOF_EXPRESSION,
                T![in] => JS_IN_EXPRESSION,
                _ => JS_BINARY_EXPRESSION,
            }
        };

        left = Present(m.complete(p, expression_kind));
    }

    if let Present(left) = &mut left {
        // Left at this point becomes the right-hand side of a binary expression
        // or is a standalone expression. Private names aren't allowed as standalone expressions
        // nor on the right-hand side
        if left.kind(p) == JS_PRIVATE_NAME {
            // test_err js private_name_presence_check_recursive
            // class A {
            // 	#prop;
            // 	test() {
            //    #prop in #prop in this;
            //    5 + #prop;
            //    #prop
            //    #prop + 5;
            //  }
            // }
            left.change_kind(p, JS_BOGUS_EXPRESSION);
            p.error(private_names_only_allowed_on_left_side_of_in_expression(
                p,
                left.range(p),
            ));
        }
    }

    left
}

/// A member or new expression with subscripts. e.g. `new foo`, `new Foo()`, `foo`, or `foo().bar[5]`
// test js new_exprs
// new Foo()
// new foo;
// new.target
// new new new new Foo();
// new Foo(bar, baz, 6 + 6, foo[bar] + ((foo) => {}) * foo?.bar)

// test_err js new_exprs
// new;
fn parse_member_expression_or_higher(p: &mut JsParser, context: ExpressionContext) -> ParsedSyntax {
    parse_primary_expression(p, context)
        .map(|lhs| parse_member_expression_rest(p, lhs, context, true, &mut false))
}

// test_err js subscripts_err
// foo()?.baz[].;
// BAR`b
fn parse_member_expression_rest(
    p: &mut JsParser,
    lhs: CompletedMarker,
    context: ExpressionContext,
    allow_optional_chain: bool,
    in_optional_chain: &mut bool,
) -> CompletedMarker {
    let mut progress = ParserProgress::default();
    let mut lhs = lhs;

    while !p.at(EOF) {
        progress.assert_progressing(p);
        lhs = match p.cur() {
            T![.] => parse_static_member_expression(p, lhs, T![.]).unwrap(),
            // Don't parse out `[` as a member expression because it may as well be the start of a computed class member
            T!['['] if !context.is_in_decorator() => {
                parse_computed_member_expression(p, lhs, false).unwrap()
            }
            T![?.] if allow_optional_chain => {
                let completed = if p.nth_at(1, T!['[']) {
                    parse_computed_member_expression(p, lhs, true).unwrap()
                } else if is_nth_at_any_name(p, 1) {
                    parse_static_member_expression(p, lhs, T![?.]).unwrap()
                } else if p.nth_at(1, BACKTICK) {
                    let m = lhs.precede(p);
                    p.bump(T![?.]);
                    let template_literal = p.start();
                    parse_template_literal(p, template_literal, true, true);
                    m.complete(p, JS_BOGUS_EXPRESSION)
                } else {
                    // '(' or any other unexpected character
                    break;
                };
                *in_optional_chain = true;
                completed
            }
            T![!] if !p.has_preceding_line_break() => {
                // test ts ts_non_null_assertion_expression
                // let a = { b: {} };
                // a!;
                // function test() {}
                // test()!
                // 	a.b.c!;
                // a!!!!!!;
                let m = lhs.precede(p);
                p.bump(T![!]);

                let mut non_null = m.complete(p, TS_NON_NULL_ASSERTION_EXPRESSION);

                if TypeScript.is_unsupported(p) {
                    non_null.change_to_bogus(p);
                    p.error(ts_only_syntax_error(
                        p,
                        "non-null assertions",
                        non_null.range(p),
                    ));
                }

                non_null
            }
            BACKTICK => {
                // test ts ts_optional_chain_call
                // (<A, B>() => {})?.<A, B>();
                let m = match lhs.kind(p) {
                    TS_INSTANTIATION_EXPRESSION => lhs.undo_completion(p),
                    _ => lhs.precede(p),
                };
                parse_template_literal(p, m, *in_optional_chain, true)
            }
            T![<] | T![<<] => {
                //  only those two possible token in cur position `parse_ts_type_arguments_in_expression` could possibly return a `Present(_)`
                if let Present(_) = parse_ts_type_arguments_in_expression(p, context) {
                    let new_marker = lhs.precede(p);
                    lhs = new_marker.complete(p, JsSyntaxKind::TS_INSTANTIATION_EXPRESSION);
                    continue;
                };
                break;
            }
            _ => {
                break;
            }
        };
    }

    lhs
}

// test_err ts ts_new_operator
// new A<test><test>();

// test ts ts_new_operator
// var c2 = new T<string>;  // Ok
// var x1 = new SS<number>(); // OK
// var x3 = new SS();         // OK
// var x4 = new SS;           // OK
fn parse_new_expr(p: &mut JsParser, context: ExpressionContext) -> ParsedSyntax {
    if !p.at(T![new]) {
        return Absent;
    }

    let m = p.start();
    p.expect(T![new]);

    // new.target
    if p.eat(T![.]) {
        if p.at(T![ident]) && p.cur_text() == "target" {
            p.bump_remap(TARGET);
        } else if is_at_identifier(p) {
            let identifier_range = p.cur_range();
            let name = p.cur_text();
            let error = p
                .err_builder(
                    format!("'{name}' is not a valid meta-property for keyword 'new'."),
                    identifier_range,
                )
                .with_hint("Did you mean 'target'?");

            p.error(error);
            p.bump_remap(T![ident]);
        } else {
            p.error(expected_identifier(p, p.cur_range()));
        }

        return Present(m.complete(p, JS_NEW_TARGET_EXPRESSION));
    }

    if let Some(lhs) = parse_primary_expression(p, context.and_ts_type_assertion_allowed(false))
        .or_add_diagnostic(p, expected_expression)
        .map(|expr| parse_member_expression_rest(p, expr, context, false, &mut false))
    {
        // test_err ts invalid_optional_chain_from_new_expressions
        // new Test<string>?.test();
        // new Test?.test();
        // new A.b?.c()
        // new (A.b)?.c()
        // new (A.b?.()).c()
        // new A.b?.()()
        if p.at(T![?.]) {
            let error = p
                .err_builder("Invalid optional chain from new expression.", p.cur_range())
                .with_hint(format!("Did you mean to call '{}()'?", lhs.text(p)));

            p.error(error);
        }
        if let TS_INSTANTIATION_EXPRESSION = lhs.kind(p) {
            lhs.undo_completion(p).abandon(p)
        };
    }

    // test ts ts_new_with_type_arguments
    // class Test<A, B, C> {}
    // new Test<A, B, C>();

    if p.at(T!['(']) {
        parse_call_arguments(p).unwrap();
    }

    Present(m.complete(p, JS_NEW_EXPRESSION))
}

// test js super_expression
// class Test extends B {
//   constructor() {
//     super();
//   }
//   test() {
//     super.test(a, b);
//     super[1];
//   }
// }
//
// test_err js super_expression_err
// class Test extends B {
//   test() {
//     super();
//     super?.test();
//   }
// }
// super();
fn parse_super_expression(p: &mut JsParser) -> ParsedSyntax {
    if !p.at(T![super]) {
        return Absent;
    }
    let super_marker = p.start();
    p.expect(T![super]);
    let mut super_expression = super_marker.complete(p, JS_SUPER_EXPRESSION);

    if p.at(T![?.]) {
        super_expression.change_kind(p, JS_BOGUS_EXPRESSION);
        p.error(p.err_builder(
            "Super doesn't support optional chaining as super can never be null",
            super_expression.range(p),
        ));
    } else if p.at(T!['(']) && !p.state().in_constructor() {
        p.error(p.err_builder(
            "`super` is only valid inside of a class constructor of a subclass.",
            super_expression.range(p),
        ));
        super_expression.change_kind(p, JS_BOGUS_EXPRESSION);
    }

    match p.cur() {
        T![.] | T!['['] | T!['('] | T![?.] => Present(super_expression),
        _ => parse_static_member_expression(p, super_expression, T![.]),
    }
}

// test js subscripts
// foo`bar`
// foo(bar)(baz)(baz)[bar]

/// A static member expression for accessing a property
// test js static_member_expression
// foo.bar
// foo.await
// foo.yield
// foo.for
// foo?.for
// foo?.bar
// class Test {
//   #bar
//   test(other) {
//     this.#bar;
//     this?.#bar;
//     other.#bar;
//     other?.#bar;
//   }
// }
fn parse_static_member_expression(
    p: &mut JsParser,
    lhs: CompletedMarker,
    operator: JsSyntaxKind,
) -> ParsedSyntax {
    // test ts ts_instantiation_expression_property_access
    // f<b>?.(c);
    // f<b>?.[c];
    // (f<b>).c;
    // (f<b>)?.c;
    // (f<b>)?.[c];
    if lhs.kind(p) == TS_INSTANTIATION_EXPRESSION {
        // test_err ts ts_instantiation_expression_property_access
        // f<b>.c;
        // f<b>?.c;
        // a?.f<c>.d;
        // f<a>.g<b>;
        p.error(p.err_builder(
            "An instantiation expression cannot be followed by a property access.",
            lhs.range(p),
        ).with_hint("You can either wrap the instantiation expression in parentheses, or delete the type arguments."));
    }

    let m = lhs.precede(p);
    p.expect(operator);

    parse_any_name(p).or_add_diagnostic(p, expected_identifier);

    Present(m.complete(p, JS_STATIC_MEMBER_EXPRESSION))
}

pub(super) fn parse_private_name(p: &mut JsParser) -> ParsedSyntax {
    if !p.at(T![#]) {
        return Absent;
    }

    let m = p.start();
    let hash_end = p.cur_range().end();
    p.expect(T![#]);

    if (is_nth_at_identifier_or_keyword(p, 0)) && hash_end != p.cur_range().start() {
        // test_err js private_name_with_space
        // class A {
        // 	# test;
        // }
        p.error(
            p.err_builder(
                "Unexpected space or comment between `#` and identifier",
                hash_end..p.cur_range().start(),
            )
            .with_hint("remove the space here"),
        );
        Present(m.complete(p, JS_BOGUS))
    } else {
        if p.cur().is_keyword() {
            p.bump_remap(T![ident]);
        } else if p.at(T![ident]) {
            p.bump(T![ident]);
        } else {
            p.error(expected_identifier(p, p.cur_range()));
        }
        Present(m.complete(p, JS_PRIVATE_NAME))
    }
}

pub(super) fn parse_any_name(p: &mut JsParser) -> ParsedSyntax {
    match p.cur() {
        T![#] => parse_private_name(p),
        _ => parse_name(p),
    }
}

/// An array expression for property access or indexing, such as `foo[0]` or `foo?.["bar"]`
// test js computed_member_expression
// foo[bar]
// foo[5 + 5]
// foo["bar"]
// foo[bar][baz]
// foo?.[bar]
fn parse_computed_member_expression(
    p: &mut JsParser,
    lhs: CompletedMarker,
    optional_chain: bool,
) -> ParsedSyntax {
    // test_err js bracket_expr_err
    // foo[]
    // foo?.[]
    // foo[
    let m = lhs.precede(p);
    if optional_chain {
        p.expect(T![?.]);
    }

    p.expect(T!['[']);
    // test js computed_member_in
    // for ({}["x" in {}];;) {}
    parse_expression(p, ExpressionContext::default()).or_add_diagnostic(p, expected_expression);

    p.expect(T![']']);

    Present(m.complete(p, JS_COMPUTED_MEMBER_EXPRESSION))
}

/// An identifier name, either an ident or a keyword
pub(super) fn parse_name(p: &mut JsParser) -> ParsedSyntax {
    if is_at_name(p) {
        let m = p.start();
        p.bump_remap(T![ident]);
        Present(m.complete(p, JS_NAME))
    } else {
        Absent
    }
}

/// Arguments to a function.
///
/// `"(" (AssignExpr ",")* ")"`

// test js call_arguments
// function foo(...args) {}
// let a, b, c, d;
// foo(a);
// foo(a, b,);
// foo(a, b, ...c);
// foo(...a, ...b, c, ...d,);
//
// test_err js invalid_arg_list
// function foo(...args) {}
// let a, b, c;
// foo(a,b;
// foo(a,b var;
// foo (,,b);
// foo (a, ...);
fn parse_call_arguments(p: &mut JsParser) -> ParsedSyntax {
    if !p.at(T!['(']) {
        return Absent;
    }

    // test js in_expr_in_arguments
    // function foo() {}
    // for (foo("call" in foo);;) {}

    let m = p.start();
    p.bump(T!['(']);
    let args_list = p.start();
    let mut first = true;
    let mut progress = ParserProgress::default();

    while !p.at(EOF) && !p.at(T![')']) {
        if first {
            first = false;
        } else {
            p.expect(T![,]);
        }

        if p.at(T![')']) {
            break;
        }

        progress.assert_progressing(p);

        let argument = if p.at(T![...]) {
            // already do a check on "..." so it's safe to unwrap
            parse_spread_element(p, ExpressionContext::default())
        } else {
            parse_assignment_expression_or_higher(p, ExpressionContext::default())
        };

        if argument.is_absent() && p.at(T![,]) {
            argument.or_add_diagnostic(p, js_parse_error::expected_expression);
            // missing element
            continue;
        }

        if argument
            .or_recover_with_token_set(
                p,
                &ParseRecoveryTokenSet::new(
                    JS_BOGUS_EXPRESSION,
                    EXPR_RECOVERY_SET.union(token_set!(T![')'], T![;], T![...])),
                )
                .enable_recovery_on_line_break(),
                js_parse_error::expected_expression,
            )
            .is_err()
        {
            break;
        }
    }

    args_list.complete(p, JS_CALL_ARGUMENT_LIST);
    p.expect(T![')']);
    Present(m.complete(p, JS_CALL_ARGUMENTS))
}

// test js parenthesized_sequence_expression
// (a, b);
// (a, b, c);
// (a, b, c, d, e, f);
// (a, b, c, d, e, f)
// (a, b, c)

// test_err js incomplete_parenthesized_sequence_expression
// (a,;
// (a, b, c;

// test js js_parenthesized_expression
// ((foo))
// (foo)

fn parse_parenthesized_expression(p: &mut JsParser) -> ParsedSyntax {
    if !p.at(T!['(']) {
        return Absent;
    }

    let m = p.start();
    p.bump(T!['(']);

    // test js for_with_in_in_parenthesized_expression
    // for((true,"selectionStart"in true);;) {}
    if p.at(T![')']) {
        // test_err js empty_parenthesized_expression
        // ();
        p.error(
            p.err_builder(
                "Parenthesized expression didnt contain anything",
                p.cur_range(),
            )
            .with_hint("Expected an expression here"),
        );
    } else {
        let first = parse_assignment_expression_or_higher(p, ExpressionContext::default());

        if p.at(T![,]) {
            parse_sequence_expression_recursive(p, first, ExpressionContext::default())
                .or_add_diagnostic(p, expected_expression);
        }
    }

    p.expect(T![')']);
    Present(m.complete(p, JS_PARENTHESIZED_EXPRESSION))
}

/// A general expression.
pub(crate) fn parse_expression(p: &mut JsParser, context: ExpressionContext) -> ParsedSyntax {
    let first = parse_assignment_expression_or_higher(p, context);

    if p.at(T![,]) {
        parse_sequence_expression_recursive(p, first, context)
    } else {
        first
    }
}

// test js sequence_expr
// 1, 2, 3, 4, 5

// test_err js sequence_expr
// 1, 2, , 4
fn parse_sequence_expression_recursive(
    p: &mut JsParser,
    left: ParsedSyntax,
    context: ExpressionContext,
) -> ParsedSyntax {
    if !p.at(T![,]) {
        return left;
    }

    let mut left = left;

    while p.at(T![,]) {
        let sequence_expr_marker =
            left.precede_or_add_diagnostic(p, js_parse_error::expected_expression);
        p.bump(T![,]);
        parse_assignment_expression_or_higher(p, context).or_add_diagnostic(p, expected_expression);

        left = Present(sequence_expr_marker.complete(p, JS_SEQUENCE_EXPRESSION))
    }

    left
}

#[inline]
pub(crate) fn is_at_expression(p: &mut JsParser) -> bool {
    is_nth_at_expression(p, 0)
}

pub(crate) fn is_nth_at_expression(p: &mut JsParser, n: usize) -> bool {
    match p.nth(n) {
        T![!]
        | T!['(']
        | T!['[']
        | T!['{']
        | T![++]
        | T![--]
        | T![~]
        | T![+]
        | T![-]
        | T![throw]
        | T![new]
        | T![typeof]
        | T![void]
        | T![delete]
        | T![ident]
        | T![...]
        | T![this]
        | T![yield]
        | T![function]
        | T![class]
        | T![import]
        | T![super]
        | T![#]
        | T![<]
        | T![/]
        | T![/=]
        | BACKTICK
        | TRUE_KW
        | FALSE_KW
        | JS_NUMBER_LITERAL
        | JS_BIGINT_LITERAL
        | JS_STRING_LITERAL
        | NULL_KW => true,
        t => t.is_contextual_keyword() || t.is_future_reserved_keyword(),
    }
}

/// A primary expression such as a literal, an object, an array, or `this`.
fn parse_primary_expression(p: &mut JsParser, context: ExpressionContext) -> ParsedSyntax {
    let parsed_literal_expression = parse_literal_expression(p);
    if parsed_literal_expression.is_present() {
        return parsed_literal_expression;
    }

    let complete = match p.cur() {
        T![this] => {
            // test js this_expr
            // this
            // this.foo
            let m = p.start();
            p.expect(T![this]);
            m.complete(p, JS_THIS_EXPRESSION)
        }
        T![@] => {
            let decorator_list = parse_decorators(p);

            return match p.cur() {
                T![class] => {
                    // test js decorator_expression_class
                    // let a = @decorator class {};
                    // let b = @first @second class foo {
                    //  constructor() {}
                    // }
                    parse_class_expression(p, decorator_list)
                }
                _ => {
                    // test_err js decorator_expression_class
                    // let a = @decorator () => {};
                    // let b = @first @second function foo() {}
                    // let a = @decorator ( () => {} )
                    decorator_list
                        .add_diagnostic_if_present(p, decorators_not_allowed)
                        .map(|mut marker| {
                            marker.change_kind(p, JS_BOGUS_EXPRESSION);
                            marker
                        });
                    parse_assignment_expression_or_higher(p, context)
                }
            };
        }
        T![class] => {
            // test js class_expr
            // let a = class {};
            // let b = class foo {
            //  constructor() {}
            // }
            // foo[class {}]
            parse_class_expression(p, Absent).unwrap()
        }
        // test js async_ident
        // let a = async;
        T![async] if is_at_async_function(p, LineBreak::DoCheck) => {
            // test js async_function_expr
            // let a = async function() {};
            // let b = async function foo() {};
            parse_function_expression(p).unwrap()
        }
        T![function] => {
            // test js function_expr
            // let a = function() {}
            // let b = function foo() {}

            parse_function_expression(p).unwrap()
        }
        // test js grouping_expr
        // ((foo))
        // (foo)
        T!['('] => parse_parenthesized_expression(p).unwrap(),
        T!['['] => parse_array_expr(p).unwrap(),
        T!['{'] if context.is_object_expression_allowed() => parse_object_expression(p).unwrap(),

        // test_err js import_keyword_in_expression_position
        // let a = import;
        T![import] if matches!(p.nth(1), T![.] | T!['(']) => {
            let m = p.start();
            p.bump_any();

            // test js import_meta
            // import.meta
            if p.eat(T![.]) {
                // test_err js import_no_meta
                // import.foo
                // import.metaa
                if p.at(T![ident]) && p.text(p.cur_range()) == "meta" {
                    p.bump_remap(META);
                    m.complete(p, JS_IMPORT_META_EXPRESSION)
                } else if p.at(T![ident]) {
                    let err = p.err_builder(
                        format!(
                            "Expected `meta` following an import keyword, but found `{}`",
                            p.text(p.cur_range())
                        ),
                        p.cur_range(),
                    );

                    p.err_and_bump(err, JS_BOGUS);
                    m.complete(p, JS_IMPORT_META_EXPRESSION)
                } else {
                    let err = p.err_builder(
                        "Expected `meta` following an import keyword, but found none",
                        p.cur_range(),
                    );

                    p.error(err);
                    m.complete(p, JS_BOGUS)
                }
            } else {
                // test js import_call
                // import("foo")
                // import("foo", { assert: { type: 'json' } })

                // test_err js import_invalid_args
                // import()
                // import(...["foo"])
                // import("foo", { assert: { type: 'json' } }, "bar")

                let args = p.start();
                p.bump(T!['(']);
                let args_list = p.start();

                let mut progress = ParserProgress::default();
                let mut error_range_start = p.cur_range().start();
                let mut args_count = 0;

                while !p.at(EOF) && !p.at(T![')']) {
                    progress.assert_progressing(p);
                    args_count += 1;

                    if args_count == 3 {
                        error_range_start = p.cur_range().start();
                    }

                    if p.at(T![...]) {
                        parse_spread_element(p, context)
                            .add_diagnostic_if_present(p, |p, range| {
                                p.err_builder("`...` is not allowed in `import()`", range)
                            })
                            .map(|mut marker| {
                                marker.change_to_bogus(p);
                                marker
                            });
                    } else {
                        parse_assignment_expression_or_higher(p, ExpressionContext::default())
                            .or_add_diagnostic(p, js_parse_error::expected_expression_assignment);
                    }

                    if p.at(T![,]) {
                        p.bump_any();
                    } else {
                        break;
                    }
                }

                args_list.complete(p, JS_CALL_ARGUMENT_LIST);
                if args_count == 0 || args_count > 2 {
                    let err = p.err_builder(
                        "`import()` requires exactly one or two arguments. ",
                        error_range_start..p.cur_range().end(),
                    );
                    p.error(err);
                }

                p.expect(T![')']);
                args.complete(p, JS_CALL_ARGUMENTS);
                m.complete(p, JS_IMPORT_CALL_EXPRESSION)
            }
        }
        T![new] => parse_new_expr(p, context).unwrap(),

        BACKTICK => {
            let m = p.start();
            parse_template_literal(p, m, false, false)
        }
        ERROR_TOKEN => {
            let m = p.start();
            p.bump_any();
            m.complete(p, JS_BOGUS)
        }
        T![ident] => parse_identifier_expression(p).unwrap(),
        // test jsx jsx_primary_expression
        // let a = <test>abcd</test>.c;

        // test ts type_assertion_primary_expression
        // let a = <number>undefined;

        // test_err ts ts_type_assertions_not_valid_at_new_expr
        // var test2 = new <any>Test2();

        // test ts ts_type_assertion
        // let a = <number>b;
        T![<] if Jsx.is_supported(p) => return parse_jsx_tag_expression(p),

        // test_err js primary_expr_invalid_recovery
        // let a = \; foo();
        t if t.is_contextual_keyword() || t.is_future_reserved_keyword() => {
            // test js identifier_reference
            // // SCRIPT
            // foo;
            // yield;
            // await;
            parse_identifier_expression(p).unwrap()
        }
        _ => {
            return Absent;
        }
    };

    Present(complete)
}

fn parse_identifier_expression(p: &mut JsParser) -> ParsedSyntax {
    parse_reference_identifier(p)
        .map(|identifier| identifier.precede(p).complete(p, JS_IDENTIFIER_EXPRESSION))
}

// test_err js identifier
// yield;
// await;
pub(crate) fn parse_reference_identifier(p: &mut JsParser) -> ParsedSyntax {
    parse_identifier(p, JS_REFERENCE_IDENTIFIER)
}

pub(crate) fn is_nth_at_reference_identifier(p: &mut JsParser, n: usize) -> bool {
    is_nth_at_identifier(p, n)
}

// test js identifier_loose_mode
// // SCRIPT
// foo;
// yield;
// await;
//
// test js identifier
// foo;
// let accessor = 5;
//
// test_err js identifier_err
// yield;
// await;
// async function test(await) {}
// function* test(yield) {}
// enum;
// implements;
// interface;

/// Parses an identifier if it is valid in this context or returns `Invalid` if the context isn't valid in this context.
/// An identifier is invalid if:
/// * It is named `await` inside of an async function
/// * It is named `yield` inside of a generator function or in strict mode
pub(super) fn parse_identifier(p: &mut JsParser, kind: JsSyntaxKind) -> ParsedSyntax {
    if !is_at_identifier(p) {
        return Absent;
    }

    let error = match p.cur() {
        T![yield] if p.state().in_generator() => Some(p.err_builder(
            "Illegal use of `yield` as an identifier in generator function",
            p.cur_range(),
        )),
        t if t.is_future_reserved_keyword() => {
            if StrictMode.is_supported(p) {
                let name = p.cur_text();
                Some(p.err_builder(
                    format!(
                        "Illegal use of reserved keyword `{}` as an identifier in strict mode",
                        name
                    ),
                    p.cur_range(),
                ))
            } else {
                None
            }
        }
        // test ts await_in_ambient_context
        // declare const await: any;
        T![await] if !p.state().in_ambient_context() => {
            if p.state().in_async() {
                Some(p.err_builder(
                    "Illegal use of `await` as an identifier in an async context",
                    p.cur_range(),
                ))
            } else if p.source_type().is_module() {
                Some(p.err_builder(
                    "Illegal use of `await` as an identifier inside of a module",
                    p.cur_range(),
                ))
            } else {
                None
            }
        }
        _ => None,
    };

    let m = p.start();
    p.bump_remap(T![ident]);
    let mut identifier = m.complete(p, kind);

    if let Some(error) = error {
        p.error(error);
        identifier.change_to_bogus(p);
    }

    Present(identifier)
}

#[inline]
pub(crate) fn is_at_identifier(p: &mut JsParser) -> bool {
    is_nth_at_identifier(p, 0)
}

#[inline]
pub(crate) fn is_nth_at_identifier(p: &mut JsParser, n: usize) -> bool {
    p.nth_at(n, T![ident])
        || p.nth(n).is_contextual_keyword()
        || p.nth(n).is_future_reserved_keyword()
}

#[inline]
pub(crate) fn is_nth_at_identifier_or_keyword(p: &mut JsParser, n: usize) -> bool {
    p.nth(n).is_keyword() || is_nth_at_identifier(p, n)
}

/// A template literal such as "`abcd ${efg}`"
// test js template_literal
// let a = `foo ${bar}`;
// let b = ``;
// let c = `${foo}`;
// let d = `foo`;
// let e = `${{ a: "string" }}`;

// test_err js template_literal
// let a = `foo ${}`
// let b = `${a a}`
fn parse_template_literal(
    p: &mut JsParser,
    marker: Marker,
    in_optional_chain: bool,
    tagged: bool,
) -> CompletedMarker {
    p.bump_with_context(BACKTICK, JsLexContext::TemplateElement { tagged });

    let elements_list = p.start();
    parse_template_elements(
        p,
        JS_TEMPLATE_CHUNK_ELEMENT,
        JS_TEMPLATE_ELEMENT,
        tagged,
        |p| {
            parse_expression(p, ExpressionContext::default())
                .or_add_diagnostic(p, js_parse_error::expected_expression)
        },
    );

    elements_list.complete(p, JS_TEMPLATE_ELEMENT_LIST);

    // test_err js template_literal_unterminated
    // let a = `${foo} bar

    // The lexer emits an error for unterminated template literals
    p.eat(BACKTICK);
    let mut completed = marker.complete(p, JS_TEMPLATE_EXPRESSION);

    // test_err js template_after_optional_chain
    // obj.val?.prop`template`
    // obj.val?.[expr]`template`
    // obj.func?.(args)`template`
    if in_optional_chain {
        p.error(p.err_builder(
            "Tagged template expressions are not permitted in an optional chain.",
            completed.range(p),
        ));
        completed.change_kind(p, JS_BOGUS_EXPRESSION);
    }

    completed
}

#[inline]
pub(crate) fn parse_template_elements<P>(
    p: &mut JsParser,
    chunk_kind: JsSyntaxKind,
    element_kind: JsSyntaxKind,
    tagged: bool,
    parse_element: P,
) where
    P: Fn(&mut JsParser) -> Option<CompletedMarker>,
{
    while !p.at(EOF) && !p.at(BACKTICK) {
        match p.cur() {
            TEMPLATE_CHUNK => {
                let m = p.start();
                p.bump_with_context(TEMPLATE_CHUNK, JsLexContext::TemplateElement { tagged });
                m.complete(p, chunk_kind);
            },
            DOLLAR_CURLY => {
                let e = p.start();
                p.bump(DOLLAR_CURLY);

                parse_element(p);
                if !p.at(T!['}']) {
                    p.error(expected_token(T!['}']));
                    // Seems there's more. For example a `${a a}`. We must eat all tokens away to avoid a panic because of an unexpected token
                    let _ =  ParseRecoveryTokenSet::new(JS_BOGUS, token_set![T!['}'], TEMPLATE_CHUNK, DOLLAR_CURLY, ERROR_TOKEN, BACKTICK]).recover(p);
                    if !p.at(T!['}']) {
                        e.complete(p, element_kind);
                        // Failed to fully recover, unclear where we are now, exit
                        break;
                    }
                }

                p.bump_with_context(T!['}'], JsLexContext::TemplateElement { tagged });
                e.complete(p, element_kind);
            }
            ERROR_TOKEN => {
                let err = p.err_builder("Invalid template literal",p.cur_range(), );
                p.error(err);
                p.bump_with_context(p.cur(), JsLexContext::TemplateElement { tagged });
            }
            t => unreachable!("Anything not template chunk or dollarcurly should have been eaten by the lexer, but {:?} was found", t),
        };
    }
}

struct ArrayElementsList;

impl ParseSeparatedList for ArrayElementsList {
    type Kind = JsSyntaxKind;
    type Parser<'a> = JsParser<'a>;
    const LIST_KIND: JsSyntaxKind = JS_ARRAY_ELEMENT_LIST;

    fn parse_element(&mut self, p: &mut JsParser) -> ParsedSyntax {
        match p.cur() {
            T![...] => parse_spread_element(p, ExpressionContext::default()),
            T![,] => Present(p.start().complete(p, JS_ARRAY_HOLE)),
            _ => parse_assignment_expression_or_higher(p, ExpressionContext::default()),
        }
    }

    fn is_at_list_end(&self, p: &mut JsParser) -> bool {
        p.at(T![']'])
    }

    fn recover(&mut self, p: &mut JsParser, parsed_element: ParsedSyntax) -> RecoveryResult {
        parsed_element.or_recover_with_token_set(
            p,
            &ParseRecoveryTokenSet::new(
                JS_BOGUS_EXPRESSION,
                EXPR_RECOVERY_SET.union(token_set!(T![']'])),
            ),
            js_parse_error::expected_array_element,
        )
    }

    fn separating_element_kind(&mut self) -> JsSyntaxKind {
        T![,]
    }

    fn allow_trailing_separating_element(&self) -> bool {
        true
    }
}

/// An array literal such as `[foo, bar, ...baz]`.
// test js array_expr
// [foo, bar];
// [foo];
// [,foo];
// [foo,];
// [,,,,,foo,,,,];
// [...a, ...b];

// test_err js array_expr_incomplete
// let a = [
fn parse_array_expr(p: &mut JsParser) -> ParsedSyntax {
    if !p.at(T!['[']) {
        return Absent;
    }
    let m = p.start();
    p.bump(T!['[']);

    // test js array_element_in_expr
    // for(["a" in {}];;) {}
    ArrayElementsList.parse_list(p);

    p.expect(T![']']);
    Present(m.complete(p, JS_ARRAY_EXPRESSION))
}

// test_err js spread
// [...]
/// A spread element consisting of three dots and an assignment expression such as `...foo`
fn parse_spread_element(p: &mut JsParser, context: ExpressionContext) -> ParsedSyntax {
    if !p.at(T![...]) {
        return Absent;
    }
    let m = p.start();
    p.bump(T![...]);
    parse_assignment_expression_or_higher(p, context)
        .or_add_diagnostic(p, js_parse_error::expected_expression_assignment);
    Present(m.complete(p, JS_SPREAD))
}

/// A left hand side expression, either a member expression or a call expression such as `foo()`.
pub(super) fn parse_lhs_expr(p: &mut JsParser, context: ExpressionContext) -> ParsedSyntax {
    // super.foo and super[bar]
    // test js super_property_access
    // super.foo
    // super[bar]
    // super[foo][bar]
    let lhs = if p.at(T![super]) {
        parse_super_expression(p)
    } else {
        parse_member_expression_or_higher(p, context)
    };

    lhs.map(|lhs_marker| parse_call_expression_rest(p, lhs_marker, context))
}

fn parse_call_expression_rest(
    p: &mut JsParser,
    lhs: CompletedMarker,
    context: ExpressionContext,
) -> CompletedMarker {
    let mut lhs = lhs;
    let mut in_optional_chain = false;
    loop {
        lhs = parse_member_expression_rest(p, lhs, context, true, &mut in_optional_chain);

        if !matches!(p.cur(), T![?.] | T![<] | T![<<] | T!['(']) {
            break lhs;
        }

        // Cloning here is necessary because parsing out the type arguments may rewind in which
        // case we want to return the `lhs`.
        let m = match lhs.kind(p) {
            TS_INSTANTIATION_EXPRESSION if !p.at(T![?.]) => lhs.clone().undo_completion(p),
            _ => lhs.clone().precede(p),
        };

        let start_pos = p.source().position();
        let optional_chain_call = p.eat(T![?.]);
        in_optional_chain = in_optional_chain || optional_chain_call;

        // test ts ts_call_expr_with_type_arguments
        // function a<A, B, C>() {}
        // a<A, B, C>();
        // (() => { a }).a<A, B, C>()
        // (() => a)<A, B, C>();
        // type A<T> = T;
        // a<<T>(arg: T) => number, number, string>();

        let type_arguments = if optional_chain_call {
            let type_arguments = parse_ts_type_arguments_in_expression(p, context).ok();
            if p.cur() == BACKTICK {
                // test ts ts_tagged_template_literal
                // html<A, B>`abcd`
                // html<A, B>`abcd`._string
                lhs = parse_template_literal(p, m, optional_chain_call, true);
                continue;
            }
            type_arguments
        } else {
            None
        };

        if type_arguments.is_some() || p.at(T!['(']) {
            parse_call_arguments(p)
                .or_add_diagnostic(p, |p, _| expected_token(T!['(']).into_diagnostic(p));
            lhs = m.complete(p, JS_CALL_EXPRESSION);
        } else {
            break if optional_chain_call {
                // If the `?.` is present and what followed was neither a valid type arguments nor valid arguments.
                // In this case, parse this as a static member access with an optional chain

                // test_err ts optional_chain_call_without_arguments
                // let a = { test: null };
                // a.test?.;
                // a.test?.<ab;
                p.error(expected_identifier(p, p.cur_range()));
                m.complete(p, JS_STATIC_MEMBER_EXPRESSION)
            } else {
                // test ts optional_chain_call_less_than
                // String(item)?.b < 0;
                // String(item)?.b <aBcd;

                // Safety:
                // * The method initially checks if the parsers at a '<', '(', or '?.' token.
                // * if the parser is at '?.': It takes the branch right above, ensuring that no token was consumed
                // * if the parser is at '<': `parse_ts_type_arguments_in_expression` rewinds if what follows aren't  valid type arguments and this is the only way we can reach this branch
                // * if the parser is at '(': This always parses out as valid arguments.
                debug_assert_eq!(p.source().position(), start_pos);
                m.abandon(p);
                lhs
            };
        }
    }
}

/// A postifx expression, either `LHSExpr [no linebreak] ++` or `LHSExpr [no linebreak] --`.
// test js postfix_expr
// foo++
// foo--
fn parse_postfix_expr(p: &mut JsParser, context: ExpressionContext) -> ParsedSyntax {
    let checkpoint = p.checkpoint();
    let lhs = parse_lhs_expr(p, context);
    lhs.map(|marker| {
        if !p.has_preceding_line_break() {
            // test js post_update_expr
            // foo++
            // foo--
            match p.cur() {
                T![++] => {
                    let assignment_target = expression_to_assignment(p, marker, checkpoint);
                    let m = assignment_target.precede(p);
                    p.bump(T![++]);
                    m.complete(p, JS_POST_UPDATE_EXPRESSION)
                }
                T![--] => {
                    let assignment_target = expression_to_assignment(p, marker, checkpoint);
                    let m = assignment_target.precede(p);
                    p.bump(T![--]);
                    m.complete(p, JS_POST_UPDATE_EXPRESSION)
                }
                _ => marker,
            }
        } else {
            marker
        }
    })
}

/// A unary expression such as `!foo` or `++bar`
pub(super) fn parse_unary_expr(p: &mut JsParser, context: ExpressionContext) -> ParsedSyntax {
    const UNARY_SINGLE: TokenSet<JsSyntaxKind> =
        token_set![T![delete], T![void], T![typeof], T![+], T![-], T![~], T![!]];

    if p.at(T![await]) {
        // test js await_expression
        // async function test() {
        //   await inner();
        //   await (inner()) + await inner();
        // }
        // async function inner() {
        //   return 4;
        // }
        // await test();

        // test_err js no_top_level_await_in_scripts
        // // SCRIPT
        // async function test() {}
        // await test();
        let m = p.start();
        let checkpoint = p.checkpoint();
        let await_range = p.cur_range();
        p.expect(T![await]);
        let unary = parse_unary_expr(p, context);

        let is_top_level_module_or_async_fn =
            p.state().in_async() && (p.state().is_top_level() || p.state().in_function());

        if !is_top_level_module_or_async_fn {
            // test js reparse_await_as_identifier
            // // SCRIPT
            // function test() { a = await; }
            // function test2() { return await; }
            if unary.is_absent() {
                p.rewind(checkpoint);
                m.abandon(p);
                return parse_identifier_expression(p);
            }

            // test_err js await_in_parameter_initializer
            // async function test(a = await b()) {}
            // function test2(a = await b()) {}

            // test_err js await_in_static_initialization_block_member
            // // SCRIPT
            // class A { static { await; } }
            // class B { static { await 10; } }

            // test_err js await_in_non_async_function
            // function test() { await 10; }

            // test_err js await_in_module
            // let await = 10;
            // console.log(await);
            p.error(p.err_builder(
                "`await` is only allowed within async functions and at the top levels of modules.",
                await_range,
            ));

            let expr = m.complete(p, JS_BOGUS_EXPRESSION);
            return Present(expr);
        }

        unary.or_add_diagnostic(p, js_parse_error::expected_unary_expression);
        let expr = m.complete(p, JS_AWAIT_EXPRESSION);
        return Present(expr);
    }

    // This is a type assertion expression if the parser is at the `<` token and JSX is disabled
    // JSX elements are parsed in parse_primary_expression.
    if p.at(T![<]) && Jsx.is_unsupported(p) {
        return TypeScript.parse_exclusive_syntax(
            p,
            |p| parse_ts_type_assertion_expression(p, context),
            |p, assertion| ts_only_syntax_error(p, "type assertion", assertion.range(p)),
        );
    }

    // test js pre_update_expr
    // ++foo
    // --foo
    if p.at(T![++]) {
        let m = p.start();
        p.bump(T![++]);
        parse_assignment(p, AssignmentExprPrecedence::Unary, context)
            .or_add_diagnostic(p, expected_simple_assignment_target);
        let complete = m.complete(p, JS_PRE_UPDATE_EXPRESSION);
        return Present(complete);
    }
    if p.at(T![--]) {
        let m = p.start();
        p.bump(T![--]);
        parse_assignment(p, AssignmentExprPrecedence::Unary, context)
            .or_add_diagnostic(p, expected_simple_assignment_target);
        let complete = m.complete(p, JS_PRE_UPDATE_EXPRESSION);
        return Present(complete);
    }

    // test js js_unary_expressions
    // delete a['test'];
    // void a;
    // typeof a;
    // +1;
    // -1;
    // ~1;
    // !true;
    // -a + -b + +a;

    // test_err js unary_expr
    // ++ ;
    // -- ;
    // -;

    if p.at_ts(UNARY_SINGLE) {
        let m = p.start();
        let op = p.cur();

        let is_delete = op == T![delete];

        if is_delete {
            p.expect(T![delete]);
        } else {
            p.bump_any();
        }

        // test js unary_delete
        // delete obj.key;
        // delete (obj).key;
        // delete obj.#member.key;
        // delete (obj.#member).key;
        // delete func().#member.key;
        // delete (func().#member).key;
        // delete obj?.#member.key;
        // delete (obj?.#member).key;
        // delete obj?.inner.#member.key;
        // delete (obj?.inner.#member).key;
        // delete obj[key];
        // delete (obj)[key];
        // delete obj.#member[key];
        // delete (obj.#member)[key];
        // delete func().#member[key];
        // delete (func().#member)[key];
        // delete obj?.#member[key];
        // delete (obj?.#member)[key];
        // delete obj?.inner.#member[key];
        // delete (obj?.inner.#member)[key];
        // delete (obj.#key, obj.key);
        // delete (#key in obj);
        // delete (obj.key);
        // delete (console.log(1));
        // delete (() => {});

        // test js unary_delete_nested
        // class TestClass { #member = true; method() { delete func(this.#member) } }
        // class TestClass { #member = true; method() { delete [this.#member] } }
        // class TestClass { #member = true; method() { delete { key: this.#member } } }
        // class TestClass { #member = true; method() { delete (() => { this.#member; }) } }
        // class TestClass { #member = true; method() { delete (param => { this.#member; }) } }
        // class TestClass { #member = true; method() { delete (async () => { this.#member; }) } }

        // test_err js unary_delete
        // delete ident;
        // delete obj.#member;
        // delete func().#member;
        // delete obj?.#member;
        // delete obj?.inner.#member;

        // test_err js unary_delete_parenthesized
        // delete (ident);
        // delete ((ident));
        // delete (obj.key, ident);
        // delete (obj.#member);
        // delete (func().#member);
        // delete (obj?.#member);
        // delete (obj?.inner.#member);
        // delete (obj.key, obj.#key);

        let mut kind = JS_UNARY_EXPRESSION;

        if is_delete {
            let checkpoint = p.checkpoint();
            parse_unary_expr(p, context).ok();

            let mut rewriter = DeleteExpressionRewriter::default();
            rewrite_events(&mut rewriter, checkpoint, p);

            rewriter.result.take().map(|res| {
                if StrictMode.is_supported(p) {
                    if let Some(range) = rewriter.exited_ident_expr {
                        kind = JS_BOGUS_EXPRESSION;
                        p.error(p.err_builder(
                            "the target for a delete operator cannot be a single identifier",
                            range,
                        ));
                    }
                }

                if let Some(range) = rewriter.exited_private_member_expr {
                    kind = JS_BOGUS_EXPRESSION;
                    p.error(p.err_builder(
                        "the target for a delete operator cannot be a private member",
                        range,
                    ));
                }

                res
            })
        } else {
            parse_unary_expr(p, context).ok()
        };

        return Present(m.complete(p, kind));
    }

    parse_postfix_expr(p, context)
}

#[derive(Default)]
struct DeleteExpressionRewriter {
    stack: Vec<(RewriteMarker, JsSyntaxKind)>,
    result: Option<CompletedMarker>,
    /// Set to true immediately after the rewriter exits an identifier expression
    exited_ident_expr: Option<TextRange>,
    /// Set to true immediately after the rewriter exits a private name
    exited_private_name: bool,
    /// Set to true immediately after the rewriter exits a member expresison with a private name
    exited_private_member_expr: Option<TextRange>,
}

impl RewriteParseEvents for DeleteExpressionRewriter {
    fn start_node(&mut self, kind: JsSyntaxKind, p: &mut RewriteParser) {
        self.stack.push((p.start(), kind));
        self.exited_ident_expr.take();
        self.exited_private_name = false;
        self.exited_private_member_expr.take();
    }

    fn finish_node(&mut self, p: &mut RewriteParser) {
        let (m, kind) = self.stack.pop().expect("stack depth mismatch");
        let node = m.complete(p, kind);

        if kind != JS_PARENTHESIZED_EXPRESSION && kind != JS_SEQUENCE_EXPRESSION {
            self.exited_private_member_expr =
                if self.exited_private_name && kind == JS_STATIC_MEMBER_EXPRESSION {
                    Some(node.range(p))
                } else {
                    None
                };

            self.exited_ident_expr = if kind == JS_IDENTIFIER_EXPRESSION {
                Some(node.range(p))
            } else {
                None
            };

            self.exited_private_name = kind == JS_PRIVATE_NAME;
        }

        self.result = Some(node.into());
    }
}

pub(super) fn is_at_name(p: &mut JsParser) -> bool {
    is_nth_at_name(p, 0)
}

pub(super) fn is_nth_at_name(p: &mut JsParser, offset: usize) -> bool {
    p.nth_at(offset, T![ident]) || p.nth(offset).is_keyword()
}

pub(super) fn is_nth_at_any_name(p: &mut JsParser, n: usize) -> bool {
    is_nth_at_name(p, n) || p.nth_at(n, T![#])
}