summaryrefslogtreecommitdiffstats
path: root/js/src/frontend/Parser.h
blob: 5f14a76227253ef89f74fc53648d91f9cd6c0efe (plain)
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set ts=8 sts=2 et sw=2 tw=80:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/* JS parser. */

#ifndef frontend_Parser_h
#define frontend_Parser_h

/*
 * [SMDOC] JS Parser
 *
 * JS parsers capable of generating ASTs from source text.
 *
 * A parser embeds token stream information, then gets and matches tokens to
 * generate a syntax tree that, if desired, BytecodeEmitter will use to compile
 * bytecode.
 *
 * Like token streams (see the comment near the top of TokenStream.h), parser
 * classes are heavily templatized -- along the token stream's character-type
 * axis, and also along a full-parse/syntax-parse axis.  Certain limitations of
 * C++ (primarily the inability to partially specialize function templates),
 * plus the desire to minimize compiled code size in duplicate function
 * template instantiations wherever possible, mean that Parser exhibits much of
 * the same unholy template/inheritance complexity as token streams.
 *
 * == ParserSharedBase ==
 *
 * ParserSharedBase is the base class for both regular JS and BinAST parsing.
 * This class contains common fields and methods between both parsers. There is
 * currently no BinAST parser here so this can potentially be merged into the
 * ParserBase type below.
 *
 * == ParserBase → ParserSharedBase, ErrorReportMixin ==
 *
 * ParserBase is the base class for regular JS parser, shared by all regular JS
 * parsers of all character types and parse-handling behavior.  It stores
 * everything character- and handler-agnostic.
 *
 * ParserBase's most important field is the parser's token stream's
 * |TokenStreamAnyChars| component, for all tokenizing aspects that are
 * character-type-agnostic.  The character-type-sensitive components residing
 * in |TokenStreamSpecific| (see the comment near the top of TokenStream.h)
 * live elsewhere in this hierarchy.  These separate locations are the reason
 * for the |AnyCharsAccess| template parameter to |TokenStreamChars| and
 * |TokenStreamSpecific|.
 *
 * == PerHandlerParser<ParseHandler> → ParserBase ==
 *
 * Certain parsing behavior varies between full parsing and syntax-only parsing
 * but does not vary across source-text character types.  For example, the work
 * to "create an arguments object for a function" obviously varies between
 * syntax and full parsing but (because no source characters are examined) does
 * not vary by source text character type.  Such functionality is implemented
 * through functions in PerHandlerParser.
 *
 * Functionality only used by syntax parsing or full parsing doesn't live here:
 * it should be implemented in the appropriate Parser<ParseHandler> (described
 * further below).
 *
 * == GeneralParser<ParseHandler, Unit> → PerHandlerParser<ParseHandler> ==
 *
 * Most parsing behavior varies across the character-type axis (and possibly
 * along the full/syntax axis).  For example:
 *
 *   * Parsing ECMAScript's Expression production, implemented by
 *     GeneralParser::expr, varies in this manner: different types are used to
 *     represent nodes in full and syntax parsing (ParseNode* versus an enum),
 *     and reading the tokens comprising the expression requires inspecting
 *     individual characters (necessarily dependent upon character type).
 *   * Reporting an error or warning does not depend on the full/syntax parsing
 *     distinction.  But error reports and warnings include a line of context
 *     (or a slice of one), for pointing out where a mistake was made.
 *     Computing such line of context requires inspecting the source text to
 *     make that line/slice of context, which requires knowing the source text
 *     character type.
 *
 * Such functionality, implemented using identical function code across these
 * axes, should live in GeneralParser.
 *
 * GeneralParser's most important field is the parser's token stream's
 * |TokenStreamSpecific| component, for all aspects of tokenizing that (contra
 * |TokenStreamAnyChars| in ParserBase above) are character-type-sensitive.  As
 * noted above, this field's existence separate from that in ParserBase
 * motivates the |AnyCharsAccess| template parameters on various token stream
 * classes.
 *
 * Everything in PerHandlerParser *could* be folded into GeneralParser (below)
 * if desired.  We don't fold in this manner because all such functions would
 * be instantiated once per Unit -- but if exactly equivalent code would be
 * generated (because PerHandlerParser functions have no awareness of Unit),
 * it's risky to *depend* upon the compiler coalescing the instantiations into
 * one in the final binary.  PerHandlerParser guarantees no duplication.
 *
 * == Parser<ParseHandler, Unit> final → GeneralParser<ParseHandler, Unit> ==
 *
 * The final (pun intended) axis of complexity lies in Parser.
 *
 * Some functionality depends on character type, yet also is defined in
 * significantly different form in full and syntax parsing.  For example,
 * attempting to parse the source text of a module will do so in full parsing
 * but immediately fail in syntax parsing -- so the former is a mess'o'code
 * while the latter is effectively |return null();|.  Such functionality is
 * defined in Parser<SyntaxParseHandler or FullParseHandler, Unit> as
 * appropriate.
 *
 * There's a crucial distinction between GeneralParser and Parser, that
 * explains why both must exist (despite taking exactly the same template
 * parameters, and despite GeneralParser and Parser existing in a one-to-one
 * relationship).  GeneralParser is one unspecialized template class:
 *
 *   template<class ParseHandler, typename Unit>
 *   class GeneralParser : ...
 *   {
 *     ...parsing functions...
 *   };
 *
 * but Parser is one undefined template class with two separate
 * specializations:
 *
 *   // Declare, but do not define.
 *   template<class ParseHandler, typename Unit> class Parser;
 *
 *   // Define a syntax-parsing specialization.
 *   template<typename Unit>
 *   class Parser<SyntaxParseHandler, Unit> final
 *     : public GeneralParser<SyntaxParseHandler, Unit>
 *   {
 *     ...parsing functions...
 *   };
 *
 *   // Define a full-parsing specialization.
 *   template<typename Unit>
 *   class Parser<SyntaxParseHandler, Unit> final
 *     : public GeneralParser<SyntaxParseHandler, Unit>
 *   {
 *     ...parsing functions...
 *   };
 *
 * This odd distinction is necessary because C++ unfortunately doesn't allow
 * partial function specialization:
 *
 *   // BAD: You can only specialize a template function if you specify *every*
 *   //      template parameter, i.e. ParseHandler *and* Unit.
 *   template<typename Unit>
 *   void
 *   GeneralParser<SyntaxParseHandler, Unit>::foo() {}
 *
 * But if you specialize Parser *as a class*, then this is allowed:
 *
 *   template<typename Unit>
 *   void
 *   Parser<SyntaxParseHandler, Unit>::foo() {}
 *
 *   template<typename Unit>
 *   void
 *   Parser<FullParseHandler, Unit>::foo() {}
 *
 * because the only template parameter on the function is Unit -- and so all
 * template parameters *are* varying, not a strict subset of them.
 *
 * So -- any parsing functionality that is differently defined for different
 * ParseHandlers, *but* is defined textually identically for different Unit
 * (even if different code ends up generated for them by the compiler), should
 * reside in Parser.
 */

#include "mozilla/Maybe.h"

#include <type_traits>
#include <utility>

#include "frontend/CompilationStencil.h"  // CompilationState
#include "frontend/ErrorReporter.h"
#include "frontend/FullParseHandler.h"
#include "frontend/FunctionSyntaxKind.h"  // FunctionSyntaxKind
#include "frontend/IteratorKind.h"
#include "frontend/NameAnalysisTypes.h"
#include "frontend/ParseContext.h"
#include "frontend/ParserAtom.h"  // ParserAtomsTable, TaggedParserAtomIndex
#include "frontend/SharedContext.h"
#include "frontend/SyntaxParseHandler.h"
#include "frontend/TokenStream.h"
#include "js/friend/ErrorMessages.h"  // JSErrNum, JSMSG_*
#include "vm/GeneratorAndAsyncKind.h"  // js::GeneratorKind, js::FunctionAsyncKind

namespace js {

class FrontendContext;
struct ErrorMetadata;

namespace frontend {

template <class ParseHandler, typename Unit>
class GeneralParser;

class SourceParseContext : public ParseContext {
 public:
  template <typename ParseHandler, typename Unit>
  SourceParseContext(GeneralParser<ParseHandler, Unit>* prs, SharedContext* sc,
                     Directives* newDirectives)
      : ParseContext(prs->fc_, prs->pc_, sc, prs->tokenStream,
                     prs->compilationState_, newDirectives,
                     std::is_same_v<ParseHandler, FullParseHandler>) {}
};

enum VarContext { HoistVars, DontHoistVars };
enum PropListType { ObjectLiteral, ClassBody, DerivedClassBody };
enum class PropertyType {
  Normal,
  Shorthand,
  CoverInitializedName,
  Getter,
  Setter,
  Method,
  GeneratorMethod,
  AsyncMethod,
  AsyncGeneratorMethod,
  Constructor,
  DerivedConstructor,
  Field,
  FieldWithAccessor,
};

enum AwaitHandling : uint8_t {
  AwaitIsName,
  AwaitIsKeyword,
  AwaitIsModuleKeyword,
  AwaitIsDisallowed
};

template <class ParseHandler, typename Unit>
class AutoAwaitIsKeyword;

template <class ParseHandler, typename Unit>
class AutoInParametersOfAsyncFunction;

class MOZ_STACK_CLASS ParserSharedBase {
 public:
  enum class Kind { Parser };

  ParserSharedBase(FrontendContext* fc, CompilationState& compilationState,
                   Kind kind);
  ~ParserSharedBase();

 public:
  FrontendContext* fc_;

  LifoAlloc& alloc_;

  CompilationState& compilationState_;

  // innermost parse context (stack-allocated)
  ParseContext* pc_;

  // For tracking used names in this parsing session.
  UsedNameTracker& usedNames_;

