Source code

Revision control

Line Code
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
/* -*- 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.
 *
 * == ParserBase → JS::AutoGCRooter, StrictModeGetter ==
 *
 * ParserBase is the base parser class, shared by all 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|.
 *
 * Of particular note: making ParserBase inherit JS::AutoGCRooter (rather than
 * placing it under one of the more-derived parser classes) means that all
 * parsers can be traced using the same AutoGCRooter mechanism: it's not
 * necessary to have separate tracing functionality for syntax/full parsers or
 * parsers of different character types.
 *
 * == 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/Array.h"
#include "mozilla/Maybe.h"
#include "mozilla/TypeTraits.h"

#include "jspubtd.h"

#include "ds/Nestable.h"
#include "frontend/BytecodeCompiler.h"
#include "frontend/FullParseHandler.h"
#include "frontend/NameAnalysisTypes.h"
#include "frontend/NameCollections.h"
#include "frontend/ParseContext.h"
#include "frontend/SharedContext.h"
#include "frontend/SyntaxParseHandler.h"
#include "frontend/TokenStream.h"

namespace js {

class ModuleObject;

namespace frontend {

class ParserBase;

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->context, prs->pc, sc, prs->tokenStream,
                     prs->usedNames, newDirectives,
                     mozilla::IsSame<ParseHandler, FullParseHandler>::value) {}
};

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

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

template <class ParseHandler, typename Unit>
class AutoAwaitIsKeyword;

template <class ParseHandler, typename Unit>
class AutoInParametersOfAsyncFunction;

class MOZ_STACK_CLASS ParserBase : public StrictModeGetter,
                                   private JS::AutoGCRooter {
 private:
  ParserBase* thisForCtor() { return this; }

  // This is needed to cast a parser to JS::AutoGCRooter.
  friend void js::frontend::TraceParser(JSTracer* trc,
                                        JS::AutoGCRooter* parser);

 public:
  JSContext* const context;

  LifoAlloc& alloc;

  TokenStreamAnyChars anyChars;
  LifoAlloc::Mark tempPoolMark;

  /* list of parsed objects and BigInts for GC tracing */
  TraceListNode* traceListHead;

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

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

  ScriptSource* ss;

  RootedScriptSourceObject sourceObject;

  /* Root atoms and objects allocated for the parsed tree. */
  AutoKeepAtoms keepAtoms;

  // 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;

  /* ParseGoal */ uint8_t parseGoal_ : 1;

 public:
  bool awaitIsKeyword() const { return awaitHandling_ != AwaitIsName; }

  bool inParametersOfAsyncFunction() const {
    return inParametersOfAsyncFunction_;
  }

  ParseGoal parseGoal() const { return ParseGoal(parseGoal_); }

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

  ParserBase(JSContext* cx, LifoAlloc& alloc,
             const JS::ReadOnlyCompileOptions& options, bool foldConstants,
             UsedNameTracker& usedNames, ScriptSourceObject* sourceObject,
             ParseGoal parseGoal);
  ~ParserBase();

  bool checkOptions();

  void trace(JSTracer* trc);

  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(); }

  virtual bool strictMode() override { return pc->sc()->strict(); }
  bool setLocalStrictMode(bool strict) {
    MOZ_ASSERT(anyChars.debugHasNoLookahead());
    return pc->sc()->setLocalStrictMode(strict);
  }

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

  bool isUnexpectedEOF() const { return isUnexpectedEOF_; }

  MOZ_MUST_USE bool warningNoOffset(unsigned errorNumber, ...);
  void errorNoOffset(unsigned errorNumber, ...);

  bool isValidStrictBinding(PropertyName* name);

  bool hasValidSimpleStrictParameterNames();

  /*
   * Create a new function object given a name (which is optional if this is
   * a function expression).
   */
  JSFunction* newFunction(HandleAtom atom, FunctionSyntaxKind kind,
                          GeneratorKind generatorKind,
                          FunctionAsyncKind asyncKind, HandleObject proto);

  // 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;
    TraceListNode* traceListHead;
  };
  Mark mark() const {
    Mark m;
    m.mark = alloc.mark();
    m.traceListHead = traceListHead;
    return m;
  }
  void release(Mark m) {
    alloc.release(m.mark);
    traceListHead = m.traceListHead;
  }

 private:
  template <typename BoxT, typename ArgT>
  BoxT* newTraceListNode(ArgT* arg);

 public:
  ObjectBox* newObjectBox(JSObject* obj);
