tree-sitter-cli 0.26.8

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

use anstyle::AnsiColor;
use anyhow::{anyhow, Context, Result};
use clap::ValueEnum;
use indoc::indoc;
use regex::{
    bytes::{Regex as ByteRegex, RegexBuilder as ByteRegexBuilder},
    Regex,
};
use schemars::{JsonSchema, Schema, SchemaGenerator};
use serde::Serialize;
use similar::{ChangeTag, TextDiff};
use tree_sitter::{format_sexp, Language, LogType, Parser, Query, Tree};
use walkdir::WalkDir;

use super::util;
use crate::{
    logger::paint,
    parse::{
        render_cst, ParseDebugType, ParseFileOptions, ParseOutput, ParseStats, ParseTheme, Stats,
    },
};

static HEADER_REGEX: LazyLock<ByteRegex> = LazyLock::new(|| {
    ByteRegexBuilder::new(
        r"^(?x)
           (?P<equals>(?:=+){3,})
           (?P<suffix1>[^=\r\n][^\r\n]*)?
           \r?\n
           (?P<test_name_and_markers>(?:([^=\r\n]|\s+:)[^\r\n]*\r?\n)+)
           ===+
           (?P<suffix2>[^=\r\n][^\r\n]*)?\r?\n",
    )
    .multi_line(true)
    .build()
    .unwrap()
});

static DIVIDER_REGEX: LazyLock<ByteRegex> = LazyLock::new(|| {
    ByteRegexBuilder::new(r"^(?P<hyphens>(?:-+){3,})(?P<suffix>[^-\r\n][^\r\n]*)?\r?\n")
        .multi_line(true)
        .build()
        .unwrap()
});

static COMMENT_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?m)^\s*;.*$").unwrap());

static WHITESPACE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\s+").unwrap());

static SEXP_FIELD_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r" \w+: \(").unwrap());

static POINT_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\s*\[\s*\d+\s*,\s*\d+\s*\]\s*").unwrap());

#[derive(Debug, PartialEq, Eq)]
pub enum TestEntry {
    Group {
        name: String,
        children: Vec<Self>,
        file_path: Option<PathBuf>,
    },
    Example {
        name: String,
        input: Vec<u8>,
        output: String,
        header_delim_len: usize,
        divider_delim_len: usize,
        has_fields: bool,
        attributes_str: String,
        attributes: TestAttributes,
        file_name: Option<String>,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TestAttributes {
    pub skip: bool,
    pub platform: bool,
    pub fail_fast: bool,
    pub error: bool,
    pub cst: bool,
    pub languages: Vec<Box<str>>,
}

impl Default for TestEntry {
    fn default() -> Self {
        Self::Group {
            name: String::new(),
            children: Vec::new(),
            file_path: None,
        }
    }
}

impl Default for TestAttributes {
    fn default() -> Self {
        Self {
            skip: false,
            platform: true,
            fail_fast: false,
            error: false,
            cst: false,
            languages: vec!["".into()],
        }
    }
}

#[derive(ValueEnum, Default, Debug, Copy, Clone, PartialEq, Eq, Serialize)]
pub enum TestStats {
    All,
    #[default]
    OutliersAndTotal,
    TotalOnly,
}

pub struct TestOptions<'a> {
    pub path: PathBuf,
    pub debug: bool,
    pub debug_graph: bool,
    pub include: Option<Regex>,
    pub exclude: Option<Regex>,
    pub file_name: Option<String>,
    pub update: bool,
    pub open_log: bool,
    pub languages: BTreeMap<&'a str, &'a Language>,
    pub color: bool,
    pub show_fields: bool,
    pub overview_only: bool,
}

/// A stateful object used to collect results from running a grammar's test suite
#[derive(Debug, Default, Serialize, JsonSchema)]
pub struct TestSummary {
    // Parse test results and associated data
    #[schemars(schema_with = "schema_as_array")]
    #[serde(serialize_with = "serialize_as_array")]
    pub parse_results: TestResultHierarchy,
    pub parse_failures: Vec<TestFailure>,
    pub parse_stats: Stats,
    #[schemars(skip)]
    #[serde(skip)]
    pub has_parse_errors: bool,
    #[schemars(skip)]
    #[serde(skip)]
    pub parse_stat_display: TestStats,

    // Other test results
    #[schemars(schema_with = "schema_as_array")]
    #[serde(serialize_with = "serialize_as_array")]
    pub highlight_results: TestResultHierarchy,
    #[schemars(schema_with = "schema_as_array")]
    #[serde(serialize_with = "serialize_as_array")]
    pub tag_results: TestResultHierarchy,
    #[schemars(schema_with = "schema_as_array")]
    #[serde(serialize_with = "serialize_as_array")]
    pub query_results: TestResultHierarchy,

    // Data used during construction
    #[schemars(skip)]
    #[serde(skip)]
    pub test_num: usize,
    // Options passed in from the CLI which control how the summary is displayed
    #[schemars(skip)]
    #[serde(skip)]
    pub color: bool,
    #[schemars(skip)]
    #[serde(skip)]
    pub overview_only: bool,
    #[schemars(skip)]
    #[serde(skip)]
    pub update: bool,
    #[schemars(skip)]
    #[serde(skip)]
    pub json: bool,
}

impl TestSummary {
    #[must_use]
    pub fn new(
        color: bool,
        stat_display: TestStats,
        parse_update: bool,
        overview_only: bool,
        json_summary: bool,
    ) -> Self {
        Self {
            color,
            parse_stat_display: stat_display,
            update: parse_update,
            overview_only,
            json: json_summary,
            test_num: 1,
            ..Default::default()
        }
    }
}

#[derive(Debug, Default, JsonSchema)]
pub struct TestResultHierarchy {
    root_group: Vec<TestResult>,
    traversal_idxs: Vec<usize>,
}

fn serialize_as_array<S>(results: &TestResultHierarchy, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    results.root_group.serialize(serializer)
}

fn schema_as_array(gen: &mut SchemaGenerator) -> Schema {
    gen.subschema_for::<Vec<TestResult>>()
}

/// Stores arbitrarily nested parent test groups and child cases. Supports creation
/// in DFS traversal order
impl TestResultHierarchy {
    /// Signifies the start of a new group's traversal during construction.
    fn push_traversal(&mut self, idx: usize) {
        self.traversal_idxs.push(idx);
    }

    /// Signifies the end of the current group's traversal during construction.
    /// Must be paired with a prior call to [`TestResultHierarchy::add_group`].
    pub fn pop_traversal(&mut self) {
        self.traversal_idxs.pop();
    }

    /// Adds a new group as a child of the current group. Caller is responsible
    /// for calling [`TestResultHierarchy::pop_traversal`] once the group is done
    /// being traversed.
    pub fn add_group(&mut self, group_name: &str) {
        let new_group_idx = self.curr_group_len();
        self.push(TestResult {
            name: group_name.to_string(),
            info: TestInfo::Group {
                children: Vec::new(),
            },
        });
        self.push_traversal(new_group_idx);
    }

    /// Adds a new test example as a child of the current group.
    /// Asserts that `test_case.info` is not [`TestInfo::Group`].
    pub fn add_case(&mut self, test_case: TestResult) {
        assert!(!matches!(test_case.info, TestInfo::Group { .. }));
        self.push(test_case);
    }

    /// Adds a new `TestResult` to the current group.
    fn push(&mut self, result: TestResult) {
        // If there are no traversal steps, we're adding to the root
        if self.traversal_idxs.is_empty() {
            self.root_group.push(result);
            return;
        }

        #[allow(clippy::manual_let_else)]
        let mut curr_group = match self.root_group[self.traversal_idxs[0]].info {
            TestInfo::Group { ref mut children } => children,
            _ => unreachable!(),
        };
        for idx in self.traversal_idxs.iter().skip(1) {
            curr_group = match curr_group[*idx].info {
                TestInfo::Group { ref mut children } => children,
                _ => unreachable!(),
            };
        }

        curr_group.push(result);
    }