 public:
  CompilationState& getCompilationState() { return compilationState_; }

  ParserAtomsTable& parserAtoms() { return compilationState_.parserAtoms; }
  const ParserAtomsTable& parserAtoms() const {
    return compilationState_.parserAtoms;
  }

  LifoAlloc& stencilAlloc() { return compilationState_.alloc; }

#if defined(DEBUG) || defined(JS_JITSPEW)
  void dumpAtom(TaggedParserAtomIndex index) const;
#endif
};

class MOZ_STACK_CLASS ParserBase : public ParserSharedBase,
                                   public ErrorReportMixin {
  using Base = ErrorReportMixin;

 public:
  TokenStreamAnyChars anyChars;

  ScriptSource* ss;

  // Perform constant-folding; must be true when interfacing with the emitter.
  const bool foldConstants_ : 1;

 protected:
#if DEBUG
  /* Our fallible 'checkOptions' member function has been called. */
  bool checkOptionsCalled_ : 1;
#endif

  /* Unexpected end of input, i.e. Eof not at top-level. */
  bool isUnexpectedEOF_ : 1;

  /* AwaitHandling */ uint8_t awaitHandling_ : 2;

  bool inParametersOfAsyncFunction_ : 1;

 public:
  JSAtom* liftParserAtomToJSAtom(TaggedParserAtomIndex index);

  bool awaitIsKeyword() const {
    return awaitHandling_ == AwaitIsKeyword ||
           awaitHandling_ == AwaitIsModuleKeyword;
  }
  bool awaitIsDisallowed() const { return awaitHandling_ == AwaitIsDisallowed; }

  bool inParametersOfAsyncFunction() const {
    return inParametersOfAsyncFunction_;
  }

  ParseGoal parseGoal() const {
    return pc_->sc()->hasModuleGoal() ? ParseGoal::Module : ParseGoal::Script;
  }

  template <class, typename>
  friend class AutoAwaitIsKeyword;
  template <class, typename>
  friend class AutoInParametersOfAsyncFunction;

  ParserBase(FrontendContext* fc, const JS::ReadOnlyCompileOptions& options,
             bool foldConstants, CompilationState& compilationState);
  ~ParserBase();

  bool checkOptions();

  const char* getFilename() const { return anyChars.getFilename(); }
  TokenPos pos() const { return anyChars.currentToken().pos; }

  // Determine whether |yield| is a valid name in the current context.
  bool yieldExpressionsSupported() const { return pc_->isGenerator(); }

  bool setLocalStrictMode(bool strict) {
    MOZ_ASSERT(anyChars.debugHasNoLookahead());
    return pc_->sc()->setLocalStrictMode(strict);
  }

 public:
  // Implement ErrorReportMixin.

  FrontendContext* getContext() const override { return fc_; }

  bool strictMode() const override { return pc_->sc()->strict(); }

  const JS::ReadOnlyCompileOptions& options() const override {
    return anyChars.options();
  }

  using Base::error;
  using Base::errorAt;
  using Base::errorNoOffset;
  using Base::errorWithNotes;
  using Base::errorWithNotesAt;
  using Base::errorWithNotesNoOffset;
  using Base::strictModeError;
  using Base::strictModeErrorAt;
  using Base::strictModeErrorNoOffset;
  using Base::strictModeErrorWithNotes;
  using Base::strictModeErrorWithNotesAt;
  using Base::strictModeErrorWithNotesNoOffset;
  using Base::warning;
  using Base::warningAt;
  using Base::warningNoOffset;

 public:
  bool isUnexpectedEOF() const { return isUnexpectedEOF_; }

  bool isValidStrictBinding(TaggedParserAtomIndex name);

  bool hasValidSimpleStrictParameterNames();

  // A Parser::Mark is the extension of the LifoAlloc::Mark to the entire
  // Parser's state. Note: clients must still take care that any ParseContext
  // that points into released ParseNodes is destroyed.
  class Mark {
    friend class ParserBase;
    LifoAlloc::Mark mark;
    CompilationState::CompilationStatePosition pos;
  };
  Mark mark() const {
    Mark m;
    m.mark = alloc_.mark();
    m.pos = compilationState_.getPosition();
    return m;
  }
  void release(Mark m) {
    alloc_.release(m.mark);
    compilationState_.rewind(m.pos);
  }

 public:
  mozilla::Maybe<GlobalScope::ParserData*> newGlobalScopeData(
      ParseContext::Scope& scope);
  mozilla::Maybe<ModuleScope::ParserData*> newModuleScopeData(
      ParseContext::Scope& scope);
  mozilla::Maybe<EvalScope::ParserData*> newEvalScopeData(
      ParseContext::Scope& scope);
  mozilla::Maybe<FunctionScope::ParserData*> newFunctionScopeData(
      ParseContext::Scope& scope, bool hasParameterExprs);
  mozilla::Maybe<VarScope::ParserData*> newVarScopeData(
      ParseContext::Scope& scope);
  mozilla::Maybe<LexicalScope::ParserData*> newLexicalScopeData(
      ParseContext::Scope& scope);
  mozilla::Maybe<ClassBodyScope::ParserData*> newClassBodyScopeData(
      ParseContext::Scope& scope);

 protected:
  enum InvokedPrediction { PredictUninvoked = false, PredictInvoked = true };
  enum ForInitLocation { InForInit, NotInForInit };

  // While on a |let| Name token, examine |next| (which must already be
  // gotten).  Indicate whether |next|, the next token already gotten with
  // modifier TokenStream::SlashIsDiv, continues a LexicalDeclaration.
  bool nextTokenContinuesLetDeclaration(TokenKind next);

  bool noteUsedNameInternal(TaggedParserAtomIndex name,
                            NameVisibility visibility,
                            mozilla::Maybe<TokenPos> tokenPosition);

  bool checkAndMarkSuperScope();

  bool leaveInnerFunction(ParseContext* outerpc);

  TaggedParserAtomIndex prefixAccessorName(PropertyType propType,
                                           TaggedParserAtomIndex propAtom);

  [[nodiscard]] bool setSourceMapInfo();

  void setFunctionEndFromCurrentToken(FunctionBox* funbox) const;
};

template <class ParseHandler>
class MOZ_STACK_CLASS PerHandlerParser : public ParserBase {
  using Base = ParserBase;

 private:
  using Node = typename ParseHandler::Node;

#define DECLARE_TYPE(typeName, longTypeName, asMethodName) \
  using longTypeName = typename ParseHandler::longTypeName;
  FOR_EACH_PARSENODE_SUBCLASS(DECLARE_TYPE)
#undef DECLARE_TYPE

 protected:
  /* State specific to the kind of parse being performed. */
  ParseHandler handler_;

  // When ParseHandler is FullParseHandler:
  //
  //   If non-null, this field holds the syntax parser used to attempt lazy
  //   parsing of inner functions. If null, then lazy parsing is disabled.
  //
  // When ParseHandler is SyntaxParseHandler:
  //
  //   If non-null, this field must be a sentinel value signaling that the
  //   syntax parse was aborted. If null, then lazy parsing was aborted due
  //   to encountering unsupported language constructs.
  //
  // |internalSyntaxParser_| is really a |Parser<SyntaxParseHandler, Unit>*|
  // where |Unit| varies per |Parser<ParseHandler, Unit>|.  But this
  // template class doesn't know |Unit|, so we store a |void*| here and make
  // |GeneralParser<ParseHandler, Unit>::getSyntaxParser| impose the real type.
  void* internalSyntaxParser_;

 private:
  // NOTE: The argument ordering here is deliberately different from the
  //       public constructor so that typos calling the public constructor
  //       are less likely to select this overload.
  PerHandlerParser(FrontendContext* fc,
                   const JS::ReadOnlyCompileOptions& options,
                   bool foldConstants, CompilationState& compilationState,
                   void* internalSyntaxParser);

 protected:
  template <typename Unit>
  PerHandlerParser(FrontendContext* fc,
                   const JS::ReadOnlyCompileOptions& options,
                   bool foldConstants, CompilationState& compilationState,
                   GeneralParser<SyntaxParseHandler, Unit>* syntaxParser)
      : PerHandlerParser(fc, options, foldConstants, compilationState,
                         static_cast<void*>(syntaxParser)) {}

  static typename ParseHandler::NullNode null() { return ParseHandler::null(); }

  NameNodeType stringLiteral();

  const char* nameIsArgumentsOrEval(Node node);

  bool noteDestructuredPositionalFormalParameter(FunctionNodeType funNode,
                                                 Node destruct);

  bool noteUsedName(
      TaggedParserAtomIndex name,
      NameVisibility visibility = NameVisibility::Public,
      mozilla::Maybe<TokenPos> tokenPosition = mozilla::Nothing()) {
    // If the we are delazifying, the BaseScript already has all the closed-over
    // info for bindings and there's no need to track used names.
    if (handler_.reuseClosedOverBindings()) {
      return true;
    }

    return ParserBase::noteUsedNameInternal(name, visibility, tokenPosition);
  }

  // Required on Scope exit.
  bool propagateFreeNamesAndMarkClosedOverBindings(ParseContext::Scope& scope);

  bool checkForUndefinedPrivateFields(EvalSharedContext* evalSc = nullptr);

  bool finishFunctionScopes(bool isStandaloneFunction);
  LexicalScopeNodeType finishLexicalScope(ParseContext::Scope& scope, Node body,
                                          ScopeKind kind = ScopeKind::Lexical);
  ClassBodyScopeNodeType finishClassBodyScope(ParseContext::Scope& scope,
                                              ListNodeType body);
  bool finishFunction(bool isStandaloneFunction = false);

  inline NameNodeType newName(TaggedParserAtomIndex name);
  inline NameNodeType newName(TaggedParserAtomIndex name, TokenPos pos);

