File: Declarations.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (2050 lines) | stat: -rw-r--r-- 72,847 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#if swift(>=6)
@_spi(RawSyntax) internal import SwiftSyntax
#else
@_spi(RawSyntax) import SwiftSyntax
#endif

extension DeclarationModifier {
  var canHaveParenthesizedArgument: Bool {
    switch self {
    case .__consuming, .__setter_access, ._const, ._local, .async,
      .borrowing, .class, .consuming, .convenience, .distributed, .dynamic,
      .final, .indirect, .infix, .isolated, .lazy, .mutating, .nonmutating,
      .optional, .override, .postfix, .prefix, .reasync, ._resultDependsOn, ._resultDependsOnSelf, .required,
      .rethrows, .static, .weak, .sending:
      return false
    case .fileprivate, .internal, .nonisolated, .package, .open, .private,
      .public, .unowned:
      return true
    }
  }
}

extension TokenConsumer {
  mutating func atStartOfFreestandingMacroExpansion() -> Bool {
    // Check if "'#' <identifier>" where the identifier is on the sameline.
    if !self.at(.pound) {
      return false
    }
    if self.peek().isAtStartOfLine {
      return false
    }
    switch self.peek().rawTokenKind {
    case .identifier:
      return true
    case .keyword:
      // allow keywords right after '#' so we can diagnose it when parsing.
      return (self.currentToken.trailingTriviaByteLength == 0 && self.peek().leadingTriviaByteLength == 0)
    default:
      return false
    }
  }

  mutating func atStartOfDeclaration(
    isAtTopLevel: Bool = false,
    allowInitDecl: Bool = true,
    allowRecovery: Bool = false
  ) -> Bool {
    if self.at(.poundIf) {
      return true
    }

    var subparser = self.lookahead()

    var hasAttribute = false
    var attributeProgress = LoopProgressCondition()
    while subparser.hasProgressed(&attributeProgress) && subparser.at(.atSign) {
      hasAttribute = true
      _ = subparser.consumeAttributeList()
    }

    var hasModifier = false
    if subparser.currentToken.isLexerClassifiedKeyword || subparser.currentToken.rawTokenKind == .identifier {
      var modifierProgress = LoopProgressCondition()
      while let (modifierKind, handle) = subparser.at(anyIn: DeclarationModifier.self),
        modifierKind != .class,
        subparser.hasProgressed(&modifierProgress)
      {
        hasModifier = true
        subparser.eat(handle)
        if modifierKind != .open && subparser.at(.leftParen) && modifierKind.canHaveParenthesizedArgument {
          // When determining whether we are at a declaration, don't consume anything in parentheses after 'open'
          // so we don't consider a function call to open as a decl modifier. This matches the C++ parser.
          subparser.consumeAnyToken()
          subparser.consume(to: .rightParen)
        }
      }
    }

    if hasAttribute {
      if subparser.at(.rightBrace) || subparser.at(.endOfFile) || subparser.at(.poundEndif) {
        return true
      }
    }

    if subparser.at(.poundIf) {
      var attrLookahead = subparser.lookahead()
      return attrLookahead.consumeIfConfigOfAttributes()
    }

    let declStartKeyword: DeclarationKeyword?
    if allowRecovery {
      declStartKeyword =
        subparser.canRecoverTo(
          anyIn: DeclarationKeyword.self,
          overrideRecoveryPrecedence: isAtTopLevel ? nil : .closingBrace
        )?.0
    } else {
      declStartKeyword = subparser.at(anyIn: DeclarationKeyword.self)?.0
    }
    switch declStartKeyword {
    case .lhs(.actor):
      // actor Foo {}
      if subparser.peek().rawTokenKind == .identifier {
        return true
      }
      // actor may be somewhere in the modifier list. Eat the tokens until we get
      // to something that isn't the start of a decl. If that is an identifier,
      // it's an actor declaration, otherwise, it isn't.
      var lookahead = subparser.lookahead()
      repeat {
        lookahead.consumeAnyToken()
      } while lookahead.atStartOfDeclaration(isAtTopLevel: isAtTopLevel, allowInitDecl: allowInitDecl)
      return lookahead.at(.identifier)
    case .lhs(.case):
      // When 'case' appears inside a function, it's probably a switch
      // case, not an enum case declaration.
      return false
    case .lhs(.`init`):
      return allowInitDecl
    case .lhs(.macro):
      // macro Foo ...
      return subparser.peek().rawTokenKind == .identifier
    case .lhs(.pound):
      // Force parsing '#<identifier>' after attributes as a macro expansion decl.
      if hasAttribute || hasModifier {
        return true
      }

      // Otherwise, parse it as an expression.
      return false
    case .some(_):
      // All other decl start keywords unconditionally start a decl.
      return true
    case nil:
      if subparser.at(anyIn: ContextualDeclKeyword.self)?.0 != nil {
        subparser.consumeAnyToken()
        return subparser.atStartOfDeclaration(
          isAtTopLevel: isAtTopLevel,
          allowInitDecl: allowInitDecl,
          allowRecovery: allowRecovery
        )
      }
      return false
    }
  }
}

extension Parser {
  struct DeclAttributes {
    var attributes: RawAttributeListSyntax
    var modifiers: RawDeclModifierListSyntax

    init(attributes: RawAttributeListSyntax, modifiers: RawDeclModifierListSyntax) {
      self.attributes = attributes
      self.modifiers = modifiers
    }
  }

  /// Parse a declaration.
  ///
  /// If `inMemberDeclList` is `true`, we know that the next item must be a
  /// declaration and thus start with a keyword. This allows further recovery.
  mutating func parseDeclaration(inMemberDeclList: Bool = false) -> RawDeclSyntax {
    // If we are at a `#if` of attributes, the `#if` directive should be
    // parsed when we're parsing the attributes.
    if self.at(.poundIf) && !self.withLookahead({ $0.consumeIfConfigOfAttributes() }) {
      let directive = self.parsePoundIfDirective { (parser, _) in
        let parsedDecl = parser.parseDeclaration()
        let semicolon = parser.consume(if: .semicolon)
        return RawMemberBlockItemSyntax(
          decl: parsedDecl,
          semicolon: semicolon,
          arena: parser.arena
        )
      } addSemicolonIfNeeded: { lastElement, newItemAtStartOfLine, parser in
        if lastElement.semicolon == nil && !newItemAtStartOfLine {
          return RawMemberBlockItemSyntax(
            lastElement.unexpectedBeforeDecl,
            decl: lastElement.decl,
            lastElement.unexpectedBetweenDeclAndSemicolon,
            semicolon: parser.missingToken(.semicolon),
            lastElement.unexpectedAfterSemicolon,
            arena: parser.arena
          )
        } else {
          return nil
        }
      } syntax: { parser, elements in
        return .decls(RawMemberBlockItemListSyntax(elements: elements, arena: parser.arena))
      }
      return RawDeclSyntax(directive)
    }

    let attrs = DeclAttributes(
      attributes: self.parseAttributeList(),
      modifiers: self.parseDeclModifierList()
    )

    let recoveryResult: (match: DeclarationKeyword, handle: RecoveryConsumptionHandle)?
    if let atResult = self.at(anyIn: DeclarationKeyword.self) {
      // We are at a keyword that starts a declaration. Parse that declaration.
      recoveryResult = (atResult.spec, .noRecovery(atResult.handle))
    } else if atFunctionDeclarationWithoutFuncKeyword() {
      // We aren't at a declaration keyword and it looks like we are at a function
      // declaration. Parse a function declaration.
      recoveryResult = (.lhs(.func), .missing(.keyword(.func)))
    } else {
      // In all other cases, use standard token recovery to find the declaration
      // to parse.
      // If we are inside a memberDecl list, we don't want to eat closing braces (which most likely close the outer context)
      // while recovering to the declaration start.
      let recoveryPrecedence = inMemberDeclList ? TokenPrecedence.closingBrace : nil
      recoveryResult = self.canRecoverTo(anyIn: DeclarationKeyword.self, overrideRecoveryPrecedence: recoveryPrecedence)
    }

    switch recoveryResult {
    case (.lhs(.import), let handle)?:
      return RawDeclSyntax(self.parseImportDeclaration(attrs, handle))
    case (.lhs(.class), let handle)?:
      return RawDeclSyntax(
        self.parseNominalTypeDeclaration(for: RawClassDeclSyntax.self, attrs: attrs, introucerHandle: handle)
      )
    case (.lhs(.enum), let handle)?:
      return RawDeclSyntax(
        self.parseNominalTypeDeclaration(for: RawEnumDeclSyntax.self, attrs: attrs, introucerHandle: handle)
      )
    case (.lhs(.case), let handle)?:
      return RawDeclSyntax(self.parseEnumCaseDeclaration(attrs, handle))
    case (.lhs(.struct), let handle)?:
      return RawDeclSyntax(
        self.parseNominalTypeDeclaration(for: RawStructDeclSyntax.self, attrs: attrs, introucerHandle: handle)
      )
    case (.lhs(.protocol), let handle)?:
      return RawDeclSyntax(
        self.parseNominalTypeDeclaration(for: RawProtocolDeclSyntax.self, attrs: attrs, introucerHandle: handle)
      )
    case (.lhs(.associatedtype), let handle)?:
      return RawDeclSyntax(self.parseAssociatedTypeDeclaration(attrs, handle))
    case (.lhs(.typealias), let handle)?:
      return RawDeclSyntax(self.parseTypealiasDeclaration(attrs, handle))
    case (.lhs(.extension), let handle)?:
      return RawDeclSyntax(self.parseExtensionDeclaration(attrs, handle))
    case (.lhs(.func), let handle)?:
      return RawDeclSyntax(self.parseFuncDeclaration(attrs, handle))
    case (.lhs(.subscript), let handle)?:
      return RawDeclSyntax(self.parseSubscriptDeclaration(attrs, handle))
    case (.lhs(.`init`), let handle)?:
      return RawDeclSyntax(self.parseInitializerDeclaration(attrs, handle))
    case (.lhs(.deinit), let handle)?:
      return RawDeclSyntax(self.parseDeinitializerDeclaration(attrs, handle))
    case (.lhs(.operator), let handle)?:
      return RawDeclSyntax(self.parseOperatorDeclaration(attrs, handle))
    case (.lhs(.precedencegroup), let handle)?:
      return RawDeclSyntax(self.parsePrecedenceGroupDeclaration(attrs, handle))
    case (.lhs(.actor), let handle)?:
      return RawDeclSyntax(
        self.parseNominalTypeDeclaration(for: RawActorDeclSyntax.self, attrs: attrs, introucerHandle: handle)
      )
    case (.lhs(.macro), let handle)?:
      return RawDeclSyntax(self.parseMacroDeclaration(attrs: attrs, introducerHandle: handle))
    case (.lhs(.pound), let handle)?:
      return RawDeclSyntax(self.parseMacroExpansionDeclaration(attrs, handle))
    case (.rhs, let handle)?:
      return RawDeclSyntax(self.parseBindingDeclaration(attrs, handle, inMemberDeclList: inMemberDeclList))
    case nil:
      break
    }

    if inMemberDeclList {
      let isProbablyVarDecl = self.at(.identifier, .wildcard) && self.peek(isAt: .colon, .equal, .comma)
      let isProbablyTupleDecl = self.at(.leftParen) && self.peek(isAt: .identifier, .wildcard)

      if isProbablyVarDecl || isProbablyTupleDecl {
        return RawDeclSyntax(self.parseBindingDeclaration(attrs, .missing(.keyword(.var))))
      }

      if self.currentToken.isEditorPlaceholder {
        let placeholder = self.parseAnyIdentifier()
        return RawDeclSyntax(
          RawMissingDeclSyntax(
            attributes: attrs.attributes,
            modifiers: attrs.modifiers,
            placeholder: placeholder,
            arena: self.arena
          )
        )
      }

      if atFunctionDeclarationWithoutFuncKeyword() {
        return RawDeclSyntax(self.parseFuncDeclaration(attrs, .missing(.keyword(.func))))
      }
    }
    return RawDeclSyntax(
      RawMissingDeclSyntax(
        attributes: attrs.attributes,
        modifiers: attrs.modifiers,
        arena: self.arena
      )
    )
  }