    fn curr_group_len(&self) -> usize {
        if self.traversal_idxs.is_empty() {
            return self.root_group.len();
        }

        #[allow(clippy::manual_let_else)]
        let mut curr_group = match self.root_group[self.traversal_idxs[0]].info {
            TestInfo::Group { ref children } => children,
            _ => unreachable!(),
        };
        for idx in self.traversal_idxs.iter().skip(1) {
            curr_group = match curr_group[*idx].info {
                TestInfo::Group { ref children } => children,
                _ => unreachable!(),
            };
        }
        curr_group.len()
    }

    #[allow(clippy::iter_without_into_iter)]
    #[must_use]
    pub fn iter(&self) -> TestResultIterWithDepth<'_> {
        let mut stack = Vec::with_capacity(self.root_group.len());
        for child in self.root_group.iter().rev() {
            stack.push((0, child));
        }
        TestResultIterWithDepth { stack }
    }
}

pub struct TestResultIterWithDepth<'a> {
    stack: Vec<(usize, &'a TestResult)>,
}

impl<'a> Iterator for TestResultIterWithDepth<'a> {
    type Item = (usize, &'a TestResult);

    fn next(&mut self) -> Option<Self::Item> {
        self.stack.pop().inspect(|(depth, result)| {
            if let TestInfo::Group { children } = &result.info {
                for child in children.iter().rev() {
                    self.stack.push((depth + 1, child));
                }
            }
        })
    }
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct TestResult {
    pub name: String,
    #[schemars(flatten)]
    #[serde(flatten)]
    pub info: TestInfo,
}

#[derive(Debug, Serialize, JsonSchema)]
#[schemars(untagged)]
#[serde(untagged)]
pub enum TestInfo {
    Group {
        children: Vec<TestResult>,
    },
    ParseTest {
        outcome: TestOutcome,
        // True parse rate, adjusted parse rate
        #[schemars(schema_with = "parse_rate_schema")]
        #[serde(serialize_with = "serialize_parse_rates")]
        parse_rate: Option<(f64, f64)>,
        test_num: usize,
    },
    AssertionTest {
        outcome: TestOutcome,
        test_num: usize,
    },
}

fn serialize_parse_rates<S>(
    parse_rate: &Option<(f64, f64)>,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    match parse_rate {
        None => serializer.serialize_none(),
        Some((first, _)) => serializer.serialize_some(first),
    }
}

fn parse_rate_schema(gen: &mut SchemaGenerator) -> Schema {
    gen.subschema_for::<Option<f64>>()
}

#[derive(Debug, Clone, Eq, PartialEq, Serialize, JsonSchema)]
pub enum TestOutcome {
    // Parse outcomes
    Passed,
    Failed,
    Updated,
    Skipped,
    Platform,

    // Highlight/Tag/Query outcomes
    AssertionPassed { assertion_count: usize },
    AssertionFailed { error: String },
}

impl TestSummary {
    fn fmt_parse_results(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let (count, total_adj_parse_time) = self
            .parse_results
            .iter()
            .filter_map(|(_, result)| match result.info {
                TestInfo::Group { .. } => None,
                TestInfo::ParseTest { parse_rate, .. } => parse_rate,
                _ => unreachable!(),
            })
            .fold((0usize, 0.0f64), |(count, rate_accum), (_, adj_rate)| {
                (count + 1, rate_accum + adj_rate)
            });

        let avg = total_adj_parse_time / count as f64;
        let std_dev = {
            let variance = self
                .parse_results
                .iter()
                .filter_map(|(_, result)| match result.info {
                    TestInfo::Group { .. } => None,
                    TestInfo::ParseTest { parse_rate, .. } => parse_rate,
                    _ => unreachable!(),
                })
                .map(|(_, rate_i)| (rate_i - avg).powi(2))
                .sum::<f64>()
                / count as f64;
            variance.sqrt()
        };

        for (depth, entry) in self.parse_results.iter() {
            write!(f, "{}", "  ".repeat(depth + 1))?;
            match &entry.info {
                TestInfo::Group { .. } => writeln!(f, "{}:", entry.name)?,
                TestInfo::ParseTest {
                    outcome,
                    parse_rate,
                    test_num,
                } => {
                    let (color, result_char) = match outcome {
                        TestOutcome::Passed => (AnsiColor::Green, "✓"),
                        TestOutcome::Failed => (AnsiColor::Red, "✗"),
                        TestOutcome::Updated => (AnsiColor::Blue, "✓"),
                        TestOutcome::Skipped => (AnsiColor::Yellow, "⌀"),
                        TestOutcome::Platform => (AnsiColor::Magenta, "⌀"),
                        _ => unreachable!(),
                    };
                    let stat_display = match (self.parse_stat_display, parse_rate) {
                        (TestStats::TotalOnly, _) | (_, None) => String::new(),
                        (display, Some((true_rate, adj_rate))) => {
                            let mut stats = if display == TestStats::All {
                                format!(" ({true_rate:.3} bytes/ms)")
                            } else {
                                String::new()
                            };
                            // 3 standard deviations below the mean, aka the "Empirical Rule"
                            if *adj_rate < 3.0f64.mul_add(-std_dev, avg) {
                                stats += &paint(
                                    self.color.then_some(AnsiColor::Yellow),
                                    &format!(
                                        " -- Warning: Slow parse rate ({true_rate:.3} bytes/ms)"
                                    ),
                                );
                            }
                            stats
                        }
                    };
                    writeln!(
                        f,
                        "{test_num:>3}. {result_char} {}{stat_display}",
                        paint(self.color.then_some(color), &entry.name),
                    )?;
                }
                TestInfo::AssertionTest { .. } => unreachable!(),
            }
        }

        // Parse failure info
        if !self.parse_failures.is_empty() && self.update && !self.has_parse_errors {
            writeln!(
                f,
                "\n{} update{}:\n",
                self.parse_failures.len(),
                if self.parse_failures.len() == 1 {
                    ""
                } else {
                    "s"
                }
            )?;

            for (i, TestFailure { name, .. }) in self.parse_failures.iter().enumerate() {
                writeln!(f, "  {}. {name}", i + 1)?;
            }
        } else if !self.parse_failures.is_empty() && !self.overview_only {
            if !self.has_parse_errors {
                writeln!(
                    f,
                    "\n{} failure{}:",
                    self.parse_failures.len(),
                    if self.parse_failures.len() == 1 {
                        ""
                    } else {
                        "s"
                    }
                )?;
            }

            if self.color {
                DiffKey.fmt(f)?;
            }
            for (
                i,
                TestFailure {
                    name,
                    actual,
                    expected,
                    is_cst,
                },
            ) in self.parse_failures.iter().enumerate()
            {
                if expected == "NO ERROR" {
                    writeln!(f, "\n  {}. {name}:\n", i + 1)?;
                    writeln!(f, "  Expected an ERROR node, but got:")?;
                    let actual = if *is_cst {
                        actual
                    } else {
                        &format_sexp(actual, 2)
                    };
                    writeln!(
                        f,
                        "  {}",
                        paint(self.color.then_some(AnsiColor::Red), actual)
                    )?;
                } else {
                    writeln!(f, "\n  {}. {name}:", i + 1)?;
                    if *is_cst {
                        writeln!(
                            f,
                            "{}",
                            TestDiff::new(actual, expected).with_color(self.color)
                        )?;
                    } else {
                        writeln!(
                            f,
                            "{}",
                            TestDiff::new(&format_sexp(actual, 2), &format_sexp(expected, 2))
                                .with_color(self.color,)
                        )?;
                    }
                }
            }
        } else {
            writeln!(f)?;
        }

        Ok(())
    }
}

impl std::fmt::Display for TestSummary {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.fmt_parse_results(f)?;

        let mut render_assertion_results =
            |name: &str, results: &TestResultHierarchy| -> std::fmt::Result {
                writeln!(f, "{name}:")?;
                for (depth, entry) in results.iter() {
                    write!(f, "{}", "  ".repeat(depth + 2))?;
                    match &entry.info {
                        TestInfo::Group { .. } => writeln!(f, "{}", entry.name)?,
                        TestInfo::AssertionTest { outcome, test_num } => match outcome {
                            TestOutcome::AssertionPassed { assertion_count } => writeln!(
                                f,
                                "{:>3}. ✓ {} ({assertion_count} assertions)",
                                test_num,
                                paint(self.color.then_some(AnsiColor::Green), &entry.name)
                            )?,
                            TestOutcome::AssertionFailed { error } => {
                                writeln!(
                                    f,
                                    "{:>3}. ✗ {}",
                                    test_num,
                                    paint(self.color.then_some(AnsiColor::Red), &entry.name)
                                )?;
                                writeln!(f, "{}  {error}", "  ".repeat(depth + 1))?;
                            }
                            _ => unreachable!(),
                        },
                        TestInfo::ParseTest { .. } => unreachable!(),
                    }
                }
                Ok(())
            };

        if !self.highlight_results.root_group.is_empty() {
            render_assertion_results("syntax highlighting", &self.highlight_results)?;
        }

        if !self.tag_results.root_group.is_empty() {
            render_assertion_results("tags", &self.tag_results)?;
        }

        if !self.query_results.root_group.is_empty() {
            render_assertion_results("queries", &self.query_results)?;
        }

        write!(f, "{}", self.parse_stats)?;

        Ok(())
    }
}

pub fn run_tests_at_path(
    parser: &mut Parser,
    opts: &TestOptions,
    test_summary: &mut TestSummary,
) -> Result<()> {
    let test_entry = parse_tests(&opts.path)?;

    let _log_session = if opts.debug_graph {
        Some(util::log_graphs(parser, "log.html", opts.open_log)?)
    } else {
        None
    };
    if opts.debug {
        parser.set_logger(Some(Box::new(|log_type, message| {
            if log_type == LogType::Lex {
                io::stderr().write_all(b"  ").unwrap();
            }
            writeln!(&mut io::stderr(), "{message}").unwrap();
        })));
    }

    let mut corrected_entries = Vec::new();
    run_tests(
        parser,
        test_entry,
        opts,
        test_summary,
        &mut corrected_entries,
        true,
    )?;

    parser.stop_printing_dot_graphs();

    if test_summary.parse_failures.is_empty() || (opts.update && !test_summary.has_parse_errors) {
        Ok(())
    } else if opts.update && test_summary.has_parse_errors {
        Err(anyhow!(indoc! {"
                Some tests failed to parse with unexpected `ERROR` or `MISSING` nodes, as shown above, and cannot be updated automatically.
                Either fix the grammar or manually update the tests if this is expected."}))
    } else {
        Err(anyhow!(""))
    }
}

pub fn check_queries_at_path(language: &Language, path: &Path) -> Result<()> {
    if path.exists() {
        for entry in WalkDir::new(path)
            .into_iter()
            .filter_map(std::result::Result::ok)
            .filter(|e| {
                e.file_type().is_file()
                    && e.path().extension().and_then(OsStr::to_str) == Some("scm")
                    && !e.path().starts_with(".")
            })
        {
            let filepath = entry.file_name().to_str().unwrap_or("");
            let content = fs::read_to_string(entry.path())
                .with_context(|| format!("Error reading query file {filepath:?}"))?;
            Query::new(language, &content)
                .with_context(|| format!("Error in query file {filepath:?}"))?;
        }
    }
    Ok(())
}

pub struct DiffKey;

impl std::fmt::Display for DiffKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "\ncorrect / {} / {}",
            paint(Some(AnsiColor::Green), "expected"),
            paint(Some(AnsiColor::Red), "unexpected")
        )?;
        Ok(())
    }
}

impl DiffKey {
    /// Writes [`DiffKey`] to stdout
    pub fn print() {
        println!("{Self}");
    }
}

pub struct TestDiff<'a> {
    pub actual: &'a str,
    pub expected: &'a str,
    pub color: bool,
}