  inline NameNodeType newPrivateName(TaggedParserAtomIndex name);

  NameNodeType newInternalDotName(TaggedParserAtomIndex name);
  NameNodeType newThisName();
  NameNodeType newNewTargetName();
  NameNodeType newDotGeneratorName();

  NameNodeType identifierReference(TaggedParserAtomIndex name);
  NameNodeType privateNameReference(TaggedParserAtomIndex name);

  Node noSubstitutionTaggedTemplate();

  inline bool processExport(Node node);
  inline bool processExportFrom(BinaryNodeType node);
  inline bool processImport(BinaryNodeType node);

  // If ParseHandler is SyntaxParseHandler:
  //   Do nothing.
  // If ParseHandler is FullParseHandler:
  //   Disable syntax parsing of all future inner functions during this
  //   full-parse.
  inline void disableSyntaxParser();

  // If ParseHandler is SyntaxParseHandler:
  //   Flag the current syntax parse as aborted due to unsupported language
  //   constructs and return false.  Aborting the current syntax parse does
  //   not disable attempts to syntax-parse future inner functions.
  // If ParseHandler is FullParseHandler:
  //    Disable syntax parsing of all future inner functions and return true.
  inline bool abortIfSyntaxParser();

  // If ParseHandler is SyntaxParseHandler:
  //   Return whether the last syntax parse was aborted due to unsupported
  //   language constructs.
  // If ParseHandler is FullParseHandler:
  //   Return false.
  inline bool hadAbortedSyntaxParse();

  // If ParseHandler is SyntaxParseHandler:
  //   Clear whether the last syntax parse was aborted.
  // If ParseHandler is FullParseHandler:
  //   Do nothing.
  inline void clearAbortedSyntaxParse();

 public:
  NameNodeType newPropertyName(TaggedParserAtomIndex key, const TokenPos& pos) {
    return handler_.newPropertyName(key, pos);
  }

  PropertyAccessType newPropertyAccess(Node expr, NameNodeType key) {
    return handler_.newPropertyAccess(expr, key);
  }

  FunctionBox* newFunctionBox(FunctionNodeType funNode,
                              TaggedParserAtomIndex explicitName,
                              FunctionFlags flags, uint32_t toStringStart,
                              Directives directives,
                              GeneratorKind generatorKind,
                              FunctionAsyncKind asyncKind);

  FunctionBox* newFunctionBox(FunctionNodeType funNode,
                              const ScriptStencil& cachedScriptData,
                              const ScriptStencilExtra& cachedScriptExtra);

 public:
  // ErrorReportMixin.

  using Base::error;
  using Base::errorAt;
  using Base::errorNoOffset;
  using Base::errorWithNotes;
  using Base::errorWithNotesAt;
  using Base::errorWithNotesNoOffset;
  using Base::strictModeError;
  using Base::strictModeErrorAt;
  using Base::strictModeErrorNoOffset;
  using Base::strictModeErrorWithNotes;
  using Base::strictModeErrorWithNotesAt;
  using Base::strictModeErrorWithNotesNoOffset;
  using Base::warning;
  using Base::warningAt;
  using Base::warningNoOffset;
};

#define ABORTED_SYNTAX_PARSE_SENTINEL reinterpret_cast<void*>(0x1)

template <>
inline void PerHandlerParser<SyntaxParseHandler>::disableSyntaxParser() {}

template <>
inline bool PerHandlerParser<SyntaxParseHandler>::abortIfSyntaxParser() {
  internalSyntaxParser_ = ABORTED_SYNTAX_PARSE_SENTINEL;
  return false;
}

template <>
inline bool PerHandlerParser<SyntaxParseHandler>::hadAbortedSyntaxParse() {
  return internalSyntaxParser_ == ABORTED_SYNTAX_PARSE_SENTINEL;
}

template <>
inline void PerHandlerParser<SyntaxParseHandler>::clearAbortedSyntaxParse() {
  internalSyntaxParser_ = nullptr;
}

#undef ABORTED_SYNTAX_PARSE_SENTINEL

// Disable syntax parsing of all future inner functions during this
// full-parse.
template <>
inline void PerHandlerParser<FullParseHandler>::disableSyntaxParser() {
  internalSyntaxParser_ = nullptr;
}

template <>
inline bool PerHandlerParser<FullParseHandler>::abortIfSyntaxParser() {
  disableSyntaxParser();
  return true;
}

template <>
inline bool PerHandlerParser<FullParseHandler>::hadAbortedSyntaxParse() {
  return false;
}

template <>
inline void PerHandlerParser<FullParseHandler>::clearAbortedSyntaxParse() {}

template <class Parser>
class ParserAnyCharsAccess {
 public:
  using TokenStreamSpecific = typename Parser::TokenStream;
  using GeneralTokenStreamChars =
      typename TokenStreamSpecific::GeneralCharsBase;

  static inline TokenStreamAnyChars& anyChars(GeneralTokenStreamChars* ts);
  static inline const TokenStreamAnyChars& anyChars(
      const GeneralTokenStreamChars* ts);
};

// Specify a value for an ES6 grammar parametrization.  We have no enum for
// [Return] because its behavior is almost exactly equivalent to checking
// whether we're in a function box -- easier and simpler than passing an extra
// parameter everywhere.
enum YieldHandling { YieldIsName, YieldIsKeyword };
enum InHandling { InAllowed, InProhibited };
enum DefaultHandling { NameRequired, AllowDefaultName };
enum TripledotHandling { TripledotAllowed, TripledotProhibited };

// For Ergonomic brand checks.
enum PrivateNameHandling { PrivateNameProhibited, PrivateNameAllowed };

template <class ParseHandler, typename Unit>
class Parser;

template <class ParseHandler, typename Unit>
class MOZ_STACK_CLASS GeneralParser : public PerHandlerParser<ParseHandler> {
 public:
  using TokenStream =
      TokenStreamSpecific<Unit, ParserAnyCharsAccess<GeneralParser>>;

 private:
  using Base = PerHandlerParser<ParseHandler>;
  using FinalParser = Parser<ParseHandler, Unit>;
  using Node = typename ParseHandler::Node;

#define DECLARE_TYPE(typeName, longTypeName, asMethodName) \
  using longTypeName = typename ParseHandler::longTypeName;
  FOR_EACH_PARSENODE_SUBCLASS(DECLARE_TYPE)
#undef DECLARE_TYPE

  using typename Base::InvokedPrediction;
  using SyntaxParser = Parser<SyntaxParseHandler, Unit>;

 protected:
  using Modifier = TokenStreamShared::Modifier;
  using Position = typename TokenStream::Position;

  using Base::PredictInvoked;
  using Base::PredictUninvoked;

  using Base::alloc_;
  using Base::awaitIsDisallowed;
  using Base::awaitIsKeyword;
  using Base::inParametersOfAsyncFunction;
  using Base::parseGoal;
#if DEBUG
  using Base::checkOptionsCalled_;
#endif
  using Base::checkForUndefinedPrivateFields;
  using Base::finishClassBodyScope;
  using Base::finishFunctionScopes;
  using Base::finishLexicalScope;
  using Base::foldConstants_;
  using Base::getFilename;
  using Base::hasValidSimpleStrictParameterNames;
  using Base::isUnexpectedEOF_;
  using Base::nameIsArgumentsOrEval;
  using Base::newDotGeneratorName;
  using Base::newFunctionBox;
  using Base::newName;
  using Base::null;
  using Base::options;
  using Base::pos;
  using Base::propagateFreeNamesAndMarkClosedOverBindings;
  using Base::setLocalStrictMode;
  using Base::stringLiteral;
  using Base::yieldExpressionsSupported;

  using Base::abortIfSyntaxParser;
  using Base::clearAbortedSyntaxParse;
  using Base::disableSyntaxParser;
  using Base::hadAbortedSyntaxParse;

 public:
  // Implement ErrorReportMixin.

  [[nodiscard]] bool computeErrorMetadata(
      ErrorMetadata* err,
      const ErrorReportMixin::ErrorOffset& offset) const override;

  using Base::error;
  using Base::errorAt;
  using Base::errorNoOffset;
  using Base::errorWithNotes;
  using Base::errorWithNotesAt;
  using Base::errorWithNotesNoOffset;
  using Base::strictModeError;
  using Base::strictModeErrorAt;
  using Base::strictModeErrorNoOffset;
  using Base::strictModeErrorWithNotes;
  using Base::strictModeErrorWithNotesAt;
  using Base::strictModeErrorWithNotesNoOffset;
  using Base::warning;
  using Base::warningAt;
  using Base::warningNoOffset;

 public:
  using Base::anyChars;
  using Base::fc_;
  using Base::handler_;
  using Base::noteUsedName;
  using Base::pc_;
  using Base::usedNames_;

 private:
  using Base::checkAndMarkSuperScope;
  using Base::finishFunction;
  using Base::identifierReference;
  using Base::leaveInnerFunction;
  using Base::newInternalDotName;
  using Base::newNewTargetName;
  using Base::newThisName;
  using Base::nextTokenContinuesLetDeclaration;
  using Base::noSubstitutionTaggedTemplate;
  using Base::noteDestructuredPositionalFormalParameter;
  using Base::prefixAccessorName;
  using Base::privateNameReference;
  using Base::processExport;
  using Base::processExportFrom;
  using Base::processImport;
  using Base::setFunctionEndFromCurrentToken;

 private:
  inline FinalParser* asFinalParser();
  inline const FinalParser* asFinalParser() const;