  /// Returns `true` if it looks like the parser is positioned at a function declaration that’s missing the `func` keyword.
  fileprivate mutating func atFunctionDeclarationWithoutFuncKeyword() -> Bool {
    var nextTokenIsLeftParenOrLeftAngle: Bool {
      self.peek(isAt: .leftParen) || self.peek().tokenText.hasPrefix("<")
    }

    if self.at(.identifier) {
      return nextTokenIsLeftParenOrLeftAngle
    } else if self.at(anyIn: Operator.self) != nil {
      if self.currentToken.tokenText.hasSuffix("<") && self.peek(isAt: .identifier) {
        return true
      }
      return nextTokenIsLeftParenOrLeftAngle
    } else {
      return false
    }
  }
}

extension Parser {
  /// Parse an import declaration.
  mutating func parseImportDeclaration(
    _ attrs: DeclAttributes,
    _ handle: RecoveryConsumptionHandle
  ) -> RawImportDeclSyntax {
    let (unexpectedBeforeImportKeyword, importKeyword) = self.eat(handle)
    let kind = self.parseImportKind()
    let path = self.parseImportPath()
    return RawImportDeclSyntax(
      attributes: attrs.attributes,
      modifiers: attrs.modifiers,
      unexpectedBeforeImportKeyword,
      importKeyword: importKeyword,
      importKindSpecifier: kind,
      path: path,
      arena: self.arena
    )
  }

  mutating func parseImportKind() -> RawTokenSyntax? {
    return self.consume(ifAnyIn: ImportDeclSyntax.ImportKindSpecifierOptions.self)
  }

  mutating func parseImportPath() -> RawImportPathComponentListSyntax {
    var elements = [RawImportPathComponentSyntax]()
    var keepGoing: RawTokenSyntax? = nil
    var loopProgress = LoopProgressCondition()
    repeat {
      let name = self.parseAnyIdentifier()
      keepGoing = self.consume(if: .period)
      elements.append(
        RawImportPathComponentSyntax(
          name: name,
          trailingPeriod: keepGoing,
          arena: self.arena
        )
      )
    } while keepGoing != nil && self.hasProgressed(&loopProgress)
    return RawImportPathComponentListSyntax(elements: elements, arena: self.arena)
  }
}

extension Parser {
  /// Parse an extension declaration.
  mutating func parseExtensionDeclaration(
    _ attrs: DeclAttributes,
    _ handle: RecoveryConsumptionHandle
  ) -> RawExtensionDeclSyntax {
    let (unexpectedBeforeExtensionKeyword, extensionKeyword) = self.eat(handle)
    let type = self.parseType()

    let inheritance: RawInheritanceClauseSyntax?
    if self.at(.colon) {
      inheritance = self.parseInheritance()
    } else {
      inheritance = nil
    }

    let whereClause: RawGenericWhereClauseSyntax?
    if self.at(.keyword(.where)) {
      whereClause = self.parseGenericWhereClause()
    } else {
      whereClause = nil
    }
    let memberBlock = self.parseMemberBlock(introducer: extensionKeyword)
    return RawExtensionDeclSyntax(
      attributes: attrs.attributes,
      modifiers: attrs.modifiers,
      unexpectedBeforeExtensionKeyword,
      extensionKeyword: extensionKeyword,
      extendedType: type,
      inheritanceClause: inheritance,
      genericWhereClause: whereClause,
      memberBlock: memberBlock,
      arena: self.arena
    )
  }
}

extension Parser {
  mutating func parseGenericParameters() -> RawGenericParameterClauseSyntax {
    if let remainingTokens = remainingTokensIfMaximumNestingLevelReached() {
      return RawGenericParameterClauseSyntax(
        remainingTokens,
        leftAngle: missingToken(.leftAngle),
        parameters: RawGenericParameterListSyntax(elements: [], arena: self.arena),
        genericWhereClause: nil,
        rightAngle: missingToken(.rightAngle),
        arena: self.arena
      )
    }

    let langle = self.expectWithoutRecovery(prefix: "<", as: .leftAngle)
    var elements = [RawGenericParameterSyntax]()
    do {
      var keepGoing: RawTokenSyntax? = nil
      var loopProgress = LoopProgressCondition()
      repeat {
        let attributes = self.parseAttributeList()

        // Parse the 'each' keyword for a type parameter pack 'each T'.
        var each = self.consume(if: .keyword(.each))

        let (unexpectedBetweenEachAndName, name) = self.expectIdentifier(allowSelfOrCapitalSelfAsIdentifier: true)
        if attributes.isEmpty && each == nil && unexpectedBetweenEachAndName == nil && name.isMissing
          && elements.isEmpty && !self.at(prefix: ">")
        {
          break
        }

        // Parse the unsupported ellipsis for a type parameter pack 'T...'.
        let unexpectedBetweenNameAndColon: RawUnexpectedNodesSyntax?
        if let ellipsis = self.consume(ifPrefix: "...", as: .ellipsis) {
          unexpectedBetweenNameAndColon = RawUnexpectedNodesSyntax([ellipsis], arena: self.arena)
          if each == nil {
            each = missingToken(.each)
          }
        } else {
          unexpectedBetweenNameAndColon = nil
        }

        // Parse the ':' followed by a type.
        let colon = self.consume(if: .colon)
        let unexpectedBeforeInherited: RawUnexpectedNodesSyntax?
        let inherited: RawTypeSyntax?
        if colon != nil {
          if self.at(.identifier, .keyword(.protocol), .keyword(.Any)) || self.atContextualPunctuator("~") {
            unexpectedBeforeInherited = nil
            inherited = self.parseType()
          } else if let classKeyword = self.consume(if: .keyword(.class)) {
            unexpectedBeforeInherited = RawUnexpectedNodesSyntax([classKeyword], arena: self.arena)
            inherited = RawTypeSyntax(
              RawIdentifierTypeSyntax(
                name: missingToken(.identifier, text: "AnyObject"),
                genericArgumentClause: nil,
                arena: self.arena
              )
            )
          } else {
            unexpectedBeforeInherited = nil
            inherited = RawTypeSyntax(RawMissingTypeSyntax(arena: self.arena))
          }
        } else {
          unexpectedBeforeInherited = nil
          inherited = nil
        }
        keepGoing = self.consume(if: .comma)
        elements.append(
          RawGenericParameterSyntax(
            attributes: attributes,
            eachKeyword: each,
            unexpectedBetweenEachAndName,
            name: name,
            unexpectedBetweenNameAndColon,
            colon: colon,
            unexpectedBeforeInherited,
            inheritedType: inherited,
            trailingComma: keepGoing,
            arena: self.arena
          )
        )
      } while keepGoing != nil && self.hasProgressed(&loopProgress)
    }

    let whereClause: RawGenericWhereClauseSyntax?
    if self.at(.keyword(.where)) {
      whereClause = self.parseGenericWhereClause()
    } else {
      whereClause = nil
    }

    let rangle = expectWithoutRecovery(prefix: ">", as: .rightAngle)

    let parameters: RawGenericParameterListSyntax
    if elements.isEmpty && rangle.isMissing {
      parameters = RawGenericParameterListSyntax(elements: [], arena: self.arena)
    } else {
      parameters = RawGenericParameterListSyntax(elements: elements, arena: self.arena)
    }
    return RawGenericParameterClauseSyntax(
      leftAngle: langle,
      parameters: parameters,
      genericWhereClause: whereClause,
      rightAngle: rangle,
      arena: self.arena
    )
  }