#ifdef ENABLE_BIGINT
  BigIntBox* newBigIntBox(BigInt* val);
#endif

  mozilla::Maybe<GlobalScope::Data*> newGlobalScopeData(
      ParseContext::Scope& scope);
  mozilla::Maybe<ModuleScope::Data*> newModuleScopeData(
      ParseContext::Scope& scope);
  mozilla::Maybe<EvalScope::Data*> newEvalScopeData(ParseContext::Scope& scope);
  mozilla::Maybe<FunctionScope::Data*> newFunctionScopeData(
      ParseContext::Scope& scope, bool hasParameterExprs);
  mozilla::Maybe<VarScope::Data*> newVarScopeData(ParseContext::Scope& scope);
  mozilla::Maybe<LexicalScope::Data*> newLexicalScopeData(
      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::None, continues a LexicalDeclaration.
  bool nextTokenContinuesLetDeclaration(TokenKind next);

  bool noteUsedNameInternal(HandlePropertyName name);
  bool hasUsedName(HandlePropertyName name);
  bool hasUsedFunctionSpecialName(HandlePropertyName name);

  bool checkAndMarkSuperScope();

  bool declareDotGeneratorName();

  bool leaveInnerFunction(ParseContext* outerpc);

  JSAtom* prefixAccessorName(PropertyType propType, HandleAtom propAtom);

  MOZ_MUST_USE bool setSourceMapInfo();
};

enum FunctionCallBehavior {
  PermitAssignmentToFunctionCalls,
  ForbidAssignmentToFunctionCalls
};

template <class ParseHandler>
class MOZ_STACK_CLASS PerHandlerParser : public 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(JSContext* cx, LifoAlloc& alloc,
                   const JS::ReadOnlyCompileOptions& options,
                   bool foldConstants, UsedNameTracker& usedNames,
                   LazyScript* lazyOuterFunction,
                   ScriptSourceObject* sourceObject, ParseGoal parseGoal,
                   void* internalSyntaxParser);

 protected:
  template <typename Unit>
  PerHandlerParser(JSContext* cx, LifoAlloc& alloc,
                   const JS::ReadOnlyCompileOptions& options,
                   bool foldConstants, UsedNameTracker& usedNames,
                   GeneralParser<SyntaxParseHandler, Unit>* syntaxParser,
                   LazyScript* lazyOuterFunction,
                   ScriptSourceObject* sourceObject, ParseGoal parseGoal)
      : PerHandlerParser(
            cx, alloc, options, foldConstants, usedNames, lazyOuterFunction,
            sourceObject, parseGoal,
            // JSOPTION_EXTRA_WARNINGS adds extra warnings not
            // generated when functions are parsed lazily.
            // ("use strict" doesn't inhibit lazy parsing.)
            static_cast<void*>(options.extraWarningsOption ? nullptr
                                                           : syntaxParser)) {}

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

  NameNodeType stringLiteral();

  const char* nameIsArgumentsOrEval(Node node);

  bool noteDestructuredPositionalFormalParameter(CodeNodeType funNode,
                                                 Node destruct);

  bool noteUsedName(HandlePropertyName name) {
    // If the we are delazifying, the LazyScript already has all the
    // closed-over info for bindings and there's no need to track used
    // names.
    if (handler.canSkipLazyClosedOverBindings()) {
      return true;
    }

    return ParserBase::noteUsedNameInternal(name);
  }

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

  bool finishFunctionScopes(bool isStandaloneFunction);
  LexicalScopeNodeType finishLexicalScope(ParseContext::Scope& scope,
                                          Node body);
  bool finishFunction(bool isStandaloneFunction = false);

  bool declareFunctionThis();
  bool declareFunctionArgumentsObject();

  inline NameNodeType newName(PropertyName* name);
  inline NameNodeType newName(PropertyName* name, TokenPos pos);

  NameNodeType newInternalDotName(HandlePropertyName name);
  NameNodeType newThisName();
  NameNodeType newDotGeneratorName();

  NameNodeType identifierReference(Handle<PropertyName*> name);

  Node noSubstitutionTaggedTemplate();

  inline bool processExport(Node node);
  inline bool processExportFrom(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:
  bool isValidSimpleAssignmentTarget(
      Node node,
      FunctionCallBehavior behavior = ForbidAssignmentToFunctionCalls);

  NameNodeType newPropertyName(PropertyName* key, const TokenPos& pos) {
    return handler.newPropertyName(key, pos);
  }

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

  FunctionBox* newFunctionBox(CodeNodeType funNode, JSFunction* fun,
                              uint32_t toStringStart, Directives directives,
                              GeneratorKind generatorKind,
                              FunctionAsyncKind asyncKind);
};