  /*
   * A class for temporarily stashing errors while parsing continues.
   *
   * The ability to stash an error is useful for handling situations where we
   * aren't able to verify that an error has occurred until later in the parse.
   * For instance | ({x=1}) | is always parsed as an object literal with
   * a SyntaxError, however, in the case where it is followed by '=>' we rewind
   * and reparse it as a valid arrow function. Here a PossibleError would be
   * set to 'pending' when the initial SyntaxError was encountered then
   * 'resolved' just before rewinding the parser.
   *
   * There are currently two kinds of PossibleErrors: Expression and
   * Destructuring errors. Expression errors are used to mark a possible
   * syntax error when a grammar production is used in an expression context.
   * For example in |{x = 1}|, we mark the CoverInitializedName |x = 1| as a
   * possible expression error, because CoverInitializedName productions
   * are disallowed when an actual ObjectLiteral is expected.
   * Destructuring errors are used to record possible syntax errors in
   * destructuring contexts. For example in |[...rest, ] = []|, we initially
   * mark the trailing comma after the spread expression as a possible
   * destructuring error, because the ArrayAssignmentPattern grammar
   * production doesn't allow a trailing comma after the rest element.
   *
   * When using PossibleError one should set a pending error at the location
   * where an error occurs. From that point, the error may be resolved
   * (invalidated) or left until the PossibleError is checked.
   *
   * Ex:
   *   PossibleError possibleError(*this);
   *   possibleError.setPendingExpressionErrorAt(pos, JSMSG_BAD_PROP_ID);
   *   // A JSMSG_BAD_PROP_ID ParseError is reported, returns false.
   *   if (!possibleError.checkForExpressionError()) {
   *       return false; // we reach this point with a pending exception
   *   }
   *
   *   PossibleError possibleError(*this);
   *   possibleError.setPendingExpressionErrorAt(pos, JSMSG_BAD_PROP_ID);
   *   // Returns true, no error is reported.
   *   if (!possibleError.checkForDestructuringError()) {
   *       return false; // not reached, no pending exception
   *   }
   *
   *   PossibleError possibleError(*this);
   *   // Returns true, no error is reported.
   *   if (!possibleError.checkForExpressionError()) {
   *       return false; // not reached, no pending exception
   *   }
   */
  class MOZ_STACK_CLASS PossibleError {
   private:
    enum class ErrorKind { Expression, Destructuring, DestructuringWarning };

    enum class ErrorState { None, Pending };

    struct Error {
      ErrorState state_ = ErrorState::None;

      // Error reporting fields.
      uint32_t offset_;
      unsigned errorNumber_;
    };

    GeneralParser<ParseHandler, Unit>& parser_;
    Error exprError_;
    Error destructuringError_;
    Error destructuringWarning_;

    // Returns the error report.
    Error& error(ErrorKind kind);

    // Return true if an error is pending without reporting.
    bool hasError(ErrorKind kind);

    // Resolve any pending error.
    void setResolved(ErrorKind kind);

    // Set a pending error. Only a single error may be set per instance and
    // error kind.
    void setPending(ErrorKind kind, const TokenPos& pos, unsigned errorNumber);

    // If there is a pending error, report it and return false, otherwise
    // return true.
    [[nodiscard]] bool checkForError(ErrorKind kind);

    // Transfer an existing error to another instance.
    void transferErrorTo(ErrorKind kind, PossibleError* other);

   public:
    explicit PossibleError(GeneralParser<ParseHandler, Unit>& parser);

    // Return true if a pending destructuring error is present.
    bool hasPendingDestructuringError();

    // Set a pending destructuring error. Only a single error may be set
    // per instance, i.e. subsequent calls to this method are ignored and
    // won't overwrite the existing pending error.
    void setPendingDestructuringErrorAt(const TokenPos& pos,
                                        unsigned errorNumber);

    // Set a pending destructuring warning. Only a single warning may be
    // set per instance, i.e. subsequent calls to this method are ignored
    // and won't overwrite the existing pending warning.
    void setPendingDestructuringWarningAt(const TokenPos& pos,
                                          unsigned errorNumber);

    // Set a pending expression error. Only a single error may be set per
    // instance, i.e. subsequent calls to this method are ignored and won't
    // overwrite the existing pending error.
    void setPendingExpressionErrorAt(const TokenPos& pos, unsigned errorNumber);

    // If there is a pending destructuring error or warning, report it and
    // return false, otherwise return true. Clears any pending expression
    // error.
    [[nodiscard]] bool checkForDestructuringErrorOrWarning();

    // If there is a pending expression error, report it and return false,
    // otherwise return true. Clears any pending destructuring error or
    // warning.
    [[nodiscard]] bool checkForExpressionError();

    // Pass pending errors between possible error instances. This is useful
    // for extending the lifetime of a pending error beyond the scope of
    // the PossibleError where it was initially set (keeping in mind that
    // PossibleError is a MOZ_STACK_CLASS).
    void transferErrorsTo(PossibleError* other);
  };

 protected:
  SyntaxParser* getSyntaxParser() const {
    return reinterpret_cast<SyntaxParser*>(Base::internalSyntaxParser_);
  }

 public:
  TokenStream tokenStream;

 public:
  GeneralParser(FrontendContext* fc, const JS::ReadOnlyCompileOptions& options,
                const Unit* units, size_t length, bool foldConstants,
                CompilationState& compilationState, SyntaxParser* syntaxParser);

  inline void setAwaitHandling(AwaitHandling awaitHandling);
  inline void setInParametersOfAsyncFunction(bool inParameters);

  /*
   * Parse a top-level JS script.
   */
  ListNodeType parse();

 private:
  /*
   * Gets the next token and checks if it matches to the given `condition`.
   * If it matches, returns true.
   * If it doesn't match, calls `errorReport` to report the error, and
   * returns false.
   * If other error happens, it returns false but `errorReport` may not be
   * called and other error will be thrown in that case.
   *
   * In any case, the already gotten token is not ungotten.
   *
   * The signature of `condition` is [...](TokenKind actual) -> bool, and
   * the signature of `errorReport` is [...](TokenKind actual).
   */
  template <typename ConditionT, typename ErrorReportT>
  [[nodiscard]] bool mustMatchTokenInternal(ConditionT condition,
                                            ErrorReportT errorReport);

 public:
  /*
   * The following mustMatchToken variants follow the behavior and parameter
   * types of mustMatchTokenInternal above.
   *
   * If modifier is omitted, `SlashIsDiv` is used.
   * If TokenKind is passed instead of `condition`, it checks if the next
   * token is the passed token.
   * If error number is passed instead of `errorReport`, it reports an
   * error with the passed errorNumber.
   */
  [[nodiscard]] bool mustMatchToken(TokenKind expected, JSErrNum errorNumber) {
    return mustMatchTokenInternal(
        [expected](TokenKind actual) { return actual == expected; },
        [this, errorNumber](TokenKind) { this->error(errorNumber); });
  }

  template <typename ConditionT>
  [[nodiscard]] bool mustMatchToken(ConditionT condition,
                                    JSErrNum errorNumber) {
    return mustMatchTokenInternal(condition, [this, errorNumber](TokenKind) {
      this->error(errorNumber);
    });
  }

  template <typename ErrorReportT>
  [[nodiscard]] bool mustMatchToken(TokenKind expected,
                                    ErrorReportT errorReport) {
    return mustMatchTokenInternal(
        [expected](TokenKind actual) { return actual == expected; },
        errorReport);
  }

 private:
  NameNodeType noSubstitutionUntaggedTemplate();
  ListNodeType templateLiteral(YieldHandling yieldHandling);
  bool taggedTemplate(YieldHandling yieldHandling, ListNodeType tagArgsList,
                      TokenKind tt);
  bool appendToCallSiteObj(CallSiteNodeType callSiteObj);
  bool addExprAndGetNextTemplStrToken(YieldHandling yieldHandling,
                                      ListNodeType nodeList, TokenKind* ttp);

  inline bool trySyntaxParseInnerFunction(
      FunctionNodeType* funNode, TaggedParserAtomIndex explicitName,
      FunctionFlags flags, uint32_t toStringStart, InHandling inHandling,
      YieldHandling yieldHandling, FunctionSyntaxKind kind,
      GeneratorKind generatorKind, FunctionAsyncKind asyncKind, bool tryAnnexB,
      Directives inheritedDirectives, Directives* newDirectives);

  inline bool skipLazyInnerFunction(FunctionNodeType funNode,
                                    uint32_t toStringStart, bool tryAnnexB);

  void setFunctionStartAtPosition(FunctionBox* funbox, TokenPos pos) const;
  void setFunctionStartAtCurrentToken(FunctionBox* funbox) const;

 public:
  /* Public entry points for parsing. */
  Node statementListItem(YieldHandling yieldHandling,
                         bool canHaveDirectives = false);

  // Parse an inner function given an enclosing ParseContext and a
  // FunctionBox for the inner function.
  [[nodiscard]] FunctionNodeType innerFunctionForFunctionBox(
      FunctionNodeType funNode, ParseContext* outerpc, FunctionBox* funbox,
      InHandling inHandling, YieldHandling yieldHandling,
      FunctionSyntaxKind kind, Directives* newDirectives);

  // Parse a function's formal parameters and its body assuming its function
  // ParseContext is already on the stack.
  bool functionFormalParametersAndBody(
      InHandling inHandling, YieldHandling yieldHandling,
      FunctionNodeType* funNode, FunctionSyntaxKind kind,
      const mozilla::Maybe<uint32_t>& parameterListEnd = mozilla::Nothing(),
      bool isStandaloneFunction = false);

 private:
  /*
   * JS parsers, from lowest to highest precedence.
   *
   * Each parser must be called during the dynamic scope of a ParseContext
   * object, pointed to by this->pc_.
   *
   * Each returns a parse node tree or null on error.
   */
  FunctionNodeType functionStmt(
      uint32_t toStringStart, YieldHandling yieldHandling,
      DefaultHandling defaultHandling,
      FunctionAsyncKind asyncKind = FunctionAsyncKind::SyncFunction);
  FunctionNodeType functionExpr(uint32_t toStringStart,
                                InvokedPrediction invoked,
                                FunctionAsyncKind asyncKind);