  mutating func parseGenericWhereClause() -> RawGenericWhereClauseSyntax {
    let (unexpectedBeforeWhereKeyword, whereKeyword) = self.expect(.keyword(.where))

    var elements = [RawGenericRequirementSyntax]()
    do {
      var keepGoing: RawTokenSyntax? = nil
      var loopProgress = LoopProgressCondition()
      repeat {
        let firstType = self.parseType()
        guard !firstType.is(RawMissingTypeSyntax.self) else {
          keepGoing = self.consume(if: .comma)
          elements.append(
            RawGenericRequirementSyntax(
              requirement: .sameTypeRequirement(
                RawSameTypeRequirementSyntax(
                  leftType: RawTypeSyntax(RawMissingTypeSyntax(arena: self.arena)),
                  equal: missingToken(.binaryOperator, text: "=="),
                  rightType: RawTypeSyntax(RawMissingTypeSyntax(arena: self.arena)),
                  arena: self.arena
                )
              ),
              trailingComma: keepGoing,
              arena: self.arena
            )
          )
          continue
        }

        enum ExpectedTokenKind: TokenSpecSet {
          case colon
          case binaryOperator
          case postfixOperator
          case prefixOperator

          init?(lexeme: Lexer.Lexeme, experimentalFeatures: Parser.ExperimentalFeatures) {
            switch (lexeme.rawTokenKind, lexeme.tokenText) {
            case (.colon, _): self = .colon
            case (.binaryOperator, "=="): self = .binaryOperator
            case (.postfixOperator, "=="): self = .postfixOperator
            case (.prefixOperator, "=="): self = .prefixOperator
            default: return nil
            }
          }

          var spec: TokenSpec {
            switch self {
            case .colon: return .colon
            case .binaryOperator: return .binaryOperator
            case .postfixOperator: return .postfixOperator
            case .prefixOperator: return .prefixOperator
            }
          }
        }

        let requirement: RawGenericRequirementSyntax.Requirement
        switch self.at(anyIn: ExpectedTokenKind.self) {
        case (.colon, let handle)?:
          let colon = self.eat(handle)
          // A conformance-requirement.
          if let (layoutSpecifier, handle) = self.at(anyIn: LayoutRequirementSyntax.LayoutSpecifierOptions.self) {
            // Parse a layout constraint.
            let specifier = self.eat(handle)

            let unexpectedBeforeLeftParen: RawUnexpectedNodesSyntax?
            let leftParen: RawTokenSyntax?
            let size: RawTokenSyntax?
            let comma: RawTokenSyntax?
            let alignment: RawTokenSyntax?
            let unexpectedBeforeRightParen: RawUnexpectedNodesSyntax?
            let rightParen: RawTokenSyntax?

            var hasArguments: Bool {
              switch layoutSpecifier {
              case ._Trivial,
                ._TrivialAtMost,
                ._TrivialStride:
                return true

              case ._UnknownLayout,
                ._RefCountedObject,
                ._NativeRefCountedObject,
                ._Class,
                ._NativeClass,
                ._BridgeObject:
                return false
              }
            }

            // Unlike the other layout constraints, _Trivial's argument list
            // is optional.
            if hasArguments && (layoutSpecifier != ._Trivial || self.at(.leftParen)) {
              (unexpectedBeforeLeftParen, leftParen) = self.expect(.leftParen)
              size = self.expectWithoutRecovery(.integerLiteral)
              comma = self.consume(if: .comma)
              if comma != nil {
                alignment = self.expectWithoutRecovery(.integerLiteral)
              } else {
                alignment = nil
              }
              (unexpectedBeforeRightParen, rightParen) = self.expect(.rightParen)
            } else {
              unexpectedBeforeLeftParen = nil
              leftParen = nil
              size = nil
              comma = nil
              alignment = nil
              unexpectedBeforeRightParen = nil
              rightParen = nil
            }

            requirement = .layoutRequirement(
              RawLayoutRequirementSyntax(
                type: firstType,
                colon: colon,
                layoutSpecifier: specifier,
                unexpectedBeforeLeftParen,
                leftParen: leftParen,
                size: size,
                comma: comma,
                alignment: alignment,
                unexpectedBeforeRightParen,
                rightParen: rightParen,
                arena: self.arena
              )
            )
          } else {
            // Parse the protocol or composition.
            let secondType = self.parseType()
            requirement = .conformanceRequirement(
              RawConformanceRequirementSyntax(
                leftType: firstType,
                colon: colon,
                rightType: secondType,
                arena: self.arena
              )
            )
          }
        case (.binaryOperator, let handle)?,
          (.postfixOperator, let handle)?,
          (.prefixOperator, let handle)?:
          let equal = self.eat(handle)
          let secondType = self.parseType()
          requirement = .sameTypeRequirement(
            RawSameTypeRequirementSyntax(
              leftType: firstType,
              equal: equal,
              rightType: secondType,
              arena: self.arena
            )
          )
        case nil:
          requirement = .sameTypeRequirement(
            RawSameTypeRequirementSyntax(
              leftType: firstType,
              equal: RawTokenSyntax(missing: .binaryOperator, text: "==", arena: self.arena),
              rightType: RawTypeSyntax(RawMissingTypeSyntax(arena: self.arena)),
              arena: self.arena
            )
          )
        }

        keepGoing = self.consume(if: .comma)
        let unexpectedBetweenBodyAndTrailingComma: RawUnexpectedNodesSyntax?

        // If there's a comma, keep parsing the list.
        // If there's a "&&", diagnose replace with a comma and keep parsing
        if let token = self.consumeIfContextualPunctuator("&&") {
          keepGoing = self.missingToken(.comma)
          unexpectedBetweenBodyAndTrailingComma = RawUnexpectedNodesSyntax([token], arena: self.arena)
        } else {
          unexpectedBetweenBodyAndTrailingComma = nil
        }

        elements.append(
          RawGenericRequirementSyntax(
            requirement: requirement,
            unexpectedBetweenBodyAndTrailingComma,
            trailingComma: keepGoing,
            arena: self.arena
          )
        )
      } while keepGoing != nil && self.hasProgressed(&loopProgress)
    }

    return RawGenericWhereClauseSyntax(
      unexpectedBeforeWhereKeyword,
      whereKeyword: whereKeyword,
      requirements: RawGenericRequirementListSyntax(elements: elements, arena: self.arena),
      arena: self.arena
    )
  }
}

extension Parser {
  mutating func parseMemberBlockItem() -> RawMemberBlockItemSyntax? {
    let startToken = self.currentToken
    if let syntax = self.loadCurrentSyntaxNodeFromCache(for: .memberBlockItem) {
      self.registerNodeForIncrementalParse(node: syntax.raw, startToken: startToken)
      return RawMemberBlockItemSyntax(syntax.raw)
    }
    if let remainingTokens = remainingTokensIfMaximumNestingLevelReached() {
      let item = RawMemberBlockItemSyntax(
        remainingTokens,
        decl: RawDeclSyntax(
          RawMissingDeclSyntax(
            attributes: self.emptyCollection(RawAttributeListSyntax.self),
            modifiers: self.emptyCollection(RawDeclModifierListSyntax.self),
            arena: self.arena
          )
        ),
        semicolon: nil,
        arena: self.arena
      )
      return item
    }

    let decl: RawDeclSyntax
    if self.at(.poundSourceLocation) {
      decl = RawDeclSyntax(self.parsePoundSourceLocationDirective())
    } else {
      decl = self.parseDeclaration(inMemberDeclList: true)
    }

    let semi = self.consume(if: .semicolon)
    var trailingSemis: [RawTokenSyntax] = []
    while let trailingSemi = self.consume(if: .semicolon) {
      trailingSemis.append(trailingSemi)
    }

    if decl.isEmpty && semi == nil && trailingSemis.isEmpty {
      return nil
    }

    let result = RawMemberBlockItemSyntax(
      decl: decl,
      semicolon: semi,
      RawUnexpectedNodesSyntax(trailingSemis, arena: self.arena),
      arena: self.arena
    )

    self.registerNodeForIncrementalParse(node: result.raw, startToken: startToken)

    return result
  }