impl<'a> TestDiff<'a> {
    #[must_use]
    pub const fn new(actual: &'a str, expected: &'a str) -> Self {
        Self {
            actual,
            expected,
            color: true,
        }
    }

    #[must_use]
    pub const fn with_color(mut self, color: bool) -> Self {
        self.color = color;
        self
    }
}

impl std::fmt::Display for TestDiff<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let diff = TextDiff::from_lines(self.actual, self.expected);
        for diff in diff.iter_all_changes() {
            match diff.tag() {
                ChangeTag::Equal => {
                    if self.color {
                        write!(f, "{diff}")?;
                    } else {
                        write!(f, " {diff}")?;
                    }
                }
                ChangeTag::Insert => {
                    if self.color {
                        write!(
                            f,
                            "{}",
                            paint(Some(AnsiColor::Green), diff.as_str().unwrap())
                        )?;
                    } else {
                        write!(f, "+{diff}")?;
                    }
                    if diff.missing_newline() {
                        writeln!(f)?;
                    }
                }
                ChangeTag::Delete => {
                    if self.color {
                        write!(f, "{}", paint(Some(AnsiColor::Red), diff.as_str().unwrap()))?;
                    } else {
                        write!(f, "-{diff}")?;
                    }
                    if diff.missing_newline() {
                        writeln!(f)?;
                    }
                }
            }
        }

        Ok(())
    }
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct TestFailure {
    name: String,
    actual: String,
    expected: String,
    is_cst: bool,
}

impl TestFailure {
    fn new<T, U, V>(name: T, actual: U, expected: V, is_cst: bool) -> Self
    where
        T: Into<String>,
        U: Into<String>,
        V: Into<String>,
    {
        Self {
            name: name.into(),
            actual: actual.into(),
            expected: expected.into(),
            is_cst,
        }
    }
}

struct TestCorrection {
    name: String,
    input: String,
    output: String,
    attributes_str: String,
    header_delim_len: usize,
    divider_delim_len: usize,
}

impl TestCorrection {
    fn new<T, U, V, W>(
        name: T,
        input: U,
        output: V,
        attributes_str: W,
        header_delim_len: usize,
        divider_delim_len: usize,
    ) -> Self
    where
        T: Into<String>,
        U: Into<String>,
        V: Into<String>,
        W: Into<String>,
    {
        Self {
            name: name.into(),
            input: input.into(),
            output: output.into(),
            attributes_str: attributes_str.into(),
            header_delim_len,
            divider_delim_len,
        }
    }
}