  Node statement(YieldHandling yieldHandling);
  bool maybeParseDirective(ListNodeType list, Node pn, bool* cont);

  LexicalScopeNodeType blockStatement(
      YieldHandling yieldHandling,
      unsigned errorNumber = JSMSG_CURLY_IN_COMPOUND);
  BinaryNodeType doWhileStatement(YieldHandling yieldHandling);
  BinaryNodeType whileStatement(YieldHandling yieldHandling);

  Node forStatement(YieldHandling yieldHandling);
  bool forHeadStart(YieldHandling yieldHandling, IteratorKind iterKind,
                    ParseNodeKind* forHeadKind, Node* forInitialPart,
                    mozilla::Maybe<ParseContext::Scope>& forLetImpliedScope,
                    Node* forInOrOfExpression);
  Node expressionAfterForInOrOf(ParseNodeKind forHeadKind,
                                YieldHandling yieldHandling);

  SwitchStatementType switchStatement(YieldHandling yieldHandling);
  ContinueStatementType continueStatement(YieldHandling yieldHandling);
  BreakStatementType breakStatement(YieldHandling yieldHandling);
  UnaryNodeType returnStatement(YieldHandling yieldHandling);
  BinaryNodeType withStatement(YieldHandling yieldHandling);
  UnaryNodeType throwStatement(YieldHandling yieldHandling);
  TernaryNodeType tryStatement(YieldHandling yieldHandling);
  LexicalScopeNodeType catchBlockStatement(
      YieldHandling yieldHandling, ParseContext::Scope& catchParamScope);
  DebuggerStatementType debuggerStatement();

  DeclarationListNodeType variableStatement(YieldHandling yieldHandling);

  LabeledStatementType labeledStatement(YieldHandling yieldHandling);
  Node labeledItem(YieldHandling yieldHandling);

  TernaryNodeType ifStatement(YieldHandling yieldHandling);
  Node consequentOrAlternative(YieldHandling yieldHandling);

  DeclarationListNodeType lexicalDeclaration(YieldHandling yieldHandling,
                                             DeclarationKind kind);

  NameNodeType moduleExportName();

  bool assertClause(ListNodeType assertionsSet);

  BinaryNodeType importDeclaration();
  Node importDeclarationOrImportExpr(YieldHandling yieldHandling);
  bool namedImports(ListNodeType importSpecSet);
  bool namespaceImport(ListNodeType importSpecSet);

  TaggedParserAtomIndex importedBinding() {
    return bindingIdentifier(YieldIsName);
  }

  BinaryNodeType exportFrom(uint32_t begin, Node specList);
  BinaryNodeType exportBatch(uint32_t begin);
  inline bool checkLocalExportNames(ListNodeType node);
  Node exportClause(uint32_t begin);
  UnaryNodeType exportFunctionDeclaration(
      uint32_t begin, uint32_t toStringStart,
      FunctionAsyncKind asyncKind = FunctionAsyncKind::SyncFunction);
  UnaryNodeType exportVariableStatement(uint32_t begin);
  UnaryNodeType exportClassDeclaration(uint32_t begin);
  UnaryNodeType exportLexicalDeclaration(uint32_t begin, DeclarationKind kind);
  BinaryNodeType exportDefaultFunctionDeclaration(
      uint32_t begin, uint32_t toStringStart,
      FunctionAsyncKind asyncKind = FunctionAsyncKind::SyncFunction);
  BinaryNodeType exportDefaultClassDeclaration(uint32_t begin);
  BinaryNodeType exportDefaultAssignExpr(uint32_t begin);
  BinaryNodeType exportDefault(uint32_t begin);
  Node exportDeclaration();

  UnaryNodeType expressionStatement(
      YieldHandling yieldHandling,
      InvokedPrediction invoked = PredictUninvoked);

  // Declaration parsing.  The main entrypoint is Parser::declarationList,
  // with sub-functionality split out into the remaining methods.

  // |blockScope| may be non-null only when |kind| corresponds to a lexical
  // declaration (that is, PNK_LET or PNK_CONST).
  //
  // The for* parameters, for normal declarations, should be null/ignored.
  // They should be non-null only when Parser::forHeadStart parses a
  // declaration at the start of a for-loop head.
  //
  // In this case, on success |*forHeadKind| is PNK_FORHEAD, PNK_FORIN, or
  // PNK_FOROF, corresponding to the three for-loop kinds.  The precise value
  // indicates what was parsed.
  //
  // If parsing recognized a for(;;) loop, the next token is the ';' within
  // the loop-head that separates the init/test parts.
  //
  // Otherwise, for for-in/of loops, the next token is the ')' ending the
  // loop-head.  Additionally, the expression that the loop iterates over was
  // parsed into |*forInOrOfExpression|.
  DeclarationListNodeType declarationList(YieldHandling yieldHandling,
                                          ParseNodeKind kind,
                                          ParseNodeKind* forHeadKind = nullptr,
                                          Node* forInOrOfExpression = nullptr);

  // The items in a declaration list are either patterns or names, with or
  // without initializers.  These two methods parse a single pattern/name and
  // any associated initializer -- and if parsing an |initialDeclaration|
  // will, if parsing in a for-loop head (as specified by |forHeadKind| being
  // non-null), consume additional tokens up to the closing ')' in a
  // for-in/of loop head, returning the iterated expression in
  // |*forInOrOfExpression|.  (An "initial declaration" is the first
  // declaration in a declaration list: |a| but not |b| in |var a, b|, |{c}|
  // but not |d| in |let {c} = 3, d|.)
  Node declarationPattern(DeclarationKind declKind, TokenKind tt,
                          bool initialDeclaration, YieldHandling yieldHandling,
                          ParseNodeKind* forHeadKind,
                          Node* forInOrOfExpression);
  Node declarationName(DeclarationKind declKind, TokenKind tt,
                       bool initialDeclaration, YieldHandling yieldHandling,
                       ParseNodeKind* forHeadKind, Node* forInOrOfExpression);

  // Having parsed a name (not found in a destructuring pattern) declared by
  // a declaration, with the current token being the '=' separating the name
  // from its initializer, parse and bind that initializer -- and possibly
  // consume trailing in/of and subsequent expression, if so directed by
  // |forHeadKind|.
  AssignmentNodeType initializerInNameDeclaration(NameNodeType binding,
                                                  DeclarationKind declKind,
                                                  bool initialDeclaration,
                                                  YieldHandling yieldHandling,
                                                  ParseNodeKind* forHeadKind,
                                                  Node* forInOrOfExpression);

  Node expr(InHandling inHandling, YieldHandling yieldHandling,
            TripledotHandling tripledotHandling,
            PossibleError* possibleError = nullptr,
            InvokedPrediction invoked = PredictUninvoked);
  Node assignExpr(InHandling inHandling, YieldHandling yieldHandling,
                  TripledotHandling tripledotHandling,
                  PossibleError* possibleError = nullptr,
                  InvokedPrediction invoked = PredictUninvoked);
  Node assignExprWithoutYieldOrAwait(YieldHandling yieldHandling);
  UnaryNodeType yieldExpression(InHandling inHandling);
  Node condExpr(InHandling inHandling, YieldHandling yieldHandling,
                TripledotHandling tripledotHandling,
                PossibleError* possibleError, InvokedPrediction invoked);
  Node orExpr(InHandling inHandling, YieldHandling yieldHandling,
              TripledotHandling tripledotHandling, PossibleError* possibleError,
              InvokedPrediction invoked);
  Node unaryExpr(YieldHandling yieldHandling,
                 TripledotHandling tripledotHandling,
                 PossibleError* possibleError = nullptr,
                 InvokedPrediction invoked = PredictUninvoked,
                 PrivateNameHandling privateNameHandling =
                     PrivateNameHandling::PrivateNameProhibited);
  Node optionalExpr(YieldHandling yieldHandling,
                    TripledotHandling tripledotHandling, TokenKind tt,
                    PossibleError* possibleError = nullptr,
                    InvokedPrediction invoked = PredictUninvoked);
  Node memberExpr(YieldHandling yieldHandling,
                  TripledotHandling tripledotHandling, TokenKind tt,
                  bool allowCallSyntax, PossibleError* possibleError,
                  InvokedPrediction invoked);
  Node primaryExpr(YieldHandling yieldHandling,
                   TripledotHandling tripledotHandling, TokenKind tt,
                   PossibleError* possibleError, InvokedPrediction invoked);
  Node exprInParens(InHandling inHandling, YieldHandling yieldHandling,
                    TripledotHandling tripledotHandling,
                    PossibleError* possibleError = nullptr);

  bool tryNewTarget(NewTargetNodeType* newTarget);

  BinaryNodeType importExpr(YieldHandling yieldHandling, bool allowCallSyntax);

  FunctionNodeType methodDefinition(uint32_t toStringStart,
                                    PropertyType propType,
                                    TaggedParserAtomIndex funName);

  /*
   * Additional JS parsers.
   */
  bool functionArguments(YieldHandling yieldHandling, FunctionSyntaxKind kind,
                         FunctionNodeType funNode);

  FunctionNodeType functionDefinition(
      FunctionNodeType funNode, uint32_t toStringStart, InHandling inHandling,
      YieldHandling yieldHandling, TaggedParserAtomIndex name,
      FunctionSyntaxKind kind, GeneratorKind generatorKind,
      FunctionAsyncKind asyncKind, bool tryAnnexB = false);

