package melange

  1. Overview
  2. Docs
Legend:
Page
Library
Module
Module type
Parameter
Class
Class type
Source

Source file statement_parser.ml

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

module Ast = Flow_ast
open Token
open Parser_env
open Flow_ast
open Parser_common
open Comment_attachment

module type STATEMENT = sig
  val for_ : env -> (Loc.t, Loc.t) Statement.t

  val if_ : env -> (Loc.t, Loc.t) Statement.t

  val let_ : env -> (Loc.t, Loc.t) Statement.t

  val try_ : env -> (Loc.t, Loc.t) Statement.t

  val while_ : env -> (Loc.t, Loc.t) Statement.t

  val with_ : env -> (Loc.t, Loc.t) Statement.t

  val block : env -> (Loc.t, Loc.t) Statement.t

  val break : env -> (Loc.t, Loc.t) Statement.t

  val continue : env -> (Loc.t, Loc.t) Statement.t

  val debugger : env -> (Loc.t, Loc.t) Statement.t

  val declare : ?in_module:bool -> env -> (Loc.t, Loc.t) Statement.t

  val declare_export_declaration : ?allow_export_type:bool -> env -> (Loc.t, Loc.t) Statement.t

  val declare_opaque_type : env -> (Loc.t, Loc.t) Statement.t

  val do_while : env -> (Loc.t, Loc.t) Statement.t

  val empty : env -> (Loc.t, Loc.t) Statement.t

  val export_declaration :
    decorators:(Loc.t, Loc.t) Class.Decorator.t list -> env -> (Loc.t, Loc.t) Statement.t

  val expression : env -> (Loc.t, Loc.t) Statement.t

  val import_declaration : env -> (Loc.t, Loc.t) Statement.t

  val interface : env -> (Loc.t, Loc.t) Statement.t

  val maybe_labeled : env -> (Loc.t, Loc.t) Statement.t

  val opaque_type : env -> (Loc.t, Loc.t) Statement.t

  val return : env -> (Loc.t, Loc.t) Statement.t

  val switch : env -> (Loc.t, Loc.t) Statement.t

  val throw : env -> (Loc.t, Loc.t) Statement.t

  val type_alias : env -> (Loc.t, Loc.t) Statement.t

  val var : env -> (Loc.t, Loc.t) Statement.t

  val const : env -> (Loc.t, Loc.t) Statement.t
end