/// This will return false if we want to "fail fast". It will bail and not parse any more tests.
fn run_tests(
    parser: &mut Parser,
    test_entry: TestEntry,
    opts: &TestOptions,
    test_summary: &mut TestSummary,
    corrected_entries: &mut Vec<TestCorrection>,
    is_root: bool,
) -> Result<bool> {
    match test_entry {
        TestEntry::Example {
            name,
            input,
            output,
            header_delim_len,
            divider_delim_len,
            has_fields,
            attributes_str,
            attributes,
            ..
        } => {
            if attributes.skip {
                test_summary.parse_results.add_case(TestResult {
                    name: name.clone(),
                    info: TestInfo::ParseTest {
                        outcome: TestOutcome::Skipped,
                        parse_rate: None,
                        test_num: test_summary.test_num,
                    },
                });
                test_summary.test_num += 1;
                return Ok(true);
            }

            if !attributes.platform {
                test_summary.parse_results.add_case(TestResult {
                    name: name.clone(),
                    info: TestInfo::ParseTest {
                        outcome: TestOutcome::Platform,
                        parse_rate: None,
                        test_num: test_summary.test_num,
                    },
                });
                test_summary.test_num += 1;
                return Ok(true);
            }

            for (i, language_name) in attributes.languages.iter().enumerate() {
                if !language_name.is_empty() {
                    let language = opts
                        .languages
                        .get(language_name.as_ref())
                        .ok_or_else(|| anyhow!("Language not found: {language_name}"))?;
                    parser.set_language(language)?;
                }
                let start = std::time::Instant::now();
                let tree = parser.parse(&input, None).unwrap();
                let parse_rate = {
                    let parse_time = start.elapsed();
                    let byte_len = tree.root_node().byte_range().len();
                    let true_parse_rate =
                        byte_len as f64 / (parse_time.as_nanos() as f64 / 1_000_000.0);
                    let adj_parse_rate = adjusted_parse_rate(&tree, parse_time);

                    test_summary.parse_stats.total_parses += 1;
                    test_summary.parse_stats.total_duration += parse_time;
                    test_summary.parse_stats.total_bytes += byte_len;

                    Some((true_parse_rate, adj_parse_rate))
                };

                if attributes.error {
                    if tree.root_node().has_error() {
                        test_summary.parse_results.add_case(TestResult {
                            name: name.clone(),
                            info: TestInfo::ParseTest {
                                outcome: TestOutcome::Passed,
                                parse_rate,
                                test_num: test_summary.test_num,
                            },
                        });
                        test_summary.parse_stats.successful_parses += 1;
                        if opts.update {
                            let input = String::from_utf8(input.clone()).unwrap();
                            let output = if attributes.cst {
                                output.clone()
                            } else {
                                format_sexp(&output, 0)
                            };
                            corrected_entries.push(TestCorrection::new(
                                &name,
                                input,
                                output,
                                &attributes_str,
                                header_delim_len,
                                divider_delim_len,
                            ));
                        }
                    } else {
                        if opts.update {
                            let input = String::from_utf8(input.clone()).unwrap();
                            // Keep the original `expected` output if the actual output has no error
                            let output = if attributes.cst {
                                output.clone()
                            } else {
                                format_sexp(&output, 0)
                            };
                            corrected_entries.push(TestCorrection::new(
                                &name,
                                input,
                                output,
                                &attributes_str,
                                header_delim_len,
                                divider_delim_len,
                            ));
                        }
                        test_summary.parse_results.add_case(TestResult {
                            name: name.clone(),
                            info: TestInfo::ParseTest {
                                outcome: TestOutcome::Failed,
                                parse_rate,
                                test_num: test_summary.test_num,
                            },
                        });
                        let actual = if attributes.cst {
                            render_test_cst(&input, &tree)?
                        } else {
                            tree.root_node().to_sexp()
                        };
                        test_summary.parse_failures.push(TestFailure::new(
                            &name,
                            actual,
                            "NO ERROR",
                            attributes.cst,
                        ));
                    }

                    if attributes.fail_fast {
                        return Ok(false);
                    }
                } else {
                    let mut actual = if attributes.cst {
                        render_test_cst(&input, &tree)?
                    } else {
                        tree.root_node().to_sexp()
                    };
                    if !(attributes.cst || opts.show_fields || has_fields) {
                        actual = strip_sexp_fields(&actual);
                    }

                    if actual == output {
                        test_summary.parse_results.add_case(TestResult {
                            name: name.clone(),
                            info: TestInfo::ParseTest {
                                outcome: TestOutcome::Passed,
                                parse_rate,
                                test_num: test_summary.test_num,
                            },
                        });
                        test_summary.parse_stats.successful_parses += 1;
                        if opts.update {
                            let input = String::from_utf8(input.clone()).unwrap();
                            let output = if attributes.cst {
                                actual
                            } else {
                                format_sexp(&output, 0)
                            };
                            corrected_entries.push(TestCorrection::new(
                                &name,
                                input,
                                output,
                                &attributes_str,
                                header_delim_len,
                                divider_delim_len,
                            ));
                        }
                    } else {
                        if opts.update {
                            let input = String::from_utf8(input.clone()).unwrap();
                            let (expected_output, actual_output) = if attributes.cst {
                                (output.clone(), actual.clone())
                            } else {
                                (format_sexp(&output, 0), format_sexp(&actual, 0))
                            };

                            // Only bail early before updating if the actual is not the output,
                            // sometimes users want to test cases that
                            // are intended to have errors, hence why this
                            // check isn't shown above
                            if actual.contains("ERROR") || actual.contains("MISSING") {
                                test_summary.has_parse_errors = true;

                                // keep the original `expected` output if the actual output has an
                                // error
                                corrected_entries.push(TestCorrection::new(
                                    &name,
                                    input,
                                    expected_output,
                                    &attributes_str,
                                    header_delim_len,
                                    divider_delim_len,
                                ));
                            } else {
                                corrected_entries.push(TestCorrection::new(
                                    &name,
                                    input,
                                    actual_output,
                                    &attributes_str,
                                    header_delim_len,
                                    divider_delim_len,
                                ));
                                test_summary.parse_results.add_case(TestResult {
                                    name: name.clone(),
                                    info: TestInfo::ParseTest {
                                        outcome: TestOutcome::Updated,
                                        parse_rate,
                                        test_num: test_summary.test_num,
                                    },
                                });
                            }
                        } else {
                            test_summary.parse_results.add_case(TestResult {
                                name: name.clone(),
                                info: TestInfo::ParseTest {
                                    outcome: TestOutcome::Failed,
                                    parse_rate,
                                    test_num: test_summary.test_num,
                                },
                            });
                        }
                        test_summary.parse_failures.push(TestFailure::new(
                            &name,
                            actual,
                            &output,
                            attributes.cst,
                        ));

                        if attributes.fail_fast {
                            return Ok(false);
                        }
                    }
                }

                if i == attributes.languages.len() - 1 {
                    // reset to the first language
                    parser.set_language(opts.languages.values().next().unwrap())?;
                }
            }
            test_summary.test_num += 1;
        }
        TestEntry::Group {
            name,
            children,
            file_path,
        } => {
            if children.is_empty() {
                return Ok(true);
            }

            let failure_count = test_summary.parse_failures.len();
            let mut ran_test_in_group = false;

            let matches_filter = |name: &str, file_name: &Option<String>, opts: &TestOptions| {
                if let (Some(test_file_path), Some(filter_file_name)) = (file_name, &opts.file_name)
                {
                    if !filter_file_name.eq(test_file_path) {
                        return false;
                    }
                }
                if let Some(include) = &opts.include {
                    include.is_match(name)
                } else if let Some(exclude) = &opts.exclude {
                    !exclude.is_match(name)
                } else {
                    true
                }
            };

            for child in children {
                if let TestEntry::Example {
                    ref name,
                    ref file_name,
                    ref input,
                    ref output,
                    ref attributes_str,
                    header_delim_len,
                    divider_delim_len,
                    ..
                } = child
                {
                    if !matches_filter(name, file_name, opts) {
                        if opts.update {
                            let input = String::from_utf8(input.clone()).unwrap();
                            let output = format_sexp(output, 0);
                            corrected_entries.push(TestCorrection::new(
                                name,
                                input,
                                output,
                                attributes_str,
                                header_delim_len,
                                divider_delim_len,
                            ));
                        }

                        test_summary.test_num += 1;
                        continue;
                    }
                }

                if !ran_test_in_group && !is_root {
                    test_summary.parse_results.add_group(&name);
                    ran_test_in_group = true;
                }
                if !run_tests(parser, child, opts, test_summary, corrected_entries, false)? {
                    // fail fast
                    return Ok(false);
                }
            }
            // Now that we're done traversing the children of the current group, pop
            // the index
            test_summary.parse_results.pop_traversal();

            if let Some(file_path) = file_path {
                if opts.update && test_summary.parse_failures.len() - failure_count > 0 {
                    write_tests(&file_path, corrected_entries)?;
                }
                corrected_entries.clear();
            }
        }
    }
    Ok(true)
}

/// Convenience wrapper to render a CST for a test entry.
fn render_test_cst(input: &[u8], tree: &Tree) -> Result<String> {
    let mut rendered_cst: Vec<u8> = Vec::new();
    let mut cursor = tree.walk();
    let opts = ParseFileOptions {
        edits: &[],
        output: ParseOutput::Cst,
        stats: &mut ParseStats::default(),
        print_time: false,
        timeout: 0,
        debug: ParseDebugType::Quiet,
        debug_graph: false,
        cancellation_flag: None,
        encoding: None,
        open_log: false,
        no_ranges: false,
        parse_theme: &ParseTheme::empty(),
    };
    render_cst(input, tree, &mut cursor, &opts, &mut rendered_cst)?;
    Ok(String::from_utf8_lossy(&rendered_cst).trim().to_string())
}