  mutating func parseMemberDeclList() -> RawMemberBlockItemListSyntax {
    var elements = [RawMemberBlockItemSyntax]()
    do {
      var loopProgress = LoopProgressCondition()
      while !self.at(.endOfFile, .rightBrace) && self.hasProgressed(&loopProgress) {
        let newItemAtStartOfLine = self.atStartOfLine
        guard let newElement = self.parseMemberBlockItem() else {
          break
        }
        if let lastItem = elements.last, lastItem.semicolon == nil && !newItemAtStartOfLine {
          elements[elements.count - 1] = RawMemberBlockItemSyntax(
            lastItem.unexpectedBeforeDecl,
            decl: lastItem.decl,
            lastItem.unexpectedBetweenDeclAndSemicolon,
            semicolon: self.missingToken(.semicolon),
            lastItem.unexpectedAfterSemicolon,
            arena: self.arena
          )

        }
        elements.append(newElement)
      }
    }
    return RawMemberBlockItemListSyntax(elements: elements, arena: self.arena)
  }

  /// `introducer` is the `struct`, `class`, ... keyword that is the cause that the member decl block is being parsed.
  /// If the left brace is missing, its indentation will be used to judge whether a following `}` was
  /// indented to close this code block or a surrounding context. See `expectRightBrace`.
  mutating func parseMemberBlock(introducer: RawTokenSyntax? = nil) -> RawMemberBlockSyntax {
    let (unexpectedBeforeLBrace, lbrace) = self.expect(.leftBrace)
    let members = parseMemberDeclList()
    let (unexpectedBeforeRBrace, rbrace) = self.expectRightBrace(leftBrace: lbrace, introducer: introducer)

    return RawMemberBlockSyntax(
      unexpectedBeforeLBrace,
      leftBrace: lbrace,
      members: members,
      unexpectedBeforeRBrace,
      rightBrace: rbrace,
      arena: self.arena
    )
  }
}

extension Parser {
  /// Parse an enum 'case' declaration.
  mutating func parseEnumCaseDeclaration(
    _ attrs: DeclAttributes,
    _ handle: RecoveryConsumptionHandle
  ) -> RawEnumCaseDeclSyntax {
    let (unexpectedBeforeCaseKeyword, caseKeyword) = self.eat(handle)
    var elements = [RawEnumCaseElementSyntax]()
    do {
      var keepGoing: RawTokenSyntax? = nil
      var loopProgress = LoopProgressCondition()
      repeat {
        let unexpectedPeriod = self.consume(if: .period)
        let (unexpectedBeforeName, name) = self.expectIdentifier(keywordRecovery: true)

        let unexpectedGenericParameters: RawUnexpectedNodesSyntax?
        if self.at(prefix: "<") {
          let genericParameters = self.parseGenericParameters()
          unexpectedGenericParameters = RawUnexpectedNodesSyntax([genericParameters], arena: self.arena)
        } else {
          unexpectedGenericParameters = nil
        }

        let parameterClause: RawEnumCaseParameterClauseSyntax?
        if self.at(TokenSpec(.leftParen)) {
          parameterClause = self.parseParameterClause(RawEnumCaseParameterClauseSyntax.self) { parser in
            parser.parseEnumCaseParameter()
          }
        } else {
          parameterClause = nil
        }

        // See if there's a raw value expression.
        let rawValue: RawInitializerClauseSyntax?
        if let eq = self.consume(if: .equal) {
          let value = self.parseExpression(flavor: .basic, pattern: .none)
          rawValue = RawInitializerClauseSyntax(
            equal: eq,
            value: value,
            arena: self.arena
          )
        } else {
          rawValue = nil
        }

        // Continue through the comma-separated list.
        keepGoing = self.consume(if: .comma)
        elements.append(
          RawEnumCaseElementSyntax(
            RawUnexpectedNodesSyntax(combining: unexpectedPeriod, unexpectedBeforeName, arena: self.arena),
            name: name,
            unexpectedGenericParameters,
            parameterClause: parameterClause,
            rawValue: rawValue,
            trailingComma: keepGoing,
            arena: self.arena
          )
        )
      } while keepGoing != nil && self.hasProgressed(&loopProgress)
    }

    return RawEnumCaseDeclSyntax(
      attributes: attrs.attributes,
      modifiers: attrs.modifiers,
      unexpectedBeforeCaseKeyword,
      caseKeyword: caseKeyword,
      elements: RawEnumCaseElementListSyntax(elements: elements, arena: self.arena),
      arena: self.arena
    )
  }

  /// Parse an associated type declaration.
  mutating func parseAssociatedTypeDeclaration(
    _ attrs: DeclAttributes,
    _ handle: RecoveryConsumptionHandle
  ) -> RawAssociatedTypeDeclSyntax {
    let (unexpectedBeforeAssocKeyword, assocKeyword) = self.eat(handle)

    // Detect an attempt to use a type parameter pack.
    let eachKeyword = self.consume(if: .keyword(.each))

    var (unexpectedBeforeName, name) = self.expectIdentifier(keywordRecovery: true)
    if eachKeyword != nil {
      unexpectedBeforeName = RawUnexpectedNodesSyntax(combining: eachKeyword, unexpectedBeforeName, arena: self.arena)
    }

    if unexpectedBeforeName == nil && name.isMissing {
      return RawAssociatedTypeDeclSyntax(
        attributes: attrs.attributes,
        modifiers: attrs.modifiers,
        unexpectedBeforeAssocKeyword,
        associatedtypeKeyword: assocKeyword,
        unexpectedBeforeName,
        name: name,
        inheritanceClause: nil,
        initializer: nil,
        genericWhereClause: nil,
        arena: self.arena
      )
    }

    // Detect an attempt to use (early syntax) type parameter pack.
    let ellipsis = self.consume(ifPrefix: "...", as: .ellipsis)

    // Parse optional inheritance clause.
    let inheritance: RawInheritanceClauseSyntax?
    if self.at(.colon) {
      inheritance = self.parseInheritance()
    } else {
      inheritance = nil
    }

    // Parse default type, if any.
    let defaultType: RawTypeInitializerClauseSyntax?
    if let equal = self.consume(if: .equal) {
      let type = self.parseType()
      defaultType = RawTypeInitializerClauseSyntax(
        equal: equal,
        value: type,
        arena: self.arena
      )
    } else {
      defaultType = nil
    }

    // Parse a 'where' clause if present.
    let whereClause: RawGenericWhereClauseSyntax?
    if self.at(.keyword(.where)) {
      whereClause = self.parseGenericWhereClause()
    } else {
      whereClause = nil
    }

    return RawAssociatedTypeDeclSyntax(
      attributes: attrs.attributes,
      modifiers: attrs.modifiers,
      unexpectedBeforeAssocKeyword,
      associatedtypeKeyword: assocKeyword,
      unexpectedBeforeName,
      name: name,
      RawUnexpectedNodesSyntax([ellipsis], arena: self.arena),
      inheritanceClause: inheritance,
      initializer: defaultType,
      genericWhereClause: whereClause,
      arena: self.arena
    )
  }
}

extension Parser {
  /// Parse an initializer declaration.
  mutating func parseInitializerDeclaration(
    _ attrs: DeclAttributes,
    _ handle: RecoveryConsumptionHandle
  ) -> RawInitializerDeclSyntax {
    let (unexpectedBeforeInitKeyword, initKeyword) = self.eat(handle)

    // Parse the '!' or '?' for a failable initializer.
    let failable: RawTokenSyntax?
    if let parsedFailable = self.consume(
      if: .exclamationMark,
      .postfixQuestionMark,
      TokenSpec(.infixQuestionMark, remapping: .postfixQuestionMark)
    ) {
      failable = parsedFailable
    } else if let parsedFailable = self.consumeIfContextualPunctuator("!", remapping: .exclamationMark) {
      failable = parsedFailable
    } else {
      failable = nil
    }

    let generics: RawGenericParameterClauseSyntax?
    if self.at(prefix: "<") {
      generics = self.parseGenericParameters()
    } else {
      generics = nil
    }

    // Parse the signature.
    let signature = self.parseFunctionSignature()

    let whereClause: RawGenericWhereClauseSyntax?
    if self.at(.keyword(.where)) {
      whereClause = self.parseGenericWhereClause()
    } else {
      whereClause = nil
    }

    let items = self.parseOptionalCodeBlock(allowInitDecl: false)

    return RawInitializerDeclSyntax(
      attributes: attrs.attributes,
      modifiers: attrs.modifiers,
      unexpectedBeforeInitKeyword,
      initKeyword: initKeyword,
      optionalMark: failable,
      genericParameterClause: generics,
      signature: signature,
      genericWhereClause: whereClause,
      body: items,
      arena: self.arena
    )
  }