module Statement
    (Parse : PARSER)
    (Type : Type_parser.TYPE)
    (Declaration : Declaration_parser.DECLARATION)
    (Object : Object_parser.OBJECT)
    (Pattern_cover : Pattern_cover.COVER) : STATEMENT = struct
  module Enum = Enum_parser.Enum (Parse)

  type for_lhs =
    | For_expression of pattern_cover
    | For_declaration of (Loc.t * (Loc.t, Loc.t) Ast.Statement.VariableDeclaration.t)

  type semicolon_type =
    | Explicit of Loc.t Comment.t list
    | Implicit of Comment_attachment.trailing_and_remover_result

  (* FunctionDeclaration is not a valid Statement, but Annex B sometimes allows it.
     However, AsyncFunctionDeclaration and GeneratorFunctionDeclaration are never
     allowed as statements. We still parse them as statements (and raise an error) to
     recover gracefully. *)
  let function_as_statement env =
    let func = Declaration._function env in
    ( if in_strict_mode env then
      function_as_statement_error_at env (fst func)
    else
      let open Ast.Statement in
      match func with
      | (loc, FunctionDeclaration { Ast.Function.async = true; _ }) ->
        error_at env (loc, Parse_error.AsyncFunctionAsStatement)
      | (loc, FunctionDeclaration { Ast.Function.generator = true; _ }) ->
        error_at env (loc, Parse_error.GeneratorFunctionAsStatement)
      | _ -> ()
    );
    func

  let string_literal env (loc, value, raw, octal) =
    if octal then strict_error env Parse_error.StrictOctalLiteral;
    let leading = Peek.comments env in
    Expect.token env (T_STRING (loc, value, raw, octal));
    let trailing = Eat.trailing_comments env in
    ( loc,
      { StringLiteral.value; raw; comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing () }
    )

  (* Semicolon insertion is handled here :(. There seem to be 2 cases where
   * semicolons are inserted. First, if we reach the EOF. Second, if the next
   * token is } or is separated by a LineTerminator.
   *)
  let semicolon ?(expected = "the token `;`") ?(required = true) env =
    match Peek.token env with
    | T_EOF
    | T_RCURLY ->
      Implicit { trailing = Eat.trailing_comments env; remove_trailing = (fun x _ -> x) }
    | T_SEMICOLON ->
      Eat.token env;
      (match Peek.token env with
      | T_EOF
      | T_RCURLY ->
        Explicit (Eat.trailing_comments env)
      | _ when Peek.is_line_terminator env -> Explicit (Eat.comments_until_next_line env)
      | _ -> Explicit [])
    | _ when Peek.is_line_terminator env ->
      Implicit (Comment_attachment.trailing_and_remover_after_last_line env)
    | _ ->
      if required then error_unexpected ~expected env;
      Explicit []

  (* Consumes and returns the trailing comments after the end of a statement. Also returns
     a remover that can remove all comments that are not trailing the previous token.

     If a statement is the end of a block or file, all comments are trailing.
     Otherwise, if a statement is followed by a new line, only comments on the current
     line are trailing. If a statement is not followed by a new line, it does not have
     trailing comments as they are instead leading comments for the next statement. *)
  let statement_end_trailing_comments env =
    match Peek.token env with
    | T_EOF
    | T_RCURLY ->
      { trailing = Eat.trailing_comments env; remove_trailing = (fun x _ -> x) }
    | _ when Peek.is_line_terminator env ->
      Comment_attachment.trailing_and_remover_after_last_line env
    | _ -> Comment_attachment.trailing_and_remover_after_last_loc env

  let variable_declaration_end ~kind env declarations =
    match semicolon env with
    | Explicit comments -> (comments, declarations)
    | Implicit { remove_trailing; _ } ->
      (* Remove trailing comments from the last declarator *)
      let declarations =
        match List.rev declarations with
        | [] -> []
        | decl :: decls ->
          let decl' =
            remove_trailing decl (fun remover decl -> remover#variable_declarator ~kind decl)
          in
          List.rev (decl' :: decls)
      in
      ([], declarations)

  let rec empty env =
    let loc = Peek.loc env in
    let leading = Peek.comments env in
    Expect.token env T_SEMICOLON;
    let { trailing; _ } = statement_end_trailing_comments env in
    ( loc,
      Statement.Empty
        { Statement.Empty.comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing () }
    )

  and break env =
    let leading = Peek.comments env in
    let (loc, (label, trailing)) =
      with_loc
        (fun env ->
          Expect.token env T_BREAK;
          let label =
            if Peek.token env = T_SEMICOLON || Peek.is_implicit_semicolon env then
              None
            else
              let ((label_loc, { Identifier.name; comments = _ }) as label) =
                Parse.identifier env
              in
              if not (SSet.mem name (labels env)) then
                error_at env (label_loc, Parse_error.UnknownLabel name);
              Some label
          in
          let (trailing, label) =
            match (semicolon env, label) with
            | (Explicit trailing, _)
            | (Implicit { trailing; _ }, None) ->
              (trailing, label)
            | (Implicit { remove_trailing; _ }, Some label) ->
              ([], Some (remove_trailing label (fun remover label -> remover#identifier label)))
          in
          (label, trailing))
        env
    in
    if label = None && not (in_loop env || in_switch env) then
      error_at env (loc, Parse_error.IllegalBreak);
    let comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing () in
    (loc, Statement.Break { Statement.Break.label; comments })

  and continue env =
    let leading = Peek.comments env in
    let (loc, (label, trailing)) =
      with_loc
        (fun env ->
          Expect.token env T_CONTINUE;
          let label =
            if Peek.token env = T_SEMICOLON || Peek.is_implicit_semicolon env then
              None
            else
              let ((label_loc, { Identifier.name; comments = _ }) as label) =
                Parse.identifier env
              in
              if not (SSet.mem name (labels env)) then
                error_at env (label_loc, Parse_error.UnknownLabel name);
              Some label
          in
          let (trailing, label) =
            match (semicolon env, label) with
            | (Explicit trailing, _)
            | (Implicit { trailing; _ }, None) ->
              (trailing, label)
            | (Implicit { remove_trailing; _ }, Some label) ->
              ([], Some (remove_trailing label (fun remover label -> remover#identifier label)))
          in
          (label, trailing))
        env
    in
    if not (in_loop env) then error_at env (loc, Parse_error.IllegalContinue);
    ( loc,
      Statement.Continue
        {
          Statement.Continue.label;
          comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
        }
    )

  and debugger =
    with_loc (fun env ->
        let leading = Peek.comments env in
        Expect.token env T_DEBUGGER;
        let pre_semicolon_trailing =
          if Peek.token env = T_SEMICOLON then
            Eat.trailing_comments env
          else
            []
        in
        let trailing =
          match semicolon env with
          | Explicit trailing
          | Implicit { trailing; _ } ->
            pre_semicolon_trailing @ trailing
        in
        Statement.Debugger
          { Statement.Debugger.comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing () }
    )

  and do_while =
    with_loc (fun env ->
        let leading = Peek.comments env in
        Expect.token env T_DO;
        let body = Parse.statement (env |> with_in_loop true) in
        (* Annex B allows labelled FunctionDeclarations (see
           sec-labelled-function-declarations), but not in IterationStatement
           (see sec-semantics-static-semantics-early-errors). *)
        if (not (in_strict_mode env)) && is_labelled_function body then
          function_as_statement_error_at env (fst body);
        let pre_keyword_trailing = Eat.trailing_comments env in
        Expect.token env T_WHILE;
        let pre_cond_trailing = Eat.trailing_comments env in
        Expect.token env T_LPAREN;
        let test = Parse.expression env in
        Expect.token env T_RPAREN;
        let past_cond_trailing =
          if Peek.token env = T_SEMICOLON then
            Eat.trailing_comments env
          else
            []
        in
        (* The rules of automatic semicolon insertion in ES5 don't mention this,
         * but the semicolon after a do-while loop is optional. This is properly
         * specified in ES6 *)
        let past_cond_trailing =
          match semicolon ~required:false env with
          | Explicit trailing -> past_cond_trailing @ trailing
          | Implicit { trailing; _ } -> trailing
        in
        let trailing = pre_keyword_trailing @ pre_cond_trailing @ past_cond_trailing in
        Statement.DoWhile
          {
            Statement.DoWhile.body;
            test;
            comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
          }
    )

  and for_ =
    let assert_can_be_forin_or_forof env err = function
      | (loc, { Statement.VariableDeclaration.declarations; _ }) ->
        (* Only a single declarator is allowed, without an init. So
         * something like
         *
         * for (var x in y) {}
         *
         * is allowed, but we disallow
         *
         * for (var x, y in z) {}
         * for (var x = 42 in y) {}
         *)
        (match declarations with
        | [(_, { Statement.VariableDeclaration.Declarator.init = None; _ })] -> ()
        | _ -> error_at env (loc, err))
    in
    (* Annex B allows labelled FunctionDeclarations (see
       sec-labelled-function-declarations), but not in IterationStatement
       (see sec-semantics-static-semantics-early-errors). *)
    let assert_not_labelled_function env body =
      if (not (in_strict_mode env)) && is_labelled_function body then
        function_as_statement_error_at env (fst body)
      else
        ()
    in
    with_loc (fun env ->
        let leading = Peek.comments env in
        Expect.token env T_FOR;
        let async = allow_await env && Eat.maybe env T_AWAIT in
        let leading = leading @ Peek.comments env in
        Expect.token env T_LPAREN;
        let comments = Flow_ast_utils.mk_comments_opt ~leading () in
        let init_starts_with_async =
          match Peek.token env with
          | T_ASYNC -> true
          | _ -> false
        in
        let (init, errs) =
          let env = env |> with_no_in true in
          match Peek.token env with
          | T_SEMICOLON -> (None, [])
          | T_LET when Peek.ith_token env ~i:1 <> T_IN ->
            let (loc, (declarations, leading, errs)) = with_loc Declaration.let_ env in
            ( Some
                (For_declaration
                   ( loc,
                     {
                       Statement.VariableDeclaration.kind = Variable.Let;
                       declarations;
                       comments = Flow_ast_utils.mk_comments_opt ~leading ();
                     }
                   )
                ),
              errs
            )
          | T_CONST ->
            let (loc, (declarations, leading, errs)) = with_loc Declaration.const env in
            ( Some
                (For_declaration
                   ( loc,
                     {
                       Statement.VariableDeclaration.kind = Variable.Const;
                       declarations;
                       comments = Flow_ast_utils.mk_comments_opt ~leading ();
                     }
                   )
                ),
              errs
            )
          | T_VAR ->
            let (loc, (declarations, leading, errs)) = with_loc Declaration.var env in
            ( Some
                (For_declaration
                   ( loc,
                     {
                       Statement.VariableDeclaration.kind = Variable.Var;
                       declarations;
                       comments = Flow_ast_utils.mk_comments_opt ~leading ();
                     }
                   )
                ),
              errs
            )
          | _ ->
            let expr = Parse.expression_or_pattern env in
            (Some (For_expression expr), [])
        in
        match Peek.token env with
        | T_OF ->
          (* This is a for of loop *)
          let left =
            match init with
            | Some (For_declaration decl) ->
              assert_can_be_forin_or_forof env Parse_error.InvalidLHSInForOf decl;
              Statement.ForOf.LeftDeclaration decl
            | Some (For_expression expr) ->
              (* #sec-for-in-and-for-of-statements-static-semantics-early-errors *)
              let patt = Pattern_cover.as_pattern ~err:Parse_error.InvalidLHSInForOf env expr in
              (match ((not async) && init_starts_with_async, patt) with
              | ( true,
                  ( _,
                    Pattern.Identifier
                      {
                        Pattern.Identifier.name =
                          (id_loc, { Identifier.name = "async"; comments = _ });
                        annot = _;
                        optional = _;
                      }
                  )
                ) ->
                (* #prod-nLtPS4oB - `for (async of ...)` is forbidden because it is
                   ambiguous whether it's a for-of with an `async` identifier, or a
                   regular for loop with an async arrow function with a param named
                   `of`. We can backtrack, so we know it's a for-of, but the spec
                   still disallows it. *)
                error_at env (id_loc, Parse_error.InvalidLHSInForOf)
              | _ -> ());
              Statement.ForOf.LeftPattern patt
            | None -> assert false
          in
          Expect.token env T_OF;
          let right = Parse.assignment env in
          Expect.token env T_RPAREN;
          let body = Parse.statement (env |> with_in_loop true) in
          assert_not_labelled_function env body;
          Statement.ForOf { Statement.ForOf.left; right; body; await = async; comments }
        | T_IN ->
          (* This is a for in loop *)
          let left =
            match init with
            | Some (For_declaration decl) ->
              assert_can_be_forin_or_forof env Parse_error.InvalidLHSInForIn decl;
              Statement.ForIn.LeftDeclaration decl
            | Some (For_expression expr) ->
              (* #sec-for-in-and-for-of-statements-static-semantics-early-errors *)
              let patt = Pattern_cover.as_pattern ~err:Parse_error.InvalidLHSInForIn env expr in
              Statement.ForIn.LeftPattern patt
            | None -> assert false
          in
          if async then
            (* If `async` is true, this should have been a for-await-of loop, but we
               recover by trying to parse like a for-in loop. *)
            Expect.token env T_OF
          else
            Expect.token env T_IN;
          let right = Parse.expression env in
          Expect.token env T_RPAREN;
          let body = Parse.statement (env |> with_in_loop true) in
          assert_not_labelled_function env body;
          Statement.ForIn { Statement.ForIn.left; right; body; each = false; comments }
        | _ ->
          (* This is a for loop *)
          errs |> List.iter (error_at env);
          if async then
            (* If `async` is true, this should have been a for-await-of loop, but we
               recover by trying to parse like a normal loop. *)
            Expect.token env T_OF
          else
            Expect.token env T_SEMICOLON;
          let init =
            match init with
            | Some (For_declaration decl) -> Some (Statement.For.InitDeclaration decl)
            | Some (For_expression expr) ->
              Some (Statement.For.InitExpression (Pattern_cover.as_expression env expr))
            | None -> None
          in
          let test =
            match Peek.token env with
            | T_SEMICOLON -> None
            | _ -> Some (Parse.expression env)
          in
          Expect.token env T_SEMICOLON;
          let update =
            match Peek.token env with
            | T_RPAREN -> None
            | _ -> Some (Parse.expression env)
          in
          Expect.token env T_RPAREN;
          let body = Parse.statement (env |> with_in_loop true) in
          assert_not_labelled_function env body;
          Statement.For { Statement.For.init; test; update; body; comments }
    )

  and if_ =
    (*
     * Either the consequent or alternate of an if statement
     *)
    let if_branch env =
      (* Normally this would just be a Statement, but Annex B allows
         FunctionDeclarations in non-strict mode. See
         sec-functiondeclarations-in-ifstatement-statement-clauses *)
      let stmt =
        if Peek.is_function env then
          function_as_statement env
        else
          Parse.statement env
      in
      (* Annex B allows labelled FunctionDeclarations in non-strict mode
         (see sec-labelled-function-declarations), but not in IfStatement
         (see sec-if-statement-static-semantics-early-errors). *)
      if (not (in_strict_mode env)) && is_labelled_function stmt then
        function_as_statement_error_at env (fst stmt);

      stmt
    in
    let alternate env =
      let leading = Peek.comments env in
      Expect.token env T_ELSE;
      let body = if_branch env in
      { Statement.If.Alternate.body; comments = Flow_ast_utils.mk_comments_opt ~leading () }
    in
    with_loc (fun env ->
        let pre_if_leading = Peek.comments env in
        Expect.token env T_IF;
        let pre_cond_leading = Peek.comments env in
        let leading = pre_if_leading @ pre_cond_leading in
        Expect.token env T_LPAREN;
        let test = Parse.expression env in
        Expect.token env T_RPAREN;
        let consequent = if_branch env in
        let alternate =
          if Peek.token env = T_ELSE then
            Some (with_loc alternate env)
          else
            None
        in
        Statement.If
          {
            Statement.If.test;
            consequent;
            alternate;
            comments = Flow_ast_utils.mk_comments_opt ~leading ();
          }
    )

  and return =
    with_loc (fun env ->
        if not (in_function env) then error env Parse_error.IllegalReturn;
        let leading = Peek.comments env in
        let start_loc = Peek.loc env in
        Expect.token env T_RETURN;
        let trailing =
          if Peek.token env = T_SEMICOLON then
            Eat.trailing_comments env
          else
            []
        in
        let argument =
          if Peek.token env = T_SEMICOLON || Peek.is_implicit_semicolon env then
            None
          else
            Some (Parse.expression env)
        in
        let return_out = Loc.btwn start_loc (Peek.loc env) in
        let (trailing, argument) =
          match (semicolon env, argument) with
          | (Explicit comments, _)
          | (Implicit { trailing = comments; _ }, None) ->
            (trailing @ comments, argument)
          | (Implicit { remove_trailing; _ }, Some arg) ->
            (trailing, Some (remove_trailing arg (fun remover arg -> remover#expression arg)))
        in
        Statement.Return
          {
            Statement.Return.argument;
            return_out;
            comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
          }
    )

  and switch =
    let case ~seen_default env =
      let leading = Peek.comments env in
      let (test, trailing) =
        match Peek.token env with
        | T_DEFAULT ->
          if seen_default then error env Parse_error.MultipleDefaultsInSwitch;
          Expect.token env T_DEFAULT;
          (None, Eat.trailing_comments env)
        | _ ->
          Expect.token env T_CASE;
          (Some (Parse.expression env), [])
      in
      let seen_default = seen_default || test = None in
      Expect.token env T_COLON;
      let { trailing = line_end_trailing; _ } = statement_end_trailing_comments env in
      let trailing = trailing @ line_end_trailing in
      let term_fn = function
        | T_RCURLY
        | T_DEFAULT
        | T_CASE ->
          true
        | _ -> false
      in
      let consequent = Parse.statement_list ~term_fn (env |> with_in_switch true) in
      let comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing () in
      let case = { Statement.Switch.Case.test; consequent; comments } in
      (case, seen_default)
    in
    let rec case_list env (seen_default, acc) =
      match Peek.token env with
      | T_EOF
      | T_RCURLY ->
        List.rev acc
      | _ ->
        let (case_, seen_default) = with_loc_extra (case ~seen_default) env in
        let acc = case_ :: acc in
        case_list env (seen_default, acc)
    in
    with_loc (fun env ->
        let leading = Peek.comments env in
        Expect.token env T_SWITCH;
        Expect.token env T_LPAREN;
        let discriminant = Parse.expression env in
        Expect.token env T_RPAREN;
        Expect.token env T_LCURLY;
        let cases = case_list env (false, []) in
        Expect.token env T_RCURLY;
        let { trailing; _ } = statement_end_trailing_comments env in
        Statement.Switch
          {
            Statement.Switch.discriminant;
            cases;
            comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
            exhaustive_out = fst discriminant;
          }
    )

  and throw =
    with_loc (fun env ->
        let leading = Peek.comments env in
        let start_loc = Peek.loc env in
        Expect.token env T_THROW;
        if Peek.is_line_terminator env then error_at env (start_loc, Parse_error.NewlineAfterThrow);
        let argument = Parse.expression env in
        let (trailing, argument) =
          match semicolon env with
          | Explicit trailing -> (trailing, argument)
          | Implicit { remove_trailing; _ } ->
            ([], remove_trailing argument (fun remover arg -> remover#expression arg))
        in
        let open Statement in
        Throw { Throw.argument; comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing () }
    )

  and try_ =
    with_loc (fun env ->
        let leading = Peek.comments env in
        Expect.token env T_TRY;
        let block =
          let block = Parse.block_body env in
          if Peek.token env = T_CATCH then
            block_remove_trailing env block
          else
            block
        in
        let handler =
          match Peek.token env with
          | T_CATCH ->
            let catch =
              with_loc
                (fun env ->
                  let leading = Peek.comments env in
                  Expect.token env T_CATCH;
                  let trailing = Eat.trailing_comments env in
                  let param =
                    if Peek.token env = T_LPAREN then (
                      Expect.token env T_LPAREN;
                      let p = Some (Parse.pattern env Parse_error.StrictCatchVariable) in
                      Expect.token env T_RPAREN;
                      p
                    ) else
                      None
                  in
                  let body = Parse.block_body env in
                  (* Fix trailing comment attachment if catch block is end of statement *)
                  let body =
                    if Peek.token env <> T_FINALLY then
                      let { remove_trailing; _ } = statement_end_trailing_comments env in
                      remove_trailing body (fun remover (loc, body) -> (loc, remover#block loc body))
                    else
                      body
                  in
                  {
                    Ast.Statement.Try.CatchClause.param;
                    body;
                    comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
                  })
                env
            in
            Some catch
          | _ -> None
        in
        let finalizer =
          match Peek.token env with
          | T_FINALLY ->
            Expect.token env T_FINALLY;
            let (loc, body) = Parse.block_body env in
            let { remove_trailing; _ } = statement_end_trailing_comments env in
            let body = remove_trailing body (fun remover body -> remover#block loc body) in
            Some (loc, body)
          | _ -> None
        in
        (* No catch or finally? That's an error! *)
        if handler = None && finalizer = None then
          error_at env (fst block, Parse_error.NoCatchOrFinally);

        Statement.Try
          {
            Statement.Try.block;
            handler;
            finalizer;
            comments = Flow_ast_utils.mk_comments_opt ~leading ();
          }
    )

  and var =
    with_loc (fun env ->
        let kind = Variable.Var in
        let (declarations, leading, errs) = Declaration.var env in
        let (trailing, declarations) = variable_declaration_end ~kind env declarations in
        errs |> List.iter (error_at env);
        Statement.VariableDeclaration
          {
            Statement.VariableDeclaration.kind;
            declarations;
            comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
          }
    )

  and const =
    with_loc (fun env ->
        let kind = Variable.Const in
        let (declarations, leading, errs) = Declaration.const env in
        let (trailing, declarations) = variable_declaration_end ~kind env declarations in
        errs |> List.iter (error_at env);
        Statement.VariableDeclaration
          {
            Statement.VariableDeclaration.kind;
            declarations;
            comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
          }
    )

  and let_ =
    with_loc (fun env ->
        let kind = Variable.Let in
        let (declarations, leading, errs) = Declaration.let_ env in
        let (trailing, declarations) = variable_declaration_end ~kind env declarations in
        errs |> List.iter (error_at env);
        Statement.VariableDeclaration
          {
            Statement.VariableDeclaration.kind;
            declarations;
            comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
          }
    )

  and while_ =
    with_loc (fun env ->
        let leading = Peek.comments env in
        Expect.token env T_WHILE;
        let leading = leading @ Peek.comments env in
        Expect.token env T_LPAREN;
        let test = Parse.expression env in
        Expect.token env T_RPAREN;
        let body = Parse.statement (env |> with_in_loop true) in
        (* Annex B allows labelled FunctionDeclarations in non-strict mode
           (see sec-labelled-function-declarations), but not in IterationStatement
           (see sec-semantics-static-semantics-early-errors). *)
        if (not (in_strict_mode env)) && is_labelled_function body then
          function_as_statement_error_at env (fst body);
        Statement.While
          { Statement.While.test; body; comments = Flow_ast_utils.mk_comments_opt ~leading () }
    )

  and with_ env =
    let (loc, stmt) =
      with_loc
        (fun env ->
          let leading = Peek.comments env in
          Expect.token env T_WITH;
          let leading = leading @ Peek.comments env in
          Expect.token env T_LPAREN;
          let _object = Parse.expression env in
          Expect.token env T_RPAREN;
          let body = Parse.statement env in
          (* Annex B allows labelled FunctionDeclarations in non-strict mode
             (see sec-labelled-function-declarations), but not in WithStatement
             (see sec-with-statement-static-semantics-early-errors). *)
          if (not (in_strict_mode env)) && is_labelled_function body then
            function_as_statement_error_at env (fst body);
          Statement.With
            { Statement.With._object; body; comments = Flow_ast_utils.mk_comments_opt ~leading () })
        env
    in
    strict_error_at env (loc, Parse_error.StrictModeWith);
    (loc, stmt)

  and block env =
    let (loc, block) = Parse.block_body env in
    let { remove_trailing; _ } = statement_end_trailing_comments env in
    let block = remove_trailing block (fun remover block -> remover#block loc block) in
    (loc, Statement.Block block)

  and maybe_labeled =
    with_loc (fun env ->
        let leading = Peek.comments env in
        match (Parse.expression env, Peek.token env) with
        | ((loc, Ast.Expression.Identifier label), T_COLON) ->
          let (_, { Identifier.name; comments = _ }) = label in
          Expect.token env T_COLON;
          if SSet.mem name (labels env) then
            error_at env (loc, Parse_error.Redeclaration ("Label", name));
          let env = add_label env name in
          let body =
            (* labelled FunctionDeclarations are allowed in non-strict mode
               (see #sec-labelled-function-declarations) *)
            if Peek.is_function env then
              function_as_statement env
            else
              Parse.statement env
          in
          Statement.Labeled
            { Statement.Labeled.label; body; comments = Flow_ast_utils.mk_comments_opt ~leading () }
        | (expression, _) ->
          let (trailing, expression) =
            match semicolon ~expected:"the end of an expression statement (`;`)" env with
            | Explicit comments -> (comments, expression)
            | Implicit { remove_trailing; _ } ->
              ([], remove_trailing expression (fun remover expr -> remover#expression expr))
          in
          let open Statement in
          Expression
            {
              Expression.expression;
              directive = None;
              comments = Flow_ast_utils.mk_comments_opt ~trailing ();
            }
    )

  and expression =
    with_loc (fun env ->
        let expression = Parse.expression env in
        let (trailing, expression) =
          match semicolon ~expected:"the end of an expression statement (`;`)" env with
          | Explicit comments -> (comments, expression)
          | Implicit { remove_trailing; _ } ->
            ([], remove_trailing expression (fun remover expr -> remover#expression expr))
        in
        let directive =
          if allow_directive env then
            match expression with
            | (_, Ast.Expression.StringLiteral { Ast.StringLiteral.raw; _ }) ->
              (* the parser may recover from errors and generate unclosed strings, where
                 the opening quote should be reliable but the closing one might not exist.
                 be defensive. *)
              if String.length raw > 1 && raw.[0] = raw.[String.length raw - 1] then
                Some (String.sub raw 1 (String.length raw - 2))
              else
                None
            | _ -> None
          else
            None
        in
        Statement.Expression
          {
            Statement.Expression.expression;
            directive;
            comments = Flow_ast_utils.mk_comments_opt ~trailing ();
          }
    )

  and type_alias_helper ~leading env =
    if not (should_parse_types env) then error env Parse_error.UnexpectedTypeAlias;
    let leading = leading @ Peek.comments env in
    Expect.token env T_TYPE;
    Eat.push_lex_mode env Lex_mode.TYPE;
    let id =
      let id = Type.type_identifier env in
      if Peek.token env = T_LESS_THAN then
        id_remove_trailing env id
      else
        id
    in
    let tparams = Type.type_params env in
    Expect.token env T_ASSIGN;
    let right = Type._type env in
    Eat.pop_lex_mode env;
    let (trailing, right) =
      match semicolon env with
      | Explicit comments -> (comments, right)
      | Implicit { remove_trailing; _ } ->
        ([], remove_trailing right (fun remover right -> remover#type_ right))
    in

    {
      Statement.TypeAlias.id;
      tparams;
      right;
      comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
    }

  and declare_type_alias env =
    with_loc
      (fun env ->
        let leading = Peek.comments env in
        Expect.token env T_DECLARE;
        let type_alias = type_alias_helper ~leading env in
        Statement.DeclareTypeAlias type_alias)
      env

  (** Type aliases squeeze into an unambiguous unused portion of the grammar: `type` is not a
      reserved word, so `type T` is otherwise two identifiers in a row and that's never valid JS.
      However, if there's a line separator between the two, ASI makes it valid JS, so line
      separators are disallowed. *)
  and type_alias env =
    if Peek.ith_is_identifier ~i:1 env && not (Peek.ith_is_implicit_semicolon ~i:1 env) then
      let (loc, type_alias) = with_loc (type_alias_helper ~leading:[]) env in
      (loc, Statement.TypeAlias type_alias)
    else
      Parse.statement env

  and opaque_type_helper ?(declare = false) ~leading env =
    if not (should_parse_types env) then error env Parse_error.UnexpectedOpaqueTypeAlias;
    let leading_opaque = leading @ Peek.comments env in
    Expect.token env T_OPAQUE;
    let leading_type = Peek.comments env in
    Expect.token env T_TYPE;
    let leading = leading_opaque @ leading_type in
    Eat.push_lex_mode env Lex_mode.TYPE;
    let id =
      let id = Type.type_identifier env in
      if Peek.token env = T_LESS_THAN then
        id_remove_trailing env id
      else
        id
    in
    let tparams = Type.type_params env in
    let supertype =
      match Peek.token env with
      | T_COLON ->
        Expect.token env T_COLON;
        Some (Type._type env)
      | _ -> None
    in
    let impltype =
      if declare then
        match Peek.token env with
        | T_ASSIGN ->
          error env Parse_error.DeclareOpaqueTypeInitializer;
          Eat.token env;
          if Peek.token env = T_SEMICOLON || Peek.is_implicit_semicolon env then
            None
          else
            Some (Type._type env)
        | _ -> None
      else (
        Expect.token env T_ASSIGN;
        Some (Type._type env)
      )
    in
    Eat.pop_lex_mode env;
    let (trailing, id, tparams, supertype, impltype) =
      match (semicolon env, tparams, supertype, impltype) with
      (* opaque type Foo = Bar; *)
      | (Explicit comments, _, _, _) -> (comments, id, tparams, supertype, impltype)
      (* opaque type Foo = Bar *)
      | (Implicit { remove_trailing; _ }, _, _, Some impl) ->
        ( [],
          id,
          tparams,
          supertype,
          Some (remove_trailing impl (fun remover impl -> remover#type_ impl))
        )
      (* opaque type Foo: Super *)
      | (Implicit { remove_trailing; _ }, _, Some super, None) ->
        ( [],
          id,
          tparams,
          Some (remove_trailing super (fun remover super -> remover#type_ super)),
          None
        )
      (* opaque type Foo<T> *)
      | (Implicit { remove_trailing; _ }, Some tparams, None, None) ->
        ( [],
          id,
          Some (remove_trailing tparams (fun remover tparams -> remover#type_params tparams)),
          None,
          None
        )
      (* declare opaque type Foo *)
      | (Implicit { remove_trailing; _ }, None, None, None) ->
        ([], remove_trailing id (fun remover id -> remover#identifier id), None, None, None)
    in

    {
      Statement.OpaqueType.id;
      tparams;
      impltype;
      supertype;
      comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
    }

  and declare_opaque_type env =
    with_loc
      (fun env ->
        let leading = Peek.comments env in
        Expect.token env T_DECLARE;
        let opaque_t = opaque_type_helper ~declare:true ~leading env in
        Statement.DeclareOpaqueType opaque_t)
      env

  and opaque_type env =
    match Peek.ith_token ~i:1 env with
    | T_TYPE ->
      let (loc, opaque_t) = with_loc (opaque_type_helper ~declare:false ~leading:[]) env in
      (loc, Statement.OpaqueType opaque_t)
    | _ -> Parse.statement env

  and interface_helper ~leading env =
    if not (should_parse_types env) then error env Parse_error.UnexpectedTypeInterface;
    let leading = leading @ Peek.comments env in
    Expect.token env T_INTERFACE;
    let id =
      let id = Type.type_identifier env in
      if Peek.token env = T_EXTENDS then
        id
      else
        id_remove_trailing env id
    in
    let tparams =
      let tparams = Type.type_params env in
      if Peek.token env = T_EXTENDS then
        tparams
      else
        type_params_remove_trailing env tparams
    in
    let (extends, body) = Type.interface_helper env in
    let { remove_trailing; _ } = statement_end_trailing_comments env in
    let body =
      remove_trailing body (fun remover (loc, body) -> (loc, remover#object_type loc body))
    in

    {
      Statement.Interface.id;
      tparams;
      body;
      extends;
      comments = Flow_ast_utils.mk_comments_opt ~leading ();
    }

  and declare_interface env =
    with_loc
      (fun env ->
        let leading = Peek.comments env in
        Expect.token env T_DECLARE;
        let iface = interface_helper ~leading env in
        Statement.DeclareInterface iface)
      env

  and interface env =
    (* disambiguate between a value named `interface`, like `var interface = 1; interface++`,
       and an interface declaration like `interface Foo {}`.` *)
    if Peek.ith_is_identifier_name ~i:1 env then
      let (loc, iface) = with_loc (interface_helper ~leading:[]) env in
      (loc, Statement.InterfaceDeclaration iface)
    else
      expression env

  and declare_class =
    let rec mixins env acc =
      let super = Type.generic env in
      let acc = super :: acc in
      match Peek.token env with
      | T_COMMA ->
        Expect.token env T_COMMA;
        mixins env acc
      | _ -> List.rev acc
      (* This is identical to `interface`, except that mixins are allowed *)
    in
    fun ~leading env ->
      let env = env |> with_strict true in
      let leading = leading @ Peek.comments env in
      Expect.token env T_CLASS;
      let id =
        let id = Parse.identifier env in
        match Peek.token env with
        | T_LESS_THAN
        | T_LCURLY ->
          id_remove_trailing env id
        | _ -> id
      in
      let tparams =
        let tparams = Type.type_params env in
        match Peek.token env with
        | T_LCURLY -> type_params_remove_trailing env tparams
        | _ -> tparams
      in
      let extends =
        if Eat.maybe env T_EXTENDS then
          let extends = Type.generic env in
          match Peek.token env with
          | T_LCURLY -> Some (generic_type_remove_trailing env extends)
          | _ -> Some extends
        else
          None
      in
      let mixins =
        match Peek.token env with
        | T_IDENTIFIER { raw = "mixins"; _ } ->
          Eat.token env;
          let mixins = mixins env [] in
          (match Peek.token env with
          | T_LCURLY -> generic_type_list_remove_trailing env mixins
          | _ -> mixins)
        | _ -> []
      in
      let implements =
        match Peek.token env with
        | T_IMPLEMENTS ->
          let implements = Object.class_implements env ~attach_leading:false in
          (match Peek.token env with
          | T_LCURLY -> Some (class_implements_remove_trailing env implements)
          | _ -> Some implements)
        | _ -> None
      in
      let body = Type._object ~is_class:true env in
      let { remove_trailing; _ } = statement_end_trailing_comments env in
      let body =
        remove_trailing body (fun remover (loc, body) -> (loc, remover#object_type loc body))
      in
      let comments = Flow_ast_utils.mk_comments_opt ~leading () in
      Statement.DeclareClass.{ id; tparams; body; extends; mixins; implements; comments }

  and declare_class_statement env =
    with_loc
      (fun env ->
        let leading = Peek.comments env in
        Expect.token env T_DECLARE;
        let fn = declare_class ~leading env in
        Statement.DeclareClass fn)
      env

  and declare_component ~leading env =
    let leading = leading @ Peek.comments env in
    Expect.identifier env "component";
    let id =
      id_remove_trailing
        env
        (* Components should have at least the same strictness as functions *)
        (Parse.identifier ~restricted_error:Parse_error.StrictFunctionName env)
    in
    let tparams = type_params_remove_trailing env (Type.type_params env) in
    let params = Type.component_param_list env in
    let (params, renders) =
      if Peek.is_renders_ident env then
        let renders = Type.renders_annotation_opt env in
        let renders = component_renders_annotation_remove_trailing env renders in
        (params, renders)
      else
        let missing_annotation = Type.renders_annotation_opt env in
        (params, missing_annotation)
    in

    let (trailing, renders) =
      match semicolon env with
      | Explicit comments -> (comments, renders)
      | Implicit { remove_trailing; _ } ->
        ( [],
          remove_trailing renders (fun remover annot -> remover#component_renders_annotation annot)
        )
    in
    {
      Statement.DeclareComponent.id;
      params;
      renders;
      tparams;
      comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
    }

  and declare_component_statement env =
    with_loc
      (fun env ->
        let leading = Peek.comments env in
        Expect.token env T_DECLARE;
        let component = declare_component ~leading env in
        Statement.DeclareComponent component)
      env

  and declare_enum env =
    with_loc
      (fun env ->
        let leading = Peek.comments env in
        Expect.token env T_DECLARE;
        let enum = Enum.declaration ~leading env in
        Statement.DeclareEnum enum)
      env

  and declare_function ?(leading = []) env =
    let leading = leading @ Peek.comments env in
    Expect.token env T_FUNCTION;
    let id = id_remove_trailing env (Parse.identifier env) in
    let annot =
      with_loc
        (fun env ->
          let tparams = type_params_remove_trailing env (Type.type_params env) in
          let params = Type.function_param_list env in
          Expect.token env T_COLON;
          Eat.push_lex_mode env Lex_mode.TYPE;
          let return =
            if is_start_of_type_guard env then
              Ast.Type.Function.TypeGuard (Type.type_guard env)
            else
              let return = Type._type env in
              let has_predicate = Peek.token env = T_CHECKS in
              if has_predicate then
                Ast.Type.Function.TypeAnnotation (type_remove_trailing env return)
              else
                Ast.Type.Function.TypeAnnotation return
          in
          Eat.pop_lex_mode env;
          Ast.Type.(Function { Function.params; return; tparams; comments = None }))
        env
    in
    let predicate = Type.predicate_opt env in
    let (trailing, annot, predicate) =
      match (semicolon env, predicate) with
      | (Explicit comments, _) -> (comments, annot, predicate)
      | (Implicit { remove_trailing; _ }, None) ->
        ([], remove_trailing annot (fun remover annot -> remover#type_ annot), None)
      | (Implicit { remove_trailing; _ }, Some pred) ->
        ([], annot, Some (remove_trailing pred (fun remover pred -> remover#predicate pred)))
    in
    let annot = (fst annot, annot) in

    {
      Statement.DeclareFunction.id;
      annot;
      predicate;
      comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
    }

  and declare_function_statement env =
    with_loc
      (fun env ->
        let leading = Peek.comments env in
        Expect.token env T_DECLARE;
        begin
          match Peek.token env with
          | T_ASYNC ->
            error env Parse_error.DeclareAsync;
            Expect.token env T_ASYNC
          | _ -> ()
        end;
        let fn = declare_function ~leading env in
        Statement.DeclareFunction fn)
      env

  and declare_var ~kind env leading =
    let leading = leading @ Peek.comments env in
    (match kind with
    | Ast.Variable.Var -> Expect.token env T_VAR
    | Ast.Variable.Let -> Expect.token env T_LET
    | Ast.Variable.Const -> Expect.token env T_CONST);
    let name = Parse.identifier ~restricted_error:Parse_error.StrictVarName env in
    let annot = Type.annotation env in
    let (trailing, name, annot) =
      match semicolon env with
      (* declare var x; *)
      | Explicit trailing -> (trailing, name, annot)
      (* declare var x *)
      | Implicit { remove_trailing; _ } ->
        ([], name, remove_trailing annot (fun remover annot -> remover#type_annotation annot))
    in

    {
      Statement.DeclareVariable.id = name;
      annot;
      kind;
      comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
    }

  and declare_var_statement ~kind env =
    with_loc
      (fun env ->
        let leading = Peek.comments env in
        Expect.token env T_DECLARE;
        let var = declare_var ~kind env leading in
        Statement.DeclareVariable var)
      env

  and declare_module =
    let rec module_items env ~module_kind acc =
      match Peek.token env with
      | T_EOF
      | T_RCURLY ->
        (module_kind, List.rev acc)
      | _ ->
        let stmt = declare ~in_module:true env in
        (* TODO: This is a semantic analysis and shouldn't be in the parser *)
        let module_kind =
          let open Statement in
          let (_loc, stmt) = stmt in
          match (module_kind, stmt) with
          (*
           * The first time we see either a `declare export` or a
           * `declare module.exports`, we lock in the kind of the module.
           *
           * `declare export type` and `declare export interface` are the two
           * exceptions to this rule because they are valid in both CommonJS
           * and ES modules (and thus do not indicate an intent for either).
           *)
          | (None, DeclareModuleExports _) -> Some DeclareModule.CommonJS
          | (None, DeclareExportDeclaration { DeclareExportDeclaration.declaration; _ }) ->
            (match declaration with
            | Some (DeclareExportDeclaration.NamedType _)
            | Some (DeclareExportDeclaration.Interface _) ->
              module_kind
            | _ -> Some DeclareModule.ES)
          (*
           * There should never be more than one `declare module.exports`
           * statement *)
          | (Some DeclareModule.CommonJS, DeclareModuleExports _) ->
            error env Parse_error.DuplicateDeclareModuleExports;
            module_kind
          (*
           * It's never ok to mix and match `declare export` and
           * `declare module.exports` in the same module because it leaves the
           * kind of the module (CommonJS vs ES) ambiguous.
           *
           * The 1 exception to this rule is that `export type/interface` are
           * both ok in CommonJS modules.
           *)
          | (Some DeclareModule.ES, DeclareModuleExports _) ->
            error env Parse_error.AmbiguousDeclareModuleKind;
            module_kind
          | ( Some DeclareModule.CommonJS,
              DeclareExportDeclaration { DeclareExportDeclaration.declaration; _ }
            ) ->
            (match declaration with
            | Some (DeclareExportDeclaration.NamedType _)
            | Some (DeclareExportDeclaration.Interface _) ->
              ()
            | _ -> error env Parse_error.AmbiguousDeclareModuleKind);
            module_kind
          | _ -> module_kind
        in
        module_items env ~module_kind (stmt :: acc)
    in
    let declare_module_ ~leading env =
      let id =
        match Peek.token env with
        | T_STRING str ->
          Statement.DeclareModule.Literal
            (string_literal_remove_trailing env (string_literal env str))
        | _ -> Statement.DeclareModule.Identifier (id_remove_trailing env (Parse.identifier env))
      in
      let (body, module_kind) =
        with_loc_extra
          (fun env ->
            let leading = Peek.comments env in
            Expect.token env T_LCURLY;
            let (module_kind, body) = module_items env ~module_kind:None [] in
            let internal =
              if body = [] then
                Peek.comments env
              else
                []
            in
            Expect.token env T_RCURLY;
            let { trailing; _ } = statement_end_trailing_comments env in
            let comments =
              Flow_ast_utils.mk_comments_with_internal_opt ~leading ~trailing ~internal ()
            in
            let body = { Statement.Block.body; comments } in
            (body, module_kind))
          env
      in
      let kind =
        match module_kind with
        | Some k -> k
        | None -> Statement.DeclareModule.CommonJS
      in
      let comments = Flow_ast_utils.mk_comments_opt ~leading () in
      Statement.(DeclareModule DeclareModule.{ id; body; kind; comments })
    in
    fun ~in_module env ->
      let start_loc = Peek.loc env in
      let leading = Peek.comments env in
      Expect.token env T_DECLARE;
      let leading = leading @ Peek.comments env in
      Expect.identifier env "module";
      if in_module || Peek.token env = T_PERIOD then
        with_loc ~start_loc (declare_module_exports ~leading) env
      else
        with_loc ~start_loc (declare_module_ ~leading) env

  and declare_module_exports ~leading env =
    let leading_period = Peek.comments env in
    Expect.token env T_PERIOD;
    let leading_exports = Peek.comments env in
    Expect.identifier env "exports";
    let leading_annot = Peek.comments env in
    let leading = List.concat [leading; leading_period; leading_exports; leading_annot] in
    let annot = Type.annotation env in
    let (annot, trailing) =
      match semicolon env with
      | Explicit trailing -> (annot, trailing)
      | Implicit { remove_trailing; _ } ->
        (remove_trailing annot (fun remover annot -> remover#type_annotation annot), [])
    in
    let comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing () in
    Statement.DeclareModuleExports { Statement.DeclareModuleExports.annot; comments }

  and declare ?(in_module = false) env =
    if not (should_parse_types env) then error env Parse_error.UnexpectedTypeDeclaration;

    (* eventually, just emit a wrapper AST node *)
    match Peek.ith_token ~i:1 env with
    | T_CLASS -> declare_class_statement env
    | T_ENUM when (parse_options env).enums -> declare_enum env
    | T_INTERFACE -> declare_interface env
    | T_TYPE ->
      (match Peek.token env with
      | T_IMPORT when in_module -> import_declaration env
      | _ -> declare_type_alias env)
    | T_OPAQUE -> declare_opaque_type env
    | T_TYPEOF when Peek.token env = T_IMPORT -> import_declaration env
    | T_FUNCTION
    | T_ASYNC ->
      declare_function_statement env
    | T_VAR -> declare_var_statement ~kind:Ast.Variable.Var env
    | T_LET -> declare_var_statement ~kind:Ast.Variable.Let env
    | T_CONST -> declare_var_statement ~kind:Ast.Variable.Const env
    | T_EXPORT when in_module -> declare_export_declaration ~allow_export_type:in_module env
    | T_IDENTIFIER { raw = "module"; _ } -> declare_module ~in_module env
    | T_IDENTIFIER { raw = "component"; _ } when (parse_options env).components ->
      declare_component_statement env
    | _ when in_module ->
      (match Peek.token env with
      | T_IMPORT ->
        error env Parse_error.InvalidNonTypeImportInDeclareModule;
        Parse.statement env
      | _ ->
        (* Oh boy, found some bad stuff in a declare module. Let's just
         * pretend it's a declare var (arbitrary choice) *)
        declare_var_statement ~kind:Ast.Variable.Var env)
    | _ -> Parse.statement env

  and export_source env =
    Expect.identifier env "from";
    match Peek.token env with
    | T_STRING str -> string_literal env str
    | _ ->
      (* Just make up a string for the error case *)
      let ret = (Peek.loc env, { StringLiteral.value = ""; raw = ""; comments = None }) in
      error_unexpected ~expected:"a string" env;
      ret

  and export_source_and_semicolon env =
    let (source_loc, source) = export_source env in
    match semicolon env with
    | Explicit trailing -> ((source_loc, source), trailing)
    | Implicit { remove_trailing; _ } ->
      ( ( source_loc,
          remove_trailing source (fun remover source -> remover#string_literal source_loc source)
        ),
        []
      )

  and export_specifiers ?(preceding_comma = true) env specifiers =
    match Peek.token env with
    | T_EOF
    | T_RCURLY ->
      List.rev specifiers
    | _ ->
      if not preceding_comma then error env Parse_error.ExportSpecifierMissingComma;
      let specifier =
        with_loc
          (fun env ->
            let local = identifier_name env in
            let exported =
              match Peek.token env with
              | T_IDENTIFIER { raw = "as"; _ } ->
                Eat.token env;
                Some (identifier_name env)
              | _ -> None
            in
            { Statement.ExportNamedDeclaration.ExportSpecifier.local; exported })
          env
      in
      let preceding_comma = Eat.maybe env T_COMMA in
      export_specifiers ~preceding_comma env (specifier :: specifiers)

  and assert_export_specifier_identifiers env specifiers =
    List.iter
      (function
        | (_, { Statement.ExportNamedDeclaration.ExportSpecifier.local = id; exported = _ }) ->
          assert_identifier_name_is_identifier ~restricted_error:Parse_error.StrictVarName env id)
      specifiers

  and export_declaration ~decorators env =
    let env = env |> with_strict true |> with_in_export true in
    let leading = Peek.comments env in
    let start_loc = Peek.loc env in
    Expect.token env T_EXPORT;
    match Peek.token env with
    | T_DEFAULT ->
      (* export default ... *)
      with_loc
        ~start_loc
        (fun env ->
          let open Statement.ExportDefaultDeclaration in
          let leading = leading @ Peek.comments env in
          let (default, ()) = with_loc (fun env -> Expect.token env T_DEFAULT) env in
          let env = with_in_export_default true env in
          let (declaration, trailing) =
            if Peek.is_function env then
              (* export default [async] function [foo] (...) { ... } *)
              let fn = Declaration._function env in
              (Declaration fn, [])
            else if Peek.is_class env then
              (* export default class foo { ... } *)
              let _class = Object.class_declaration env decorators in
              (Declaration _class, [])
            else if Peek.token env = T_ENUM then
              (* export default enum foo { ... } *)
              (Declaration (Declaration.enum_declaration env), [])
            else if Peek.is_component env then
              (* export default component foo { ... } *)
              (Declaration (Declaration.component env), [])
            else
              (* export default [assignment expression]; *)
              let expr = Parse.assignment env in
              let (expr, trailing) =
                match semicolon env with
                | Explicit trailing -> (expr, trailing)
                | Implicit { remove_trailing; _ } ->
                  (remove_trailing expr (fun remover expr -> remover#expression expr), [])
              in
              (Expression expr, trailing)
          in
          Statement.ExportDefaultDeclaration
            {
              default;
              declaration;
              comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
            })
        env
    | T_TYPE when Peek.ith_token ~i:1 env <> T_LCURLY ->
      (* export type ... *)
      with_loc
        ~start_loc
        (fun env ->
          let open Statement.ExportNamedDeclaration in
          if not (should_parse_types env) then error env Parse_error.UnexpectedTypeExport;
          match Peek.ith_token ~i:1 env with
          | T_MULT ->
            Expect.token env T_TYPE;
            let specifier_loc = Peek.loc env in
            Expect.token env T_MULT;
            let (source, trailing) = export_source_and_semicolon env in
            Statement.ExportNamedDeclaration
              {
                declaration = None;
                specifiers = Some (ExportBatchSpecifier (specifier_loc, None));
                source = Some source;
                export_kind = Statement.ExportType;
                comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
              }
          | T_ENUM ->
            error env Parse_error.EnumInvalidExport;
            Expect.token env T_TYPE;
            Statement.ExportNamedDeclaration
              {
                declaration = None;
                specifiers = None;
                source = None;
                export_kind = Statement.ExportType;
                comments = Flow_ast_utils.mk_comments_opt ~leading ();
              }
          | _ ->
            let (loc, type_alias) = with_loc (type_alias_helper ~leading:[]) env in
            let type_alias = (loc, Statement.TypeAlias type_alias) in
            Statement.ExportNamedDeclaration
              {
                declaration = Some type_alias;
                specifiers = None;
                source = None;
                export_kind = Statement.ExportType;
                comments = Flow_ast_utils.mk_comments_opt ~leading ();
              })
        env
    | T_OPAQUE ->
      (* export opaque type ... *)
      with_loc
        ~start_loc
        (fun env ->
          let open Statement.ExportNamedDeclaration in
          let (loc, opaque_t) = with_loc (opaque_type_helper ~leading:[]) env in
          let opaque_t = (loc, Statement.OpaqueType opaque_t) in
          Statement.ExportNamedDeclaration
            {
              declaration = Some opaque_t;
              specifiers = None;
              source = None;
              export_kind = Statement.ExportType;
              comments = Flow_ast_utils.mk_comments_opt ~leading ();
            })
        env
    | T_INTERFACE ->
      (* export interface I { ... } *)
      with_loc
        ~start_loc
        (fun env ->
          let open Statement.ExportNamedDeclaration in
          if not (should_parse_types env) then error env Parse_error.UnexpectedTypeExport;
          let interface =
            let (loc, iface) = with_loc (interface_helper ~leading:[]) env in
            (loc, Statement.InterfaceDeclaration iface)
          in
          Statement.ExportNamedDeclaration
            {
              declaration = Some interface;
              specifiers = None;
              source = None;
              export_kind = Statement.ExportType;
              comments = Flow_ast_utils.mk_comments_opt ~leading ();
            })
        env
    | _ when Peek.is_class env ->
      with_loc
        ~start_loc
        (fun env ->
          let stmt = Object.class_declaration env decorators in
          Statement.ExportNamedDeclaration
            {
              Statement.ExportNamedDeclaration.declaration = Some stmt;
              specifiers = None;
              source = None;
              export_kind = Statement.ExportValue;
              comments = Flow_ast_utils.mk_comments_opt ~leading ();
            })
        env
    | _ when Peek.is_function env ->
      with_loc
        ~start_loc
        (fun env ->
          error_on_decorators env decorators;
          let stmt = Declaration._function env in
          Statement.ExportNamedDeclaration
            {
              Statement.ExportNamedDeclaration.declaration = Some stmt;
              specifiers = None;
              source = None;
              export_kind = Statement.ExportValue;
              comments = Flow_ast_utils.mk_comments_opt ~leading ();
            })
        env
    | T_LET
    | T_CONST
    | T_VAR ->
      with_loc
        ~start_loc
        (fun env ->
          let stmt = Parse.statement_list_item env ~decorators in
          Statement.ExportNamedDeclaration
            {
              Statement.ExportNamedDeclaration.declaration = Some stmt;
              specifiers = None;
              source = None;
              export_kind = Statement.ExportValue;
              comments = Flow_ast_utils.mk_comments_opt ~leading ();
            })
        env
    | T_ENUM when (parse_options env).enums ->
      with_loc
        ~start_loc
        (fun env ->
          let stmt = Parse.statement_list_item env ~decorators in
          Statement.ExportNamedDeclaration
            {
              Statement.ExportNamedDeclaration.declaration = Some stmt;
              specifiers = None;
              source = None;
              export_kind = Statement.ExportValue;
              comments = Flow_ast_utils.mk_comments_opt ~leading ();
            })
        env
    (* export component *)
    | _ when Peek.is_component env ->
      with_loc
        ~start_loc
        (fun env ->
          let stmt = Declaration.component env in
          Statement.ExportNamedDeclaration
            {
              Statement.ExportNamedDeclaration.declaration = Some stmt;
              specifiers = None;
              source = None;
              export_kind = Statement.ExportValue;
              comments = Flow_ast_utils.mk_comments_opt ~leading ();
            })
        env
    | T_MULT ->
      with_loc
        ~start_loc
        (fun env ->
          let open Statement.ExportNamedDeclaration in
          let loc = Peek.loc env in
          Expect.token env T_MULT;
          let local_name =
            match Peek.token env with
            | T_IDENTIFIER { raw = "as"; _ } ->
              Eat.token env;
              Some (identifier_name env)
            | _ -> None
          in
          let specifiers = Some (ExportBatchSpecifier (loc, local_name)) in
          let (source, trailing) = export_source_and_semicolon env in
          Statement.ExportNamedDeclaration
            {
              declaration = None;
              specifiers;
              source = Some source;
              export_kind = Statement.ExportValue;
              comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
            })
        env
    | _ ->
      let open Statement.ExportNamedDeclaration in
      let export_kind =
        if Eat.maybe env T_TYPE then
          Statement.ExportType
        else
          Statement.ExportValue
      in
      if Eat.maybe env T_LCURLY then
        with_loc
          ~start_loc
          (fun env ->
            let specifiers = export_specifiers env [] in
            Expect.token env T_RCURLY;
            let (source, trailing) =
              match Peek.token env with
              | T_IDENTIFIER { raw = "from"; _ } ->
                let (source, trailing) = export_source_and_semicolon env in
                (Some source, trailing)
              | _ ->
                assert_export_specifier_identifiers env specifiers;
                let trailing =
                  match semicolon env with
                  | Explicit trailing -> trailing
                  | Implicit { trailing; _ } -> trailing
                in
                (None, trailing)
            in
            Statement.ExportNamedDeclaration
              {
                declaration = None;
                specifiers = Some (ExportSpecifiers specifiers);
                source;
                export_kind;
                comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
              })
          env
      else (
        (* error. recover by ignoring the `export` *)
        error_unexpected ~expected:"a declaration, statement or export specifiers" env;
        Parse.statement_list_item env ~decorators
      )

  and declare_export_declaration ?(allow_export_type = false) =
    with_loc (fun env ->
        if not (should_parse_types env) then error env Parse_error.UnexpectedTypeDeclaration;
        let leading = Peek.comments env in
        Expect.token env T_DECLARE;
        let env = env |> with_strict true |> with_in_export true in
        let leading = leading @ Peek.comments env in
        Expect.token env T_EXPORT;
        Statement.DeclareExportDeclaration.(
          match Peek.token env with
          | T_DEFAULT ->
            (* declare export default ... *)
            let leading = leading @ Peek.comments env in
            let (default, ()) = with_loc (fun env -> Expect.token env T_DEFAULT) env in
            let env = with_in_export_default true env in
            let (declaration, trailing) =
              match Peek.token env with
              | T_FUNCTION ->
                (* declare export default function foo (...): ...  *)
                let fn = with_loc declare_function env in
                (Some (Function fn), [])
              | T_CLASS ->
                (* declare export default class foo { ... } *)
                let class_ = with_loc (declare_class ~leading:[]) env in
                (Some (Class class_), [])
              | T_IDENTIFIER { raw = "component"; _ } when (parse_options env).components ->
                (* declare export default component Foo() { ... } *)
                let component = with_loc (declare_component ~leading:[]) env in
                (Some (Component component), [])
              | _ ->
                (* declare export default [type]; *)
                let type_ = Type._type env in
                let (type_, trailing) =
                  match semicolon env with
                  | Explicit trailing -> (type_, trailing)
                  | Implicit { remove_trailing; _ } ->
                    (remove_trailing type_ (fun remover type_ -> remover#type_ type_), [])
                in
                (Some (DefaultType type_), trailing)
            in
            let comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing () in
            Statement.DeclareExportDeclaration
              { default = Some default; declaration; specifiers = None; source = None; comments }
          | T_LET
          | T_CONST
          | T_VAR
          | T_CLASS
          | T_FUNCTION ->
            let declaration =
              match Peek.token env with
              | T_FUNCTION ->
                (* declare export function foo (...): ...  *)
                let fn = with_loc declare_function env in
                Some (Function fn)
              | T_CLASS ->
                (* declare export class foo { ... } *)
                let class_ = with_loc (declare_class ~leading:[]) env in
                Some (Class class_)
              | T_VAR ->
                (* declare export var foo: ... *)
                let var = with_loc (fun env -> declare_var ~kind:Ast.Variable.Var env []) env in
                Some (Variable var)
              | T_LET ->
                (* declare export let foo: ... *)
                let var = with_loc (fun env -> declare_var ~kind:Ast.Variable.Let env []) env in
                Some (Variable var)
              | T_CONST ->
                (* declare export const foo: ... *)
                let var = with_loc (fun env -> declare_var ~kind:Ast.Variable.Const env []) env in
                Some (Variable var)
              | _ -> assert false
            in
            let comments = Flow_ast_utils.mk_comments_opt ~leading () in
            Statement.DeclareExportDeclaration
              { default = None; declaration; specifiers = None; source = None; comments }
          | T_IDENTIFIER { raw = "component"; _ } when (parse_options env).components ->
            let declaration =
              (* declare export component Foo() { ... } *)
              let component = with_loc (declare_component ~leading:[]) env in
              Some (Component component)
            in
            let comments = Flow_ast_utils.mk_comments_opt ~leading () in
            Statement.DeclareExportDeclaration
              { default = None; declaration; specifiers = None; source = None; comments }
          | T_MULT ->
            (* declare export * from 'foo' *)
            let loc = Peek.loc env in
            Expect.token env T_MULT;
            let local_name =
              match Peek.token env with
              | T_IDENTIFIER { raw = "as"; _ } ->
                Eat.token env;
                Some (Parse.identifier env)
              | _ -> None
            in
            let specifiers =
              Statement.ExportNamedDeclaration.(Some (ExportBatchSpecifier (loc, local_name)))
            in
            let (source, trailing) = export_source_and_semicolon env in
            let comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing () in
            Statement.DeclareExportDeclaration
              { default = None; declaration = None; specifiers; source = Some source; comments }
          | T_TYPE when allow_export_type ->
            (* declare export type = ... *)
            let alias = with_loc (type_alias_helper ~leading:[]) env in
            let comments = Flow_ast_utils.mk_comments_opt ~leading () in
            Statement.DeclareExportDeclaration
              {
                default = None;
                declaration = Some (NamedType alias);
                specifiers = None;
                source = None;
                comments;
              }
          | T_OPAQUE ->
            (* declare export opaque type = ... *)
            let opaque = with_loc (opaque_type_helper ~declare:true ~leading:[]) env in
            let comments = Flow_ast_utils.mk_comments_opt ~leading () in
            Statement.DeclareExportDeclaration
              {
                default = None;
                declaration = Some (NamedOpaqueType opaque);
                specifiers = None;
                source = None;
                comments;
              }
          | T_INTERFACE when allow_export_type ->
            (* declare export interface ... *)
            let iface = with_loc (interface_helper ~leading:[]) env in
            let comments = Flow_ast_utils.mk_comments_opt ~leading () in
            Statement.DeclareExportDeclaration
              {
                default = None;
                declaration = Some (Interface iface);
                specifiers = None;
                source = None;
                comments;
              }
          | T_ENUM when (parse_options env).enums ->
            (* declare export enum ... *)
            let enum = with_loc Enum.declaration env in
            let comments = Flow_ast_utils.mk_comments_opt ~leading () in
            Statement.DeclareExportDeclaration
              {
                default = None;
                declaration = Some (Enum enum);
                specifiers = None;
                source = None;
                comments;
              }
          | _ ->
            (match Peek.token env with
            | T_TYPE -> error env Parse_error.DeclareExportType
            | T_INTERFACE -> error env Parse_error.DeclareExportInterface
            | _ -> ());
            Expect.token env T_LCURLY;
            let specifiers = export_specifiers env [] in
            Expect.token env T_RCURLY;
            let (source, trailing) =
              match Peek.token env with
              | T_IDENTIFIER { raw = "from"; _ } ->
                let (source, trailing) = export_source_and_semicolon env in
                (Some source, trailing)
              | _ ->
                assert_export_specifier_identifiers env specifiers;
                let trailing =
                  match semicolon env with
                  | Explicit trailing -> trailing
                  | Implicit { trailing; _ } -> trailing
                in
                (None, trailing)
            in
            let comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing () in
            Statement.DeclareExportDeclaration
              {
                default = None;
                declaration = None;
                specifiers = Some (Statement.ExportNamedDeclaration.ExportSpecifiers specifiers);
                source;
                comments;
              }
        )
    )

  and import_declaration =
    Statement.ImportDeclaration.(
      let missing_source env =
        (* Just make up a string for the error case *)
        let loc = Peek.loc_skip_lookahead env in
        (loc, { StringLiteral.value = ""; raw = ""; comments = None })
      in
      let source env =
        match Peek.token env with
        | T_IDENTIFIER { raw = "from"; _ } ->
          Eat.token env;
          (match Peek.token env with
          | T_STRING str -> string_literal env str
          | _ ->
            error_unexpected ~expected:"a string" env;
            missing_source env)
        | _ ->
          error_unexpected ~expected:"the keyword `from`" env;
          missing_source env
      in
      let is_type_import = function
        | T_TYPE
        | T_TYPEOF ->
          true
        | _ -> false
        (* `x` or `x as y` in a specifier *)
      in
      let with_maybe_as ~for_type ?error_if_type env =
        let identifier env =
          if for_type then
            Type.type_identifier env
          else
            Parse.identifier env
        in
        match Peek.ith_token ~i:1 env with
        | T_IDENTIFIER { raw = "as"; _ } ->
          let remote = identifier_name env in
          Eat.token env;

          (* as *)
          let local = Some (identifier env) in
          (remote, local)
        | T_EOF
        | T_COMMA
        | T_RCURLY ->
          (identifier env, None)
        | _ -> begin
          match (error_if_type, Peek.token env) with
          | (Some error_if_type, T_TYPE)
          | (Some error_if_type, T_TYPEOF) ->
            error env error_if_type;
            Eat.token env;

            (* consume `type` or `typeof` *)
            (Type.type_identifier env, None)
          | _ -> (identifier env, None)
        end
        (*
           ImportSpecifier[Type]:
             [~Type] ImportedBinding
             [~Type] IdentifierName ImportedTypeBinding
             [~Type] IdentifierName IdentifierName ImportedBinding
             [~Type] IdentifierName IdentifierName IdentifierName ImportedTypeBinding
             [+Type] ImportedTypeBinding
             [+Type] IdentifierName IdentifierName ImportedTypeBinding

           Static Semantics:

           `IdentifierName ImportedTypeBinding`:
           - It is a Syntax Error if IdentifierName's StringValue is not "type" or "typeof"

           `IdentifierName IdentifierName ImportedBinding`:
           - It is a Syntax Error if the second IdentifierName's StringValue is not "as"

           `IdentifierName IdentifierName IdentifierName  ImportedTypeBinding`:
           - It is a Syntax Error if the first IdentifierName's StringValue is not "type"
             or "typeof", and the third IdentifierName's StringValue is not "as"
        *)
      in

      let specifier env =
        let kind =
          match Peek.token env with
          | T_TYPE -> Some ImportType
          | T_TYPEOF -> Some ImportTypeof
          | _ -> None
        in
        if is_type_import (Peek.token env) then
          (* consume `type`, but we don't know yet whether this is `type foo` or
             `type as foo`. *)
          let type_keyword_or_remote = identifier_name env in
          match Peek.token env with
          (* `type` (a value) *)
          | T_EOF
          | T_RCURLY
          | T_COMMA ->
            let remote = type_keyword_or_remote in
            (* `type` becomes a value *)
            assert_identifier_name_is_identifier env remote;
            { remote; local = None; remote_name_def_loc = None; kind = None }
          (* `type as foo` (value named `type`) or `type as,` (type named `as`) *)
          | T_IDENTIFIER { raw = "as"; _ } -> begin
            match Peek.ith_token ~i:1 env with
            | T_EOF
            | T_RCURLY
            | T_COMMA ->
              (* `type as` *)
              { remote = Type.type_identifier env; remote_name_def_loc = None; local = None; kind }
            | T_IDENTIFIER { raw = "as"; _ } ->
              (* `type as as foo` *)
              let remote = identifier_name env in
              (* first `as` *)
              Eat.token env;

              (* second `as` *)
              let local = Some (Type.type_identifier env) in
              (* `foo` *)
              { remote; remote_name_def_loc = None; local; kind }
            | _ ->
              (* `type as foo` *)
              let remote = type_keyword_or_remote in
              (* `type` becomes a value *)
              assert_identifier_name_is_identifier env remote;
              Eat.token env;

              (* `as` *)
              let local = Some (Parse.identifier env) in
              { remote; remote_name_def_loc = None; local; kind = None }
          end
          (* `type x`, or `type x as y` *)
          | _ ->
            let (remote, local) = with_maybe_as ~for_type:true env in
            { remote; remote_name_def_loc = None; local; kind }
        else
          (* standard `x` or `x as y` *)
          let (remote, local) = with_maybe_as ~for_type:false env in
          { remote; remote_name_def_loc = None; local; kind = None }
        (* specifier in an `import type { ... }` *)
      in
      let type_specifier env =
        let (remote, local) =
          with_maybe_as
            env
            ~for_type:true
            ~error_if_type:Parse_error.ImportTypeShorthandOnlyInPureImport
        in
        { remote; remote_name_def_loc = None; local; kind = None }
        (* specifier in an `import typeof { ... }` *)
      in
      let typeof_specifier env =
        let (remote, local) =
          with_maybe_as
            env
            ~for_type:true
            ~error_if_type:Parse_error.ImportTypeShorthandOnlyInPureImport
        in
        { remote; remote_name_def_loc = None; local; kind = None }
      in
      let rec specifier_list ?(preceding_comma = true) env statement_kind acc =
        match Peek.token env with
        | T_EOF
        | T_RCURLY ->
          List.rev acc
        | _ ->
          if not preceding_comma then error env Parse_error.ImportSpecifierMissingComma;
          let specifier =
            match statement_kind with
            | ImportType -> type_specifier env
            | ImportTypeof -> typeof_specifier env
            | ImportValue -> specifier env
          in
          let preceding_comma = Eat.maybe env T_COMMA in
          specifier_list ~preceding_comma env statement_kind (specifier :: acc)
      in
      let named_or_namespace_specifier env import_kind =
        match Peek.token env with
        | T_MULT ->
          let id =
            with_loc_opt
              (fun env ->
                (* consume T_MULT *)
                Eat.token env;
                match Peek.token env with
                | T_IDENTIFIER { raw = "as"; _ } ->
                  (* consume "as" *)
                  Eat.token env;
                  (match import_kind with
                  | ImportType
                  | ImportTypeof ->
                    Some (Type.type_identifier env)
                  | ImportValue -> Some (Parse.identifier env))
                | _ ->
                  error_unexpected ~expected:"the keyword `as`" env;
                  None)
              env
          in
          (match id with
          | Some id -> Some (ImportNamespaceSpecifier id)
          | None -> None)
        | _ ->
          Expect.token env T_LCURLY;
          let specifiers = specifier_list env import_kind [] in
          Expect.token env T_RCURLY;
          Some (ImportNamedSpecifiers specifiers)
      in
      let semicolon_and_trailing env source =
        match semicolon env with
        | Explicit trailing -> (trailing, source)
        | Implicit { remove_trailing; _ } ->
          ( [],
            remove_trailing source (fun remover (loc, source) ->
                (loc, remover#string_literal loc source)
            )
          )
      in
      let with_specifiers import_kind env leading =
        let specifiers = named_or_namespace_specifier env import_kind in
        let source = source env in
        let (trailing, source) = semicolon_and_trailing env source in
        Statement.ImportDeclaration
          {
            import_kind;
            source;
            specifiers;
            default = None;
            comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
          }
      in
      let with_default import_kind env leading =
        let default_specifier =
          match import_kind with
          | ImportType
          | ImportTypeof ->
            {
              Statement.ImportDeclaration.identifier = Type.type_identifier env;
              remote_default_name_def_loc = None;
            }
          | ImportValue ->
            {
              Statement.ImportDeclaration.identifier = Parse.identifier env;
              remote_default_name_def_loc = None;
            }
        in
        let additional_specifiers =
          match Peek.token env with
          | T_COMMA ->
            (* `import Foo, ...` *)
            Expect.token env T_COMMA;
            named_or_namespace_specifier env import_kind
          | _ -> None
        in
        let source = source env in
        let (trailing, source) = semicolon_and_trailing env source in
        Statement.ImportDeclaration
          {
            import_kind;
            source;
            specifiers = additional_specifiers;
            default = Some default_specifier;
            comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
          }
      in
      with_loc (fun env ->
          let env = env |> with_strict true in
          let leading = Peek.comments env in
          Expect.token env T_IMPORT;

          match Peek.token env with
          (* `import * as ns from "ModuleName";` *)
          | T_MULT -> with_specifiers ImportValue env leading
          (* `import { ... } from "ModuleName";` *)
          | T_LCURLY -> with_specifiers ImportValue env leading
          (* `import "ModuleName";` *)
          | T_STRING str ->
            let source = string_literal env str in
            let (trailing, source) = semicolon_and_trailing env source in
            Statement.ImportDeclaration
              {
                import_kind = ImportValue;
                source;
                specifiers = None;
                default = None;
                comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
              }
          (* `import type [...] from "ModuleName";`
             note that if [...] is missing, we're importing a value named `type`! *)
          | T_TYPE when should_parse_types env -> begin
            match Peek.ith_token ~i:1 env with
            (* `import type, { other, names } from "ModuleName";` *)
            | T_COMMA
            (* `import type from "ModuleName";` *)
            | T_IDENTIFIER { raw = "from"; _ } ->
              (* Importing the exported value named "type". This is not a type-import.*)
              with_default ImportValue env leading
            (* `import type *` is invalid, since the namespace can't be a type *)
            | T_MULT ->
              (* consume `type` *)
              Eat.token env;

              (* unexpected `*` *)
              error_unexpected env;

              with_specifiers ImportType env leading
            | T_LCURLY ->
              (* consume `type` *)
              Eat.token env;

              with_specifiers ImportType env leading
            | _ ->
              (* consume `type` *)
              Eat.token env;

              with_default ImportType env leading
          end
          (* `import typeof ... from "ModuleName";` *)
          | T_TYPEOF when should_parse_types env ->
            Expect.token env T_TYPEOF;
            begin
              match Peek.token env with
              | T_MULT
              | T_LCURLY ->
                with_specifiers ImportTypeof env leading
              | _ -> with_default ImportTypeof env leading
            end
          (* import Foo from "ModuleName"; *)
          | _ -> with_default ImportValue env leading
      )
    )
end
OCaml

Innovation. Community. Security.