// Parse time is interpreted in ns before converting to ms to avoid truncation issues
// Parse rates often have several outliers, leading to a large standard deviation. Taking
// the log of these rates serves to "flatten" out the distribution, yielding a more
// usable standard deviation for finding statistically significant slow parse rates
// NOTE: This is just a heuristic
#[must_use]
pub fn adjusted_parse_rate(tree: &Tree, parse_time: Duration) -> f64 {
    f64::ln(
        tree.root_node().byte_range().len() as f64 / (parse_time.as_nanos() as f64 / 1_000_000.0),
    )
}

fn write_tests(file_path: &Path, corrected_entries: &[TestCorrection]) -> Result<()> {
    let mut buffer = fs::File::create(file_path)?;
    write_tests_to_buffer(&mut buffer, corrected_entries)
}

fn write_tests_to_buffer(
    buffer: &mut impl Write,
    corrected_entries: &[TestCorrection],
) -> Result<()> {
    for (
        i,
        TestCorrection {
            name,
            input,
            output,
            attributes_str,
            header_delim_len,
            divider_delim_len,
        },
    ) in corrected_entries.iter().enumerate()
    {
        if i > 0 {
            writeln!(buffer)?;
        }
        writeln!(
            buffer,
            "{}\n{name}\n{}{}\n{input}\n{}\n\n{}",
            "=".repeat(*header_delim_len),
            if attributes_str.is_empty() {
                attributes_str.clone()
            } else {
                format!("{attributes_str}\n")
            },
            "=".repeat(*header_delim_len),
            "-".repeat(*divider_delim_len),
            output.trim()
        )?;
    }
    Ok(())
}

pub fn parse_tests(path: &Path) -> io::Result<TestEntry> {
    let name = path
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("")
        .to_string();
    if path.is_dir() {
        let mut children = Vec::new();
        for entry in fs::read_dir(path)? {
            let entry = entry?;
            let hidden = entry.file_name().to_str().unwrap_or("").starts_with('.');
            if !hidden {
                children.push(entry.path());
            }
        }
        children.sort_by(|a, b| {
            a.file_name()
                .unwrap_or_default()
                .cmp(b.file_name().unwrap_or_default())
        });
        let children = children
            .iter()
            .map(|path| parse_tests(path))
            .collect::<io::Result<Vec<TestEntry>>>()?;
        Ok(TestEntry::Group {
            name,
            children,
            file_path: None,
        })
    } else {
        let content = fs::read_to_string(path)?;
        Ok(parse_test_content(name, &content, Some(path.to_path_buf())))
    }
}

#[must_use]
pub fn strip_sexp_fields(sexp: &str) -> String {
    SEXP_FIELD_REGEX.replace_all(sexp, " (").to_string()
}

#[must_use]
pub fn strip_points(sexp: &str) -> String {
    POINT_REGEX.replace_all(sexp, "").to_string()
}