  /// Parse a deinitializer declaration.
  mutating func parseDeinitializerDeclaration(
    _ attrs: DeclAttributes,
    _ handle: RecoveryConsumptionHandle
  ) -> RawDeinitializerDeclSyntax {
    let (unexpectedBeforeDeinitKeyword, deinitKeyword) = self.eat(handle)

    var unexpectedNameAndSignature: [RawSyntax?] = []

    // async is a contextual keyword
    // must be parsed before attempting to parse identifier
    var effectSpecifiers = parseDeinitEffectSpecifiers()

    if effectSpecifiers == nil {
      if let identifier = self.consume(if: TokenSpec(.identifier, allowAtStartOfLine: false)).map(RawSyntax.init) {
        unexpectedNameAndSignature.append(identifier)
      }
      effectSpecifiers = parseDeinitEffectSpecifiers()
    }
    if effectSpecifiers == nil && self.at(TokenSpec(.leftParen, allowAtStartOfLine: false)) {
      let input = parseParameterClause(RawFunctionParameterClauseSyntax.self) { parser in
        parser.parseFunctionParameter()
      }
      unexpectedNameAndSignature.append(RawSyntax(input))

      effectSpecifiers = parseDeinitEffectSpecifiers()
    }

    var unexpectedAfterAsync: [RawSyntax?] = []
    /// Only allow recovery to the arrow with exprKeyword precedence so we only
    /// skip over misplaced identifiers and don't e.g. recover to an arrow in a 'where' clause.
    if self.canRecoverTo(TokenSpec(.arrow, recoveryPrecedence: .exprKeyword)) != nil {
      let output = self.parseFunctionReturnClause(effectSpecifiers: &effectSpecifiers, allowNamedOpaqueResultType: true)
      unexpectedAfterAsync.append(RawSyntax(output))
    }

    let items = self.parseOptionalCodeBlock()
    return RawDeinitializerDeclSyntax(
      attributes: attrs.attributes,
      modifiers: attrs.modifiers,
      unexpectedBeforeDeinitKeyword,
      deinitKeyword: deinitKeyword,
      RawUnexpectedNodesSyntax(unexpectedNameAndSignature, arena: self.arena),
      effectSpecifiers: effectSpecifiers,
      RawUnexpectedNodesSyntax(unexpectedAfterAsync, arena: arena),
      body: items,
      arena: self.arena
    )
  }
}

extension Parser {
  /// If a `throws` keyword appears right in front of the `arrow`, it is returned as `misplacedThrowsKeyword` so it can be synthesized in front of the arrow.
  mutating func parseFunctionReturnClause(
    effectSpecifiers: inout (some RawMisplacedEffectSpecifiersTrait)?,
    allowNamedOpaqueResultType: Bool
  ) -> RawReturnClauseSyntax {
    let (unexpectedBeforeArrow, arrow) = self.expect(.arrow)
    let unexpectedBeforeReturnType = self.parseMisplacedEffectSpecifiers(&effectSpecifiers)
    let type: RawTypeSyntax
    if allowNamedOpaqueResultType {
      type = self.parseResultType()
    } else {
      type = self.parseType()
    }
    let unexpectedAfterReturnType = self.parseMisplacedEffectSpecifiers(&effectSpecifiers)
    let returnClause = RawReturnClauseSyntax(
      unexpectedBeforeArrow,
      arrow: arrow,
      unexpectedBeforeReturnType,
      type: type,
      unexpectedAfterReturnType,
      arena: self.arena
    )
    return returnClause
  }
}

extension Parser {
  mutating func parseFuncDeclaration(
    _ attrs: DeclAttributes,
    _ handle: RecoveryConsumptionHandle
  ) -> RawFunctionDeclSyntax {
    let (unexpectedBeforeFuncKeyword, funcKeyword) = self.eat(handle)
    let unexpectedBeforeIdentifier: RawUnexpectedNodesSyntax?
    let unexpectedAfterIdentifier: RawUnexpectedNodesSyntax?
    let identifier: RawTokenSyntax
    if self.at(anyIn: Operator.self) != nil || self.at(.exclamationMark, .prefixAmpersand) {
      var name = self.currentToken.tokenText
      if !currentToken.isEditorPlaceholder && name.hasSuffix("<") && self.peek(isAt: .identifier) {
        name = SyntaxText(rebasing: name.dropLast())
      }
      unexpectedBeforeIdentifier = nil
      identifier = self.consumePrefix(name, as: .binaryOperator)
      unexpectedAfterIdentifier = nil
    } else {
      (unexpectedBeforeIdentifier, identifier) = self.expectIdentifier(keywordRecovery: true)

      if currentToken.isEditorPlaceholder {
        let editorPlaceholder = self.parseAnyIdentifier()
        unexpectedAfterIdentifier = RawUnexpectedNodesSyntax([editorPlaceholder], arena: self.arena)
      } else {
        unexpectedAfterIdentifier = nil
      }
    }

    let genericParams: RawGenericParameterClauseSyntax?
    if self.at(prefix: "<") {
      genericParams = self.parseGenericParameters()
    } else {
      genericParams = nil
    }

    let signature = self.parseFunctionSignature()

    let generics: RawGenericWhereClauseSyntax?
    if self.at(.keyword(.where)) {
      generics = self.parseGenericWhereClause()
    } else {
      generics = nil
    }

    let body = self.parseOptionalCodeBlock()
    return RawFunctionDeclSyntax(
      attributes: attrs.attributes,
      modifiers: attrs.modifiers,
      unexpectedBeforeFuncKeyword,
      funcKeyword: funcKeyword,
      unexpectedBeforeIdentifier,
      name: identifier,
      unexpectedAfterIdentifier,
      genericParameterClause: genericParams,
      signature: signature,
      genericWhereClause: generics,
      body: body,
      arena: self.arena
    )
  }

  mutating func parseFunctionSignature() -> RawFunctionSignatureSyntax {
    let parameterClause = self.parseParameterClause(RawFunctionParameterClauseSyntax.self) { parser in
      parser.parseFunctionParameter()
    }

    var effectSpecifiers = self.parseFunctionEffectSpecifiers()

    var returnClause: RawReturnClauseSyntax?

    /// Only allow recovery to the arrow with exprKeyword precedence so we only
    /// skip over misplaced identifiers and don't e.g. recover to an arrow in a 'where' clause.
    if self.canRecoverTo(TokenSpec(.arrow, recoveryPrecedence: .exprKeyword)) != nil {
      returnClause = self.parseFunctionReturnClause(
        effectSpecifiers: &effectSpecifiers,
        allowNamedOpaqueResultType: true
      )
    } else {
      returnClause = nil
    }

    return RawFunctionSignatureSyntax(
      parameterClause: parameterClause,
      effectSpecifiers: effectSpecifiers,
      returnClause: returnClause,
      arena: self.arena
    )
  }
}

extension Parser {
  /// Parse a subscript declaration.
  mutating func parseSubscriptDeclaration(
    _ attrs: DeclAttributes,
    _ handle: RecoveryConsumptionHandle
  ) -> RawSubscriptDeclSyntax {
    let (unexpectedBeforeSubscriptKeyword, subscriptKeyword) = self.eat(handle)

    let unexpectedName: RawTokenSyntax?
    if self.at(.identifier) && self.peek().tokenText.hasPrefix("<") || self.peek(isAt: .leftParen) {
      unexpectedName = self.consumeAnyToken()
    } else {
      unexpectedName = nil
    }

    let genericParameterClause: RawGenericParameterClauseSyntax?
    if self.at(prefix: "<") {
      genericParameterClause = self.parseGenericParameters()
    } else {
      genericParameterClause = nil
    }

    let parameterClause = self.parseParameterClause(RawFunctionParameterClauseSyntax.self) { parser in
      parser.parseFunctionParameter()
    }

    var misplacedEffectSpecifiers: RawFunctionEffectSpecifiersSyntax?
    let returnClause = self.parseFunctionReturnClause(
      effectSpecifiers: &misplacedEffectSpecifiers,
      allowNamedOpaqueResultType: true
    )

    // Parse a 'where' clause if present.
    let genericWhereClause: RawGenericWhereClauseSyntax?
    if self.at(.keyword(.where)) {
      genericWhereClause = self.parseGenericWhereClause()
    } else {
      genericWhereClause = nil
    }

    // Parse getter and setter.
    let accessor: RawAccessorBlockSyntax?
    if self.at(.leftBrace) || self.at(anyIn: AccessorDeclSyntax.AccessorSpecifierOptions.self) != nil {
      accessor = self.parseAccessorBlock()
    } else {
      accessor = nil
    }

    return RawSubscriptDeclSyntax(
      attributes: attrs.attributes,
      modifiers: attrs.modifiers,
      unexpectedBeforeSubscriptKeyword,
      subscriptKeyword: subscriptKeyword,
      RawUnexpectedNodesSyntax([unexpectedName], arena: self.arena),
      genericParameterClause: genericParameterClause,
      parameterClause: parameterClause,
      returnClause: returnClause,
      genericWhereClause: genericWhereClause,
      accessorBlock: accessor,
      arena: self.arena
    )
  }
}