#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 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 };

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::awaitIsKeyword;
  using Base::inParametersOfAsyncFunction;
  using Base::parseGoal;
#if DEBUG
  using Base::checkOptionsCalled;
#endif
  using Base::finishFunctionScopes;
  using Base::finishLexicalScope;
  using Base::foldConstants;
  using Base::getFilename;
  using Base::hasUsedFunctionSpecialName;
  using Base::hasValidSimpleStrictParameterNames;
  using Base::isUnexpectedEOF_;
  using Base::keepAtoms;
  using Base::nameIsArgumentsOrEval;
  using Base::newFunction;
  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::traceListHead;
  using Base::yieldExpressionsSupported;

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

 public:
  using Base::anyChars;
  using Base::context;
  using Base::handler;
  using Base::isValidSimpleAssignmentTarget;
  using Base::pc;
  using Base::usedNames;

 private:
  using Base::checkAndMarkSuperScope;
  using Base::declareDotGeneratorName;
  using Base::declareFunctionArgumentsObject;
  using Base::declareFunctionThis;
  using Base::finishFunction;
  using Base::hasUsedName;
  using Base::identifierReference;
  using Base::leaveInnerFunction;
  using Base::newDotGeneratorName;
  using Base::newInternalDotName;
  using Base::newThisName;
  using Base::nextTokenContinuesLetDeclaration;
  using Base::noSubstitutionTaggedTemplate;
  using Base::noteDestructuredPositionalFormalParameter;
  using Base::noteUsedName;
  using Base::prefixAccessorName;
  using Base::processExport;
  using Base::processExportFrom;

 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.
    MOZ_MUST_USE bool checkForError(ErrorKind kind);

    // If there is a pending warning, report it and return either false or
    // true depending on the werror option, otherwise return true.
    MOZ_MUST_USE bool checkForWarning(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.
    MOZ_MUST_USE bool checkForDestructuringErrorOrWarning();

    // If there is a pending expression error, report it and return false,
    // otherwise return true. Clears any pending destructuring error or
    // warning.
    MOZ_MUST_USE 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(JSContext* cx, LifoAlloc& alloc,
                const JS::ReadOnlyCompileOptions& options, const Unit* units,
                size_t length, bool foldConstants, UsedNameTracker& usedNames,
                SyntaxParser* syntaxParser, LazyScript* lazyOuterFunction,
                ScriptSourceObject* sourceObject, ParseGoal parseGoal);

  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>
  MOZ_MUST_USE bool mustMatchTokenInternal(ConditionT condition,
                                           Modifier modifier,
                                           ErrorReportT errorReport);

 public:
  /*
   * The following mustMatchToken variants follow the behavior and parameter
   * types of mustMatchTokenInternal above.
   *
   * If modifier is omitted, `None` 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.
   */
  MOZ_MUST_USE bool mustMatchToken(TokenKind expected, Modifier modifier,
                                   JSErrNum errorNumber) {
    return mustMatchTokenInternal(
        [expected](TokenKind actual) { return actual == expected; }, modifier,
        [this, errorNumber](TokenKind) { this->error(errorNumber); });
  }

  MOZ_MUST_USE bool mustMatchToken(TokenKind excpected, JSErrNum errorNumber) {
    return mustMatchToken(excpected, TokenStream::None, errorNumber);
  }

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

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

  template <typename ErrorReportT>
  MOZ_MUST_USE bool mustMatchToken(TokenKind expected,
                                   ErrorReportT errorReport) {
    return mustMatchToken(expected, TokenStream::None, errorReport);
  }

  /* Report the given error at the current offset. */
  void error(unsigned errorNumber, ...);
  void errorWithNotes(UniquePtr<JSErrorNotes> notes, unsigned errorNumber, ...);

  /* Report the given error at the given offset. */
  void errorAt(uint32_t offset, unsigned errorNumber, ...);
  void errorWithNotesAt(UniquePtr<JSErrorNotes> notes, uint32_t offset,
                        unsigned errorNumber, ...);

  /*
   * Handle a strict mode error at the current offset.  Report an error if in
   * strict mode code, or warn if not, using the given error number and
   * arguments.
   */
  MOZ_MUST_USE bool strictModeError(unsigned errorNumber, ...);

  /*
   * Handle a strict mode error at the given offset.  Report an error if in
   * strict mode code, or warn if not, using the given error number and
   * arguments.
   */
  MOZ_MUST_USE bool strictModeErrorAt(uint32_t offset, unsigned errorNumber,
                                      ...);

  /* Report the given warning at the current offset. */
  MOZ_MUST_USE bool warning(unsigned errorNumber, ...);

  /* Report the given warning at the given offset. */
  MOZ_MUST_USE bool warningAt(uint32_t offset, unsigned errorNumber, ...);

  /*
   * If extra warnings are enabled, report the given warning at the current
   * offset.
   */
  MOZ_MUST_USE bool extraWarning(unsigned errorNumber, ...);

  /*
   * If extra warnings are enabled, report the given warning at the given
   * offset.
   */
  MOZ_MUST_USE bool extraWarningAt(uint32_t offset, unsigned errorNumber, ...);

 private:
  GeneralParser* thisForCtor() { return this; }

  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(
      CodeNodeType* funNode, HandleFunction fun, uint32_t toStringStart,
      InHandling inHandling, YieldHandling yieldHandling,
      FunctionSyntaxKind kind, GeneratorKind generatorKind,
      FunctionAsyncKind asyncKind, bool tryAnnexB,
      Directives inheritedDirectives, Directives* newDirectives);

  inline bool skipLazyInnerFunction(CodeNodeType funNode,
                                    uint32_t toStringStart,
                                    FunctionSyntaxKind kind, bool tryAnnexB);

 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.
  MOZ_MUST_USE CodeNodeType innerFunctionForFunctionBox(
      CodeNodeType 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, CodeNodeType* 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.
   */
  CodeNodeType functionStmt(
      uint32_t toStringStart, YieldHandling yieldHandling,
      DefaultHandling defaultHandling,
      FunctionAsyncKind asyncKind = FunctionAsyncKind::SyncFunction);
  CodeNodeType 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, 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();

  Node variableStatement(YieldHandling yieldHandling);

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

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

  ListNodeType lexicalDeclaration(YieldHandling yieldHandling,
                                  DeclarationKind kind);

  inline BinaryNodeType importDeclaration();
  Node importDeclarationOrImportExpr(YieldHandling yieldHandling);

  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|.
  ListNodeType 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);
  NameNodeType 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|.
  bool 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 = PredictUninvoked);
  Node orExpr(InHandling inHandling, YieldHandling yieldHandling,
              TripledotHandling tripledotHandling, PossibleError* possibleError,
              InvokedPrediction invoked = PredictUninvoked);
  Node unaryExpr(YieldHandling yieldHandling,
                 TripledotHandling tripledotHandling,
                 PossibleError* possibleError = nullptr,
                 InvokedPrediction invoked = PredictUninvoked);
  Node memberExpr(YieldHandling yieldHandling,
                  TripledotHandling tripledotHandling, TokenKind tt,
                  bool allowCallSyntax = true,
                  PossibleError* possibleError = nullptr,
                  InvokedPrediction invoked = PredictUninvoked);
  Node primaryExpr(YieldHandling yieldHandling,
                   TripledotHandling tripledotHandling, TokenKind tt,
                   PossibleError* possibleError,
                   InvokedPrediction invoked = PredictUninvoked);
  Node exprInParens(InHandling inHandling, YieldHandling yieldHandling,
                    TripledotHandling tripledotHandling,
                    PossibleError* possibleError = nullptr);

  bool tryNewTarget(BinaryNodeType* newTarget);

  BinaryNodeType importExpr(YieldHandling yieldHandling, bool allowCallSyntax);

  CodeNodeType methodDefinition(uint32_t toStringStart, PropertyType propType,
                                HandleAtom funName);

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

  CodeNodeType functionDefinition(CodeNodeType funNode, uint32_t toStringStart,
                                  InHandling inHandling,
                                  YieldHandling yieldHandling, HandleAtom 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.
  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(JSAtom* exportName);
  inline bool checkExportedNamesForArrayBinding(ListNodeType array);
  inline bool checkExportedNamesForObjectBinding(ListNodeType obj);
  inline bool checkExportedNamesForDeclaration(Node node);
  inline bool checkExportedNamesForDeclarationList(ListNodeType node);
  inline bool checkExportedNameForFunction(CodeNodeType funNode);
  inline bool checkExportedNameForClass(ClassNodeType classNode);
  inline bool checkExportedNameForClause(NameNodeType nameNode);

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

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

  PropertyName* labelOrIdentifierReference(YieldHandling yieldHandling);

  PropertyName* labelIdentifier(YieldHandling yieldHandling) {
    return labelOrIdentifierReference(yieldHandling);
  }

  PropertyName* identifierReference(YieldHandling yieldHandling) {
    return labelOrIdentifierReference(yieldHandling);
  }

  bool matchLabel(YieldHandling yieldHandling,
                  MutableHandle<PropertyName*> label);

  // Indicate if the next token (tokenized as Operand) 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(HandlePropertyName name, DeclarationKind prevKind,
                           TokenPos pos, uint32_t prevPos);
  bool notePositionalFormalParameter(CodeNodeType funNode,
                                     HandlePropertyName name, uint32_t beginPos,
                                     bool disallowDuplicateParams,
                                     bool* duplicatedParam);

  bool checkLexicalDeclarationDirectlyWithinBlock(ParseContext::Statement& stmt,
                                                  DeclarationKind kind,
                                                  TokenPos pos);

  enum PropertyNameContext {
    PropertyNameInLiteral,
    PropertyNameInPattern,
    PropertyNameInClass
  };
  Node propertyName(YieldHandling yieldHandling,
                    PropertyNameContext propertyNameContext,
                    const mozilla::Maybe<DeclarationKind>& maybeDecl,
                    ListNodeType propList, PropertyType* propType,
                    MutableHandleAtom propAtom);
  UnaryNodeType computedPropertyName(
      YieldHandling yieldHandling,
      const mozilla::Maybe<DeclarationKind>& maybeDecl, ListNodeType literal);
  ListNodeType arrayInitializer(YieldHandling yieldHandling,
                                PossibleError* possibleError);
  inline RegExpLiteralType newRegExp();

  ListNodeType objectLiteral(YieldHandling yieldHandling,
                             PossibleError* possibleError);

  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);
  }