fn parse_test_content(name: String, content: &str, file_path: Option<PathBuf>) -> TestEntry {
    let mut children = Vec::new();
    let bytes = content.as_bytes();
    let mut prev_name = String::new();
    let mut prev_attributes_str = String::new();
    let mut prev_header_end = 0;

    // Find the first test header in the file, and determine if it has a
    // custom suffix. If so, then this suffix will be used to identify
    // all subsequent headers and divider lines in the file.
    let first_suffix = HEADER_REGEX
        .captures(bytes)
        .and_then(|c| c.name("suffix1"))
        .map(|m| String::from_utf8_lossy(m.as_bytes()));

    // Find all of the `===` test headers, which contain the test names.
    // Ignore any matches whose suffix does not match the first header
    // suffix in the file.
    let header_matches = HEADER_REGEX.captures_iter(bytes).filter_map(|c| {
        let header_delim_len = c.name("equals").map_or(80, |m| m.as_bytes().len());
        let suffix1 = c
            .name("suffix1")
            .map(|m| String::from_utf8_lossy(m.as_bytes()));
        let suffix2 = c
            .name("suffix2")
            .map(|m| String::from_utf8_lossy(m.as_bytes()));

        let (mut skip, mut platform, mut fail_fast, mut error, mut cst, mut languages) =
            (false, None, false, false, false, vec![]);

        let test_name_and_markers = c
            .name("test_name_and_markers")
            .map_or("".as_bytes(), |m| m.as_bytes());

        let mut test_name = String::new();
        let mut attributes_str = String::new();

        let mut seen_marker = false;

        let test_name_and_markers = str::from_utf8(test_name_and_markers).unwrap();
        for line in test_name_and_markers
            .split_inclusive('\n')
            .filter(|s| !s.is_empty())
        {
            let trimmed_line = line.trim();
            match trimmed_line.split('(').next().unwrap() {
                ":skip" => (seen_marker, skip) = (true, true),
                ":platform" => {
                    if let Some(platforms) = trimmed_line.strip_prefix(':').and_then(|s| {
                        s.strip_prefix("platform(")
                            .and_then(|s| s.strip_suffix(')'))
                    }) {
                        seen_marker = true;
                        platform = Some(
                            platform.unwrap_or(false) || platforms.trim() == std::env::consts::OS,
                        );
                    }
                }
                ":fail-fast" => (seen_marker, fail_fast) = (true, true),
                ":error" => (seen_marker, error) = (true, true),
                ":language" => {
                    if let Some(lang) = trimmed_line.strip_prefix(':').and_then(|s| {
                        s.strip_prefix("language(")
                            .and_then(|s| s.strip_suffix(')'))
                    }) {
                        seen_marker = true;
                        languages.push(lang.into());
                    }
                }
                ":cst" => (seen_marker, cst) = (true, true),
                _ if !seen_marker => {
                    test_name.push_str(line);
                }
                _ => {}
            }
        }
        attributes_str.push_str(test_name_and_markers.strip_prefix(&test_name).unwrap());

        // prefer skip over error, both shouldn't be set
        if skip {
            error = false;
        }

        // add a default language if none are specified, will defer to the first language
        if languages.is_empty() {
            languages.push("".into());
        }

        if suffix1 == first_suffix && suffix2 == first_suffix {
            let header_range = c.get(0).unwrap().range();
            let test_name = if test_name.is_empty() {
                None
            } else {
                Some(test_name.trim_end().to_string())
            };
            let attributes_str = if attributes_str.is_empty() {
                None
            } else {
                Some(attributes_str.trim_end().to_string())
            };
            Some((
                header_delim_len,
                header_range,
                test_name,
                attributes_str,
                TestAttributes {
                    skip,
                    platform: platform.unwrap_or(true),
                    fail_fast,
                    error,
                    cst,
                    languages,
                },
            ))
        } else {
            None
        }
    });

    let (mut prev_header_len, mut prev_attributes) = (80, TestAttributes::default());
    for (header_delim_len, header_range, test_name, attributes_str, attributes) in header_matches
        .chain(Some((
            80,
            bytes.len()..bytes.len(),
            None,
            None,
            TestAttributes::default(),
        )))
    {
        // Find the longest line of dashes following each test description. That line
        // separates the input from the expected output. Ignore any matches whose suffix
        // does not match the first suffix in the file.
        if prev_header_end > 0 {
            let divider_range = DIVIDER_REGEX
                .captures_iter(&bytes[prev_header_end..header_range.start])
                .filter_map(|m| {
                    let divider_delim_len = m.name("hyphens").map_or(80, |m| m.as_bytes().len());
                    let suffix = m
                        .name("suffix")
                        .map(|m| String::from_utf8_lossy(m.as_bytes()));
                    if suffix == first_suffix {
                        let range = m.get(0).unwrap().range();
                        Some((
                            divider_delim_len,
                            (prev_header_end + range.start)..(prev_header_end + range.end),
                        ))
                    } else {
                        None
                    }
                })
                .max_by_key(|(_, range)| range.len());

            if let Some((divider_delim_len, divider_range)) = divider_range {
                if let Ok(output) = str::from_utf8(&bytes[divider_range.end..header_range.start]) {
                    let mut input = bytes[prev_header_end..divider_range.start].to_vec();

                    // Remove trailing newline from the input.
                    input.pop();
                    if input.last() == Some(&b'\r') {
                        input.pop();
                    }

                    let (output, has_fields) = if prev_attributes.cst {
                        (output.trim().to_string(), false)
                    } else {
                        // Remove all comments
                        let output = COMMENT_REGEX.replace_all(output, "").to_string();

                        // Normalize the whitespace in the expected output.
                        let output = WHITESPACE_REGEX.replace_all(output.trim(), " ");
                        let output = output.replace(" )", ")");

                        // Identify if the expected output has fields indicated. If not, then
                        // fields will not be checked.
                        let has_fields = SEXP_FIELD_REGEX.is_match(&output);

                        (output, has_fields)
                    };

                    let file_name = if let Some(ref path) = file_path {
                        path.file_name().map(|n| n.to_string_lossy().to_string())
                    } else {
                        None
                    };

                    let t = TestEntry::Example {
                        name: prev_name,
                        input,
                        output,
                        header_delim_len: prev_header_len,
                        divider_delim_len,
                        has_fields,
                        attributes_str: prev_attributes_str,
                        attributes: prev_attributes,
                        file_name,
                    };

                    children.push(t);
                }
            }
        }
        prev_attributes = attributes;
        prev_name = test_name.unwrap_or_default();
        prev_attributes_str = attributes_str.unwrap_or_default();
        prev_header_len = header_delim_len;
        prev_header_end = header_range.end;
    }
    TestEntry::Group {
        name,
        children,
        file_path,
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use crate::tests::get_language;

    use super::*;

    #[test]
    fn test_parse_test_content_simple() {
        let entry = parse_test_content(
            "the-filename".to_string(),
            r"
===============
The first test
===============

a b c

---

(a
    (b c))

================
The second test
================
d
---
(d)
        "
            .trim(),
            None,
        );

        assert_eq!(
            entry,
            TestEntry::Group {
                name: "the-filename".to_string(),
                children: vec![
                    TestEntry::Example {
                        name: "The first test".to_string(),
                        input: b"\na b c\n".to_vec(),
                        output: "(a (b c))".to_string(),
                        header_delim_len: 15,
                        divider_delim_len: 3,
                        has_fields: false,
                        attributes_str: String::new(),
                        attributes: TestAttributes::default(),
                        file_name: None,
                    },
                    TestEntry::Example {
                        name: "The second test".to_string(),
                        input: b"d".to_vec(),
                        output: "(d)".to_string(),
                        header_delim_len: 16,
                        divider_delim_len: 3,
                        has_fields: false,
                        attributes_str: String::new(),
                        attributes: TestAttributes::default(),
                        file_name: None,
                    },
                ],
                file_path: None,
            }
        );
    }

    #[test]
    fn test_parse_test_content_with_dashes_in_source_code() {
        let entry = parse_test_content(
            "the-filename".to_string(),
            r"
==================
Code with dashes
==================
abc
---
defg
----
hijkl
-------

(a (b))

=========================
Code ending with dashes
=========================
abc
-----------
-------------------

(c (d))
        "
            .trim(),
            None,
        );

        assert_eq!(
            entry,
            TestEntry::Group {
                name: "the-filename".to_string(),
                children: vec![
                    TestEntry::Example {
                        name: "Code with dashes".to_string(),
                        input: b"abc\n---\ndefg\n----\nhijkl".to_vec(),
                        output: "(a (b))".to_string(),
                        header_delim_len: 18,
                        divider_delim_len: 7,
                        has_fields: false,
                        attributes_str: String::new(),
                        attributes: TestAttributes::default(),
                        file_name: None,
                    },
                    TestEntry::Example {
                        name: "Code ending with dashes".to_string(),
                        input: b"abc\n-----------".to_vec(),
                        output: "(c (d))".to_string(),
                        header_delim_len: 25,
                        divider_delim_len: 19,
                        has_fields: false,
                        attributes_str: String::new(),
                        attributes: TestAttributes::default(),
                        file_name: None,
                    },
                ],
                file_path: None,
            }
        );
    }

    #[test]
    fn test_format_sexp() {
        assert_eq!(format_sexp("", 0), "");
        assert_eq!(
            format_sexp("(a b: (c) (d) e: (f (g (h (MISSING i)))))", 0),
            r"
(a
  b: (c)
  (d)
  e: (f
    (g
      (h
        (MISSING i)))))
"
            .trim()
        );
        assert_eq!(
            format_sexp("(program (ERROR (UNEXPECTED ' ')) (identifier))", 0),
            r"
(program
  (ERROR
    (UNEXPECTED ' '))
  (identifier))
"
            .trim()
        );
        assert_eq!(
            format_sexp(r#"(source_file (MISSING ")"))"#, 0),
            r#"
(source_file
  (MISSING ")"))
        "#
            .trim()
        );
        assert_eq!(
            format_sexp(
                r"(source_file (ERROR (UNEXPECTED 'f') (UNEXPECTED '+')))",
                0
            ),
            r"
(source_file
  (ERROR
    (UNEXPECTED 'f')
    (UNEXPECTED '+')))
"
            .trim()
        );
    }

    #[test]
    fn test_write_tests_to_buffer() {
        let mut buffer = Vec::new();
        let corrected_entries = vec![
            TestCorrection::new(
                "title 1".to_string(),
                "input 1".to_string(),
                "output 1".to_string(),
                String::new(),
                80,
                80,
            ),
            TestCorrection::new(
                "title 2".to_string(),
                "input 2".to_string(),
                "output 2".to_string(),
                String::new(),
                80,
                80,
            ),
        ];
        write_tests_to_buffer(&mut buffer, &corrected_entries).unwrap();
        assert_eq!(
            String::from_utf8(buffer).unwrap(),
            r"
================================================================================
title 1
================================================================================
input 1
--------------------------------------------------------------------------------

output 1

================================================================================
title 2
================================================================================
input 2
--------------------------------------------------------------------------------

output 2
"
            .trim_start()
            .to_string()
        );
    }

    #[test]
    fn test_parse_test_content_with_comments_in_sexp() {
        let entry = parse_test_content(
            "the-filename".to_string(),
            r#"
==================
sexp with comment
==================
code
---

; Line start comment
(a (b))

==================
sexp with comment between
==================
code
---

; Line start comment
(a
; ignore this
    (b)
    ; also ignore this
)

=========================
sexp with ';'
=========================
code
---

(MISSING ";")
        "#
            .trim(),
            None,
        );

        assert_eq!(
            entry,
            TestEntry::Group {
                name: "the-filename".to_string(),
                children: vec![
                    TestEntry::Example {
                        name: "sexp with comment".to_string(),
                        input: b"code".to_vec(),
                        output: "(a (b))".to_string(),
                        header_delim_len: 18,
                        divider_delim_len: 3,
                        has_fields: false,
                        attributes_str: String::new(),
                        attributes: TestAttributes::default(),
                        file_name: None,
                    },
                    TestEntry::Example {
                        name: "sexp with comment between".to_string(),
                        input: b"code".to_vec(),
                        output: "(a (b))".to_string(),
                        header_delim_len: 18,
                        divider_delim_len: 3,
                        has_fields: false,
                        attributes_str: String::new(),
                        attributes: TestAttributes::default(),
                        file_name: None,
                    },
                    TestEntry::Example {
                        name: "sexp with ';'".to_string(),
                        input: b"code".to_vec(),
                        output: "(MISSING \";\")".to_string(),
                        header_delim_len: 25,
                        divider_delim_len: 3,
                        has_fields: false,
                        attributes_str: String::new(),
                        attributes: TestAttributes::default(),
                        file_name: None,
                    }
                ],
                file_path: None,
            }
        );
    }

    #[test]
    fn test_parse_test_content_with_suffixes() {
        let entry = parse_test_content(
            "the-filename".to_string(),
            r"
==================asdf\()[]|{}*+?^$.-
First test
==================asdf\()[]|{}*+?^$.-

=========================
NOT A TEST HEADER
=========================
-------------------------

---asdf\()[]|{}*+?^$.-

(a)

==================asdf\()[]|{}*+?^$.-
Second test
==================asdf\()[]|{}*+?^$.-

=========================
NOT A TEST HEADER
=========================
-------------------------

---asdf\()[]|{}*+?^$.-

(a)

=========================asdf\()[]|{}*+?^$.-
Test name with = symbol
=========================asdf\()[]|{}*+?^$.-

=========================
NOT A TEST HEADER
=========================
-------------------------

---asdf\()[]|{}*+?^$.-

(a)

==============================asdf\()[]|{}*+?^$.-
Test containing equals
==============================asdf\()[]|{}*+?^$.-

===

------------------------------asdf\()[]|{}*+?^$.-

(a)

==============================asdf\()[]|{}*+?^$.-
Subsequent test containing equals
==============================asdf\()[]|{}*+?^$.-

===

------------------------------asdf\()[]|{}*+?^$.-

(a)
"
            .trim(),
            None,
        );

        let expected_input = b"\n=========================\n\
            NOT A TEST HEADER\n\
            =========================\n\
            -------------------------\n"
            .to_vec();
        pretty_assertions::assert_eq!(
            entry,
            TestEntry::Group {
                name: "the-filename".to_string(),
                children: vec![
                    TestEntry::Example {
                        name: "First test".to_string(),
                        input: expected_input.clone(),
                        output: "(a)".to_string(),
                        header_delim_len: 18,
                        divider_delim_len: 3,
                        has_fields: false,
                        attributes_str: String::new(),
                        attributes: TestAttributes::default(),
                        file_name: None,
                    },
                    TestEntry::Example {
                        name: "Second test".to_string(),
                        input: expected_input.clone(),
                        output: "(a)".to_string(),
                        header_delim_len: 18,
                        divider_delim_len: 3,
                        has_fields: false,
                        attributes_str: String::new(),
                        attributes: TestAttributes::default(),
                        file_name: None,
                    },
                    TestEntry::Example {
                        name: "Test name with = symbol".to_string(),
                        input: expected_input,
                        output: "(a)".to_string(),
                        header_delim_len: 25,
                        divider_delim_len: 3,
                        has_fields: false,
                        attributes_str: String::new(),
                        attributes: TestAttributes::default(),
                        file_name: None,
                    },
                    TestEntry::Example {
                        name: "Test containing equals".to_string(),
                        input: "\n===\n".into(),
                        output: "(a)".into(),
                        header_delim_len: 30,
                        divider_delim_len: 30,
                        has_fields: false,
                        attributes_str: String::new(),
                        attributes: TestAttributes::default(),
                        file_name: None,
                    },
                    TestEntry::Example {
                        name: "Subsequent test containing equals".to_string(),
                        input: "\n===\n".into(),
                        output: "(a)".into(),
                        header_delim_len: 30,
                        divider_delim_len: 30,
                        has_fields: false,
                        attributes_str: String::new(),
                        attributes: TestAttributes::default(),
                        file_name: None,
                    }
                ],
                file_path: None,
            }
        );
    }

    #[test]
    fn test_parse_test_content_with_newlines_in_test_names() {
        let entry = parse_test_content(
            "the-filename".to_string(),
            r"
===============
name
with
newlines
===============
a
---
(b)

====================
name with === signs
====================
code with ----
---
(d)
",
            None,
        );

        assert_eq!(
            entry,
            TestEntry::Group {
                name: "the-filename".to_string(),
                file_path: None,
                children: vec![
                    TestEntry::Example {
                        name: "name\nwith\nnewlines".to_string(),
                        input: b"a".to_vec(),
                        output: "(b)".to_string(),
                        header_delim_len: 15,
                        divider_delim_len: 3,
                        has_fields: false,
                        attributes_str: String::new(),
                        attributes: TestAttributes::default(),
                        file_name: None,
                    },
                    TestEntry::Example {
                        name: "name with === signs".to_string(),
                        input: b"code with ----".to_vec(),
                        output: "(d)".to_string(),
                        header_delim_len: 20,
                        divider_delim_len: 3,
                        has_fields: false,
                        attributes_str: String::new(),
                        attributes: TestAttributes::default(),
                        file_name: None,
                    }
                ]
            }
        );
    }

    #[test]
    fn test_parse_test_with_markers() {
        // do one with :skip, we should not see it in the entry output

        let entry = parse_test_content(
            "the-filename".to_string(),
            r"
=====================
Test with skip marker
:skip
=====================
a
---
(b)
",
            None,
        );

        assert_eq!(
            entry,
            TestEntry::Group {
                name: "the-filename".to_string(),
                file_path: None,
                children: vec![TestEntry::Example {
                    name: "Test with skip marker".to_string(),
                    input: b"a".to_vec(),
                    output: "(b)".to_string(),
                    header_delim_len: 21,
                    divider_delim_len: 3,
                    has_fields: false,
                    attributes_str: ":skip".to_string(),
                    attributes: TestAttributes {
                        skip: true,
                        platform: true,
                        fail_fast: false,
                        error: false,
                        cst: false,
                        languages: vec!["".into()]
                    },
                    file_name: None,
                }]
            }
        );

        let entry = parse_test_content(
            "the-filename".to_string(),
            &format!(
                r"
=========================
Test with platform marker
:platform({})
:fail-fast
=========================
a
---
(b)

=============================
Test with bad platform marker
:platform({})

:language(foo)
=============================
a
---
(b)

====================
Test with cst marker
:cst
====================
1
---
0:0 - 1:0   source_file
0:0 - 0:1   expression
0:0 - 0:1     number_literal `1`
",
                std::env::consts::OS,
                if std::env::consts::OS == "linux" {
                    "macos"
                } else {
                    "linux"
                }
            ),
            None,
        );

        assert_eq!(
            entry,
            TestEntry::Group {
                name: "the-filename".to_string(),
                file_path: None,
                children: vec![
                    TestEntry::Example {
                        name: "Test with platform marker".to_string(),
                        input: b"a".to_vec(),
                        output: "(b)".to_string(),
                        header_delim_len: 25,
                        divider_delim_len: 3,
                        has_fields: false,
                        attributes_str: format!(":platform({})\n:fail-fast", std::env::consts::OS),
                        attributes: TestAttributes {
                            skip: false,
                            platform: true,
                            fail_fast: true,
                            error: false,
                            cst: false,
                            languages: vec!["".into()]
                        },
                        file_name: None,
                    },
                    TestEntry::Example {
                        name: "Test with bad platform marker".to_string(),
                        input: b"a".to_vec(),
                        output: "(b)".to_string(),
                        header_delim_len: 29,
                        divider_delim_len: 3,
                        has_fields: false,
                        attributes_str: if std::env::consts::OS == "linux" {
                            ":platform(macos)\n\n:language(foo)".to_string()
                        } else {
                            ":platform(linux)\n\n:language(foo)".to_string()
                        },
                        attributes: TestAttributes {
                            skip: false,
                            platform: false,
                            fail_fast: false,
                            error: false,
                            cst: false,
                            languages: vec!["foo".into()]
                        },
                        file_name: None,
                    },
                    TestEntry::Example {
                        name: "Test with cst marker".to_string(),
                        input: b"1".to_vec(),
                        output: "0:0 - 1:0   source_file
0:0 - 0:1   expression
0:0 - 0:1     number_literal `1`"
                            .to_string(),
                        header_delim_len: 20,
                        divider_delim_len: 3,
                        has_fields: false,
                        attributes_str: ":cst".to_string(),
                        attributes: TestAttributes {
                            skip: false,
                            platform: true,
                            fail_fast: false,
                            error: false,
                            cst: true,
                            languages: vec!["".into()]
                        },
                        file_name: None,
                    }
                ]
            }
        );
    }

    fn clear_parse_rate(result: &mut TestResult) {
        let test_case_info = &mut result.info;
        match test_case_info {
            TestInfo::ParseTest {
                ref mut parse_rate, ..
            } => {
                assert!(parse_rate.is_some());
                *parse_rate = None;
            }
            TestInfo::Group { .. } | TestInfo::AssertionTest { .. } => {
                panic!("Unexpected test result")
            }
        }
    }

    #[test]
    fn run_tests_simple() {
        let mut parser = Parser::new();
        let language = get_language("c");
        parser
            .set_language(&language)
            .expect("Failed to set language");
        let mut languages = BTreeMap::new();
        languages.insert("c", &language);
        let opts = TestOptions {
            path: PathBuf::from("foo"),
            debug: true,
            debug_graph: false,
            include: None,
            exclude: None,
            file_name: None,
            update: false,
            open_log: false,
            languages,
            color: true,
            show_fields: false,
            overview_only: false,
        };

        // NOTE: The following test cases are combined to work around a race condition
        // in the loader
        {
            let test_entry = TestEntry::Group {
                name: "foo".to_string(),
                file_path: None,
                children: vec![TestEntry::Example {
                    name: "C Test 1".to_string(),
                    input: b"1;\n".to_vec(),
                    output: "(translation_unit (expression_statement (number_literal)))"
                        .to_string(),
                    header_delim_len: 25,
                    divider_delim_len: 3,
                    has_fields: false,
                    attributes_str: String::new(),
                    attributes: TestAttributes::default(),
                    file_name: None,
                }],
            };

            let mut test_summary = TestSummary::new(true, TestStats::All, false, false, false);
            let mut corrected_entries = Vec::new();
            run_tests(
                &mut parser,
                test_entry,
                &opts,
                &mut test_summary,
                &mut corrected_entries,
                true,
            )
            .expect("Failed to run tests");

            // parse rates will always be different, so we need to clear out these
            // fields to reliably assert equality below
            clear_parse_rate(&mut test_summary.parse_results.root_group[0]);
            test_summary.parse_stats.total_duration = Duration::from_secs(0);

            let json_results = serde_json::to_string(&test_summary).unwrap();

            assert_eq!(
                json_results,
                json!({
                  "parse_results": [
                    {
                      "name": "C Test 1",
                      "outcome": "Passed",
                      "parse_rate": null,
                      "test_num": 1
                    }
                  ],
                  "parse_failures": [],
                  "parse_stats": {
                    "successful_parses": 1,
                    "total_parses": 1,
                    "total_bytes": 3,
                    "total_duration": {
                      "secs": 0,
                      "nanos": 0,
                    }
                  },
                  "highlight_results": [],
                  "tag_results": [],
                  "query_results": []
                })
                .to_string()
            );
        }
        {
            let test_entry = TestEntry::Group {
                name: "corpus".to_string(),
                file_path: None,
                children: vec![
                    TestEntry::Group {
                        name: "group1".to_string(),
                        // This test passes
                        children: vec![TestEntry::Example {
                            name: "C Test 1".to_string(),
                            input: b"1;\n".to_vec(),
                            output: "(translation_unit (expression_statement (number_literal)))"
                                .to_string(),
                            header_delim_len: 25,
                            divider_delim_len: 3,
                            has_fields: false,
                            attributes_str: String::new(),
                            attributes: TestAttributes::default(),
                            file_name: None,
                        }],
                        file_path: None,
                    },
                    TestEntry::Group {
                        name: "group2".to_string(),
                        children: vec![
                            // This test passes
                            TestEntry::Example {
                                name: "C Test 2".to_string(),
                                input: b"1;\n".to_vec(),
                                output:
                                    "(translation_unit (expression_statement (number_literal)))"
                                        .to_string(),
                                header_delim_len: 25,
                                divider_delim_len: 3,
                                has_fields: false,
                                attributes_str: String::new(),
                                attributes: TestAttributes::default(),
                                file_name: None,
                            },
                            // This test fails, and is marked with fail-fast
                            TestEntry::Example {
                                name: "C Test 3".to_string(),
                                input: b"1;\n".to_vec(),
                                output:
                                    "(translation_unit (expression_statement (string_literal)))"
                                        .to_string(),
                                header_delim_len: 25,
                                divider_delim_len: 3,
                                has_fields: false,
                                attributes_str: String::new(),
                                attributes: TestAttributes {
                                    fail_fast: true,
                                    ..Default::default()
                                },
                                file_name: None,
                            },
                        ],
                        file_path: None,
                    },
                    // This group never runs because of the previous failure
                    TestEntry::Group {
                        name: "group3".to_string(),
                        // This test fails, and is marked with fail-fast
                        children: vec![TestEntry::Example {
                            name: "C Test 4".to_string(),
                            input: b"1;\n".to_vec(),
                            output: "(translation_unit (expression_statement (number_literal)))"
                                .to_string(),
                            header_delim_len: 25,
                            divider_delim_len: 3,
                            has_fields: false,
                            attributes_str: String::new(),
                            attributes: TestAttributes::default(),
                            file_name: None,
                        }],
                        file_path: None,
                    },
                ],
            };

            let mut test_summary = TestSummary::new(true, TestStats::All, false, false, false);
            let mut corrected_entries = Vec::new();
            run_tests(
                &mut parser,
                test_entry,
                &opts,
                &mut test_summary,
                &mut corrected_entries,
                true,
            )
            .expect("Failed to run tests");

            // parse rates will always be different, so we need to clear out these
            // fields to reliably assert equality below
            {
                let test_group_1_info = &mut test_summary.parse_results.root_group[0].info;
                match test_group_1_info {
                    TestInfo::Group {
                        ref mut children, ..
                    } => clear_parse_rate(&mut children[0]),
                    TestInfo::ParseTest { .. } | TestInfo::AssertionTest { .. } => {
                        panic!("Unexpected test result");
                    }
                }
                let test_group_2_info = &mut test_summary.parse_results.root_group[1].info;
                match test_group_2_info {
                    TestInfo::Group {
                        ref mut children, ..
                    } => {
                        clear_parse_rate(&mut children[0]);
                        clear_parse_rate(&mut children[1]);
                    }
                    TestInfo::ParseTest { .. } | TestInfo::AssertionTest { .. } => {
                        panic!("Unexpected test result");
                    }
                }
                test_summary.parse_stats.total_duration = Duration::from_secs(0);
            }

            let json_results = serde_json::to_string(&test_summary).unwrap();

            assert_eq!(
                json_results,
                json!({
                  "parse_results": [
                    {
                      "name": "group1",
                      "children": [
                        {
                          "name": "C Test 1",
                          "outcome": "Passed",
                          "parse_rate": null,
                          "test_num": 1
                        }
                      ]
                    },
                    {
                      "name": "group2",
                      "children": [
                        {
                          "name": "C Test 2",
                          "outcome": "Passed",
                          "parse_rate": null,
                          "test_num": 2
                        },
                        {
                          "name": "C Test 3",
                          "outcome": "Failed",
                          "parse_rate": null,
                          "test_num": 3
                        }
                      ]
                    }
                  ],
                  "parse_failures": [
                    {
                      "name": "C Test 3",
                      "actual": "(translation_unit (expression_statement (number_literal)))",
                      "expected": "(translation_unit (expression_statement (string_literal)))",
                      "is_cst": false,
                    }
                  ],
                  "parse_stats": {
                    "successful_parses": 2,
                    "total_parses": 3,
                    "total_bytes": 9,
                    "total_duration": {
                      "secs": 0,
                      "nanos": 0,
                    }
                  },
                  "highlight_results": [],
                  "tag_results": [],
                  "query_results": []
                })
                .to_string()
            );
        }
    }
}