  // Parse a function body.  Pass StatementListBody if the body is a list of
  // statements; pass ExpressionBody if the body is a single expression.
  //
  // Don't include opening LeftCurly token when invoking.
  enum FunctionBodyType { StatementListBody, ExpressionBody };
  LexicalScopeNodeType functionBody(InHandling inHandling,
                                    YieldHandling yieldHandling,
                                    FunctionSyntaxKind kind,
                                    FunctionBodyType type);

  UnaryNodeType unaryOpExpr(YieldHandling yieldHandling, ParseNodeKind kind,
                            uint32_t begin);

  Node condition(InHandling inHandling, YieldHandling yieldHandling);

  ListNodeType argumentList(YieldHandling yieldHandling, bool* isSpread,
                            PossibleError* possibleError = nullptr);
  Node destructuringDeclaration(DeclarationKind kind,
                                YieldHandling yieldHandling, TokenKind tt);
  Node destructuringDeclarationWithoutYieldOrAwait(DeclarationKind kind,
                                                   YieldHandling yieldHandling,
                                                   TokenKind tt);

  inline bool checkExportedName(TaggedParserAtomIndex exportName);
  inline bool checkExportedNamesForArrayBinding(ListNodeType array);
  inline bool checkExportedNamesForObjectBinding(ListNodeType obj);
  inline bool checkExportedNamesForDeclaration(Node node);
  inline bool checkExportedNamesForDeclarationList(
      DeclarationListNodeType node);
  inline bool checkExportedNameForFunction(FunctionNodeType funNode);
  inline bool checkExportedNameForClass(ClassNodeType classNode);
  inline bool checkExportedNameForClause(NameNodeType nameNode);

  enum ClassContext { ClassStatement, ClassExpression };
  ClassNodeType classDefinition(YieldHandling yieldHandling,
                                ClassContext classContext,
                                DefaultHandling defaultHandling);

  struct ClassInitializedMembers {
    // The number of instance class fields.
    size_t instanceFields = 0;

    // The number of instance class fields with computed property names.
    size_t instanceFieldKeys = 0;

    // The number of static class fields.
    size_t staticFields = 0;

    // The number of static blocks
    size_t staticBlocks = 0;

    // The number of static class fields with computed property names.
    size_t staticFieldKeys = 0;

    // The number of instance class private methods.
    size_t privateMethods = 0;

    // The number of instance class private accessors.
    size_t privateAccessors = 0;

    bool hasPrivateBrand() const {
      return privateMethods > 0 || privateAccessors > 0;
    }
  };
#ifdef ENABLE_DECORATORS
  ListNodeType decoratorList(YieldHandling yieldHandling);
#endif
  [[nodiscard]] bool classMember(
      YieldHandling yieldHandling,
      const ParseContext::ClassStatement& classStmt,
      TaggedParserAtomIndex className, uint32_t classStartOffset,
      HasHeritage hasHeritage, ClassInitializedMembers& classInitializedMembers,
      ListNodeType& classMembers, bool* done);
  [[nodiscard]] bool finishClassConstructor(
      const ParseContext::ClassStatement& classStmt,
      TaggedParserAtomIndex className, HasHeritage hasHeritage,
      uint32_t classStartOffset, uint32_t classEndOffset,
      const ClassInitializedMembers& classInitializedMembers,
      ListNodeType& classMembers);

  FunctionNodeType privateMethodInitializer(
      TokenPos propNamePos, TaggedParserAtomIndex propAtom,
      TaggedParserAtomIndex storedMethodAtom);
  FunctionNodeType fieldInitializerOpt(
      TokenPos propNamePos, Node name, TaggedParserAtomIndex atom,
      ClassInitializedMembers& classInitializedMembers, bool isStatic,
      HasHeritage hasHeritage);

  FunctionNodeType synthesizePrivateMethodInitializer(
      TaggedParserAtomIndex propAtom, AccessorType accessorType,
      TokenPos propNamePos);

#ifdef ENABLE_DECORATORS
  Node synthesizeAccessor(Node propName, TokenPos propNamePos,
                          TaggedParserAtomIndex propAtom,
                          TaggedParserAtomIndex privateStateNameAtom,
                          bool isStatic, FunctionSyntaxKind syntaxKind,
                          ListNodeType decorators,
                          ClassInitializedMembers& classInitializedMembers);

  FunctionNodeType synthesizeAccessorBody(TokenPos propNamePos,
                                          TaggedParserAtomIndex atom,
                                          FunctionSyntaxKind syntaxKind);
#endif

  FunctionNodeType staticClassBlock(
      ClassInitializedMembers& classInitializedMembers);

  FunctionNodeType synthesizeConstructor(TaggedParserAtomIndex className,
                                         TokenPos synthesizedBodyPos,
                                         HasHeritage hasHeritage);

 protected:
  FunctionNodeType synthesizeConstructorBody(TokenPos synthesizedBodyPos,
                                             HasHeritage hasHeritage,
                                             FunctionNodeType funNode,
                                             FunctionBox* funbox);

 private:
  bool checkBindingIdentifier(TaggedParserAtomIndex ident, uint32_t offset,
                              YieldHandling yieldHandling,
                              TokenKind hint = TokenKind::Limit);

  TaggedParserAtomIndex labelOrIdentifierReference(YieldHandling yieldHandling);

  TaggedParserAtomIndex labelIdentifier(YieldHandling yieldHandling) {
    return labelOrIdentifierReference(yieldHandling);
  }

  TaggedParserAtomIndex identifierReference(YieldHandling yieldHandling) {
    return labelOrIdentifierReference(yieldHandling);
  }

  bool matchLabel(YieldHandling yieldHandling, TaggedParserAtomIndex* labelOut);

  // Indicate if the next token (tokenized with SlashIsRegExp) is |in| or |of|.
  // If so, consume it.
  bool matchInOrOf(bool* isForInp, bool* isForOfp);

 private:
  bool checkIncDecOperand(Node operand, uint32_t operandOffset);
  bool checkStrictAssignment(Node lhs);

  void reportMissingClosing(unsigned errorNumber, unsigned noteNumber,
                            uint32_t openedPos);

  void reportRedeclaration(TaggedParserAtomIndex name, DeclarationKind prevKind,
                           TokenPos pos, uint32_t prevPos);
  bool notePositionalFormalParameter(FunctionNodeType funNode,
                                     TaggedParserAtomIndex name,
                                     uint32_t beginPos,
                                     bool disallowDuplicateParams,
                                     bool* duplicatedParam);

  enum PropertyNameContext {
    PropertyNameInLiteral,
    PropertyNameInPattern,
    PropertyNameInClass,
#ifdef ENABLE_RECORD_TUPLE
    PropertyNameInRecord
#endif
  };
  Node propertyName(YieldHandling yieldHandling,
                    PropertyNameContext propertyNameContext,
                    const mozilla::Maybe<DeclarationKind>& maybeDecl,
                    ListNodeType propList, TaggedParserAtomIndex* propAtomOut);
  Node propertyOrMethodName(YieldHandling yieldHandling,
                            PropertyNameContext propertyNameContext,
                            const mozilla::Maybe<DeclarationKind>& maybeDecl,
                            ListNodeType propList, PropertyType* propType,
                            TaggedParserAtomIndex* propAtomOut);
  UnaryNodeType computedPropertyName(
      YieldHandling yieldHandling,
      const mozilla::Maybe<DeclarationKind>& maybeDecl,
      PropertyNameContext propertyNameContext, ListNodeType literal);
  ListNodeType arrayInitializer(YieldHandling yieldHandling,
                                PossibleError* possibleError);
  inline RegExpLiteralType newRegExp();

  ListNodeType objectLiteral(YieldHandling yieldHandling,
                             PossibleError* possibleError);

#ifdef ENABLE_RECORD_TUPLE
  ListNodeType recordLiteral(YieldHandling yieldHandling);
  ListNodeType tupleLiteral(YieldHandling yieldHandling);
#endif

  BinaryNodeType bindingInitializer(Node lhs, DeclarationKind kind,
                                    YieldHandling yieldHandling);
  NameNodeType bindingIdentifier(DeclarationKind kind,
                                 YieldHandling yieldHandling);
  Node bindingIdentifierOrPattern(DeclarationKind kind,
                                  YieldHandling yieldHandling, TokenKind tt);
  ListNodeType objectBindingPattern(DeclarationKind kind,
                                    YieldHandling yieldHandling);
  ListNodeType arrayBindingPattern(DeclarationKind kind,
                                   YieldHandling yieldHandling);

  enum class TargetBehavior {
    PermitAssignmentPattern,
    ForbidAssignmentPattern
  };
  bool checkDestructuringAssignmentTarget(
      Node expr, TokenPos exprPos, PossibleError* exprPossibleError,
      PossibleError* possibleError,
      TargetBehavior behavior = TargetBehavior::PermitAssignmentPattern);
  void checkDestructuringAssignmentName(NameNodeType name, TokenPos namePos,
                                        PossibleError* possibleError);
  bool checkDestructuringAssignmentElement(Node expr, TokenPos exprPos,
                                           PossibleError* exprPossibleError,
                                           PossibleError* possibleError);

  NumericLiteralType newNumber(const Token& tok) {
    return handler_.newNumber(tok.number(), tok.decimalPoint(), tok.pos);
  }

  inline BigIntLiteralType newBigInt();

  enum class OptionalKind {
    NonOptional = 0,
    Optional,
  };
  Node memberPropertyAccess(
      Node lhs, OptionalKind optionalKind = OptionalKind::NonOptional);
  Node memberPrivateAccess(
      Node lhs, OptionalKind optionalKind = OptionalKind::NonOptional);
  Node memberElemAccess(Node lhs, YieldHandling yieldHandling,
                        OptionalKind optionalKind = OptionalKind::NonOptional);
  Node memberSuperCall(Node lhs, YieldHandling yieldHandling);
  Node memberCall(TokenKind tt, Node lhs, YieldHandling yieldHandling,
                  PossibleError* possibleError,
                  OptionalKind optionalKind = OptionalKind::NonOptional);