extension Parser {
  /// Parse a variable declaration starting with a leading 'let' or 'var' keyword.
  ///
  /// If `inMemberDeclList` is `true`, we know that the next item needs to be a
  /// declaration that is started by a keyword. Thus, we in the following case
  /// we know that `set` can't start a new declaration and we can thus recover
  /// by synthesizing a missing `{` in front of `set`.
  /// ```
  /// var x: Int
  ///   set {
  ///   }
  /// }
  /// ```
  mutating func parseBindingDeclaration(
    _ attrs: DeclAttributes,
    _ handle: RecoveryConsumptionHandle,
    inMemberDeclList: Bool = false
  ) -> RawVariableDeclSyntax {
    let (unexpectedBeforeIntroducer, introducer) = self.eat(handle)
    let hasTryBeforeIntroducer = unexpectedBeforeIntroducer?.containsToken(where: { TokenSpec(.try) ~= $0 }) ?? false

    var elements = [RawPatternBindingSyntax]()
    do {
      var keepGoing: RawTokenSyntax? = nil
      var loopProgress = LoopProgressCondition()
      repeat {

        var (pattern, typeAnnotation) = self.parseTypedPattern()

        // Parse an initializer if present.
        let initializer: RawInitializerClauseSyntax?
        if let equal = self.consume(if: .equal) {
          var value = self.parseExpression(flavor: .basic, pattern: .none)
          if hasTryBeforeIntroducer && !value.is(RawTryExprSyntax.self) {
            value = RawExprSyntax(
              RawTryExprSyntax(
                tryKeyword: missingToken(.try),
                questionOrExclamationMark: nil,
                expression: value,
                arena: self.arena
              )
            )
          }
          initializer = RawInitializerClauseSyntax(
            equal: equal,
            value: value,
            arena: self.arena
          )
        } else if self.at(TokenSpec(.leftParen, allowAtStartOfLine: false)),
          let typeAnnotationUnwrapped = typeAnnotation
        {
          // If we have a '(' after the type in the annotation, the type annotation
          // is probably a constructor call. Rewrite the nodes to remove the type
          // annotation and form an initializer clause from it instead.
          typeAnnotation = nil
          let initExpr = parsePostfixExpressionSuffix(
            RawExprSyntax(
              RawTypeExprSyntax(
                type: typeAnnotationUnwrapped.type,
                typeAnnotation?.unexpectedAfterType,
                arena: self.arena
              )
            ),
            flavor: .basic,
            pattern: .none
          )
          initializer = RawInitializerClauseSyntax(
            RawUnexpectedNodesSyntax(
              combining:
                typeAnnotationUnwrapped.unexpectedBeforeColon,
              typeAnnotationUnwrapped.colon,
              typeAnnotationUnwrapped.unexpectedBetweenColonAndType,
              arena: self.arena
            ),
            equal: missingToken(.equal),
            value: initExpr,
            arena: self.arena
          )
        } else if self.atStartOfExpression(), !self.at(.leftBrace), !self.atStartOfLine {
          let missingEqual = RawTokenSyntax(missing: .equal, arena: self.arena)
          let expr = self.parseExpression(flavor: .basic, pattern: .none)
          initializer = RawInitializerClauseSyntax(
            equal: missingEqual,
            value: expr,
            arena: self.arena
          )
        } else {
          initializer = nil
        }

        let accessors: RawAccessorBlockSyntax?
        if self.at(.leftBrace)
          || (inMemberDeclList && self.at(anyIn: AccessorDeclSyntax.AccessorSpecifierOptions.self) != nil
            && !self.at(.keyword(.`init`)))
        {
          accessors = self.parseAccessorBlock()
        } else {
          accessors = nil
        }

        keepGoing = self.consume(if: .comma)
        elements.append(
          RawPatternBindingSyntax(
            pattern: pattern,
            typeAnnotation: typeAnnotation,
            initializer: initializer,
            accessorBlock: accessors,
            trailingComma: keepGoing,
            arena: self.arena
          )
        )
      } while keepGoing != nil && self.hasProgressed(&loopProgress)
    }

    return RawVariableDeclSyntax(
      attributes: attrs.attributes,
      modifiers: attrs.modifiers,
      unexpectedBeforeIntroducer,
      bindingSpecifier: introducer,
      bindings: RawPatternBindingListSyntax(elements: elements, arena: self.arena),
      arena: self.arena
    )
  }

  struct AccessorIntroducer {
    var attributes: RawAttributeListSyntax
    var modifier: RawDeclModifierSyntax?
    var kind: AccessorDeclSyntax.AccessorSpecifierOptions
    var unexpectedBeforeToken: RawUnexpectedNodesSyntax?
    var token: RawTokenSyntax
  }

  mutating func parseAccessorIntroducer(
    forcedKind: (AccessorDeclSyntax.AccessorSpecifierOptions, TokenConsumptionHandle)? = nil
  ) -> AccessorIntroducer? {
    // Check there is an identifier before consuming
    var look = self.lookahead()
    let _ = look.consumeAttributeList()
    let hasModifier = look.consume(ifAnyIn: AccessorModifier.self) != nil
    guard let (kind, _) = look.at(anyIn: AccessorDeclSyntax.AccessorSpecifierOptions.self) ?? forcedKind else {
      return nil
    }

    let attrs = self.parseAttributeList()

    // Parse the contextual keywords for 'mutating' and 'nonmutating' before
    // get and set.
    let modifier: RawDeclModifierSyntax?
    if hasModifier {
      let (unexpectedBeforeName, name) = self.expect(anyIn: AccessorModifier.self, default: .mutating)
      modifier = RawDeclModifierSyntax(
        unexpectedBeforeName,
        name: name,
        detail: nil,
        arena: self.arena
      )
    } else {
      modifier = nil
    }

    let (unexpectedBeforeIntroducer, introducer) = self.expect(kind.spec)
    return AccessorIntroducer(
      attributes: attrs,
      modifier: modifier,
      kind: kind,
      unexpectedBeforeToken: unexpectedBeforeIntroducer,
      token: introducer
    )
  }

  /// Parse an accessor.
  mutating func parseAccessorDecl() -> RawAccessorDeclSyntax {
    let forcedHandle = TokenConsumptionHandle(spec: .keyword(.get), tokenIsMissing: true)
    let introducer = parseAccessorIntroducer(forcedKind: (.get, forcedHandle))!
    return parseAccessorDecl(introducer: introducer)
  }

  /// Parse an accessor once we know we have an introducer
  mutating func parseAccessorDecl(
    introducer: AccessorIntroducer
  ) -> RawAccessorDeclSyntax {
    // 'set' and 'willSet' can have an optional name.  This isn't valid in a
    // protocol, but we parse and then reject it for better QoI.
    let parameters: RawAccessorParametersSyntax?
    if [AccessorDeclSyntax.AccessorSpecifierOptions.set, .willSet, .didSet, .`init`].contains(introducer.kind),
      let lparen = self.consume(if: .leftParen)
    {
      let (unexpectedBeforeName, name) = self.expectIdentifier()
      let (unexpectedBeforeRParen, rparen) = self.expect(.rightParen)
      parameters = RawAccessorParametersSyntax(
        leftParen: lparen,
        unexpectedBeforeName,
        name: name,
        unexpectedBeforeRParen,
        rightParen: rparen,
        arena: self.arena
      )
    } else {
      parameters = nil
    }

    let effectSpecifiers = self.parseAccessorEffectSpecifiers()

    let body = self.parseOptionalCodeBlock()
    return RawAccessorDeclSyntax(
      attributes: introducer.attributes,
      modifier: introducer.modifier,
      introducer.unexpectedBeforeToken,
      accessorSpecifier: introducer.token,
      parameters: parameters,
      effectSpecifiers: effectSpecifiers,
      body: body,
      arena: self.arena
    )
  }

  mutating func parseAccessorList() -> RawAccessorDeclListSyntax? {
    // Collect all explicit accessors to a list.
    var elements = [RawAccessorDeclSyntax]()
    do {
      var loopProgress = LoopProgressCondition()
      while !self.at(.endOfFile, .rightBrace) && self.hasProgressed(&loopProgress) {
        guard let introducer = self.parseAccessorIntroducer() else {
          break
        }

        elements.append(parseAccessorDecl(introducer: introducer))
      }
    }
    if elements.isEmpty {
      return nil
    } else {
      return RawAccessorDeclListSyntax(elements: elements, arena: self.arena)
    }
  }

  /// Parse the body of a variable declaration. This can include explicit
  /// getters, setters, and observers, or the body of a computed property.
  mutating func parseAccessorBlock() -> RawAccessorBlockSyntax {
    // Parse getter and setter.
    let unexpectedBeforeLBrace: RawUnexpectedNodesSyntax?
    let lbrace: RawTokenSyntax
    if self.at(anyIn: AccessorDeclSyntax.AccessorSpecifierOptions.self) != nil {
      unexpectedBeforeLBrace = nil
      lbrace = missingToken(.leftBrace)
    } else {
      (unexpectedBeforeLBrace, lbrace) = self.expect(.leftBrace)
    }

    let accessorList = parseAccessorList()

    // There can only be an implicit getter if no other accessors were
    // seen before this one.
    guard let accessorList else {
      let body = parseCodeBlockItemList(until: { $0.at(.rightBrace) })

      let (unexpectedBeforeRBrace, rbrace) = self.expect(.rightBrace)
      return RawAccessorBlockSyntax(
        unexpectedBeforeLBrace,
        leftBrace: lbrace,
        accessors: .getter(body),
        unexpectedBeforeRBrace,
        rightBrace: rbrace,
        arena: self.arena
      )
    }

    let (unexpectedBeforeRBrace, rbrace) = self.expect(.rightBrace)
    return RawAccessorBlockSyntax(
      unexpectedBeforeLBrace,
      leftBrace: lbrace,
      accessors: .accessors(accessorList),
      unexpectedBeforeRBrace,
      rightBrace: rbrace,
      arena: self.arena
    )
  }
}