#ifdef ENABLE_BIGINT
  inline BigIntLiteralType newBigInt();
#endif

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

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

  ListNodeType statementList(YieldHandling yieldHandling);

  MOZ_MUST_USE CodeNodeType innerFunction(
      CodeNodeType funNode, ParseContext* outerpc, HandleFunction fun,
      uint32_t toStringStart, InHandling inHandling,
      YieldHandling yieldHandling, FunctionSyntaxKind kind,
      GeneratorKind generatorKind, FunctionAsyncKind asyncKind, bool tryAnnexB,
      Directives inheritedDirectives, Directives* newDirectives);

  bool matchOrInsertSemicolon();

  bool noteDeclaredName(HandlePropertyName name, DeclarationKind kind,
                        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::context;
  using Base::hadAbortedSyntaxParse;
  using Base::innerFunctionForFunctionBox;
  using Base::tokenStream;

 private:
  using Base::alloc;
#if DEBUG
  using Base::checkOptionsCalled;
#endif
  using Base::error;
  using Base::errorAt;
  using Base::finishFunctionScopes;
  using Base::functionFormalParametersAndBody;
  using Base::handler;
  using Base::innerFunction;
  using Base::keepAtoms;
  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.

  PropertyName* 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();
#ifdef ENABLE_BIGINT
  BigIntLiteralType newBigInt();
#endif

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

  inline BinaryNodeType importDeclaration();
  inline bool checkLocalExportNames(ListNodeType node);
  inline bool checkExportedName(JSAtom* exportName);
  inline bool checkExportedNamesForArrayBinding(ListNodeType array);
  inline bool checkExportedNamesForObjectBinding(ListNodeType obj);
  inline bool checkExportedNamesForDeclaration(Node node);
  inline bool checkExportedNamesForDeclarationList(ListNodeType node);
  inline bool checkExportedNameForFunction(CodeNodeType funNode);
  inline bool checkExportedNameForClass(ClassNodeType classNode);
  inline bool checkExportedNameForClause(NameNodeType nameNode);

  bool trySyntaxParseInnerFunction(
      CodeNodeType* funNode, HandleFunction fun, uint32_t toStringStart,
      InHandling inHandling, YieldHandling yieldHandling,
      FunctionSyntaxKind kind, GeneratorKind generatorKind,
      FunctionAsyncKind asyncKind, bool tryAnnexB,
      Directives inheritedDirectives, Directives* newDirectives);

  bool skipLazyInnerFunction(CodeNodeType funNode, uint32_t toStringStart,
                             FunctionSyntaxKind kind, 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;

 private:
  using Base::alloc;
  using Base::checkLabelOrIdentifierReference;
#if DEBUG
  using Base::checkOptionsCalled;
#endif
  using Base::context;
  using Base::error;
  using Base::errorAt;
  using Base::finishFunctionScopes;
  using Base::finishLexicalScope;
  using Base::innerFunction;
  using Base::innerFunctionForFunctionBox;
  using Base::keepAtoms;
  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::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.

  PropertyName* 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();
#ifdef ENABLE_BIGINT
  BigIntLiteralType newBigInt();
#endif

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

  BinaryNodeType importDeclaration();
  bool checkLocalExportNames(ListNodeType node);
  bool checkExportedName(JSAtom* exportName);
  bool checkExportedNamesForArrayBinding(ListNodeType array);
  bool checkExportedNamesForObjectBinding(ListNodeType obj);
  bool checkExportedNamesForDeclaration(Node node);
  bool checkExportedNamesForDeclarationList(ListNodeType node);
  bool checkExportedNameForFunction(CodeNodeType funNode);
  bool checkExportedNameForClass(ClassNodeType classNode);
  inline bool checkExportedNameForClause(NameNodeType nameNode);

  bool trySyntaxParseInnerFunction(
      CodeNodeType* funNode, HandleFunction fun, uint32_t toStringStart,
      InHandling inHandling, YieldHandling yieldHandling,
      FunctionSyntaxKind kind, GeneratorKind generatorKind,
      FunctionAsyncKind asyncKind, bool tryAnnexB,
      Directives inheritedDirectives, Directives* newDirectives);

  bool skipLazyInnerFunction(CodeNodeType funNode, uint32_t toStringStart,
                             FunctionSyntaxKind kind, 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.
  CodeNodeType standaloneLazyFunction(HandleFunction fun,
                                      uint32_t toStringStart, bool strict,
                                      GeneratorKind generatorKind,
                                      FunctionAsyncKind asyncKind);

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

  bool checkStatementsEOF();

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

  bool namedImportsOrNamespaceImport(TokenKind tt, ListNodeType importSpecSet);

  PropertyName* importedBinding() { return bindingIdentifier(YieldIsName); }

  bool checkLocalExportName(PropertyName* 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(
      mozilla::IsBaseOf<GeneralTokenStreamChars, TokenStreamSpecific>::value,
      "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(static_cast<Parser*>(nullptr)->tokenStream);
  static_assert(
      mozilla::IsSame<ActualTokenStreamType, TokenStreamSpecific>::value,
      "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_);
  }
};

template <typename Scope>
extern typename Scope::Data* NewEmptyBindingData(JSContext* cx,
                                                 LifoAlloc& alloc,
                                                 uint32_t numBindings);

mozilla::Maybe<GlobalScope::Data*> NewGlobalScopeData(
    JSContext* context, ParseContext::Scope& scope, LifoAlloc& alloc,
    ParseContext* pc);
mozilla::Maybe<EvalScope::Data*> NewEvalScopeData(JSContext* context,
                                                  ParseContext::Scope& scope,
                                                  LifoAlloc& alloc,
                                                  ParseContext* pc);
mozilla::Maybe<FunctionScope::Data*> NewFunctionScopeData(
    JSContext* context, ParseContext::Scope& scope, bool hasParameterExprs,
    LifoAlloc& alloc, ParseContext* pc);
mozilla::Maybe<VarScope::Data*> NewVarScopeData(JSContext* context,
                                                ParseContext::Scope& scope,
                                                LifoAlloc& alloc,
                                                ParseContext* pc);
mozilla::Maybe<LexicalScope::Data*> NewLexicalScopeData(
    JSContext* context, ParseContext::Scope& scope, LifoAlloc& alloc,
    ParseContext* pc);

JSFunction* AllocNewFunction(JSContext* cx, HandleAtom atom,
                             FunctionSyntaxKind kind,
                             GeneratorKind generatorKind,
                             FunctionAsyncKind asyncKind, HandleObject proto,
                             bool isSelfHosting = false,
                             bool inFunctionBox = false);

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

#endif /* frontend_Parser_h */