 protected:
  // Match the current token against the BindingIdentifier production with
  // the given Yield parameter.  If there is no match, report a syntax
  // error.
  TaggedParserAtomIndex bindingIdentifier(YieldHandling yieldHandling);

  bool checkLabelOrIdentifierReference(TaggedParserAtomIndex ident,
                                       uint32_t offset,
                                       YieldHandling yieldHandling,
                                       TokenKind hint = TokenKind::Limit);

  ListNodeType statementList(YieldHandling yieldHandling);

  [[nodiscard]] FunctionNodeType innerFunction(
      FunctionNodeType funNode, ParseContext* outerpc,
      TaggedParserAtomIndex explicitName, FunctionFlags flags,
      uint32_t toStringStart, InHandling inHandling,
      YieldHandling yieldHandling, FunctionSyntaxKind kind,
      GeneratorKind generatorKind, FunctionAsyncKind asyncKind, bool tryAnnexB,
      Directives inheritedDirectives, Directives* newDirectives);

  // Implements Automatic Semicolon Insertion.
  //
  // Use this to match `;` in contexts where ASI is allowed. Call this after
  // ruling out all other possibilities except `;`, by peeking ahead if
  // necessary.
  //
  // Unlike most optional Modifiers, this method's `modifier` argument defaults
  // to SlashIsRegExp, since that's by far the most common case: usually an
  // optional semicolon is at the end of a statement or declaration, and the
  // next token could be a RegExp literal beginning a new ExpressionStatement.
  bool matchOrInsertSemicolon(Modifier modifier = TokenStream::SlashIsRegExp);

  bool noteDeclaredName(TaggedParserAtomIndex name, DeclarationKind kind,
                        TokenPos pos, ClosedOver isClosedOver = ClosedOver::No);

  bool noteDeclaredPrivateName(Node nameNode, TaggedParserAtomIndex name,
                               PropertyType propType, FieldPlacement placement,
                               TokenPos pos);

 private:
  inline bool asmJS(ListNodeType list);
};

template <typename Unit>
class MOZ_STACK_CLASS Parser<SyntaxParseHandler, Unit> final
    : public GeneralParser<SyntaxParseHandler, Unit> {
  using Base = GeneralParser<SyntaxParseHandler, Unit>;
  using Node = SyntaxParseHandler::Node;

#define DECLARE_TYPE(typeName, longTypeName, asMethodName) \
  using longTypeName = SyntaxParseHandler::longTypeName;
  FOR_EACH_PARSENODE_SUBCLASS(DECLARE_TYPE)
#undef DECLARE_TYPE

  using SyntaxParser = Parser<SyntaxParseHandler, Unit>;

  // Numerous Base::* functions have bodies like
  //
  //   return asFinalParser()->func(...);
  //
  // and must be able to call functions here.  Add a friendship relationship
  // so functions here can be hidden when appropriate.
  friend class GeneralParser<SyntaxParseHandler, Unit>;

 public:
  using Base::Base;

  // Inherited types, listed here to have non-dependent names.
  using typename Base::Modifier;
  using typename Base::Position;
  using typename Base::TokenStream;

  // Inherited functions, listed here to have non-dependent names.

 public:
  using Base::anyChars;
  using Base::clearAbortedSyntaxParse;
  using Base::hadAbortedSyntaxParse;
  using Base::innerFunctionForFunctionBox;
  using Base::tokenStream;

 public:
  // ErrorReportMixin.

  using Base::error;
  using Base::errorAt;
  using Base::errorNoOffset;
  using Base::errorWithNotes;
  using Base::errorWithNotesAt;
  using Base::errorWithNotesNoOffset;
  using Base::strictModeError;
  using Base::strictModeErrorAt;
  using Base::strictModeErrorNoOffset;
  using Base::strictModeErrorWithNotes;
  using Base::strictModeErrorWithNotesAt;
  using Base::strictModeErrorWithNotesNoOffset;
  using Base::warning;
  using Base::warningAt;
  using Base::warningNoOffset;

 private:
  using Base::alloc_;
#if DEBUG
  using Base::checkOptionsCalled_;
#endif
  using Base::checkForUndefinedPrivateFields;
  using Base::finishFunctionScopes;
  using Base::functionFormalParametersAndBody;
  using Base::handler_;
  using Base::innerFunction;
  using Base::matchOrInsertSemicolon;
  using Base::mustMatchToken;
  using Base::newFunctionBox;
  using Base::newLexicalScopeData;
  using Base::newModuleScopeData;
  using Base::newName;
  using Base::noteDeclaredName;
  using Base::null;
  using Base::options;
  using Base::pc_;
  using Base::pos;
  using Base::propagateFreeNamesAndMarkClosedOverBindings;
  using Base::ss;
  using Base::statementList;
  using Base::stringLiteral;
  using Base::usedNames_;

 private:
  using Base::abortIfSyntaxParser;
  using Base::disableSyntaxParser;

 public:
  // Functions with multiple overloads of different visibility.  We can't
  // |using| the whole thing into existence because of the visibility
  // distinction, so we instead must manually delegate the required overload.

  TaggedParserAtomIndex bindingIdentifier(YieldHandling yieldHandling) {
    return Base::bindingIdentifier(yieldHandling);
  }

  // Functions present in both Parser<ParseHandler, Unit> specializations.

  inline void setAwaitHandling(AwaitHandling awaitHandling);
  inline void setInParametersOfAsyncFunction(bool inParameters);

  RegExpLiteralType newRegExp();
  BigIntLiteralType newBigInt();

  // Parse a module.
  ModuleNodeType moduleBody(ModuleSharedContext* modulesc);

  inline bool checkLocalExportNames(ListNodeType node);
  inline bool checkExportedName(TaggedParserAtomIndex exportName);
  inline bool checkExportedNamesForArrayBinding(ListNodeType array);
  inline bool checkExportedNamesForObjectBinding(ListNodeType obj);
  inline bool checkExportedNamesForDeclaration(Node node);
  inline bool checkExportedNamesForDeclarationList(
      DeclarationListNodeType node);
  inline bool checkExportedNameForFunction(FunctionNodeType funNode);
  inline bool checkExportedNameForClass(ClassNodeType classNode);
  inline bool checkExportedNameForClause(NameNodeType nameNode);

  bool trySyntaxParseInnerFunction(
      FunctionNodeType* funNode, TaggedParserAtomIndex explicitName,
      FunctionFlags flags, uint32_t toStringStart, InHandling inHandling,
      YieldHandling yieldHandling, FunctionSyntaxKind kind,
      GeneratorKind generatorKind, FunctionAsyncKind asyncKind, bool tryAnnexB,
      Directives inheritedDirectives, Directives* newDirectives);

  bool skipLazyInnerFunction(FunctionNodeType funNode, uint32_t toStringStart,
                             bool tryAnnexB);

  bool asmJS(ListNodeType list);

  // Functions present only in Parser<SyntaxParseHandler, Unit>.
};

template <typename Unit>
class MOZ_STACK_CLASS Parser<FullParseHandler, Unit> final
    : public GeneralParser<FullParseHandler, Unit> {
  using Base = GeneralParser<FullParseHandler, Unit>;
  using Node = FullParseHandler::Node;

#define DECLARE_TYPE(typeName, longTypeName, asMethodName) \
  using longTypeName = FullParseHandler::longTypeName;
  FOR_EACH_PARSENODE_SUBCLASS(DECLARE_TYPE)
#undef DECLARE_TYPE

  using SyntaxParser = Parser<SyntaxParseHandler, Unit>;

  // Numerous Base::* functions have bodies like
  //
  //   return asFinalParser()->func(...);
  //
  // and must be able to call functions here.  Add a friendship relationship
  // so functions here can be hidden when appropriate.
  friend class GeneralParser<FullParseHandler, Unit>;

 public:
  using Base::Base;

  // Inherited types, listed here to have non-dependent names.
  using typename Base::Modifier;
  using typename Base::Position;
  using typename Base::TokenStream;

  // Inherited functions, listed here to have non-dependent names.

 public:
  using Base::anyChars;
  using Base::clearAbortedSyntaxParse;
  using Base::functionFormalParametersAndBody;
  using Base::hadAbortedSyntaxParse;
  using Base::handler_;
  using Base::newFunctionBox;
  using Base::options;
  using Base::pc_;
  using Base::pos;
  using Base::ss;
  using Base::tokenStream;

 public:
  // ErrorReportMixin.

  using Base::error;
  using Base::errorAt;
  using Base::errorNoOffset;
  using Base::errorWithNotes;
  using Base::errorWithNotesAt;
  using Base::errorWithNotesNoOffset;
  using Base::strictModeError;
  using Base::strictModeErrorAt;
  using Base::strictModeErrorNoOffset;
  using Base::strictModeErrorWithNotes;
  using Base::strictModeErrorWithNotesAt;
  using Base::strictModeErrorWithNotesNoOffset;
  using Base::warning;
  using Base::warningAt;
  using Base::warningNoOffset;

 private:
  using Base::alloc_;
  using Base::checkLabelOrIdentifierReference;
#if DEBUG
  using Base::checkOptionsCalled_;
#endif
  using Base::checkForUndefinedPrivateFields;
  using Base::fc_;
  using Base::finishClassBodyScope;
  using Base::finishFunctionScopes;
  using Base::finishLexicalScope;
  using Base::innerFunction;
  using Base::innerFunctionForFunctionBox;
  using Base::matchOrInsertSemicolon;
  using Base::mustMatchToken;
  using Base::newEvalScopeData;
  using Base::newFunctionScopeData;
  using Base::newGlobalScopeData;
  using Base::newLexicalScopeData;
  using Base::newModuleScopeData;
  using Base::newName;
  using Base::newVarScopeData;
  using Base::noteDeclaredName;
  using Base::noteUsedName;
  using Base::null;
  using Base::propagateFreeNamesAndMarkClosedOverBindings;
  using Base::statementList;
  using Base::stringLiteral;
  using Base::usedNames_;

  using Base::abortIfSyntaxParser;
  using Base::disableSyntaxParser;
  using Base::getSyntaxParser;

 public:
  // Functions with multiple overloads of different visibility.  We can't
  // |using| the whole thing into existence because of the visibility
  // distinction, so we instead must manually delegate the required overload.

  TaggedParserAtomIndex bindingIdentifier(YieldHandling yieldHandling) {
    return Base::bindingIdentifier(yieldHandling);
  }

  // Functions present in both Parser<ParseHandler, Unit> specializations.

  friend class AutoAwaitIsKeyword<SyntaxParseHandler, Unit>;
  inline void setAwaitHandling(AwaitHandling awaitHandling);

  friend class AutoInParametersOfAsyncFunction<SyntaxParseHandler, Unit>;
  inline void setInParametersOfAsyncFunction(bool inParameters);

  RegExpLiteralType newRegExp();
  BigIntLiteralType newBigInt();

  // Parse a module.
  ModuleNodeType moduleBody(ModuleSharedContext* modulesc);

  bool checkLocalExportNames(ListNodeType node);
  bool checkExportedName(TaggedParserAtomIndex exportName);
  bool checkExportedNamesForArrayBinding(ListNodeType array);
  bool checkExportedNamesForObjectBinding(ListNodeType obj);
  bool checkExportedNamesForDeclaration(Node node);
  bool checkExportedNamesForDeclarationList(DeclarationListNodeType node);
  bool checkExportedNameForFunction(FunctionNodeType funNode);
  bool checkExportedNameForClass(ClassNodeType classNode);
  inline bool checkExportedNameForClause(NameNodeType nameNode);

  bool trySyntaxParseInnerFunction(
      FunctionNodeType* funNode, TaggedParserAtomIndex explicitName,
      FunctionFlags flags, uint32_t toStringStart, InHandling inHandling,
      YieldHandling yieldHandling, FunctionSyntaxKind kind,
      GeneratorKind generatorKind, FunctionAsyncKind asyncKind, bool tryAnnexB,
      Directives inheritedDirectives, Directives* newDirectives);

  [[nodiscard]] bool advancePastSyntaxParsedFunction(
      SyntaxParser* syntaxParser);

  bool skipLazyInnerFunction(FunctionNodeType funNode, uint32_t toStringStart,
                             bool tryAnnexB);

  // Functions present only in Parser<FullParseHandler, Unit>.

  // Parse the body of an eval.
  //
  // Eval scripts are distinguished from global scripts in that in ES6, per
  // 18.2.1.1 steps 9 and 10, all eval scripts are executed under a fresh
  // lexical scope.
  LexicalScopeNodeType evalBody(EvalSharedContext* evalsc);

  // Parse a function, given only its arguments and body. Used for lazily
  // parsed functions.
  FunctionNodeType standaloneLazyFunction(CompilationInput& input,
                                          uint32_t toStringStart, bool strict,
                                          GeneratorKind generatorKind,
                                          FunctionAsyncKind asyncKind);

  // Parse a function, used for the Function, GeneratorFunction, and
  // AsyncFunction constructors.
  FunctionNodeType standaloneFunction(
      const mozilla::Maybe<uint32_t>& parameterListEnd,
      FunctionSyntaxKind syntaxKind, GeneratorKind generatorKind,
      FunctionAsyncKind asyncKind, Directives inheritedDirectives,
      Directives* newDirectives);

  bool checkStatementsEOF();

  // Parse the body of a global script.
  ListNodeType globalBody(GlobalSharedContext* globalsc);

  bool checkLocalExportName(TaggedParserAtomIndex ident, uint32_t offset) {
    return checkLabelOrIdentifierReference(ident, offset, YieldIsName);
  }

  bool asmJS(ListNodeType list);
};

template <class Parser>
/* static */ inline const TokenStreamAnyChars&
ParserAnyCharsAccess<Parser>::anyChars(const GeneralTokenStreamChars* ts) {
  // The structure we're walking through looks like this:
  //
  //   struct ParserBase
  //   {
  //       ...;
  //       TokenStreamAnyChars anyChars;
  //       ...;
  //   };
  //   struct Parser : <class that ultimately inherits from ParserBase>
  //   {
  //       ...;
  //       TokenStreamSpecific tokenStream;
  //       ...;
  //   };
  //
  // We're passed a GeneralTokenStreamChars* (this being a base class of
  // Parser::tokenStream).  We cast that pointer to a TokenStreamSpecific*,
  // then translate that to the enclosing Parser*, then return the |anyChars|
  // member within.

  static_assert(std::is_base_of_v<GeneralTokenStreamChars, TokenStreamSpecific>,
                "the static_cast<> below assumes a base-class relationship");
  const auto* tss = static_cast<const TokenStreamSpecific*>(ts);

  auto tssAddr = reinterpret_cast<uintptr_t>(tss);

  using ActualTokenStreamType = decltype(std::declval<Parser>().tokenStream);
  static_assert(std::is_same_v<ActualTokenStreamType, TokenStreamSpecific>,
                "Parser::tokenStream must have type TokenStreamSpecific");

  uintptr_t parserAddr = tssAddr - offsetof(Parser, tokenStream);

  return reinterpret_cast<const Parser*>(parserAddr)->anyChars;
}

template <class Parser>
/* static */ inline TokenStreamAnyChars& ParserAnyCharsAccess<Parser>::anyChars(
    GeneralTokenStreamChars* ts) {
  const TokenStreamAnyChars& anyCharsConst =
      anyChars(const_cast<const GeneralTokenStreamChars*>(ts));

  return const_cast<TokenStreamAnyChars&>(anyCharsConst);
}

template <class ParseHandler, typename Unit>
class MOZ_STACK_CLASS AutoAwaitIsKeyword {
  using GeneralParser = frontend::GeneralParser<ParseHandler, Unit>;