extension Parser {
  /// Parse a typealias declaration.
  mutating func parseTypealiasDeclaration(
    _ attrs: DeclAttributes,
    _ handle: RecoveryConsumptionHandle
  ) -> RawTypeAliasDeclSyntax {
    let (unexpectedBeforeTypealiasKeyword, typealiasKeyword) = self.eat(handle)
    let (unexpectedBeforeName, name) = self.expectIdentifier(keywordRecovery: true)

    // Parse a generic parameter list if it is present.
    let generics: RawGenericParameterClauseSyntax?
    if self.at(prefix: "<") {
      generics = self.parseGenericParameters()
    } else {
      generics = nil
    }

    // Parse the binding alias.
    let unexpectedBeforeEqual: RawUnexpectedNodesSyntax?
    let equal: RawTokenSyntax
    if let colon = self.consume(if: .colon) {
      unexpectedBeforeEqual = RawUnexpectedNodesSyntax(elements: [RawSyntax(colon)], arena: self.arena)
      equal = missingToken(.equal)
    } else {
      (unexpectedBeforeEqual, equal) = self.expect(.equal)
    }
    let value = self.parseType()
    let initializer = RawTypeInitializerClauseSyntax(
      unexpectedBeforeEqual,
      equal: equal,
      value: value,
      arena: self.arena
    )

    // Parse a 'where' clause if present.
    let genericWhereClause: RawGenericWhereClauseSyntax?
    if self.at(.keyword(.where)) {
      genericWhereClause = self.parseGenericWhereClause()
    } else {
      genericWhereClause = nil
    }

    return RawTypeAliasDeclSyntax(
      attributes: attrs.attributes,
      modifiers: attrs.modifiers,
      unexpectedBeforeTypealiasKeyword,
      typealiasKeyword: typealiasKeyword,
      unexpectedBeforeName,
      name: name,
      genericParameterClause: generics,
      initializer: initializer,
      genericWhereClause: genericWhereClause,
      arena: self.arena
    )
  }
}

extension Parser {
  struct OperatorDeclIntroducer {
    var unexpectedBeforeFixity: RawUnexpectedNodesSyntax?
    var fixity: RawTokenSyntax
    var unexpectedBeforeOperatorKeyword: RawUnexpectedNodesSyntax?
    var operatorKeyword: RawTokenSyntax
  }

  /// Parse an operator declaration.
  mutating func parseOperatorDeclIntroducer(
    _ attrs: DeclAttributes,
    _ handle: RecoveryConsumptionHandle
  ) -> OperatorDeclIntroducer {
    func isFixity(_ modifier: RawDeclModifierSyntax) -> Bool {
      switch modifier.name {
      case .keyword(.prefix),
        .keyword(.infix),
        .keyword(.postfix):
        return true
      default:
        return false
      }
    }

    var unexpectedBeforeFixity = RawUnexpectedNodesSyntax(attrs.attributes.elements, arena: self.arena)

    var fixity: RawTokenSyntax?
    var unexpectedAfterFixity: RawUnexpectedNodesSyntax?

    let modifiers = attrs.modifiers.elements
    if let firstFixityIndex = modifiers.firstIndex(where: { isFixity($0) }) {
      let fixityModifier = modifiers[firstFixityIndex]
      fixity = fixityModifier.name

      unexpectedBeforeFixity = RawUnexpectedNodesSyntax(
        combining: unexpectedBeforeFixity,
        RawUnexpectedNodesSyntax(Array(modifiers[0..<firstFixityIndex]), arena: self.arena),
        fixityModifier.unexpectedBeforeName,
        arena: self.arena
      )

      unexpectedAfterFixity = RawUnexpectedNodesSyntax(
        combining: fixityModifier.unexpectedBetweenNameAndDetail,
        RawUnexpectedNodesSyntax([fixityModifier.detail], arena: self.arena),
        fixityModifier.unexpectedAfterDetail,
        RawUnexpectedNodesSyntax(Array(modifiers[modifiers.index(after: firstFixityIndex)...]), arena: self.arena),
        arena: self.arena
      )

    } else {
      unexpectedBeforeFixity = RawUnexpectedNodesSyntax(
        combining: unexpectedBeforeFixity,
        RawUnexpectedNodesSyntax(modifiers, arena: self.arena),
        arena: self.arena
      )
    }

    var (unexpectedBeforeOperatorKeyword, operatorKeyword) = self.expect(.keyword(.operator))

    unexpectedBeforeOperatorKeyword = RawUnexpectedNodesSyntax(
      combining: unexpectedAfterFixity,
      unexpectedBeforeOperatorKeyword,
      arena: self.arena
    )

    return OperatorDeclIntroducer(
      unexpectedBeforeFixity: unexpectedBeforeFixity,
      fixity: fixity ?? self.missingToken(.prefix),
      unexpectedBeforeOperatorKeyword: unexpectedBeforeOperatorKeyword,
      operatorKeyword: operatorKeyword
    )
  }

  mutating func parseOperatorDeclaration(
    _ attrs: DeclAttributes,
    _ handle: RecoveryConsumptionHandle
  ) -> RawOperatorDeclSyntax {
    let introducer = parseOperatorDeclIntroducer(attrs, handle)

    let unexpectedBeforeName: RawUnexpectedNodesSyntax?
    let name: RawTokenSyntax
    switch self.canRecoverTo(anyIn: OperatorLike.self) {
    case (_, let handle)?:
      (unexpectedBeforeName, name) = self.eat(handle)
    default:
      if let identifier = self.consume(
        if: TokenSpec(.identifier, allowAtStartOfLine: false),
        TokenSpec(.dollarIdentifier, allowAtStartOfLine: false)
      ) {
        // Recover if the developer tried to use an identifier as the operator name
        unexpectedBeforeName = RawUnexpectedNodesSyntax([identifier], arena: self.arena)
      } else {
        unexpectedBeforeName = nil
      }
      name = missingToken(.binaryOperator)
    }

    // Eat any subsequent tokens that are not separated to the operator by trivia.
    // The developer most likely intended these to be part of the operator name.
    var identifiersAfterOperatorName: [RawTokenSyntax] = []
    var loopProgress = LoopProgressCondition()
    while (identifiersAfterOperatorName.last ?? name).trailingTriviaByteLength == 0,
      self.currentToken.leadingTriviaByteLength == 0,
      !self.at(.colon, .leftBrace, .endOfFile),
      self.hasProgressed(&loopProgress)
    {
      identifiersAfterOperatorName.append(consumeAnyToken())
    }

    // Parse (or diagnose) a specified precedence group and/or
    // designated protocol. These both look like identifiers, so we
    // parse them both as identifiers here and sort it out in type
    // checking.
    let precedenceAndTypes: RawOperatorPrecedenceAndTypesSyntax?
    if let colon = self.consume(if: .colon) {
      let (unexpectedBeforeIdentifier, identifier) = self.expectIdentifier(allowSelfOrCapitalSelfAsIdentifier: true)
      var types = [RawDesignatedTypeSyntax]()
      while let comma = self.consume(if: .comma) {
        // Technically, we should only accept identifiers for the designated
        // types but the C++ parser accepted anything, which we mimick.
        // It's not worth fixing since designated types are no longer allowed
        // anyway.
        let designatedType = self.consumeAnyToken()
        types.append(
          RawDesignatedTypeSyntax(
            leadingComma: comma,
            name: designatedType,
            arena: self.arena
          )
        )
      }
      precedenceAndTypes = RawOperatorPrecedenceAndTypesSyntax(
        colon: colon,
        unexpectedBeforeIdentifier,
        precedenceGroup: identifier,
        designatedTypes: RawDesignatedTypeListSyntax(
          elements: types,
          arena: self.arena
        ),
        arena: self.arena
      )
    } else {
      precedenceAndTypes = nil
    }
    let unexpectedAtEnd: RawUnexpectedNodesSyntax?
    if let leftBrace = self.consume(if: .leftBrace) {
      let attributeList = self.parsePrecedenceGroupAttributeListSyntax()
      let rightBrace = self.consume(if: .rightBrace)
      unexpectedAtEnd = RawUnexpectedNodesSyntax(
        elements: [
          RawSyntax(leftBrace),
          RawSyntax(attributeList),
          rightBrace.map(RawSyntax.init),
        ].compactMap({ $0 }),
        arena: self.arena
      )
    } else {
      unexpectedAtEnd = nil
    }
    return RawOperatorDeclSyntax(
      introducer.unexpectedBeforeFixity,
      fixitySpecifier: introducer.fixity,
      introducer.unexpectedBeforeOperatorKeyword,
      operatorKeyword: introducer.operatorKeyword,
      unexpectedBeforeName,
      name: name,
      RawUnexpectedNodesSyntax(identifiersAfterOperatorName, arena: self.arena),
      operatorPrecedenceAndTypes: precedenceAndTypes,
      unexpectedAtEnd,
      arena: self.arena
    )
  }

  /// Parse a precedence group declaration.
  mutating func parsePrecedenceGroupDeclaration(
    _ attrs: DeclAttributes,
    _ handle: RecoveryConsumptionHandle
  ) -> RawPrecedenceGroupDeclSyntax {
    let (unexpectedBeforeGroup, group) = self.eat(handle)
    let (unexpectedBeforeName, name) = self.expectIdentifier(allowSelfOrCapitalSelfAsIdentifier: true)
    let (unexpectedBeforeLBrace, lbrace) = self.expect(.leftBrace)

    let groupAttributes = self.parsePrecedenceGroupAttributeListSyntax()

    let (unexpectedBeforeRBrace, rbrace) = self.expect(.rightBrace)
    return RawPrecedenceGroupDeclSyntax(
      attributes: attrs.attributes,
      modifiers: attrs.modifiers,
      unexpectedBeforeGroup,
      precedencegroupKeyword: group,
      unexpectedBeforeName,
      name: name,
      unexpectedBeforeLBrace,
      leftBrace: lbrace,
      groupAttributes: groupAttributes,
      unexpectedBeforeRBrace,
      rightBrace: rbrace,
      arena: self.arena
    )
  }