 private:
  GeneralParser* parser_;
  AwaitHandling oldAwaitHandling_;

 public:
  AutoAwaitIsKeyword(GeneralParser* parser, AwaitHandling awaitHandling) {
    parser_ = parser;
    oldAwaitHandling_ = static_cast<AwaitHandling>(parser_->awaitHandling_);

    // 'await' is always a keyword in module contexts, so we don't modify
    // the state when the original handling is AwaitIsModuleKeyword.
    if (oldAwaitHandling_ != AwaitIsModuleKeyword) {
      parser_->setAwaitHandling(awaitHandling);
    }
  }

  ~AutoAwaitIsKeyword() { parser_->setAwaitHandling(oldAwaitHandling_); }
};

template <class ParseHandler, typename Unit>
class MOZ_STACK_CLASS AutoInParametersOfAsyncFunction {
  using GeneralParser = frontend::GeneralParser<ParseHandler, Unit>;

 private:
  GeneralParser* parser_;
  bool oldInParametersOfAsyncFunction_;

 public:
  AutoInParametersOfAsyncFunction(GeneralParser* parser, bool inParameters) {
    parser_ = parser;
    oldInParametersOfAsyncFunction_ = parser_->inParametersOfAsyncFunction_;
    parser_->setInParametersOfAsyncFunction(inParameters);
  }

  ~AutoInParametersOfAsyncFunction() {
    parser_->setInParametersOfAsyncFunction(oldInParametersOfAsyncFunction_);
  }
};

GlobalScope::ParserData* NewEmptyGlobalScopeData(FrontendContext* fc,
                                                 LifoAlloc& alloc,
                                                 uint32_t numBindings);

VarScope::ParserData* NewEmptyVarScopeData(FrontendContext* fc,
                                           LifoAlloc& alloc,
                                           uint32_t numBindings);

LexicalScope::ParserData* NewEmptyLexicalScopeData(FrontendContext* fc,
                                                   LifoAlloc& alloc,
                                                   uint32_t numBindings);

FunctionScope::ParserData* NewEmptyFunctionScopeData(FrontendContext* fc,
                                                     LifoAlloc& alloc,
                                                     uint32_t numBindings);

mozilla::Maybe<GlobalScope::ParserData*> NewGlobalScopeData(
    JSContext* cx, FrontendContext* fc, ParseContext::Scope& scope,
    LifoAlloc& alloc, ParseContext* pc);

mozilla::Maybe<EvalScope::ParserData*> NewEvalScopeData(
    JSContext* cx, FrontendContext* fc, ParseContext::Scope& scope,
    LifoAlloc& alloc, ParseContext* pc);

mozilla::Maybe<FunctionScope::ParserData*> NewFunctionScopeData(
    JSContext* cx, FrontendContext* fc, ParseContext::Scope& scope,
    bool hasParameterExprs, LifoAlloc& alloc, ParseContext* pc);

mozilla::Maybe<VarScope::ParserData*> NewVarScopeData(
    JSContext* cx, FrontendContext* fc, ParseContext::Scope& scope,
    LifoAlloc& alloc, ParseContext* pc);

mozilla::Maybe<LexicalScope::ParserData*> NewLexicalScopeData(
    JSContext* cx, FrontendContext* fc, ParseContext::Scope& scope,
    LifoAlloc& alloc, ParseContext* pc);

bool FunctionScopeHasClosedOverBindings(ParseContext* pc);
bool LexicalScopeHasClosedOverBindings(ParseContext* pc,
                                       ParseContext::Scope& scope);

} /* namespace frontend */
} /* namespace js */

#endif /* frontend_Parser_h */