  mutating func parsePrecedenceGroupAttributeListSyntax() -> RawPrecedenceGroupAttributeListSyntax {
    enum LabelText: TokenSpecSet {
      case associativity
      case assignment
      case higherThan
      case lowerThan

      init?(lexeme: Lexer.Lexeme, experimentalFeatures: Parser.ExperimentalFeatures) {
        switch PrepareForKeywordMatch(lexeme) {
        case TokenSpec(.associativity): self = .associativity
        case TokenSpec(.assignment): self = .assignment
        case TokenSpec(.higherThan): self = .higherThan
        case TokenSpec(.lowerThan): self = .lowerThan
        default: return nil
        }
      }

      var spec: TokenSpec {
        switch self {
        case .associativity: return .keyword(.associativity)
        case .assignment: return .keyword(.assignment)
        case .higherThan: return .keyword(.higherThan)
        case .lowerThan: return .keyword(.lowerThan)
        }
      }
    }

    var elements = [RawPrecedenceGroupAttributeListSyntax.Element]()
    do {
      var attributesProgress = LoopProgressCondition()
      LOOP: while !self.at(.endOfFile, .rightBrace) && self.hasProgressed(&attributesProgress) {
        switch self.at(anyIn: LabelText.self) {
        case (.associativity, let handle)?:
          let associativity = self.eat(handle)
          let (unexpectedBeforeColon, colon) = self.expect(.colon)
          var (unexpectedBeforeValue, value) = self.expect(
            .keyword(.left),
            .keyword(.right),
            .keyword(.none),
            default: .keyword(.none)
          )
          if value.isMissing, let identifier = self.consume(if: .identifier) {
            unexpectedBeforeValue = RawUnexpectedNodesSyntax(
              combining: unexpectedBeforeValue,
              identifier,
              arena: self.arena
            )
          }
          elements.append(
            .precedenceGroupAssociativity(
              RawPrecedenceGroupAssociativitySyntax(
                associativityLabel: associativity,
                unexpectedBeforeColon,
                colon: colon,
                unexpectedBeforeValue,
                value: value,
                arena: self.arena
              )
            )
          )
        case (.assignment, let handle)?:
          let assignmentKeyword = self.eat(handle)
          let (unexpectedBeforeColon, colon) = self.expect(.colon)
          let (unexpectedBeforeValue, value) = self.expect(
            anyIn: PrecedenceGroupAssignmentSyntax.ValueOptions.self,
            default: .true
          )
          let unexpectedAfterFlag: RawUnexpectedNodesSyntax?
          if value.isMissing,
            let unexpectedIdentifier = self.consume(if: TokenSpec(.identifier, allowAtStartOfLine: false))
          {
            unexpectedAfterFlag = RawUnexpectedNodesSyntax([unexpectedIdentifier], arena: self.arena)
          } else {
            unexpectedAfterFlag = nil
          }
          elements.append(
            .precedenceGroupAssignment(
              RawPrecedenceGroupAssignmentSyntax(
                assignmentLabel: assignmentKeyword,
                unexpectedBeforeColon,
                colon: colon,
                unexpectedBeforeValue,
                value: value,
                unexpectedAfterFlag,
                arena: self.arena
              )
            )
          )
        case (.higherThan, let handle)?,
          (.lowerThan, let handle)?:
          // "lowerThan" and "higherThan" are contextual keywords.
          let level = self.eat(handle)
          let (unexpectedBeforeColon, colon) = self.expect(.colon)
          var names = [RawPrecedenceGroupNameSyntax]()
          do {
            var keepGoing: RawTokenSyntax? = nil
            var namesProgress = LoopProgressCondition()
            repeat {
              let (unexpectedBeforeName, name) = self.expectIdentifier()
              keepGoing = self.consume(if: .comma)
              names.append(
                RawPrecedenceGroupNameSyntax(
                  unexpectedBeforeName,
                  name: name,
                  trailingComma: keepGoing,
                  arena: self.arena
                )
              )
            } while keepGoing != nil && self.hasProgressed(&namesProgress)
          }
          elements.append(
            .precedenceGroupRelation(
              RawPrecedenceGroupRelationSyntax(
                higherThanOrLowerThanLabel: level,
                unexpectedBeforeColon,
                colon: colon,
                precedenceGroups: RawPrecedenceGroupNameListSyntax(elements: names, arena: self.arena),
                arena: self.arena
              )
            )
          )
        case nil:
          break LOOP
        }
      }
    }
    return RawPrecedenceGroupAttributeListSyntax(elements: elements, arena: self.arena)
  }
}

extension Parser {
  /// Parse a macro declaration.
  mutating func parseMacroDeclaration(
    attrs: DeclAttributes,
    introducerHandle: RecoveryConsumptionHandle
  ) -> RawMacroDeclSyntax {
    let (unexpectedBeforeIntroducerKeyword, introducerKeyword) = self.eat(introducerHandle)
    let (unexpectedBeforeName, name) = self.expectIdentifier(keywordRecovery: true)

    // Optional generic parameters.
    let genericParams: RawGenericParameterClauseSyntax?
    if self.at(prefix: "<") {
      genericParams = self.parseGenericParameters()
    } else {
      genericParams = nil
    }

    // Macro signature, which is either value-like or function-like.
    let signature = self.parseFunctionSignature()

    // Initializer, if any.
    let definition: RawInitializerClauseSyntax?
    if let equal = self.consume(if: .equal) {
      let expr = self.parseExpression(flavor: .basic, pattern: .none)
      definition = RawInitializerClauseSyntax(
        equal: equal,
        value: expr,
        arena: self.arena
      )
    } else {
      definition = nil
    }

    // Parse a 'where' clause if present.
    let whereClause: RawGenericWhereClauseSyntax?
    if self.at(.keyword(.where)) {
      whereClause = self.parseGenericWhereClause()
    } else {
      whereClause = nil
    }

    return RawMacroDeclSyntax(
      attributes: attrs.attributes,
      modifiers: attrs.modifiers,
      unexpectedBeforeIntroducerKeyword,
      macroKeyword: introducerKeyword,
      unexpectedBeforeName,
      name: name,
      genericParameterClause: genericParams,
      signature: signature,
      definition: definition,
      genericWhereClause: whereClause,
      arena: self.arena
    )
  }

  /// Parse a macro expansion as a declaration.
  mutating func parseMacroExpansionDeclaration(
    _ attrs: DeclAttributes,
    _ handle: RecoveryConsumptionHandle
  ) -> RawMacroExpansionDeclSyntax {

    var (unexpectedBeforePound, pound) = self.eat(handle)
    if pound.trailingTriviaByteLength > 0 || currentToken.leadingTriviaByteLength > 0 {
      // If there are whitespaces after '#' diagnose.
      let diagnostic = TokenDiagnostic(
        .extraneousTrailingWhitespaceError,
        byteOffset: pound.leadingTriviaByteLength + pound.tokenText.count
      )
      pound = pound.tokenView.withTokenDiagnostic(tokenDiagnostic: diagnostic, arena: self.arena)
    }
    let unexpectedBeforeMacro: RawUnexpectedNodesSyntax?
    let macro: RawTokenSyntax
    if !self.atStartOfLine {
      (unexpectedBeforeMacro, macro) = self.expectIdentifier(allowKeywordsAsIdentifier: true)
    } else {
      unexpectedBeforeMacro = nil
      macro = self.missingToken(.identifier)
    }

    // Parse the optional generic argument list.
    let generics: RawGenericArgumentClauseSyntax?
    if self.withLookahead({ $0.canParseAsGenericArgumentList() }) {
      generics = self.parseGenericArguments()
    } else {
      generics = nil
    }

    // Parse the optional parenthesized argument list.
    let leftParen = self.consume(if: TokenSpec(.leftParen, allowAtStartOfLine: false))
    let args: [RawLabeledExprSyntax]
    let unexpectedBeforeRightParen: RawUnexpectedNodesSyntax?
    let rightParen: RawTokenSyntax?
    if leftParen != nil {
      args = parseArgumentListElements(pattern: .none)
      (unexpectedBeforeRightParen, rightParen) = self.expect(.rightParen)
    } else {
      args = []
      unexpectedBeforeRightParen = nil
      rightParen = nil
    }

    // Parse the optional trailing closures.
    let trailingClosure: RawClosureExprSyntax?
    let additionalTrailingClosures: RawMultipleTrailingClosureElementListSyntax
    if self.at(.leftBrace),
      self.withLookahead({ $0.atValidTrailingClosure(flavor: .basic) })
    {
      (trailingClosure, additionalTrailingClosures) =
        self.parseTrailingClosures(flavor: .basic)
    } else {
      trailingClosure = nil
      additionalTrailingClosures = self.emptyCollection(RawMultipleTrailingClosureElementListSyntax.self)
    }

    return RawMacroExpansionDeclSyntax(
      attributes: attrs.attributes,
      modifiers: attrs.modifiers,
      unexpectedBeforePound,
      pound: pound,
      unexpectedBeforeMacro,
      macroName: macro,
      genericArgumentClause: generics,
      leftParen: leftParen,
      arguments: RawLabeledExprListSyntax(
        elements: args,
        arena: self.arena
      ),
      unexpectedBeforeRightParen,
      rightParen: rightParen,
      trailingClosure: trailingClosure,
      additionalTrailingClosures: additionalTrailingClosures,
      arena: self.arena
    )
  }
}