mds-cli 0.5.1

MDS (Markdown Script) compiler — command-line interface
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
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
//! The CLI's panic output (#389).
//!
//! A panic in `mds` is an internal compiler error. The run prints two fixed lines on
//! stderr — that it failed, and where to report it — and exits 101. The panic's message
//! and location are never shown: a panic message can carry a user's text or a build
//! machine's absolute paths. With `RUST_BACKTRACE` set to anything but `0`, a backtrace
//! follows the two lines, every line escaped; it still never shows the message.
//!
//! # The trigger
//!
//! A debug build of `mds` panics on purpose when `MDS_TEST_PANIC` asks it to: `main`
//! panics in the command's dispatch, `thread` in a thread the dispatch starts and waits
//! for, `compile:<stem>` in the compile of a file with that file stem — one file of a
//! directory run or a watch session, which goes on without it — and `notify` / `ctrlc`
//! in `mds watch`'s file-event callback / Ctrl-C handler, each on a thread of its own.
//! The payload carries a sentinel word, a raw ESC and the absolute path of the working
//! directory — a fresh temporary directory in every test here — so a test can tell that
//! none of it reached stderr. A release build compiles the trigger out
//! (`the_trigger_is_compiled_only_into_debug_builds`).
//!
//! # `RUST_BACKTRACE`
//!
//! CI sets `RUST_BACKTRACE=1` for every job, and a panic's output depends on it, so every
//! run here sets it or removes it (`every_run_sets_or_removes_rust_backtrace`).
//!
//! # With the `debug-panics` feature
//!
//! The never-shipped `debug-panics` feature prints the panic's message and location after
//! the two lines. The tests that pin the default output (`default_output`) are compiled
//! out under it, and `with_debug_panics` runs instead. It is the positive control for the
//! payload: the text the default tests look for is really in the panic they trigger.

mod common;
use common::{closed_pipe, mds_bin};

use std::io::Read;
use std::ops::RangeInclusive;
use std::path::{Path, PathBuf};
use std::process::{Child, Stdio};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

/// What `mds` prints when it panics, built as the CLI builds it: the issue tracker is the
/// manifest's repository followed by `/issues`.
const ICE_TEXT: &str = concat!(
    "mds: internal compiler error\n",
    "note: this is a bug in mds; please report it at ",
    env!("CARGO_PKG_REPOSITORY"),
    "/issues\n",
);

/// The word the trigger's payload carries (`panic_trigger` in `src/output.rs`).
const SENTINEL: &str = "mds-test-panic-payload";

/// The variable that asks a debug build of `mds` to panic.
const TRIGGER: &str = "MDS_TEST_PANIC";

/// The variable a panic's backtrace depends on.
const RUST_BACKTRACE: &str = "RUST_BACKTRACE";

/// Failure bound for one run. A run takes milliseconds; this only stops a hung child from
/// hanging the suite.
const RUN_TIMEOUT: Duration = Duration::from_secs(60);

/// How long a panic may take to end the run — on any thread, with stderr open or closed.
const PANIC_EXIT_BOUND: Duration = Duration::from_secs(10);

/// How often [`wait_bounded`] polls the child for exit.
const POLL: Duration = Duration::from_millis(5);

/// How a run sets `RUST_BACKTRACE`.
#[derive(Clone, Copy, Debug)]
enum Backtrace {
    Unset,
    Set(&'static str),
}

/// Where a run's stderr goes.
#[derive(Clone, Copy, Debug)]
enum Stderr {
    Piped,
    /// A pipe whose reader is gone before the run starts.
    Closed,
}

/// What one run left behind.
struct Run {
    code: Option<i32>,
    stdout: String,
    /// Empty when stderr was closed.
    stderr: String,
    took: Duration,
}

/// A fresh working directory holding `ok.mds`, which `mds check` passes.
fn fixture() -> tempfile::TempDir {
    let dir = tempfile::tempdir().expect("tempdir");
    std::fs::write(dir.path().join("ok.mds"), "Hello\n").expect("write ok.mds");
    dir
}

/// Run `mds check ok.mds` in `dir`, asking for a panic at `panic_at` (none for `None`),
/// with `RUST_BACKTRACE` as `backtrace` says and stderr as `stderr` says.
fn run_mds(dir: &Path, panic_at: Option<&str>, backtrace: Backtrace, stderr: Stderr) -> Run {
    run_args(dir, &["check", "ok.mds"], panic_at, backtrace, stderr)
}

/// Run `mds <args>` in `dir`, asking for a panic at `panic_at` (none for `None`), with
/// `RUST_BACKTRACE` as `backtrace` says and stderr as `stderr` says.
fn run_args(
    dir: &Path,
    args: &[&str],
    panic_at: Option<&str>,
    backtrace: Backtrace,
    stderr: Stderr,
) -> Run {
    let mut cmd = mds_bin();
    cmd.args(args)
        .current_dir(dir)
        .stdin(Stdio::null())
        .stdout(Stdio::piped());
    match panic_at {
        Some(at) => cmd.env(TRIGGER, at),
        None => cmd.env_remove(TRIGGER),
    };
    match backtrace {
        Backtrace::Unset => cmd.env_remove(RUST_BACKTRACE),
        Backtrace::Set(value) => cmd.env(RUST_BACKTRACE, value),
    };
    match stderr {
        Stderr::Piped => cmd.stderr(Stdio::piped()),
        Stderr::Closed => cmd.stderr(closed_pipe()),
    };
    let started = Instant::now();
    let mut child = cmd.spawn().expect("spawn mds");
    let out = drain(child.stdout.take());
    let err = drain(child.stderr.take());
    let code = wait_bounded(&mut child);
    Run {
        code,
        took: started.elapsed(),
        stdout: joined(out),
        stderr: joined(err),
    }
}

/// Drain one child pipe on its own thread so neither pipe can fill and stall the child.
fn drain<R: Read + Send + 'static>(pipe: Option<R>) -> Option<JoinHandle<Vec<u8>>> {
    pipe.map(|mut pipe| {
        std::thread::spawn(move || {
            let mut bytes = Vec::new();
            let _ = pipe.read_to_end(&mut bytes);
            bytes
        })
    })
}

fn joined(handle: Option<JoinHandle<Vec<u8>>>) -> String {
    let bytes = handle
        .map(|h| h.join().expect("pipe drain thread"))
        .unwrap_or_default();
    String::from_utf8_lossy(&bytes).into_owned()
}

/// Wait for `child` to exit, killing it if [`RUN_TIMEOUT`] passes first.
fn wait_bounded(child: &mut Child) -> Option<i32> {
    let deadline = Instant::now() + RUN_TIMEOUT;
    loop {
        if let Some(status) = child.try_wait().expect("poll the mds child") {
            return status.code();
        }
        if Instant::now() >= deadline {
            let _ = child.kill();
            let _ = child.wait();
            panic!("mds did not exit within {RUN_TIMEOUT:?}");
        }
        std::thread::sleep(POLL);
    }
}

// ── Behaviour ─────────────────────────────────────────────────────────────────

/// A panic with stderr closed still exits 101 — not by a signal, not by an abort: the
/// hook's write fails and the hook carries on. Main thread and another thread, with and
/// without a backtrace.
///
/// Control: with stderr open the same run reaches the hook and prints the text.
#[test]
fn a_panic_with_stderr_closed_exits_101_not_by_a_signal() {
    let dir = fixture();
    for panic_at in ["main", "thread"] {
        let open = run_mds(dir.path(), Some(panic_at), Backtrace::Unset, Stderr::Piped);
        assert_eq!(
            open.code,
            Some(101),
            "control ({panic_at}): with stderr open a panic exits 101; stderr:\n{}",
            open.stderr
        );
        assert!(
            open.stderr.starts_with(ICE_TEXT),
            "control ({panic_at}): with stderr open the hook prints the text; it was:\n{}",
            open.stderr
        );
        for backtrace in [Backtrace::Unset, Backtrace::Set("1")] {
            let closed = run_mds(dir.path(), Some(panic_at), backtrace, Stderr::Closed);
            assert_eq!(
                closed.code,
                Some(101),
                "a panic ({panic_at}, {backtrace:?}) with stderr closed exits 101, not by a \
                 signal (None)"
            );
            assert_eq!(closed.stdout, "", "a panic writes nothing to stdout");
            assert!(
                closed.took < PANIC_EXIT_BOUND,
                "the run ends within {PANIC_EXIT_BOUND:?}; it took {:?}",
                closed.took
            );
        }
    }
}

/// The default output: exactly the text, and with `RUST_BACKTRACE` a backtrace. Compiled
/// out under `debug-panics`, which prints the panic's message and location as well.
#[cfg(not(feature = "debug-panics"))]
mod default_output {
    use super::*;
    use crate::common::count_occurrences;
    use crate::common::{
        spawn_watch_ready, spawn_watch_unsynchronized, wait_for_tap_count, write_atomic,
        ChildGuard, PipeTap,
    };

    /// The first line of the backtrace `RUST_BACKTRACE` adds.
    const BACKTRACE_HEADER: &str = "stack backtrace:\n";

    /// What a run without a backtrace must never show on top of the payload: the default
    /// panic message's source location (`src/output.rs:12:5`).
    const LOCATION_NEEDLES: &[&str] = &["src/", "src\\", ".rs:"];

    /// What a panic's output must never show of the trigger's payload: its sentinel, its
    /// raw ESC, and the working directory it names — as the test made it and as the OS
    /// resolves it — and the default panic message's shape: `panicked at` and a thread
    /// name.
    fn payload_needles(dir: &Path) -> Vec<String> {
        let canonical = dir
            .canonicalize()
            .expect("canonicalize the working directory");
        // Non-vacuity: the two paths name the directory the run worked in.
        assert!(dir.is_absolute() && dir.is_dir() && canonical.is_dir());
        vec![
            SENTINEL.to_string(),
            char::from(0x1b).to_string(),
            dir.display().to_string(),
            canonical.display().to_string(),
            "panicked at".to_string(),
            "thread '".to_string(),
        ]
    }

    fn location_needles() -> Vec<String> {
        LOCATION_NEEDLES.iter().map(|s| (*s).to_string()).collect()
    }

    /// Assert that `text` shows none of `needles`.
    fn assert_shows_none(text: &str, needles: &[String], what: &str) {
        for needle in needles {
            assert!(!needle.is_empty(), "non-vacuity: a needle is never empty");
            assert!(
                !text.contains(needle.as_str()),
                "{what}: stderr must not show {needle:?}; it was:\n{text}"
            );
        }
    }

    /// Whether `line` holds no character the CLI escapes: WIRE escaping leaves it as it is.
    fn is_plain(line: &str) -> bool {
        mds::sanitize_control_chars_wire(line) == line
    }

    /// The frame a real backtrace of a panic names: the CLI's panic hook.
    const HOOK_FRAME: &str = "mds::output::on_panic";

    /// The fewest numbered frames a real backtrace shows.
    const MIN_FRAMES: usize = 3;

    /// `line` without the crate hashes of v0 symbol names — a `[`, one or more hex digits
    /// and a `]`, right after a crate's name — so that
    /// `mds[1fc92abd4b2f6a9a]::output::on_panic` reads `mds::output::on_panic`, as the
    /// legacy name `mds::output::on_panic::h…` does. rustc emits either scheme, and
    /// `RUST_BACKTRACE=full` prints a v0 name's hashes.
    fn without_crate_hashes(line: &str) -> String {
        let mut parts = line.split('[');
        let mut clean = parts.next().unwrap_or_default().to_string();
        for part in parts {
            let hex = part.len()
                - part
                    .trim_start_matches(|c: char| c.is_ascii_hexdigit())
                    .len();
            let after_a_name = clean.ends_with(|c: char| c.is_ascii_alphanumeric() || c == '_');
            match part[hex..].strip_prefix(']') {
                Some(rest) if hex > 0 && after_a_name => clean.push_str(rest),
                _ => {
                    clean.push('[');
                    clean.push_str(part);
                }
            }
        }
        clean
    }

    /// Whether a line of `backtrace` names [`HOOK_FRAME`], in either symbol-name scheme.
    fn names_the_hook(backtrace: &str) -> bool {
        backtrace
            .lines()
            .any(|line| without_crate_hashes(line).contains(HOOK_FRAME))
    }

    /// How many lines of `backtrace` start a frame: its number, right-aligned, then `: `
    /// (`   4: mds::output::on_panic`). A frame's `at <file>:<line>` line and a function
    /// inlined into it carry no number.
    fn numbered_frames(backtrace: &str) -> usize {
        backtrace
            .lines()
            .filter(|line| {
                let numbered = line.trim_start_matches(' ');
                let digits = numbered.len()
                    - numbered
                        .trim_start_matches(|c: char| c.is_ascii_digit())
                        .len();
                digits > 0 && numbered[digits..].starts_with(": ")
            })
            .count()
    }

    /// The backtrace check reads both of rustc's symbol-name schemes. A legacy name ends in
    /// a hash (`mds::output::on_panic::h0123456789abcdef`); a v0 name printed in full keeps
    /// its crate's hash (`mds[1fc92abd4b2f6a9a]::output::on_panic`, as CI's rustc prints
    /// it with `RUST_BACKTRACE=full`), so as it stands it never reads `mds::`.
    ///
    /// Controls: the v0 line fails a plain `mds::` check; a bracket that is not a crate
    /// hash is kept; another frame, of std or of the CLI, does not name the hook; a frame's
    /// `at` line and a function inlined into a frame are not frames, so two frames with
    /// their `at` lines fall short of [`MIN_FRAMES`] though they are more than two lines.
    #[test]
    fn the_backtrace_check_reads_both_symbol_name_schemes() {
        const V0: &str = "   5:     0x55f9020bb0b0 - mds[1fc92abd4b2f6a9a]::output::on_panic";
        const LEGACY: &str = "   5:     0x55f9020bb0b0 - mds::output::on_panic::h0123456789abcdef";
        assert!(
            !V0.contains("mds::"),
            "control: the v0 line fails a plain `mds::` check"
        );
        for line in [V0, LEGACY] {
            assert!(names_the_hook(line), "{line:?} names the hook's frame");
        }
        assert_eq!(
            without_crate_hashes(V0),
            "   5:     0x55f9020bb0b0 - mds::output::on_panic"
        );
        assert_eq!(
            without_crate_hashes(LEGACY),
            LEGACY,
            "a legacy name has no crate hash"
        );
        assert_eq!(
            without_crate_hashes("<std[6c98fd8553dbae28]::backtrace::Backtrace>::create"),
            "<std::backtrace::Backtrace>::create",
            "every crate hash on a line goes"
        );
        for kept in ["<[f32]>::len", "x[]", "x[1f", "x[1fz]", "x[0x1f]", "[1f]"] {
            assert_eq!(without_crate_hashes(kept), kept, "not a crate hash");
        }
        for other in [
            "   8:     0x55f902661992 - std[6c98fd8553dbae28]::panicking::panic",
            "  14:     0x55f90206a7f4 - mds[1fc92abd4b2f6a9a]::run",
        ] {
            assert!(
                !names_the_hook(other),
                "control: {other:?} is not the hook's frame"
            );
        }

        let frames = [
            "stack backtrace:",
            "   4: mds::output::write_backtrace",
            "             at ./crates/mds-cli/src/output.rs:604:21",
            "      mds::output::inlined_into_frame_4",
            "  12:     0x55f90206a7f4 - mds[1fc92abd4b2f6a9a]::run",
            "                               at /w/crates/mds-cli/src/main.rs:500:5",
            "1000: main",
        ];
        assert_eq!(
            numbered_frames(&frames.join("\n")),
            3,
            "only a numbered line starts a frame"
        );
        let two_frames = frames[..6].join("\n");
        assert!(
            two_frames.lines().count() > 2 && numbered_frames(&two_frames) < MIN_FRAMES,
            "control: two frames with their `at` lines fall short of {MIN_FRAMES} frames"
        );
    }

    /// A panic prints exactly the internal compiler error text and exits 101: never the
    /// payload's sentinel, ESC or absolute path, never `panicked at`, a source location or
    /// a thread name.
    ///
    /// Control: without the trigger the same command passes, so the panic is the
    /// trigger's; the exact text is the positive half of the absence checks.
    #[test]
    fn a_panic_prints_only_the_internal_compiler_error_text_and_exits_101() {
        let dir = fixture();
        let control = run_mds(dir.path(), None, Backtrace::Unset, Stderr::Piped);
        assert_eq!(
            (control.code, control.stderr.as_str()),
            (Some(0), "OK: ok.mds\n"),
            "control: without the trigger `mds check ok.mds` passes"
        );

        let run = run_mds(dir.path(), Some("main"), Backtrace::Unset, Stderr::Piped);
        assert_eq!(
            run.code,
            Some(101),
            "a panic exits 101; stderr:\n{}",
            run.stderr
        );
        assert_eq!(
            run.stderr, ICE_TEXT,
            "stderr is exactly the internal compiler error text"
        );
        assert_eq!(run.stdout, "", "a panic writes nothing to stdout");
        assert_shows_none(&run.stderr, &payload_needles(dir.path()), "a panic");
        assert_shows_none(&run.stderr, &location_needles(), "a panic");
    }

    /// `RUST_BACKTRACE` set to `1` or `full` adds a backtrace after the text, and only
    /// that: every line of it escaped, and still nothing of the payload. `0` adds nothing.
    ///
    /// Controls: the line check finds a raw ESC; the backtrace is a real one, naming the
    /// panic hook's frame in either symbol-name scheme among at least [`MIN_FRAMES`]
    /// numbered frames (`the_backtrace_check_reads_both_symbol_name_schemes`).
    #[test]
    fn rust_backtrace_adds_only_an_escaped_backtrace() {
        let dir = fixture();
        assert!(
            !is_plain(&format!("frame {}[2J", char::from(0x1b))),
            "control: the line check finds a raw ESC"
        );

        let off = run_mds(dir.path(), Some("main"), Backtrace::Set("0"), Stderr::Piped);
        assert_eq!(
            (off.code, off.stderr.as_str()),
            (Some(101), ICE_TEXT),
            "RUST_BACKTRACE=0 asks for no backtrace"
        );

        for value in ["1", "full"] {
            let run = run_mds(
                dir.path(),
                Some("main"),
                Backtrace::Set(value),
                Stderr::Piped,
            );
            assert_eq!(
                run.code,
                Some(101),
                "RUST_BACKTRACE={value}: a panic exits 101; stderr:\n{}",
                run.stderr
            );
            let backtrace = run.stderr.strip_prefix(ICE_TEXT).unwrap_or_else(|| {
                panic!(
                    "RUST_BACKTRACE={value}: stderr starts with the internal compiler error \
                     text; it was:\n{}",
                    run.stderr
                )
            });
            assert!(
                backtrace.starts_with(BACKTRACE_HEADER),
                "RUST_BACKTRACE={value}: the backtrace follows the text; stderr:\n{}",
                run.stderr
            );
            assert!(
                names_the_hook(backtrace),
                "RUST_BACKTRACE={value}: a real backtrace names the panic hook's frame, \
                 {HOOK_FRAME}; it was:\n{backtrace}"
            );
            assert!(
                numbered_frames(backtrace) >= MIN_FRAMES,
                "RUST_BACKTRACE={value}: a real backtrace shows at least {MIN_FRAMES} \
                 numbered frames; it was:\n{backtrace}"
            );
            for line in backtrace.split_terminator('\n') {
                assert!(
                    is_plain(line),
                    "RUST_BACKTRACE={value}: every backtrace line is escaped; got {line:?}"
                );
            }
            assert_shows_none(
                &run.stderr,
                &payload_needles(dir.path()),
                &format!("RUST_BACKTRACE={value}"),
            );
        }
    }

    /// A panic on a thread other than the one running the command ends the run: the text
    /// once, exit 101, within [`PANIC_EXIT_BOUND`]. Without the hook the thread would die
    /// alone, and the command would go on and pass.
    ///
    /// Control: without the trigger the same command passes.
    #[test]
    fn a_panic_on_another_thread_ends_the_run_with_the_text_once_and_exit_101() {
        let dir = fixture();
        let control = run_mds(dir.path(), None, Backtrace::Unset, Stderr::Piped);
        assert_eq!(
            (control.code, control.stderr.as_str()),
            (Some(0), "OK: ok.mds\n"),
            "control: without the trigger `mds check ok.mds` passes"
        );

        let run = run_mds(dir.path(), Some("thread"), Backtrace::Unset, Stderr::Piped);
        assert_eq!(
            run.code,
            Some(101),
            "a panic on another thread ends the run with 101; stderr:\n{}",
            run.stderr
        );
        assert_eq!(run.stderr, ICE_TEXT, "stderr is exactly the text");
        assert_eq!(
            count_occurrences(&run.stderr, "internal compiler error"),
            1,
            "the text is printed once"
        );
        assert!(
            run.took < PANIC_EXIT_BOUND,
            "the run ends within {PANIC_EXIT_BOUND:?} of the panic; it took {:?}",
            run.took
        );
        assert_eq!(run.stdout, "");
        assert_shows_none(&run.stderr, &payload_needles(dir.path()), "a thread panic");
        assert_shows_none(&run.stderr, &location_needles(), "a thread panic");
    }

    // ── A batch goes on past a file whose compile panics ──────────────────────
    //
    // Directory runs of `mds build`, `check`, `fmt` and `lint` over `d/a.mds`, `d/b.mds`
    // and `d/c.mds`, with the trigger panicking in `b.mds`'s compile, format or analysis.

    /// A working directory holding `d/a.mds`, `d/b.mds` and `d/c.mds`, each `source(name)`.
    fn batch(source: impl Fn(&str) -> String) -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("tempdir");
        let d = dir.path().join("d");
        std::fs::create_dir(&d).expect("create d");
        for name in ["a", "b", "c"] {
            std::fs::write(d.join(format!("{name}.mds")), source(name)).expect("write a source");
        }
        dir
    }

    /// `mds <args>` in `dir`, panicking in `b.mds` when `panic` is set.
    fn run_batch(dir: &Path, args: &[&str], panic: bool) -> Run {
        let panic_at = panic.then_some("compile:b");
        run_args(dir, args, panic_at, Backtrace::Unset, Stderr::Piped)
    }

    /// The text of `path`.
    fn read(path: &Path) -> String {
        std::fs::read_to_string(path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()))
    }

    /// What a batch run with one panic shows of it: exit 101, the text exactly once, and
    /// nothing of the payload on either stream.
    fn assert_one_panic(run: &Run, dir: &Path, what: &str) {
        assert_eq!(
            run.code,
            Some(101),
            "{what}: a panic in one file makes the run exit 101; stderr:\n{}",
            run.stderr
        );
        assert_eq!(
            count_occurrences(&run.stderr, ICE_TEXT),
            1,
            "{what}: the text is printed once, for the one panic; stderr:\n{}",
            run.stderr
        );
        assert_shows_none(&run.stderr, &payload_needles(dir), what);
        assert_shows_none(&run.stdout, &payload_needles(dir), what);
    }

    /// The lines of `stderr` that are neither a line of the text nor a line starting with
    /// one of `status`: what is left to report a panic a second time.
    fn other_lines<'a>(stderr: &'a str, status: &[&str]) -> Vec<&'a str> {
        let ice: Vec<&str> = ICE_TEXT.lines().collect();
        stderr
            .lines()
            .filter(|line| !ice.contains(line) && !status.iter().any(|s| line.starts_with(s)))
            .collect()
    }

    /// A source with one warning: a frontmatter key its body never uses.
    fn warned(name: &str) -> String {
        format!("---\nunused: 1\n---\nHello {name}\n")
    }

    /// `mds build <dir>` goes on past a file whose compile panics (#389): the other two are
    /// compiled and written, the one that panicked is not and counts as failed, and the text
    /// is the panic's one report.
    ///
    /// Control: without the trigger all three are written.
    #[test]
    fn a_directory_build_goes_on_past_a_file_whose_compile_panics() {
        let control_dir = batch(|name| format!("Hello {name}\n"));
        let control = run_batch(control_dir.path(), &["build", "d"], false);
        assert_eq!(
            control.code,
            Some(0),
            "control: stderr:\n{}",
            control.stderr
        );
        assert!(
            control.stderr.ends_with("3 built, 0 failed\n"),
            "control: stderr:\n{}",
            control.stderr
        );
        for name in ["a", "b", "c"] {
            let output = control_dir.path().join("d").join(format!("{name}.md"));
            assert_eq!(read(&output), format!("Hello {name}\n"), "control");
        }

        let dir = batch(|name| format!("Hello {name}\n"));
        let run = run_batch(dir.path(), &["build", "d"], true);
        assert_one_panic(&run, dir.path(), "build");
        let d = dir.path().join("d");
        for name in ["a", "c"] {
            assert_eq!(
                read(&d.join(format!("{name}.md"))),
                format!("Hello {name}\n"),
                "the other files are compiled and written"
            );
        }
        assert!(
            !d.join("b.md").exists(),
            "the file whose compile panicked is not written"
        );
        let compiled = run
            .stderr
            .lines()
            .filter(|line| line.starts_with("Compiled to "))
            .count();
        assert_eq!(compiled, 2, "stderr:\n{}", run.stderr);
        assert_eq!(
            other_lines(&run.stderr, &["Compiled to "]),
            ["2 built, 1 failed"],
            "the file counts as failed, and nothing but the text reports the panic"
        );
    }

    /// `mds check <dir>` goes on past a file whose check panics (#389): the other two are
    /// checked, the one that panicked counts as failed, and the text is the panic's one
    /// report.
    ///
    /// Control: without the trigger all three pass.
    #[test]
    fn a_directory_check_goes_on_past_a_file_whose_check_panics() {
        let dir = batch(|name| format!("Hello {name}\n"));
        let control = run_batch(dir.path(), &["check", "d"], false);
        assert_eq!(
            (control.code, control.stderr.as_str()),
            (Some(0), "3 passed, 0 failed\n"),
            "control"
        );

        let run = run_batch(dir.path(), &["check", "d"], true);
        assert_one_panic(&run, dir.path(), "check");
        assert_eq!(
            run.stderr,
            format!("{ICE_TEXT}2 passed, 1 failed\n"),
            "the other files are checked, the file counts as failed, and nothing but the \
             text reports the panic"
        );
    }

    /// `mds fmt <dir>` goes on past a file whose format panics (#389): the other two are
    /// rewritten, the one that panicked is left as it was and counts as failed, and the
    /// text is the panic's one report.
    ///
    /// Control: without the trigger all three are rewritten.
    #[test]
    fn a_directory_fmt_goes_on_past_a_file_whose_format_panics() {
        let unformatted = |name: &str| format!("Hello {name}\r\n");
        let control_dir = batch(unformatted);
        let control = run_batch(control_dir.path(), &["fmt", "d"], false);
        assert_eq!(
            control.code,
            Some(0),
            "control: stderr:\n{}",
            control.stderr
        );
        assert!(
            control
                .stderr
                .ends_with("3 formatted, 0 unchanged, 0 failed\n"),
            "control: stderr:\n{}",
            control.stderr
        );
        for name in ["a", "b", "c"] {
            let source = control_dir.path().join("d").join(format!("{name}.mds"));
            assert_eq!(read(&source), format!("Hello {name}\n"), "control");
        }

        let dir = batch(unformatted);
        let run = run_batch(dir.path(), &["fmt", "d"], true);
        assert_one_panic(&run, dir.path(), "fmt");
        let d = dir.path().join("d");
        for name in ["a", "c"] {
            assert_eq!(
                read(&d.join(format!("{name}.mds"))),
                format!("Hello {name}\n"),
                "the other files are formatted"
            );
        }
        assert_eq!(
            read(&d.join("b.mds")),
            unformatted("b"),
            "the file whose format panicked is left as it was"
        );
        assert_eq!(
            other_lines(&run.stderr, &["Formatted: "]),
            ["2 formatted, 0 unchanged, 1 failed"],
            "the file counts as failed, and nothing but the text reports the panic"
        );
    }

    /// `mds lint <dir>` goes on past a file whose analysis panics (#389): the other two are
    /// linted and show their findings, the one that panicked counts under "with errors",
    /// and nothing names it — the text is the panic's one report.
    ///
    /// Control: without the trigger each file's warning is shown, naming its file.
    #[test]
    fn a_directory_lint_goes_on_past_a_file_whose_analysis_panics() {
        let dir = batch(warned);
        let control = run_batch(dir.path(), &["lint", "d"], false);
        assert_eq!(
            control.code,
            Some(1),
            "control: stderr:\n{}",
            control.stderr
        );
        assert!(
            control
                .stderr
                .ends_with("0 clean, 3 with warnings, 0 with errors, 0 resource-limited\n"),
            "control: stderr:\n{}",
            control.stderr
        );
        for name in ["a.mds", "b.mds", "c.mds"] {
            assert!(
                control.stderr.contains(name),
                "control: a finding's frame names {name}; stderr:\n{}",
                control.stderr
            );
        }

        let run = run_batch(dir.path(), &["lint", "d"], true);
        assert_one_panic(&run, dir.path(), "lint");
        assert!(
            run.stderr
                .ends_with("0 clean, 2 with warnings, 1 with errors, 0 resource-limited\n"),
            "the file counts under \"with errors\"; stderr:\n{}",
            run.stderr
        );
        for name in ["a.mds", "c.mds"] {
            assert!(
                run.stderr.contains(name),
                "the other files are linted; stderr:\n{}",
                run.stderr
            );
        }
        for needle in ["b.mds", "mds::internal"] {
            assert!(
                !run.stderr.contains(needle),
                "nothing but the text reports the panic: {needle:?}; stderr:\n{}",
                run.stderr
            );
        }
    }

    /// `mds lint --format json <dir>` records a file whose analysis panicked as an internal
    /// error, in the one document the run prints, and counts it under "with errors" (#389):
    /// `{"file": …, "error": {"code": "mds::internal", "message": "internal compiler
    /// error", …}}` — nothing of the panic itself. The other two files are linted.
    ///
    /// Control: without the trigger each file's entry holds its warning.
    #[test]
    fn a_directory_lint_json_records_a_file_whose_analysis_panics_as_an_internal_error() {
        let dir = batch(warned);
        let args = ["lint", "--format", "json", "d"];
        let control = run_batch(dir.path(), &args, false);
        assert_eq!(
            (control.code, control.stderr.as_str()),
            (
                Some(1),
                "0 clean, 3 with warnings, 0 with errors, 0 resource-limited\n"
            ),
            "control"
        );
        let document: serde_json::Value =
            serde_json::from_str(&control.stdout).expect("control: stdout is one document");
        let files = document["files"].as_array().expect("control: files[]");
        assert_eq!(files.len(), 3, "control: {document}");
        for (entry, name) in files.iter().zip(["a.mds", "b.mds", "c.mds"]) {
            assert_eq!(entry["file"], name, "control: {document}");
            assert_eq!(
                entry["diagnostics"][0]["rule"], "unused-variable",
                "control: {document}"
            );
        }

        let run = run_batch(dir.path(), &args, true);
        assert_one_panic(&run, dir.path(), "lint --format json");
        assert_eq!(
            run.stderr,
            format!("{ICE_TEXT}0 clean, 2 with warnings, 1 with errors, 0 resource-limited\n"),
            "the file counts under \"with errors\", and stderr reports the panic only with \
             the text"
        );
        assert_eq!(
            run.stdout.lines().count(),
            1,
            "one document; stdout:\n{}",
            run.stdout
        );
        let document: serde_json::Value =
            serde_json::from_str(&run.stdout).expect("stdout is one document");
        assert_eq!(document["version"], 1, "{document}");
        assert_eq!(document["truncated"], false, "{document}");
        let files = document["files"].as_array().expect("files[]");
        assert_eq!(files.len(), 3, "an entry per file: {document}");
        assert_eq!(
            files[1],
            serde_json::json!({
                "file": "b.mds",
                "error": {
                    "code": "mds::internal",
                    "message": "internal compiler error",
                    "help": null,
                    "span": null,
                },
            }),
            "the file whose analysis panicked is an internal error: {document}"
        );
        for (entry, name) in [(&files[0], "a.mds"), (&files[2], "c.mds")] {
            assert_eq!(entry["file"], name, "{document}");
            assert_eq!(
                entry["diagnostics"][0]["rule"], "unused-variable",
                "the other files are linted: {document}"
            );
        }
    }

    /// `mds lint --fix`'s fix pipeline lints its candidate again, inside a catch (#389): a
    /// panic there leaves the file as it was and the run exits 101. Under `--format json`
    /// the run's one document is the error document with the internal error; in human
    /// output the text is the panic's one report. A file argument reaches the pipeline's
    /// catch: its own lint is not caught, and the trigger fires only in a catch.
    ///
    /// Control: without the trigger the fix is written.
    #[test]
    fn a_panic_in_the_fix_pipeline_leaves_the_file_as_it_was_and_reports_only_the_text() {
        const FIXABLE: &str = "@if \"a\" == \"a\":\n@end\n\nHello\n";
        let dir = tempfile::tempdir().expect("tempdir");
        let source = dir.path().join("x.mds");
        std::fs::write(&source, FIXABLE).expect("write x.mds");
        let control = run_args(
            dir.path(),
            &["lint", "--fix", "x.mds"],
            None,
            Backtrace::Unset,
            Stderr::Piped,
        );
        assert_eq!(
            (control.code, control.stderr.as_str()),
            (Some(0), "Fixed: x.mds\n"),
            "control"
        );
        assert_eq!(read(&source), "\nHello\n", "control: the fix is written");

        for format in ["json", "human"] {
            std::fs::write(&source, FIXABLE).expect("write x.mds");
            let run = run_args(
                dir.path(),
                &["lint", "--fix", "--format", format, "x.mds"],
                Some("compile:x"),
                Backtrace::Unset,
                Stderr::Piped,
            );
            assert_one_panic(&run, dir.path(), format);
            assert_eq!(
                run.stderr, ICE_TEXT,
                "{format}: the text is the panic's one report"
            );
            assert_eq!(
                read(&source),
                FIXABLE,
                "{format}: the file is left as it was"
            );
            let expected = match format {
                "json" => concat!(
                    "{\"error\":{\"code\":\"mds::internal\",\"help\":null,",
                    "\"message\":\"internal compiler error\",\"span\":null},\"version\":1}\n"
                ),
                _ => "",
            };
            assert_eq!(run.stdout, expected, "{format}: stdout");
        }
    }

    // ── A watch session goes on past a compile that panics ────────────────────

    /// Failure bound for one step of a watch session: going live, or what an edit leads
    /// to. A step takes milliseconds.
    const WATCH_STEP: Duration = Duration::from_secs(20);

    /// `mds watch --quiet --poll-interval 0 <args>` in `dir`, asking for a panic at
    /// `panic_at`, once it is live. `--quiet` leaves the panic's text the only thing on
    /// stderr, and without an idle tick only an edit starts a rebuild.
    fn watch_live(dir: &Path, args: &[&str], panic_at: Option<&str>) -> (ChildGuard, PipeTap) {
        let mut cmd = watch_command(dir, args, panic_at);
        cmd.env_remove(RUST_BACKTRACE);
        let (child, stderr, _) = spawn_watch_ready(&mut cmd);
        (ChildGuard(child), stderr)
    }

    /// [`watch_live`]'s session, not waited for: `ready` is the file it creates once it is
    /// live.
    fn watch_starting(
        dir: &Path,
        args: &[&str],
        panic_at: Option<&str>,
        ready: &Path,
    ) -> (ChildGuard, PipeTap) {
        let mut cmd = watch_command(dir, args, panic_at);
        cmd.env_remove(RUST_BACKTRACE).env("MDS_TEST_READY", ready);
        let (child, stderr, _) = spawn_watch_unsynchronized(&mut cmd);
        (ChildGuard(child), stderr)
    }

    /// The `mds watch` command [`watch_live`] and [`watch_starting`] spawn.
    fn watch_command(dir: &Path, args: &[&str], panic_at: Option<&str>) -> std::process::Command {
        let mut cmd = mds_bin();
        cmd.args(["watch", "--quiet", "--poll-interval", "0"])
            .args(args)
            .current_dir(dir)
            .stdin(Stdio::null())
            .stdout(Stdio::null());
        match panic_at {
            Some(at) => cmd.env(TRIGGER, at),
            None => cmd.env_remove(TRIGGER),
        };
        cmd
    }

    /// Ctrl-C the session, and return its exit code. Panics when it has not ended within
    /// [`WATCH_STEP`].
    ///
    /// Unix-only: it sends SIGINT with `libc::kill`; Windows has no way for a test to send
    /// one child process a Ctrl-C.
    #[cfg(unix)]
    fn interrupt(session: &mut ChildGuard) -> Option<i32> {
        let pid = libc::pid_t::try_from(session.id()).expect("a pid fits pid_t");
        // SAFETY: `kill` only sends a signal, to the child this test spawned and has not
        // reaped, so the pid names no other process.
        let sent = unsafe { libc::kill(pid, libc::SIGINT) };
        assert_eq!(sent, 0, "send SIGINT to the session");
        exit_code_within(session, WATCH_STEP)
    }

    /// The session's exit code once it ends, within `bound`; panics when it has not.
    ///
    /// Unix-only: [`interrupt`] is its only caller.
    #[cfg(unix)]
    fn exit_code_within(session: &mut ChildGuard, bound: Duration) -> Option<i32> {
        let deadline = Instant::now() + bound;
        loop {
            if let Some(status) = session.0.try_wait().expect("poll the session") {
                return status.code();
            }
            assert!(
                Instant::now() < deadline,
                "the session did not end within {bound:?}"
            );
            std::thread::sleep(POLL);
        }
    }

    /// Whether the session is still running.
    fn running(session: &mut ChildGuard) -> bool {
        session.0.try_wait().expect("poll the session").is_none()
    }

    /// Wait until `path` holds `text`, within [`WATCH_STEP`]; when it does not, `what`
    /// fails, said with what the file holds by then and the watcher's `stderr` so far —
    /// where a write it could not make, or anything else it printed, shows.
    #[track_caller]
    fn assert_file_comes_to_hold(path: &Path, text: &str, stderr: &PipeTap, what: &str) {
        let deadline = Instant::now() + WATCH_STEP;
        loop {
            let now = std::fs::read_to_string(path);
            if now.as_deref().is_ok_and(|now| now == text) {
                return;
            }
            assert!(
                Instant::now() < deadline,
                "{what}: {} did not come to hold {text:?} within {WATCH_STEP:?} (it holds \
                 {now:?}); the watcher's stderr so far:\n{}",
                path.display(),
                stderr.text()
            );
            std::thread::sleep(POLL);
        }
    }

    /// A quiet session's whole stderr after `panics` or more panics: the text, once per
    /// panic, and nothing else.
    fn assert_only_the_text(stderr: &str, panics: usize, what: &str) {
        let printed = count_occurrences(stderr, ICE_TEXT);
        assert!(
            printed >= panics,
            "{what}: the text for each of at least {panics} panics; stderr:\n{stderr}"
        );
        assert_eq!(
            stderr,
            ICE_TEXT.repeat(printed),
            "{what}: the text once per panic, and nothing else"
        );
    }

    /// `mds watch <file>` whose compile panics goes on watching (#389): the startup compile
    /// prints the text, an edit starts a rebuild that prints it again, and the session
    /// stays live. No output is written, and nothing but the text reports a panic. The
    /// session is killed: its exit code at Ctrl-C is
    /// [`a_watch_session_that_caught_a_compile_panic_exits_101_at_ctrl_c`]'s to pin.
    ///
    /// Control: without the trigger the session writes the output and rebuilds it on the
    /// edit.
    #[test]
    fn a_watched_file_whose_compile_panics_is_watched_on() {
        let control_dir = tempfile::tempdir().expect("tempdir");
        let source = control_dir.path().join("x.mds");
        std::fs::write(&source, "Hello\n").expect("write x.mds");
        let (mut control, stderr) = watch_live(control_dir.path(), &["x.mds"], None);
        let output = control_dir.path().join("x.md");
        assert_file_comes_to_hold(&output, "Hello\n", &stderr, "control: the output");
        write_atomic(&source, "Hello again\n");
        assert_file_comes_to_hold(
            &output,
            "Hello again\n",
            &stderr,
            "control: the edit rebuilds",
        );
        assert_eq!(stderr.finish_text(&mut control), "", "control: --quiet");

        let dir = tempfile::tempdir().expect("tempdir");
        let source = dir.path().join("x.mds");
        std::fs::write(&source, "Hello\n").expect("write x.mds");
        let (mut session, stderr) = watch_live(dir.path(), &["x.mds"], Some("compile:x"));
        let before = count_occurrences(
            &wait_for_tap_count(&stderr, ICE_TEXT, 1, WATCH_STEP),
            ICE_TEXT,
        );
        write_atomic(&source, "Hello again\n");
        wait_for_tap_count(&stderr, ICE_TEXT, before + 1, WATCH_STEP);
        assert!(
            running(&mut session),
            "a compile that panics does not end the session"
        );
        assert_only_the_text(&stderr.finish_text(&mut session), before + 1, "file");
        assert!(
            !dir.path().join("x.md").exists(),
            "a compile that panicked writes no output"
        );
    }

    /// `mds watch <dir>` goes on past a source whose compile panics (#389): the startup
    /// writes the other source's output, an edit to it rebuilds it, and the session stays
    /// live. Nothing but the text reports a panic. The session is killed: its exit code at
    /// Ctrl-C is [`a_watch_session_that_caught_a_compile_panic_exits_101_at_ctrl_c`]'s to
    /// pin.
    ///
    /// Control: without the trigger both outputs are written and the edit rebuilds.
    #[test]
    fn a_watched_directory_goes_on_past_a_source_whose_compile_panics() {
        let sources = || {
            let dir = tempfile::tempdir().expect("tempdir");
            let d = dir.path().join("d");
            std::fs::create_dir(&d).expect("create d");
            for name in ["a", "b"] {
                std::fs::write(d.join(format!("{name}.mds")), format!("Hello {name}\n"))
                    .expect("write a source");
            }
            dir
        };

        let control_dir = sources();
        let d = control_dir.path().join("d");
        let (mut control, stderr) = watch_live(control_dir.path(), &["d"], None);
        for name in ["a", "b"] {
            assert_file_comes_to_hold(
                &d.join(format!("{name}.md")),
                &format!("Hello {name}\n"),
                &stderr,
                &format!("control: {name}.md"),
            );
        }
        write_atomic(&d.join("b.mds"), "Hello again b\n");
        assert_file_comes_to_hold(
            &d.join("b.md"),
            "Hello again b\n",
            &stderr,
            "control: the edit rebuilds",
        );
        assert_eq!(stderr.finish_text(&mut control), "", "control: --quiet");

        let dir = sources();
        let d = dir.path().join("d");
        let (mut session, stderr) = watch_live(dir.path(), &["d"], Some("compile:a"));
        wait_for_tap_count(&stderr, ICE_TEXT, 1, WATCH_STEP);
        assert_file_comes_to_hold(
            &d.join("b.md"),
            "Hello b\n",
            &stderr,
            "the startup compiles the other source",
        );
        write_atomic(&d.join("b.mds"), "Hello again b\n");
        assert_file_comes_to_hold(
            &d.join("b.md"),
            "Hello again b\n",
            &stderr,
            "an edit after the panic rebuilds",
        );
        assert!(
            running(&mut session),
            "a compile that panics does not end the session"
        );
        assert_only_the_text(&stderr.finish_text(&mut session), 1, "directory");
        assert!(
            !d.join("a.md").exists(),
            "a compile that panicked writes no output"
        );
    }

    /// A watch session that caught a panic compiling a source exits 101 when Ctrl-C stops
    /// it, watching a file or a directory (#389); nothing but the text reports the panic.
    ///
    /// Control: without the trigger Ctrl-C stops the session with 0.
    ///
    /// Unix-only: Ctrl-C is SIGINT sent by [`interrupt`]; what needs no Ctrl-C runs on every
    /// OS in [`a_watched_file_whose_compile_panics_is_watched_on`] and
    /// [`a_watched_directory_goes_on_past_a_source_whose_compile_panics`].
    #[cfg(unix)]
    #[test]
    fn a_watch_session_that_caught_a_compile_panic_exits_101_at_ctrl_c() {
        for watched in [Watched::File, Watched::Directory] {
            let fixture = WatchFixture::new(watched);
            let (mut control, stderr) = watch_live(fixture.dir(), fixture.args(), None);
            assert_eq!(interrupt(&mut control), Some(0), "control ({watched:?})");
            assert_eq!(
                stderr.finish_text(&mut control),
                "",
                "control ({watched:?}): --quiet"
            );

            let fixture = WatchFixture::new(watched);
            let (mut session, stderr) =
                watch_live(fixture.dir(), fixture.args(), Some("compile:x"));
            wait_for_tap_count(&stderr, ICE_TEXT, 1, WATCH_STEP);
            assert_eq!(
                interrupt(&mut session),
                Some(101),
                "{watched:?}: stopped, a session that caught a panic exits 101"
            );
            assert_only_the_text(
                &stderr.finish_text(&mut session),
                1,
                &format!("{watched:?}"),
            );
        }
    }

    // ── A panic on a watch session's own threads ends it at once ──────────────

    /// How `mds watch` is started for a test that runs it both ways: on a file, or on a
    /// directory.
    #[derive(Clone, Copy, Debug)]
    enum Watched {
        File,
        Directory,
    }

    /// A working directory for a [`Watched`] session: `x.mds`, or `d/x.mds`.
    struct WatchFixture {
        dir: tempfile::TempDir,
        watched: Watched,
    }

    impl WatchFixture {
        fn new(watched: Watched) -> Self {
            let dir = tempfile::tempdir().expect("tempdir");
            let fixture = Self { dir, watched };
            if let Some(parent) = fixture.source().parent() {
                std::fs::create_dir_all(parent).expect("create the source's directory");
            }
            std::fs::write(fixture.source(), "Hello\n").expect("write the source");
            fixture
        }

        fn dir(&self) -> &Path {
            self.dir.path()
        }

        /// What `mds watch` is given.
        fn args(&self) -> &'static [&'static str] {
            match self.watched {
                Watched::File => &["x.mds"],
                Watched::Directory => &["d"],
            }
        }

        fn source(&self) -> PathBuf {
            match self.watched {
                Watched::File => self.dir().join("x.mds"),
                Watched::Directory => self.dir().join("d").join("x.mds"),
            }
        }

        fn output_file(&self) -> PathBuf {
            self.source().with_extension("md")
        }
    }

    /// A panic in `mds watch`'s Ctrl-C handler, which runs on a thread of its own, ends the
    /// session at once (#389): the text once and exit 101 — not the 0 of a session Ctrl-C
    /// stopped — within [`PANIC_EXIT_BOUND`].
    ///
    /// Control: without the trigger Ctrl-C stops the session with 0.
    ///
    /// Unix-only: the panic is raised by the Ctrl-C a test sends as SIGINT ([`interrupt`]),
    /// which it cannot send one child process on Windows.
    #[cfg(unix)]
    #[test]
    fn a_panic_in_the_watch_ctrl_c_handler_ends_the_session_with_101() {
        for watched in [Watched::File, Watched::Directory] {
            let fixture = WatchFixture::new(watched);
            let (mut control, stderr) = watch_live(fixture.dir(), fixture.args(), None);
            assert_eq!(interrupt(&mut control), Some(0), "control ({watched:?})");
            assert_eq!(
                stderr.finish_text(&mut control),
                "",
                "control ({watched:?})"
            );

            let (mut session, stderr) = watch_live(fixture.dir(), fixture.args(), Some("ctrlc"));
            let started = Instant::now();
            assert_eq!(
                interrupt(&mut session),
                Some(101),
                "{watched:?}: a panic in the Ctrl-C handler ends the session with 101"
            );
            assert!(
                started.elapsed() < PANIC_EXIT_BOUND,
                "{watched:?}: at once; it took {:?}",
                started.elapsed()
            );
            assert_eq!(
                stderr.finish_text(&mut session),
                ICE_TEXT,
                "{watched:?}: the text, once"
            );
        }
    }

    /// A panic in `mds watch`'s file-event callback, which runs on notify's thread, ends the
    /// session at once (#389): the text once and exit 101, within [`PANIC_EXIT_BOUND`] of
    /// the event. Without that the thread would die alone, and the session would watch on
    /// without its events. The session's own startup write can be the first event;
    /// otherwise an edit is.
    ///
    /// Control: without the trigger an edit reaches the callback and rebuilds; that session
    /// is then killed, its exit code no part of the control.
    #[test]
    fn a_panic_in_the_watch_file_event_callback_ends_the_session_with_101() {
        for watched in [Watched::File, Watched::Directory] {
            let fixture = WatchFixture::new(watched);
            let (mut control, stderr) = watch_live(fixture.dir(), fixture.args(), None);
            assert_file_comes_to_hold(
                &fixture.output_file(),
                "Hello\n",
                &stderr,
                &format!("control ({watched:?})"),
            );
            write_atomic(&fixture.source(), "Hello again\n");
            assert_file_comes_to_hold(
                &fixture.output_file(),
                "Hello again\n",
                &stderr,
                &format!("control ({watched:?}): the edit reaches the callback"),
            );
            assert_eq!(
                stderr.finish_text(&mut control),
                "",
                "control ({watched:?})"
            );

            let fixture = WatchFixture::new(watched);
            let ready_dir = tempfile::tempdir().expect("tempdir");
            let ready = ready_dir.path().join("watch-ready");
            let (mut session, stderr) =
                watch_starting(fixture.dir(), fixture.args(), Some("notify"), &ready);
            let deadline = Instant::now() + WATCH_STEP;
            let mut since = Instant::now();
            let mut edited = false;
            let code = loop {
                if let Some(status) = session.0.try_wait().expect("poll the session") {
                    break status.code();
                }
                if !edited && ready.exists() {
                    write_atomic(&fixture.source(), "Hello again\n");
                    since = Instant::now();
                    edited = true;
                }
                assert!(
                    Instant::now() < deadline,
                    "{watched:?}: a panic in the file-event callback must end the session; \
                     it was still running after {WATCH_STEP:?} (edited: {edited}); \
                     stderr:\n{}",
                    stderr.text()
                );
                std::thread::sleep(POLL);
            };
            assert!(
                since.elapsed() < PANIC_EXIT_BOUND,
                "{watched:?}: at once; it took {:?}",
                since.elapsed()
            );
            assert_eq!(
                code,
                Some(101),
                "{watched:?}: a panic in the file-event callback ends the session with 101"
            );
            assert_eq!(
                stderr.finish_text(&mut session),
                ICE_TEXT,
                "{watched:?}: the text, once"
            );
        }
    }
}

/// With the never-shipped `debug-panics` feature: the panic's message and location follow
/// the text, escaped.
#[cfg(feature = "debug-panics")]
mod with_debug_panics {
    use super::*;

    /// The six-character escape the CLI writes in place of `ch` (a backslash, `u` and four
    /// hex digits), built at runtime.
    fn escaped(ch: char) -> String {
        format!("{}u{:04X}", '\\', u32::from(ch))
    }

    /// The payload the default tests look for is the one the trigger panics with: its
    /// sentinel, its ESC (escaped) and the working directory's path follow the text, with
    /// the location of the panic.
    #[test]
    fn the_message_and_location_follow_the_text_escaped() {
        let dir = fixture();
        let run = run_mds(dir.path(), Some("main"), Backtrace::Unset, Stderr::Piped);
        assert_eq!(run.code, Some(101), "stderr:\n{}", run.stderr);
        let detail = run.stderr.strip_prefix(ICE_TEXT).unwrap_or_else(|| {
            panic!(
                "stderr starts with the internal compiler error text; it was:\n{}",
                run.stderr
            )
        });
        let canonical = dir.path().canonicalize().expect("canonicalize");
        for needle in [
            SENTINEL.to_string(),
            escaped(char::from(0x1b)),
            canonical.display().to_string(),
            "output.rs".to_string(),
        ] {
            assert!(
                detail.contains(needle.as_str()),
                "the detail shows {needle:?}; it was:\n{detail}"
            );
        }
        assert!(
            !run.stderr.contains(char::from(0x1b)),
            "the detail is escaped; stderr:\n{}",
            run.stderr
        );
    }
}

// ── Lexical pins ──────────────────────────────────────────────────────────────

/// Every run here sets or removes `RUST_BACKTRACE`: the function holding a `.spawn(` /
/// `.output(` / `.status(` call, or a call of a shared helper that spawns `mds watch`
/// ([`SPAWN_HELPERS`]), also calls `env(RUST_BACKTRACE, …)` or
/// `env_remove(RUST_BACKTRACE)` in code, not in a comment. CI sets `RUST_BACKTRACE=1`
/// globally, which would otherwise flip every arm that expects no backtrace.
#[test]
fn every_run_sets_or_removes_rust_backtrace() {
    let own = read_source("tests/panic_hook.rs");
    let found = runs_without_rust_backtrace(&own);
    assert!(
        found.runs >= 1,
        "non-vacuity: panic_hook.rs starts a process somewhere"
    );
    assert!(
        found.stray.is_empty(),
        "a run in panic_hook.rs leaves RUST_BACKTRACE to the environment, at lines {:?}",
        found.stray
    );

    // Controls: a run that never names it, and one that names it only in a comment, are
    // reported; a run that sets it or removes it is not.
    let bare = "fn f() {\n    let _ = mds_bin().spawn();\n}\n";
    assert_eq!(runs_without_rust_backtrace(bare).stray, vec![2]);
    let commented =
        "fn f() {\n    // cmd.env_remove(RUST_BACKTRACE);\n    let _ = cmd.output();\n}\n";
    assert_eq!(runs_without_rust_backtrace(commented).stray, vec![3]);
    let set = "fn f() {\n    cmd.env(RUST_BACKTRACE, \"1\");\n    let _ = cmd.status();\n}\n";
    assert_eq!(runs_without_rust_backtrace(set).stray, Vec::<usize>::new());
    let removed = "fn f() {\n    cmd.env_remove(RUST_BACKTRACE);\n    let _ = cmd.spawn();\n}\n";
    assert_eq!(
        runs_without_rust_backtrace(removed).stray,
        Vec::<usize>::new()
    );
    for helper in SPAWN_HELPERS {
        let bare = format!("fn f() {{\n    let _ = {helper}&mut cmd);\n}}\n");
        assert_eq!(
            runs_without_rust_backtrace(&bare).stray,
            vec![2],
            "a bare `{helper}` must be reported"
        );
        let removed = format!(
            "fn f() {{\n    cmd.env_remove(RUST_BACKTRACE);\n    let _ = {helper}&mut cmd);\n}}\n"
        );
        assert_eq!(
            runs_without_rust_backtrace(&removed).stray,
            Vec::<usize>::new()
        );
    }
}

/// The helpers of `tests/common` that spawn `mds watch`, as a call starts.
const SPAWN_HELPERS: &[&str] = &[
    "spawn_watch_ready(",
    "spawn_watch_unsynchronized(",
    "spawn_watch_ready_stderr_untapped(",
];

/// The panic hook — `on_panic` in `src/output.rs` — records the panic before anything
/// else, then writes one constant and nothing about the panic: exactly one `write_all`,
/// of `ICE_TEXT`; no print or format macro, no miette, no `.payload()` or `.location()`,
/// nothing that can panic; the hook's `PanicHookInfo` named only on the lines the
/// `debug-panics` feature gates. `main` installs it first. The panic machinery stays
/// where [`CLI_PANIC_MACHINERY`] and [`CORE_PANIC_MACHINERY`] list it: only
/// `install_panic_hook` sets a hook and only `catch_panic` catches a panic, so no catch
/// site can report one a second time, and nothing unwinds without the hook.
///
/// Controls: each of those, planted into the real hook's body or the real sources, is
/// reported.
#[test]
fn the_hook_writes_one_constant_and_nothing_about_the_panic() {
    let output = read_source("src/output.rs");
    let found = hook_findings(&output);
    assert!(
        found.is_empty(),
        "the panic hook must write only the internal compiler error text:\n{}",
        found.join("\n")
    );

    const ICE_WRITE: &str = "let _ = stderr.write_all(ICE_TEXT.as_bytes());";
    assert!(
        output.contains(ICE_WRITE),
        "precondition: the hook writes the text with `{ICE_WRITE}`"
    );
    for plant in [
        "eprintln!(\"planted\");",
        "crate::output::ewriteln!(\"planted\");",
        "let _ = format!(\"planted\");",
        "let _ = std::fmt::Write::write_fmt(&mut text, format_args!(\"planted\"));",
        "miette::miette!(\"planted\");",
        "let _ = info.payload();",
        "let _ = info.location();",
        "let _ = stderr.write_all(b\"planted\");",
        "let _ = std::io::stderr().lock().unwrap();",
    ] {
        let planted = output.replacen(ICE_WRITE, &format!("{ICE_WRITE}\n    {plant}"), 1);
        assert!(
            !hook_findings(&planted).is_empty(),
            "`{plant}` planted in the hook must be reported"
        );
    }
    let not_constant = output.replacen(ICE_WRITE, "let _ = stderr.write_all(text.as_bytes());", 1);
    assert!(
        !hook_findings(&not_constant).is_empty(),
        "a hook that writes anything but ICE_TEXT must be reported"
    );
    // The panic recorded after the write: a hook blocked in the write would leave the
    // run to exit without it.
    const RECORD: &str = "OUTPUT_STATE.note_panicked();\n";
    let record_last = output.replacen(RECORD, "", 1).replacen(
        ICE_WRITE,
        &format!("{ICE_WRITE}\n    {RECORD}"),
        1,
    );
    assert_ne!(
        record_last, output,
        "precondition: the hook records the panic with `{RECORD}`"
    );
    assert!(
        !hook_findings(&record_last).is_empty(),
        "a hook that writes before it records the panic must be reported"
    );

    // Installed first in `main`.
    let main = read_source("src/main.rs");
    let main_code = blank(&main, true);
    let body = fn_body(&main_code, "main").expect("main.rs defines `fn main`");
    let first = main_code[*body.start() + 1..].trim_start();
    assert!(
        first.starts_with("output::install_panic_hook();"),
        "`main` installs the panic hook before anything else; its body starts:\n{}",
        &first[..first.len().min(120)]
    );

    // The panic machinery, in mds-cli and in mds-core, whose code runs inside the CLI's
    // catch.
    let cli = crate_sources();
    let core = core_sources();
    for (krate, sources, allowed) in [
        ("mds-cli", &cli, CLI_PANIC_MACHINERY),
        ("mds-core", &core, CORE_PANIC_MACHINERY),
    ] {
        let found = machinery_findings(sources, allowed);
        assert!(
            found.is_empty(),
            "{krate}: the panic machinery must stay where it is listed:\n{}",
            found.join("\n")
        );
    }
    let plant = |sources: &[(String, String)], file: &str, body: &str| {
        plant_in(sources, file, |text| {
            text.push_str(&format!("\nfn planted() {{\n    {body}\n}}\n"));
        })
    };
    let missed: Vec<&str> = [
        (
            machinery_findings(
                &plant(&cli, "main.rs", "std::panic::resume_unwind(Box::new(0u8));"),
                CLI_PANIC_MACHINERY,
            ),
            "a `resume_unwind` in main.rs",
        ),
        (
            machinery_findings(
                &plant(
                    &cli,
                    "output.rs",
                    "let _ = std::panic::catch_unwind(|| ());",
                ),
                CLI_PANIC_MACHINERY,
            ),
            "a second `catch_unwind` in output.rs",
        ),
        (
            machinery_findings(
                &plant(&cli, "watch.rs", "let _ = std::panic::take_hook();"),
                CLI_PANIC_MACHINERY,
            ),
            "a `take_hook` in watch.rs",
        ),
        (
            machinery_findings(
                &plant(&core, "lib.rs", "let _ = std::panic::catch_unwind(|| ());"),
                CORE_PANIC_MACHINERY,
            ),
            "a `catch_unwind` in mds-core's lib.rs",
        ),
        (
            machinery_findings(
                &plant(&core, "lib.rs", "std::panic::set_hook(Box::new(|_| ()));"),
                CORE_PANIC_MACHINERY,
            ),
            "a `set_hook` in mds-core's lib.rs",
        ),
        (
            machinery_findings(
                &plant(&core, "lib.rs", "std::panic::resume_unwind(Box::new(0u8));"),
                CORE_PANIC_MACHINERY,
            ),
            "a `resume_unwind` in mds-core's lib.rs",
        ),
        (
            machinery_findings(
                &cli,
                &[
                    CLI_PANIC_MACHINERY,
                    &[("take_hook", "output.rs", "install_panic_hook")],
                ]
                .concat(),
            ),
            "a listed place that does not name its function",
        ),
    ]
    .into_iter()
    .filter(|(found, _)| found.is_empty())
    .map(|(_, what)| what)
    .collect();
    assert!(
        missed.is_empty(),
        "each of these must be reported; missed: {missed:?}"
    );
}

/// The trigger compiles only into a debug build: every mention of `MDS_TEST_PANIC` and
/// every `panic_any` in the crate sit inside `mod panic_trigger`, whose attributes hold
/// `#[cfg(debug_assertions)]`; each of its functions ([`TRIGGER_FNS`]) has a release
/// build's stub that does nothing. The payload the module builds carries the sentinel
/// these tests look for.
///
/// Controls: the module without its `cfg`, a mention outside it, a release stub that does
/// something, for the dispatch's trigger and for the compile's, and a trigger function
/// without a release stub are each reported.
#[test]
fn the_trigger_is_compiled_only_into_debug_builds() {
    let output = read_source("src/output.rs");
    let sources = crate_sources();
    let found = trigger_findings(&sources);
    assert!(
        found.is_empty(),
        "the panic trigger must be compiled only into debug builds:\n{}",
        found.join("\n")
    );

    let with_literals = blank(&output, false);
    let module = mod_body(&blank(&output, true), "panic_trigger")
        .expect("output.rs holds `mod panic_trigger`");
    let module_text = &with_literals[module];
    for needle in [
        format!("\"{SENTINEL}\""),
        "0x1b".to_string(),
        "current_dir".to_string(),
    ] {
        assert!(
            module_text.contains(needle.as_str()),
            "the trigger's payload is built from {needle}"
        );
    }

    let with = |from: &str, to: &str| -> Vec<(String, String)> {
        let planted = output.replacen(from, to, 1);
        assert_ne!(planted, output, "precondition: output.rs holds {from:?}");
        sources
            .iter()
            .map(|(name, src)| {
                let src = if name == "output.rs" { &planted } else { src };
                (name.clone(), src.clone())
            })
            .collect()
    };
    let ungated = with(
        "#[cfg(debug_assertions)]\nmod panic_trigger",
        "mod panic_trigger",
    );
    assert!(
        !trigger_findings(&ungated).is_empty(),
        "a trigger module without `#[cfg(debug_assertions)]` must be reported"
    );
    let outside = with(
        "pub(crate) fn panic_on_request() {}",
        "pub(crate) fn panic_on_request() {\n    let _ = std::env::var_os(\"MDS_TEST_PANIC\");\n}",
    );
    assert!(
        !trigger_findings(&outside).is_empty(),
        "a trigger outside the module must be reported"
    );
    let busy_stub = with(
        "pub(crate) fn panic_on_request() {}",
        "pub(crate) fn panic_on_request() {\n    let _ = 1;\n}",
    );
    assert!(
        !trigger_findings(&busy_stub).is_empty(),
        "a release stub that does anything must be reported"
    );
    let busy_compile_stub = with(
        "fn panic_on_compile(_label: &Path) {}",
        "fn panic_on_compile(_label: &Path) {\n    let _ = 1;\n}",
    );
    assert!(
        !trigger_findings(&busy_compile_stub).is_empty(),
        "a compile trigger's release stub that does anything must be reported"
    );
    let no_stub = with("pub(crate) fn panic_in_handler(_handler: &str) {}", "");
    assert!(
        !trigger_findings(&no_stub).is_empty(),
        "a trigger function without a release stub must be reported"
    );
}

/// The pause between a rewrite's read and its replace (#160) compiles only into a debug
/// build, as the panic trigger does: every mention of `MDS_TEST_PAUSE_BEFORE_REPLACE` sits
/// inside `mod pause_trigger`, whose attributes hold `#[cfg(debug_assertions)]`, and
/// `pause_before_replace` has a release build's stub that does nothing.
///
/// Controls: the module without its `cfg`, a mention outside it, a release stub that does
/// something, and no release stub are each reported.
#[test]
fn the_pause_before_a_replace_is_compiled_only_into_debug_builds() {
    let write = read_source("src/write.rs");
    let sources = crate_sources();
    let found = gate_findings(&sources, &PAUSE_TRIGGER);
    assert!(
        found.is_empty(),
        "the pause before a replace must be compiled only into debug builds:\n{}",
        found.join("\n")
    );

    let with = |from: &str, to: &str| -> Vec<(String, String)> {
        let planted = write.replacen(from, to, 1);
        assert_ne!(planted, write, "precondition: write.rs holds {from:?}");
        sources
            .iter()
            .map(|(name, src)| {
                let src = if name == "write.rs" { &planted } else { src };
                (name.clone(), src.clone())
            })
            .collect()
    };
    let stub = "pub(crate) fn pause_before_replace() {}";
    for (planted, what) in [
        (
            with(
                "#[cfg(debug_assertions)]\nmod pause_trigger",
                "mod pause_trigger",
            ),
            "a pause module without `#[cfg(debug_assertions)]`",
        ),
        (
            with(
                stub,
                "pub(crate) fn pause_before_replace() {\n    \
                 let _ = std::env::var_os(\"MDS_TEST_PAUSE_BEFORE_REPLACE\");\n}",
            ),
            "the pause's variable outside its module",
        ),
        (
            with(
                stub,
                "pub(crate) fn pause_before_replace() {\n    let _ = 1;\n}",
            ),
            "a release stub that does something",
        ),
        (with(stub, ""), "a pause without a release stub"),
    ] {
        assert!(
            !gate_findings(&planted, &PAUSE_TRIGGER).is_empty(),
            "{what} must be reported"
        );
    }
}

#[test]
fn the_pause_after_a_walk_is_compiled_only_into_debug_builds() {
    let output = read_source("src/output.rs");
    let sources = crate_sources();
    let gate = DebugGate {
        module: "walk_pause_trigger",
        needles: &[("MDS_TEST_PAUSE_AFTER_WALK", true)],
        fns: &["pause_after_walk"],
    };
    let found = gate_findings(&sources, &gate);
    assert!(found.is_empty(), "{}", found.join("\n"));

    let stub = "pub(crate) fn pause_after_walk() {}";
    for (from, to) in [
        (
            "#[cfg(debug_assertions)]\nmod walk_pause_trigger",
            "mod walk_pause_trigger",
        ),
        (
            stub,
            "pub(crate) fn pause_after_walk() { let _ = std::env::var_os(\"MDS_TEST_PAUSE_AFTER_WALK\"); }",
        ),
        (stub, "pub(crate) fn pause_after_walk() { let _ = 1; }"),
        (stub, ""),
    ] {
        let planted = output.replacen(from, to, 1);
        assert_ne!(planted, output, "precondition: output.rs holds {from:?}");
        let planted_sources: Vec<_> = sources
            .iter()
            .map(|(name, src)| {
                let src = if name == "output.rs" { &planted } else { src };
                (name.clone(), src.clone())
            })
            .collect();
        assert!(!gate_findings(&planted_sources, &gate).is_empty());
    }
}

/// The pause between a directory watch batch's split and its compile (#160), the pause
/// between a watch rebuild's look and its reads (#380) and the pause between a file
/// rebuild's reads and its baseline (#380), the pause before a watch compile, and the pause
/// between a rebuild's reads and its late look (#380) compile only into a debug build, as
/// the pause before a replace does: every mention of `MDS_TEST_PAUSE_AFTER_BATCH_SPLIT`,
/// `MDS_TEST_PAUSE_AFTER_LOOK`, `MDS_TEST_PAUSE_AFTER_READ`,
/// `MDS_TEST_PAUSE_BEFORE_WATCH_COMPILE` and `MDS_TEST_PAUSE_BEFORE_LATE_LOOK` sits inside
/// `mod batch_pause_trigger`, whose attributes hold `#[cfg(debug_assertions)]`, and each
/// pause function has a release build's stub that does nothing.
///
/// Controls: the module without its `cfg`, a mention of any of the variables outside it, a
/// release stub that does something, and no release stub for any of the pauses are each
/// reported.
#[test]
fn the_pause_after_a_batch_split_is_compiled_only_into_debug_builds() {
    let watch = read_source("src/watch.rs");
    let sources = crate_sources();
    let found = gate_findings(&sources, &BATCH_PAUSE_TRIGGER);
    assert!(
        found.is_empty(),
        "the pauses after a batch's split, after a rebuild's look, after a file \
         rebuild's reads, before a watch compile and before a late look must be compiled \
         only into debug builds:\n{}",
        found.join("\n")
    );

    let with = |from: &str, to: &str| -> Vec<(String, String)> {
        let planted = watch.replacen(from, to, 1);
        assert_ne!(planted, watch, "precondition: watch.rs holds {from:?}");
        sources
            .iter()
            .map(|(name, src)| {
                let src = if name == "watch.rs" { &planted } else { src };
                (name.clone(), src.clone())
            })
            .collect()
    };
    let stub = "fn pause_after_batch_split() {}";
    let look_stub = "fn pause_after_look() {}";
    let read_stub = "fn pause_after_read() {}";
    let compile_stub = "fn pause_before_compile() {}";
    let late_stub = "fn pause_before_late_look() {}";
    for (planted, what) in [
        (
            with(
                "#[cfg(debug_assertions)]\nmod batch_pause_trigger",
                "mod batch_pause_trigger",
            ),
            "a pause module without `#[cfg(debug_assertions)]`",
        ),
        (
            with(
                stub,
                "fn pause_after_batch_split() {\n    \
                 let _ = std::env::var_os(\"MDS_TEST_PAUSE_AFTER_BATCH_SPLIT\");\n}",
            ),
            "the pause's variable outside its module",
        ),
        (
            with(stub, "fn pause_after_batch_split() {\n    let _ = 1;\n}"),
            "a release stub that does something",
        ),
        (with(stub, ""), "a pause without a release stub"),
        (
            with(
                look_stub,
                "fn pause_after_look() {\n    \
                 let _ = std::env::var_os(\"MDS_TEST_PAUSE_AFTER_LOOK\");\n}",
            ),
            "the look pause's variable outside its module",
        ),
        (with(look_stub, ""), "a look pause without a release stub"),
        (
            with(
                read_stub,
                "fn pause_after_read() {\n    \
                 let _ = std::env::var_os(\"MDS_TEST_PAUSE_AFTER_READ\");\n}",
            ),
            "the read pause's variable outside its module",
        ),
        (with(read_stub, ""), "a read pause without a release stub"),
        (
            with(
                compile_stub,
                "fn pause_before_compile() {\n    \
                 let _ = std::env::var_os(\"MDS_TEST_PAUSE_BEFORE_WATCH_COMPILE\");\n}",
            ),
            "the compile pause's variable outside its module",
        ),
        (
            with(compile_stub, "fn pause_before_compile() { let _ = 1; }"),
            "a compile release stub that does something",
        ),
        (
            with(compile_stub, ""),
            "a compile pause without a release stub",
        ),
        (
            with(
                late_stub,
                "fn pause_before_late_look() {\n    \
                 let _ = std::env::var_os(\"MDS_TEST_PAUSE_BEFORE_LATE_LOOK\");\n}",
            ),
            "the late-look pause's variable outside its module",
        ),
        (
            with(late_stub, "fn pause_before_late_look() { let _ = 1; }"),
            "a late-look release stub that does something",
        ),
        (
            with(late_stub, ""),
            "a late-look pause without a release stub",
        ),
    ] {
        assert!(
            !gate_findings(&planted, &BATCH_PAUSE_TRIGGER).is_empty(),
            "{what} must be reported"
        );
    }
}

/// The readiness marker `mds watch` creates for the test suite once it is watching (#390)
/// compiles only into a debug build, as the pauses do: every mention of `MDS_TEST_READY`,
/// and every mention of `create_ready_marker`, which writes the marker, sits inside
/// `mod ready_trigger`, whose attributes hold `#[cfg(debug_assertions)]`, and
/// `emit_ready_marker` has a release build's stub that does nothing.
///
/// Controls: the module without its `cfg`, the variable outside it, the marker's writer
/// called outside it, a release stub that does something, and no release stub are each
/// reported.
#[test]
fn the_readiness_marker_is_compiled_only_into_debug_builds() {
    let watch = read_source("src/watch.rs");
    let sources = crate_sources();
    let found = gate_findings(&sources, &READY_TRIGGER);
    assert!(
        found.is_empty(),
        "the readiness marker must be compiled only into debug builds:\n{}",
        found.join("\n")
    );

    let with = |from: &str, to: &str| -> Vec<(String, String)> {
        let planted = watch.replacen(from, to, 1);
        assert_ne!(planted, watch, "precondition: watch.rs holds {from:?}");
        sources
            .iter()
            .map(|(name, src)| {
                let src = if name == "watch.rs" { &planted } else { src };
                (name.clone(), src.clone())
            })
            .collect()
    };
    let stub = "fn emit_ready_marker() {}";
    for (planted, what) in [
        (
            with(
                "#[cfg(debug_assertions)]\nmod ready_trigger",
                "mod ready_trigger",
            ),
            "a readiness module without `#[cfg(debug_assertions)]`",
        ),
        (
            with(
                stub,
                "fn emit_ready_marker() {\n    \
                 let _ = std::env::var_os(\"MDS_TEST_READY\");\n}",
            ),
            "the readiness variable outside its module",
        ),
        (
            with(
                stub,
                &format!(
                    "{stub}\n\nfn planted(p: &Path) {{\n    let _ = create_ready_marker(p);\n}}"
                ),
            ),
            "the marker's writer called outside its module",
        ),
        (
            with(stub, "fn emit_ready_marker() {\n    let _ = 1;\n}"),
            "a release stub that does something",
        ),
        (with(stub, ""), "a readiness marker without a release stub"),
    ] {
        assert!(
            !gate_findings(&planted, &READY_TRIGGER).is_empty(),
            "{what} must be reported"
        );
    }
}

/// A panic in one file's compile fails that file alone (#389), so each per-file catch — a
/// `catch_compile` call — wraps that compile and nothing else: its closure is
/// `AssertUnwindSafe(|| <one call>)`, the call is one of [`COMPILE_CALLS`] as written
/// there, and no argument of it writes, deletes or changes state. Each of those mds-cli
/// defines is defined once, in its file, and neither it nor a function of mds-cli it
/// reaches writes, renames or deletes a file, writes to stdout or ends the process
/// ([`compile_reach_findings`]). A panic abandons the closure part-way, so only what the
/// closure holds is left unfinished. The catches sit where [`COMPILE_CATCHES`] lists
/// them, one per compile of a batch, and `catch_panic`, which catches around anything,
/// only where [`PANIC_CATCHES`] lists it.
///
/// The check is lexical: it follows calls by name, and does not see into a macro,
/// mds-core, or a call through a function pointer or a trait object.
///
/// Controls, each planted into the real sources and reported for its own reason: a state
/// change beside the compile, a write in its place, an argument that changes state, a
/// mutable borrow, a call chained onto the compile, a closure not wrapped in
/// `AssertUnwindSafe`, a catch gone from a listed place, one in an unlisted place, a
/// `catch_panic` outside its places, a helper named like the compile in its place, a
/// write inside a compile, a write in a function it calls, a delete in a method it calls,
/// an exit inside a compile, and a second compile of the same name. A write that no catch
/// reaches is not reported.
#[test]
fn each_catch_wraps_one_compile_call_and_nothing_else() {
    let sources = crate_sources();
    let found = catch_findings(&sources);
    assert!(
        found.is_empty(),
        "each catch must wrap one compile call and nothing else:\n{}",
        found.join("\n")
    );

    let replaced = |file: &str, from: &str, to: &str| {
        plant_in(&sources, file, |text| {
            let changed = text.replacen(from, to, 1);
            assert_ne!(&changed, text, "precondition: {file} holds {from:?}");
            *text = changed;
        })
    };
    let appended = |file: &str, body: &str| {
        plant_in(&sources, file, |text| {
            text.push_str(&format!("\nfn planted(src: &Path) {{\n    {body}\n}}\n"));
        })
    };
    let defined = |file: &str, item: &str| {
        plant_in(&sources, file, |text| text.push_str(&format!("\n{item}\n")))
    };
    let plants = [
        (
            replaced(
                "build.rs",
                "compile_native_to_content(fs, file, runtime_vars.clone(), quiet, opts)",
                "{ fail_count += 1; compile_native_to_content(fs, file, \
                 runtime_vars.clone(), quiet, opts) }",
            ),
            "more than one call",
            "a state change beside the compile",
        ),
        (
            replaced(
                "fmt.rs",
                "AssertUnwindSafe(|| format_source_named(&source, base_dir, &file_name))",
                "AssertUnwindSafe(|| atomic_write_file(file, &source, Durability::Fsync))",
            ),
            "not a compile",
            "a write in place of the compile",
        ),
        (
            replaced(
                "lint.rs",
                "mds::lint_native_fs(fs, path, ctx.runtime_vars.clone(), &config)",
                "mds::lint_native_fs(fs, path, ctx.base_dir_cache.borrow_mut().remove(path), &config)",
            ),
            "changes state",
            "an argument that changes state",
        ),
        (
            replaced(
                "build.rs",
                "compile_native_to_content(fs, file, runtime_vars.clone(), quiet, opts)",
                "compile_native_to_content(fs, file, runtime_vars.clone(), quiet, &mut opts)",
            ),
            "changes state",
            "a mutable borrow",
        ),
        (
            replaced(
                "main.rs",
                "mds::check_native_fs(fs, file, runtime_vars.clone()))",
                "mds::check_native_fs(fs, file, runtime_vars.clone()).map(|c| c))",
            ),
            "more than its one call",
            "a call chained onto the compile",
        ),
        (
            replaced(
                "main.rs",
                "AssertUnwindSafe(|| mds::check_native_fs(fs, file, runtime_vars.clone()))",
                "|| mds::check_native_fs(fs, file, runtime_vars.clone())",
            ),
            "AssertUnwindSafe",
            "a closure not wrapped in `AssertUnwindSafe`",
        ),
        (
            replaced("fmt.rs", "= catch_compile(", "= uncaught("),
            "must hold one",
            "a catch gone from a listed place",
        ),
        (
            appended(
                "watch.rs",
                "let _ = crate::output::catch_compile(src, AssertUnwindSafe(|| \
                 compile_to_content(src, None, true, mds::CompileOptions::default())));",
            ),
            "not a listed place",
            "a catch in an unlisted place",
        ),
        (
            appended("watch.rs", "let _ = crate::output::catch_panic(|| src);"),
            "outside its places",
            "a `catch_panic` outside its places",
        ),
        (
            replaced(
                "lint.rs",
                "AssertUnwindSafe(|| mds::lint_native_fs(fs, path, ctx.runtime_vars.clone(), &config))",
                "AssertUnwindSafe(|| lint_native_fs(fs, path, ctx.runtime_vars.clone(), &config))",
            ),
            "not a compile",
            "a helper named like the compile in its place",
        ),
        (
            replaced(
                "build.rs",
                "let kind = OutputKind::from(&result.output);",
                "crate::output::atomic_write_file(input, \"\", Durability::Fsync)?;\n    \
                 let kind = OutputKind::from(&result.output);",
            ),
            "which calls `atomic_write_file`",
            "a write inside the compile a catch calls",
        ),
        (
            replaced(
                "build.rs",
                "CompiledOutput::Markdown(s) => Ok(s),",
                "CompiledOutput::Markdown(s) => { std::fs::write(\"x\", &s).ok(); Ok(s) }",
            ),
            "which calls `fs::write`",
            "a write in a function the compile calls",
        ),
        (
            replaced(
                "lint.rs",
                "let residual = mds::lint_str_named(",
                "std::fs::remove_file(self.base_dir).ok();\n        \
                 let residual = mds::lint_str_named(",
            ),
            "which calls `remove_file`",
            "a delete in a method the compile calls",
        ),
        (
            replaced(
                "fmt.rs",
                "let changed = formatted != source;",
                "crate::output::exit(1);\n    let changed = formatted != source;",
            ),
            "which calls `exit`",
            "an exit in the formatter a catch calls",
        ),
        (
            defined(
                "watch.rs",
                "fn compile_to_content(input: &Path) -> Result<()> {\n    \
                 crate::output::atomic_write_file(input, \"\", Durability::Fsync)\n}",
            ),
            "must be defined once",
            "a second compile of the same name",
        ),
    ];
    let mut missed = Vec::new();
    for (planted, reason, what) in &plants {
        let found = catch_findings(planted);
        if !found.iter().any(|finding| finding.contains(reason)) {
            missed.push(format!("{what} (expected {reason:?}; found {found:?})"));
        }
    }
    assert!(
        missed.is_empty(),
        "each of these must be reported:\n{}",
        missed.join("\n")
    );

    let unreached = defined(
        "watch.rs",
        "fn planted_unreached() {\n    std::fs::write(\"x\", \"\").ok();\n}",
    );
    let found = catch_findings(&unreached);
    assert!(
        found.is_empty(),
        "control: a write that no catch reaches is not reported; found {found:?}"
    );
}

/// Each native or WASM host manifest declares `debug-panics` but never enables it
/// through a default or another feature. Each manifest gets the same controls.
///
/// Controls ([`assert_never_on_by_default`]): each way of turning it on, a declaration
/// that enables something, and a manifest that does not declare it are reported; a mention
/// in a comment is not.
#[test]
fn debug_panics_is_never_on_by_default() {
    for (manifest, other) in [
        ("Cargo.toml", "startup-race-probe"),
        ("../mds-napi/Cargo.toml", "verbose"),
        ("../mds-python/Cargo.toml", "extension-module"),
        ("../mds-wasm/Cargo.toml", "verbose"),
    ] {
        assert_never_on_by_default(manifest, "debug-panics", other);
    }
}

/// `startup-race-probe`, which delays `mds watch`'s startup on purpose, must never ship
/// enabled either, and is held to the same rule as `debug-panics`, with the same controls.
#[test]
fn startup_race_probe_is_never_on_by_default() {
    assert_never_on_by_default("Cargo.toml", "startup-race-probe", "debug-panics");
}

/// `feature` has no finding in the manifest, and each planted way to enable it is
/// reported. `other` names a companion feature. A comment enables nothing.
fn assert_never_on_by_default(path: &str, feature: &str, other: &str) {
    let manifest = read_source(path);
    let found = feature_findings(&manifest, feature);
    assert!(
        found.is_empty(),
        "{path}'s `{feature}` feature must stay off by default:\n{}",
        found.join("\n")
    );
    let declared = format!("{feature} = []");
    let after_declared =
        |extra: &str| manifest.replacen(&declared, &format!("{declared}\n{extra}"), 1);
    let plants = [
        (
            after_declared(&format!("default = [\"{feature}\"]")),
            "a default that enables it",
        ),
        (
            after_declared(&format!("default = [\n    \"{feature}\",\n]")),
            "a default over several lines that enables it",
        ),
        (
            after_declared(&format!("default = ['{feature}']")),
            "a default that names it in a literal string",
        ),
        (
            after_declared(&format!("verbose = [\"{other}\", \"{feature}\"]")),
            "another feature that enables it",
        ),
        (
            after_declared(&format!("verbose = [\"a#b\", \"{feature}\"]")),
            "a feature that enables it after a `#` inside a string",
        ),
        (
            format!("features.default = [\"{feature}\"]\n{manifest}"),
            "a dotted `features.default` that enables it",
        ),
        (
            manifest.replacen(&declared, &format!("{feature} = [\"{other}\"]"), 1),
            "a declaration that enables another feature",
        ),
        (
            manifest.replacen(&declared, "", 1),
            "a manifest that does not declare it",
        ),
    ];
    let mut missed = Vec::new();
    for (planted, what) in &plants {
        assert_ne!(
            planted, &manifest,
            "precondition: the plant changes Cargo.toml ({feature}: {what})"
        );
        if feature_findings(planted, feature).is_empty() {
            missed.push(*what);
        }
    }
    assert!(
        missed.is_empty(),
        "each of these must be reported for `{feature}`; missed: {missed:?}"
    );
    let commented = after_declared(&format!("# default = [\"{feature}\"]"));
    assert_eq!(
        feature_findings(&commented, feature),
        Vec::<String>::new(),
        "a mention of `{feature}` in a comment turns nothing on"
    );
}

/// Both native host funnels enter the shared boundary. A helper name in a
/// comment, literal, or different function must not satisfy the scan.
#[test]
fn native_host_funnels_use_the_shared_panic_boundary() {
    let mut found = Vec::new();
    for (path, funnel) in [
        ("../mds-napi/src/lib.rs", "run_catching"),
        ("../mds-python/src/lib.rs", "guard"),
    ] {
        let source = read_source(path);
        let planted = format!(
            "fn {funnel}() {{\n\
             // mds::host_panic::catching(f);\n\
             let text = \"mds::host_panic::catching(f)\";\n\
             std::panic::catch_unwind(f);\n\
             }}\nfn decoy() {{ mds::host_panic::catching(f); }}"
        );
        assert_eq!(
            host_boundary_findings(&planted, funnel),
            [format!("{funnel} must call mds::host_panic::catching once")],
            "{path}: a planted funnel without the call must fail the scan"
        );
        found.extend(
            host_boundary_findings(&source, funnel)
                .into_iter()
                .map(|finding| format!("{path}: {finding}")),
        );
    }
    assert_eq!(
        found,
        Vec::<String>::new(),
        "native funnels must use the shared boundary"
    );
}

fn host_boundary_findings(source: &str, funnel: &str) -> Vec<String> {
    let code = blank(source, true);
    let bodies: Vec<_> = fn_bodies(&code)
        .into_iter()
        .filter(|(name, _)| name == funnel)
        .collect();
    if bodies.len() != 1
        || calls_ending_with(&code[bodies[0].1.clone()], "mds::host_panic::catching").len() != 1
    {
        return vec![format!("{funnel} must call mds::host_panic::catching once")];
    }
    Vec::new()
}

/// Build inputs must not select the local-only panic feature. Each input gets a
/// planted selection in memory. Commands also get an all-features control.
#[test]
fn build_entry_points_leave_debug_panics_off() {
    let inputs = [
        (
            "../mds-python/pyproject.toml",
            "features = [\"pyo3/abi3-py311\"]",
        ),
        ("../mds-napi/package.json", "napi build --release --no-js"),
        (
            "../../packages/mds-wasm/package.json",
            "wasm-pack build ../../crates/mds-wasm --target nodejs",
        ),
        (
            "../../.github/workflows/release.yml",
            "napi build --platform --release",
        ),
    ];
    assert!(
        inputs
            .iter()
            .any(|(path, _)| *path == "../../packages/mds-wasm/package.json"),
        "the WASM workspace build script must receive the planted feature controls"
    );
    for (path, anchor) in inputs {
        let source = read_source(path);
        assert!(
            source.contains(anchor),
            "{path}: the build input must exist"
        );
        let replacements = if anchor.starts_with("features =") {
            vec!["features = [\"pyo3/abi3-py311\", \"debug-panics\"]".to_string()]
        } else {
            vec![
                format!("{anchor} --features debug-panics"),
                format!("{anchor} --all-features"),
            ]
        };
        for replacement in replacements {
            let planted = source.replacen(anchor, &replacement, 1);
            assert_ne!(planted, source, "{path}: the control must change the input");
            assert_eq!(
                build_feature_findings(&planted).len(),
                1,
                "{path}: the planted {replacement} must fail the scan"
            );
        }
        assert_eq!(
            build_feature_findings(&source),
            Vec::<String>::new(),
            "{path}: build entry points must not enable panic details"
        );
        assert!(
            build_feature_findings(&format!("{source}\n# debug-panics --all-features")).is_empty()
        );
    }
}

/// Conservatively refuse either spelling anywhere outside a line comment.
fn build_feature_findings(source: &str) -> Vec<String> {
    source
        .lines()
        .enumerate()
        .filter(|(_, line)| {
            let code = toml_code(line);
            code.contains("debug-panics") || code.contains("--all-features")
        })
        .map(|(line, _)| format!("line {} enables panic details", line + 1))
        .collect()
}

#[test]
fn wasm_installs_no_panic_hook_and_the_policy_states_why() {
    let sources = rust_sources("../mds-wasm/src", "lib.rs", 1);
    for needle in [
        "set_hook",
        "take_hook",
        "mds::host_panic::install",
        "mds::host_panic::catching",
    ] {
        let planted = plant_in(&sources, "lib.rs", |source| {
            source.push_str(&format!("\nfn planted() {{ {needle}(f); }}\n"));
        });
        assert_eq!(
            wasm_hook_findings(&planted).len(),
            1,
            "the WASM scan must reject a planted {needle}"
        );
    }
    assert_eq!(wasm_hook_findings(&sources), Vec::<String>::new());
    let policy = read_source("../../SECURITY.md");
    assert!(policy.contains("on wasm32-unknown-unknown, the default hook has no output channel"));
}

fn wasm_hook_findings(sources: &[(String, String)]) -> Vec<String> {
    sources
        .iter()
        .flat_map(|(path, source)| {
            let code = blank(source, true);
            ["set_hook", "take_hook", "host_panic"]
                .into_iter()
                .filter(|needle| !ident_positions(&code, needle).is_empty())
                .map(|needle| format!("{path} must not name {needle}"))
                .collect::<Vec<_>>()
        })
        .collect()
}

// ── Lexical helpers ───────────────────────────────────────────────────────────

/// A file of `crates/mds-cli`, by its path under the package.
fn read_source(relative: &str) -> String {
    let path = Path::new(env!("CARGO_MANIFEST_DIR")).join(relative);
    std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()))
}

/// Every `.rs` file under `crates/mds-cli/src/`, by its path below `src/`, with its text.
fn crate_sources() -> Vec<(String, String)> {
    rust_sources("src", "main.rs", 8)
}

/// Every `.rs` file under `crates/mds-core/src/`, by its path below `src/` (`lib.rs`,
/// `lint/mod.rs`), with its text.
fn core_sources() -> Vec<(String, String)> {
    rust_sources("../mds-core/src", "lib.rs", 20)
}

/// A copy of `sources` with the text of `file` changed by `edit`: a control planted into
/// the real sources, which are left as they are.
fn plant_in(
    sources: &[(String, String)],
    file: &str,
    edit: impl FnOnce(&mut String),
) -> Vec<(String, String)> {
    let mut planted = sources.to_vec();
    let (_, text) = planted
        .iter_mut()
        .find(|(name, _)| name == file)
        .unwrap_or_else(|| panic!("precondition: the sources hold {file}"));
    edit(text);
    planted
}

/// Every `.rs` file under `relative` (from this package's directory), by its path below
/// it with `/` between names, with its text. Non-vacuity: the walk found `root_file` and
/// at least `at_least` files.
fn rust_sources(relative: &str, root_file: &str, at_least: usize) -> Vec<(String, String)> {
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join(relative);
    let mut pending: Vec<PathBuf> = vec![root.clone()];
    let mut files = Vec::new();
    for _ in 0..64 {
        let Some(dir) = pending.pop() else { break };
        for entry in std::fs::read_dir(&dir).expect("read a source directory") {
            let path = entry.expect("read a source directory entry").path();
            if path.is_dir() {
                pending.push(path);
            } else if path.extension().is_some_and(|e| e == "rs") {
                let below = path.strip_prefix(&root).expect("a path below the root");
                let name = below
                    .components()
                    .map(|part| part.as_os_str().to_string_lossy())
                    .collect::<Vec<_>>()
                    .join("/");
                let text = std::fs::read_to_string(&path).expect("read a source");
                files.push((name, text));
            }
        }
    }
    assert!(
        pending.is_empty(),
        "{relative} nests deeper than the walk's bound"
    );
    assert!(
        files.iter().any(|(name, _)| name == root_file) && files.len() >= at_least,
        "non-vacuity: the walk of {relative} found {root_file} and at least {at_least} \
         files; found {}",
        files.len()
    );
    files.sort();
    files
}

/// The std functions that change what a panic does: set or take the panic hook, catch a
/// panic, or unwind without calling the hook at all.
const PANIC_MACHINERY: &[&str] = &["set_hook", "take_hook", "catch_unwind", "resume_unwind"];

/// Where mds-cli's sources name the [`PANIC_MACHINERY`], as (function, file, the `fn` it
/// is named in): the hook is set in one place and a panic is caught in one place, so no
/// catch site reports a panic a second time. `resume_unwind` has no place: it unwinds
/// without calling the hook, so its panic prints nothing and records nothing for the
/// exit code, and on a thread that nothing catches it ends that thread alone.
const CLI_PANIC_MACHINERY: &[(&str, &str, &str)] = &[
    ("set_hook", "output.rs", "install_panic_hook"),
    ("catch_unwind", "output.rs", "catch_panic"),
];

/// Where mds-core's sources name the [`PANIC_MACHINERY`]: two unit tests and the
/// native hosts' opt-in boundary helper. Core compile functions do not call that
/// helper, so the CLI keeps its own hook and catch.
const CORE_PANIC_MACHINERY: &[(&str, &str, &str)] = &[
    ("take_hook", "host_panic.rs", "install"),
    ("set_hook", "host_panic.rs", "install"),
    ("catch_unwind", "host_panic.rs", "catching"),
    (
        "catch_unwind",
        "resolver_tests.rs",
        "attach_import_span_non_boundary_offset_degrades_to_zero_len_span",
    ),
    (
        "catch_unwind",
        "resolver_tests.rs",
        "check_child_only_blocks_non_boundary_offset_degrades",
    ),
];

/// What is wrong with the panic machinery in `sources` (see
/// [`the_hook_writes_one_constant_and_nothing_about_the_panic`]); empty when nothing is:
/// every [`PANIC_MACHINERY`] name in code outside the places `allowed` lists, and every
/// listed place that does not name its function exactly once.
fn machinery_findings(sources: &[(String, String)], allowed: &[(&str, &str, &str)]) -> Vec<String> {
    let mut found = Vec::new();
    let mut named = vec![0usize; allowed.len()];
    for (name, src) in sources {
        let code = blank(src, true);
        for needle in PANIC_MACHINERY {
            for (at, _) in code.match_indices(needle) {
                let inside = innermost_fn(&code, at).map(|(fn_name, _)| fn_name);
                let place = allowed.iter().position(|(function, file, in_fn)| {
                    function == needle && file == name && inside.as_deref() == Some(*in_fn)
                });
                match place {
                    Some(place) => named[place] += 1,
                    None => found.push(format!(
                        "{name}:{}: `{needle}` in `{}`",
                        line_of(&code, at),
                        inside.as_deref().unwrap_or("-")
                    )),
                }
            }
        }
    }
    for ((function, file, in_fn), count) in allowed.iter().zip(named) {
        if count != 1 {
            found.push(format!(
                "{file}: `{in_fn}` must name `{function}` once; it names it {count} times"
            ));
        }
    }
    found
}

/// Where each per-file catch sits in mds-cli's sources, as (file, the `fn` it is in): the
/// compile of one file of a batch — a directory run, or a watch session (#389).
const COMPILE_CATCHES: &[(&str, &str)] = &[
    ("build.rs", "run_build_directory"),
    ("fmt.rs", "format_one_file"),
    ("lint.rs", "lint_dir_entry"),
    ("lint.rs", "lint_input"),
    ("main.rs", "run_check_directory"),
    ("watch.rs", "compile_caught"),
];

/// What a catch's closure may call, as the call is written there, and the file of mds-cli
/// that defines it — `None` for a function of mds-core. Each compiles, checks, formats or
/// lints one file, and writes nothing: [`compile_reach_findings`] follows the ones mds-cli
/// defines.
const COMPILE_CALLS: &[(&str, Option<&str>)] = &[
    ("compile_to_content", Some("build.rs")),
    ("compile_native_to_content", Some("build.rs")),
    ("mds::check_native_fs", None),
    ("format_source_named", Some("fmt.rs")),
    ("mds::lint_native_fs", None),
    ("run_fix_pipeline", Some("lint.rs")),
];

/// What a compile a catch wraps must never reach, through the functions of mds-cli it
/// calls: a write, rename or delete of a file, a write to stdout, or an end of the process.
/// A call matches when its path ends with the entry, so `fs::write` is `std::fs::write(`.
/// Stderr's status lines — a compile's warnings — are not in it: the writer formats a line
/// before it writes it, so a panic leaves no part of one.
const WRITES: &[&str] = &[
    "atomic_write_file",
    "write_output",
    "write_session_output",
    "write_stdout",
    "fs::write",
    "fs::copy",
    "File::create",
    "OpenOptions::new",
    "persist",
    "persist_noclobber",
    "rename",
    "remove_file",
    "remove_dir",
    "remove_dir_all",
    "create_dir",
    "create_dir_all",
    "hard_link",
    "set_permissions",
    "probe_and_remove_stale",
    "verify_then_delete_map",
    "exit",
    "exit_after_panic",
];

/// The first path segments of a call into another crate — mds-cli's dependencies and the
/// standard library — which [`compile_reach_findings`] does not follow.
const OTHER_CRATES: &[&str] = &[
    "mds",
    "std",
    "core",
    "alloc",
    "clap",
    "serde",
    "serde_json",
    "miette",
    "notify",
    "ctrlc",
    "similar",
    "tempfile",
];

/// What the compile call's arguments may not hold: a write, a delete, a change to state, a
/// mutable borrow, an assignment, a macro, a closure, a statement.
const STATE_CHANGES: &[&str] = &[
    "write", "remove", "delete", "rename", "create", "insert", "push", "clear", "take", "exit",
    "print", "&mut", "=", "!", "|", ";", "{",
];

/// Where mds-cli calls `catch_panic` outside its test modules, as (file, the `fn` it is
/// in): `main`, around the whole command, and `catch_compile`.
const PANIC_CATCHES: &[(&str, &str)] = &[("main.rs", "main"), ("output.rs", "catch_compile")];

/// What is wrong with the per-file catches in `sources` (see
/// [`each_catch_wraps_one_compile_call_and_nothing_else`]); empty when nothing is.
fn catch_findings(sources: &[(String, String)]) -> Vec<String> {
    let mut found = Vec::new();
    let mut placed: Vec<(String, String)> = Vec::new();
    for (name, src) in sources {
        let code = blank(src, true);
        let tests = mod_body(&code, "tests");
        // A call of `function` outside the test module: a `(` follows its name.
        let calls = |function: &str| -> Vec<(usize, String)> {
            ident_positions(&code, function)
                .into_iter()
                .filter(|at| {
                    code[at + function.len()..].trim_start().starts_with('(')
                        && !tests.as_ref().is_some_and(|t| t.contains(at))
                })
                .map(|at| {
                    let inside = innermost_fn(&code, at).map_or_else(|| "-".to_string(), |f| f.0);
                    (at, inside)
                })
                .collect()
        };
        for (at, inside) in calls("catch_compile") {
            if let Err(reason) = catch_closure(&code, at) {
                found.push(format!(
                    "{name}:{} (`{inside}`): {reason}",
                    line_of(&code, at)
                ));
            }
            placed.push((name.clone(), inside));
        }
        for (at, inside) in calls("catch_panic") {
            if !PANIC_CATCHES.contains(&(name.as_str(), inside.as_str())) {
                found.push(format!(
                    "{name}:{}: `catch_panic` in `{inside}`, outside its places",
                    line_of(&code, at)
                ));
            }
        }
    }
    for (file, in_fn) in COMPILE_CATCHES {
        let count = placed
            .iter()
            .filter(|(name, inside)| name == file && inside == in_fn)
            .count();
        if count != 1 {
            found.push(format!(
                "{file}: `{in_fn}` must hold one `catch_compile`; it holds {count}"
            ));
        }
    }
    for (file, inside) in &placed {
        if !COMPILE_CATCHES.contains(&(file.as_str(), inside.as_str())) {
            found.push(format!(
                "{file}: a `catch_compile` in `{inside}`, which is not a listed place"
            ));
        }
    }
    found.extend(compile_reach_findings(sources));
    found
}

/// Check the closure of the `catch_compile` call at byte `at` of blanked `code`: its
/// second argument is `AssertUnwindSafe(|| <one call>)`, the call one of
/// [`COMPILE_CALLS`], nothing chained onto it, and none of [`STATE_CHANGES`] in its
/// arguments.
fn catch_closure(code: &str, at: usize) -> Result<(), String> {
    let open = at + code[at..].find('(').ok_or("no argument list")?;
    let close = closing_paren(code, open).ok_or("an argument list that never closes")?;
    let args = top_level_parts(&code[open + 1..close]);
    let [_label, closure] = args.as_slice() else {
        return Err(format!(
            "takes {} arguments, not a label and a closure",
            args.len()
        ));
    };
    let closure: String = closure.split_whitespace().collect();
    let body = closure
        .strip_prefix("AssertUnwindSafe(")
        .or_else(|| closure.strip_prefix("std::panic::AssertUnwindSafe("))
        .and_then(|inner| inner.strip_suffix(')'))
        .and_then(|inner| {
            inner
                .strip_prefix("||")
                .or_else(|| inner.strip_prefix("move||"))
        })
        .ok_or_else(|| format!("its closure is not `AssertUnwindSafe(|| …)`: `{closure}`"))?;
    let body = body
        .strip_prefix('{')
        .and_then(|inner| inner.strip_suffix('}'))
        .unwrap_or(body);
    let paren = body
        .find('(')
        .ok_or_else(|| format!("its closure calls nothing: `{body}`"))?;
    let callee = &body[..paren];
    if !callee
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == ':')
    {
        return Err(format!("its closure wraps more than one call: `{body}`"));
    }
    if !COMPILE_CALLS.iter().any(|(call, _)| *call == callee) {
        return Err(format!(
            "its closure calls `{callee}`, which is not a compile"
        ));
    }
    let end = closing_paren(body, paren).ok_or("a call that never closes")?;
    if end + 1 != body.len() {
        return Err(format!("its closure does more than its one call: `{body}`"));
    }
    let call_args = &body[paren + 1..end];
    match STATE_CHANGES
        .iter()
        .find(|change| call_args.contains(**change))
    {
        Some(change) => Err(format!(
            "its call changes state: `{change}` in `{call_args}`"
        )),
        None => Ok(()),
    }
}

/// What is wrong with the compiles the catches call, in `sources`: each of mds-cli's
/// [`COMPILE_CALLS`] is defined once, in its file, and neither it nor any function of
/// mds-cli it reaches calls one of [`WRITES`].
///
/// A call is a name followed by `(`, a method call's included, unless its path starts
/// with one of [`OTHER_CRATES`]. It leads to every function of mds-cli outside the test
/// modules with that name — each one, when several types define it — so the walk sees
/// more than a compile runs, never less. It does not see into a macro, a function of
/// another crate (mds-core's among them), or a call through a function pointer or a
/// trait object.
fn compile_reach_findings(sources: &[(String, String)]) -> Vec<String> {
    let codes: Vec<(&str, String)> = sources
        .iter()
        .map(|(name, src)| (name.as_str(), blank(src, true)))
        .collect();
    // Every `fn` of mds-cli outside its test modules: (index into `codes`, name, body).
    let mut defs: Vec<(usize, String, RangeInclusive<usize>)> = Vec::new();
    for (index, (_, code)) in codes.iter().enumerate() {
        let tests = mod_body(code, "tests");
        for (name, body) in fn_bodies(code) {
            if !tests.as_ref().is_some_and(|t| t.contains(body.start())) {
                defs.push((index, name, body));
            }
        }
    }
    let mut found = Vec::new();
    for (callee, file) in COMPILE_CALLS {
        let Some(file) = file else { continue };
        let mut pending: Vec<usize> = (0..defs.len()).filter(|&i| defs[i].1 == *callee).collect();
        let places: Vec<&str> = pending.iter().map(|&i| codes[defs[i].0].0).collect();
        if places != [*file] {
            found.push(format!(
                "`{callee}` must be defined once, in {file}; it is defined in {places:?}"
            ));
        }
        // Each function is looked at once, so the walk ends after `defs.len()` steps.
        let mut seen = vec![false; defs.len()];
        while let Some(i) = pending.pop() {
            if std::mem::replace(&mut seen[i], true) {
                continue;
            }
            let (index, name, body) = &defs[i];
            let (file_name, code) = &codes[*index];
            let text = &code[body.clone()];
            for write in WRITES {
                if let Some(at) = calls_ending_with(text, write).first() {
                    found.push(format!(
                        "{file_name}:{}: `{callee}` reaches `{name}`, which calls `{write}`",
                        line_of(code, body.start() + at)
                    ));
                }
            }
            let called = called_names(text);
            pending.extend((0..defs.len()).filter(|&j| !seen[j] && called.contains(&defs[j].1)));
        }
    }
    found
}

/// Byte offsets in blanked `text` of the calls whose path ends with `path`: its last name,
/// then `(`, with the rest of `path` written just before that name.
fn calls_ending_with(text: &str, path: &str) -> Vec<usize> {
    let name = path.rsplit("::").next().unwrap_or(path);
    ident_positions(text, name)
        .into_iter()
        .filter(|&at| {
            text[at + name.len()..].trim_start().starts_with('(')
                && text[..at + name.len()].ends_with(path)
        })
        .collect()
}

/// The names blanked `text` calls — each a name followed by `(` — except a call whose path
/// starts with one of [`OTHER_CRATES`].
fn called_names(text: &str) -> std::collections::HashSet<String> {
    let b = text.as_bytes();
    let mut names = std::collections::HashSet::new();
    let mut i = 0usize;
    while i < b.len() {
        if !is_ident_byte(b[i]) || prev_is_ident(b, i) {
            i += 1;
            continue;
        }
        let end = i + b[i..].iter().take_while(|c| is_ident_byte(**c)).count();
        if text[end..].trim_start().starts_with('(') && !OTHER_CRATES.contains(&path_head(text, i))
        {
            names.insert(text[i..end].to_string());
        }
        i = end;
    }
    names
}

/// The first name of the path that ends with the name at byte `at` of `text`:
/// `std` for `std::fs::write`, the name itself when nothing precedes it.
fn path_head(text: &str, at: usize) -> &str {
    let mut start = at;
    while start >= 2 && &text[start - 2..start] == "::" {
        let segment_end = start - 2;
        let segment_start = text[..segment_end]
            .bytes()
            .rposition(|c| !is_ident_byte(c))
            .map_or(0, |p| p + 1);
        if segment_start == segment_end {
            break;
        }
        start = segment_start;
    }
    let end = start
        + text[start..]
            .bytes()
            .take_while(|c| is_ident_byte(*c))
            .count();
    &text[start..end]
}

/// Index of the `)` closing the `(` at `open` in `text`, blanked of literals.
fn closing_paren(text: &str, open: usize) -> Option<usize> {
    let mut depth = 0usize;
    for (i, c) in text.bytes().enumerate().skip(open) {
        match c {
            b'(' => depth += 1,
            b')' => {
                depth -= 1;
                if depth == 0 {
                    return Some(i);
                }
            }
            _ => {}
        }
    }
    None
}

/// `text` split at its top-level commas, each part trimmed, empty parts left out (a
/// trailing comma).
fn top_level_parts(text: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut depth = 0usize;
    let mut start = 0usize;
    for (i, c) in text.bytes().enumerate() {
        match c {
            b'(' | b'[' | b'{' => depth += 1,
            b')' | b']' | b'}' => depth = depth.saturating_sub(1),
            b',' if depth == 0 => {
                parts.push(text[start..i].trim());
                start = i + 1;
            }
            _ => {}
        }
    }
    parts.push(text[start..].trim());
    parts.retain(|part| !part.is_empty());
    parts
}

/// Where `src` runs a process without setting or removing `RUST_BACKTRACE` (see
/// [`every_run_sets_or_removes_rust_backtrace`]).
struct UnsetRuns {
    /// Every `.spawn(` / `.output(` / `.status(` call in code, and every call of a
    /// [`SPAWN_HELPERS`] helper.
    runs: usize,
    /// 1-based lines of the calls whose function names `RUST_BACKTRACE` in neither an
    /// `env(RUST_BACKTRACE, …)` nor an `env_remove(RUST_BACKTRACE)` call.
    stray: Vec<usize>,
}

fn runs_without_rust_backtrace(src: &str) -> UnsetRuns {
    let code = blank(src, true);
    let mut found = UnsetRuns {
        runs: 0,
        stray: Vec::new(),
    };
    let calls = [".spawn(", ".output(", ".status("]
        .into_iter()
        .chain(SPAWN_HELPERS.iter().copied());
    for call in calls {
        for (at, _) in code.match_indices(call) {
            found.runs += 1;
            let sets = innermost_fn(&code, at).is_some_and(|(_, body)| {
                let text: String = code[body].split_whitespace().collect();
                text.contains("env(RUST_BACKTRACE,") || text.contains("env_remove(RUST_BACKTRACE)")
            });
            if !sets {
                found.stray.push(line_of(&code, at));
            }
        }
    }
    found.stray.sort_unstable();
    found
}

/// What is wrong with the panic hook in `output` (the text of `src/output.rs`); empty
/// when nothing is (see [`the_hook_writes_one_constant_and_nothing_about_the_panic`]).
fn hook_findings(output: &str) -> Vec<String> {
    let code = blank(output, true);
    let with_literals = blank(output, false);
    let Some(body) = fn_body(&code, "on_panic") else {
        return vec!["output.rs defines no `fn on_panic`".to_string()];
    };
    let text = &code[body.clone()];
    let compact: String = text.split_whitespace().collect();
    let mut found = Vec::new();

    // The panic is recorded before anything that can wait: a hook blocked in its write
    // must not leave the run to exit without it.
    if !code[body.start() + 1..]
        .trim_start()
        .starts_with("OUTPUT_STATE.note_panicked();")
    {
        found.push(
            "the hook must record the panic first: its body starts \
             `OUTPUT_STATE.note_panicked();`"
                .to_string(),
        );
    }
    let writes = compact.matches("write_all(").count();
    if writes != 1 || !compact.contains("write_all(ICE_TEXT.as_bytes())") {
        found.push(format!(
            "the hook must make exactly one `write_all`, of `ICE_TEXT`; it makes {writes}"
        ));
    }
    for required in ["note_panicked()", "exit_after_panic()"] {
        if !compact.contains(required) {
            found.push(format!("the hook must call `{required}`"));
        }
    }
    for forbidden in [
        "print",
        "format",
        "write!",
        "writeln!",
        "ewrite",
        "miette",
        "payload",
        "location",
        "downcast",
        "to_string",
        "Display",
        "Debug",
        "unwrap",
        "expect",
        "panic!",
        "unreachable!",
        "assert",
        "dbg!",
    ] {
        if text.contains(forbidden) {
            found.push(format!("the hook names `{forbidden}`"));
        }
    }
    // `info`, the hook's `PanicHookInfo`, only on a line directly under one of the two
    // feature gates.
    let gates = [
        "#[cfg(feature = \"debug-panics\")]",
        "#[cfg(not(feature = \"debug-panics\"))]",
    ];
    for at in ident_positions(text, "info") {
        let at = body.start() + at;
        let gated = attributes_above(&with_literals, at)
            .first()
            .is_some_and(|above| gates.contains(above));
        if !gated {
            found.push(format!(
                "the hook names its `PanicHookInfo` outside a `debug-panics` gate, at line {}",
                line_of(&code, at)
            ));
        }
    }
    found
}

/// What is wrong with the trigger's gating across `sources`; empty when nothing is (see
/// [`the_trigger_is_compiled_only_into_debug_builds`]).
fn trigger_findings(sources: &[(String, String)]) -> Vec<String> {
    gate_findings(sources, &PANIC_TRIGGER)
}

/// A hook that only a debug build may hold: the module it lives in, the words that may
/// appear only inside that module — each looked for with string literals kept (`true`) or
/// blanked (`false`) — and its functions, each with a release build's stub that does
/// nothing.
struct DebugGate {
    module: &'static str,
    needles: &'static [(&'static str, bool)],
    fns: &'static [&'static str],
}

/// The panic trigger (#389): `MDS_TEST_PANIC` and `panic_any`, in `mod panic_trigger`.
const PANIC_TRIGGER: DebugGate = DebugGate {
    module: "panic_trigger",
    needles: &[("MDS_TEST_PANIC", true), ("panic_any", false)],
    fns: TRIGGER_FNS,
};

/// The pause between a rewrite's read and its replace (#160):
/// `MDS_TEST_PAUSE_BEFORE_REPLACE`, in `mod pause_trigger`.
const PAUSE_TRIGGER: DebugGate = DebugGate {
    module: "pause_trigger",
    needles: &[("MDS_TEST_PAUSE_BEFORE_REPLACE", true)],
    fns: &["pause_before_replace"],
};

/// The pause between a directory watch batch's split and its compile (#160),
/// `MDS_TEST_PAUSE_AFTER_BATCH_SPLIT`, the pause between a watch rebuild's look and its
/// reads (#380), `MDS_TEST_PAUSE_AFTER_LOOK`, and the pause between a file rebuild's reads
/// and its baseline (#380), `MDS_TEST_PAUSE_AFTER_READ`, all in `mod batch_pause_trigger`.
/// The same module holds `MDS_TEST_PAUSE_BEFORE_WATCH_COMPILE` before entry resolution. It also
/// holds `MDS_TEST_PAUSE_BEFORE_LATE_LOOK`, between a rebuild's reads and its late empty-file
/// check (#380).
const BATCH_PAUSE_TRIGGER: DebugGate = DebugGate {
    module: "batch_pause_trigger",
    needles: &[
        ("MDS_TEST_PAUSE_AFTER_BATCH_SPLIT", true),
        ("MDS_TEST_PAUSE_AFTER_LOOK", true),
        ("MDS_TEST_PAUSE_AFTER_READ", true),
        ("MDS_TEST_PAUSE_BEFORE_WATCH_COMPILE", true),
        ("MDS_TEST_PAUSE_BEFORE_LATE_LOOK", true),
    ],
    fns: &[
        "pause_after_batch_split",
        "pause_after_look",
        "pause_after_read",
        "pause_before_compile",
        "pause_before_late_look",
    ],
};

/// The readiness marker `mds watch` creates once it is watching (#390): `MDS_TEST_READY`,
/// and `create_ready_marker`, which writes the marker by path and has no release stub
/// because only `emit_ready_marker` calls it, both in `mod ready_trigger`.
const READY_TRIGGER: DebugGate = DebugGate {
    module: "ready_trigger",
    needles: &[("MDS_TEST_READY", true), ("create_ready_marker", false)],
    fns: &["emit_ready_marker"],
};

/// What is wrong with `gate`'s gating across `sources`; empty when nothing is: its module
/// is one, under `#[cfg(debug_assertions)]`; its words appear in it alone; and each of its
/// functions is defined there once and once outside it as an empty stub under
/// `#[cfg(not(debug_assertions))]`.
fn gate_findings(sources: &[(String, String)], gate: &DebugGate) -> Vec<String> {
    let module_item = format!("mod {}", gate.module);
    let mut found = Vec::new();
    let mut modules = 0usize;
    let mut defined = vec![0usize; gate.fns.len()];
    let mut stubs = vec![0usize; gate.fns.len()];
    for (name, src) in sources {
        let code = blank(src, true);
        let with_literals = blank(src, false);
        let module = mod_body(&code, gate.module);
        if let Some(module) = &module {
            modules += 1;
            let item = with_literals[..*module.start()]
                .rfind(&module_item)
                .unwrap_or(0);
            if !attributes_above(&with_literals, item).contains(&"#[cfg(debug_assertions)]") {
                found.push(format!(
                    "{name}: `{module_item}` is not under `#[cfg(debug_assertions)]`"
                ));
            }
        }
        let inside = |at: usize| module.as_ref().is_some_and(|m| m.contains(&at));
        for &(needle, literals) in gate.needles {
            let view = if literals { &with_literals } else { &code };
            for (at, _) in view.match_indices(needle) {
                if !inside(at) {
                    found.push(format!(
                        "{name}:{}: `{needle}` outside `{module_item}`",
                        line_of(&code, at)
                    ));
                }
            }
        }
        // Each function: defined in the module, and a release build's stub outside it,
        // under `#[cfg(not(debug_assertions))]`, with an empty body.
        for (fn_name, body) in fn_bodies(&code) {
            let Some(index) = gate.fns.iter().position(|f| *f == fn_name) else {
                continue;
            };
            if inside(*body.start()) {
                defined[index] += 1;
                continue;
            }
            stubs[index] += 1;
            let item = with_literals[..*body.start()]
                .rfind(&format!("fn {fn_name}"))
                .unwrap_or(0);
            if !attributes_above(&with_literals, item).contains(&"#[cfg(not(debug_assertions))]") {
                found.push(format!(
                    "{name}: a `{fn_name}` outside the module is not under \
                     `#[cfg(not(debug_assertions))]`"
                ));
            }
            let inner = code[body.clone()]
                .trim_matches(|c: char| c == '{' || c == '}' || c.is_whitespace())
                .to_string();
            if !inner.is_empty() {
                found.push(format!(
                    "{name}: the release build's `{fn_name}` must do nothing; it does \
                     `{inner}`"
                ));
            }
        }
    }
    if modules != 1 {
        found.push(format!(
            "the crate must hold exactly one `{module_item}`; it holds {modules}"
        ));
    }
    for ((fn_name, defined), stubs) in gate.fns.iter().zip(defined).zip(stubs) {
        if defined != 1 || stubs != 1 {
            found.push(format!(
                "`{fn_name}` must be defined once in `{module_item}` and once as a \
                 release build's stub; it is defined {defined} and {stubs} times"
            ));
        }
    }
    found
}

/// The trigger's functions: `panic_on_request` in the dispatch, `panic_on_compile` in
/// `catch_compile`, `panic_in_handler` in `mds watch`'s file-event callback and Ctrl-C
/// handler.
const TRIGGER_FNS: &[&str] = &["panic_on_request", "panic_on_compile", "panic_in_handler"];

/// What is wrong with the test-only `feature` in `manifest`; empty when nothing is (see
/// [`assert_never_on_by_default`]): every line, comments left out, that names it in
/// quotes — a value, which is how a feature turns another on, whether the list sits on one
/// line or several and whatever key holds it (`default`, `features.default`) — and a
/// `[features]` table that does not declare it as `<feature> = []`. The declaration's key
/// is bare, so it is no quoted mention; a key written in quotes is reported too.
fn feature_findings(manifest: &str, feature: &str) -> Vec<String> {
    let mut found = Vec::new();
    let mut in_features = false;
    let mut declared = false;
    let quoted = [format!("\"{feature}\""), format!("'{feature}'")];
    for (index, line) in manifest.lines().enumerate() {
        let line = toml_code(line).trim();
        if quoted.iter().any(|quoted| line.contains(quoted.as_str())) {
            found.push(format!(
                "Cargo.toml:{}: `{line}` names `{feature}` as a value, which turns it on",
                index + 1
            ));
        }
        if line.starts_with('[') {
            in_features = line == "[features]";
            continue;
        }
        let Some((key, value)) = line.split_once('=').filter(|_| in_features) else {
            continue;
        };
        if key.trim() == feature {
            declared = true;
            let value = value.trim();
            if value != "[]" {
                found.push(format!("`{feature}` must enable nothing; it is {value}"));
            }
        }
    }
    if !declared {
        found.push(format!(
            "Cargo.toml's [features] does not declare `{feature}`"
        ));
    }
    found
}

/// `line` of a TOML file without its comment: the text before the first `#` that is not
/// inside a string — `"…"`, with `\` escapes, or `'…'`, as TOML writes one on a line.
fn toml_code(line: &str) -> &str {
    let mut open: Option<char> = None;
    let mut escaped = false;
    for (at, c) in line.char_indices() {
        match open {
            Some('"') if escaped => escaped = false,
            Some('"') if c == '\\' => escaped = true,
            Some(quote) if c == quote => open = None,
            Some(_) => {}
            None if c == '"' || c == '\'' => open = Some(c),
            None if c == '#' => return &line[..at],
            None => {}
        }
    }
    line
}

/// `src` with comments — and, when `literals` is set, string and char literals — blanked
/// to spaces, byte for byte and newlines kept, so a byte offset names the same place in
/// every view of a file and a search of the blanked text finds code only.
fn blank(src: &str, literals: bool) -> String {
    fn blank_range(out: &mut [u8], from: usize, to: usize) {
        for byte in &mut out[from..to] {
            if *byte != b'\n' {
                *byte = b' ';
            }
        }
    }
    let b = src.as_bytes();
    let mut out = b.to_vec();
    let mut i = 0usize;
    while i < b.len() {
        if let Some(end) = literal_end(src, i) {
            if literals {
                blank_range(&mut out, i, end);
            }
            i = end;
        } else if b[i..].starts_with(b"//") {
            let end = src[i..].find('\n').map_or(b.len(), |rel| i + rel);
            blank_range(&mut out, i, end);
            i = end;
        } else if b[i..].starts_with(b"/*") {
            let start = i;
            let mut depth = 0usize;
            while i < b.len() {
                if b[i..].starts_with(b"/*") {
                    depth += 1;
                    i += 2;
                } else if b[i..].starts_with(b"*/") {
                    depth -= 1;
                    i += 2;
                    if depth == 0 {
                        break;
                    }
                } else {
                    i += 1;
                }
            }
            blank_range(&mut out, start, i.min(b.len()));
        } else {
            i += 1;
        }
    }
    String::from_utf8(out).expect("blanking writes ASCII spaces over whole characters")
}

/// If a string, raw string or char literal starts at `i`, the index just past it.
fn literal_end(src: &str, i: usize) -> Option<usize> {
    let b = src.as_bytes();
    let starts_word = !prev_is_ident(b, i);
    let raw = match b[i] {
        b'r' if starts_word => Some(i + 1),
        b'b' if starts_word && b.get(i + 1) == Some(&b'r') => Some(i + 2),
        _ => None,
    };
    if let Some(open) = raw {
        let hashes = b[open..].iter().take_while(|c| **c == b'#').count();
        let quote = open + hashes;
        if b.get(quote) != Some(&b'"') {
            return None;
        }
        let close = format!("\"{}", "#".repeat(hashes));
        return Some(
            src[quote + 1..]
                .find(&close)
                .map_or(b.len(), |rel| quote + 1 + rel + close.len()),
        );
    }
    match b[i] {
        b'"' => {
            let mut j = i + 1;
            while j < b.len() {
                match b[j] {
                    b'\\' => j += 2,
                    b'"' => return Some(j + 1),
                    _ => j += 1,
                }
            }
            Some(b.len())
        }
        b'\'' => {
            if b.get(i + 1) == Some(&b'\\') {
                // An escape: a newline, a quote, a hex or a braced codepoint.
                let close = src.get(i + 3..)?.find('\'')?;
                return Some(i + 3 + close + 1);
            }
            // One character and a closing quote; otherwise a lifetime or a label.
            let ch = src[i + 1..].chars().next()?;
            let after = i + 1 + ch.len_utf8();
            (b.get(after) == Some(&b'\'')).then_some(after + 1)
        }
        _ => None,
    }
}

fn prev_is_ident(b: &[u8], i: usize) -> bool {
    i > 0 && is_ident_byte(b[i - 1])
}

fn is_ident_byte(c: u8) -> bool {
    c.is_ascii_alphanumeric() || c == b'_'
}

/// Byte offsets in `text` where the identifier `name` stands on its own.
fn ident_positions(text: &str, name: &str) -> Vec<usize> {
    let b = text.as_bytes();
    text.match_indices(name)
        .map(|(at, _)| at)
        .filter(|at| {
            !prev_is_ident(b, *at) && !b.get(at + name.len()).copied().is_some_and(is_ident_byte)
        })
        .collect()
}

/// The 1-based line of byte offset `at`.
fn line_of(text: &str, at: usize) -> usize {
    text[..at].matches('\n').count() + 1
}

/// Index of the `}` closing the `{` at `open` in blanked `code`.
fn closing_brace(code: &str, open: usize) -> Option<usize> {
    let mut depth = 0usize;
    for (i, c) in code.bytes().enumerate().skip(open) {
        match c {
            b'{' => depth += 1,
            b'}' => {
                depth -= 1;
                if depth == 0 {
                    return Some(i);
                }
            }
            _ => {}
        }
    }
    None
}

/// Every `fn` with a body in blanked `code`: its name and its body's byte range, braces
/// included. The body opens at the first `{` outside the signature's parentheses and
/// brackets; a `;` there first means the `fn` has no body.
fn fn_bodies(code: &str) -> Vec<(String, RangeInclusive<usize>)> {
    let b = code.as_bytes();
    let mut found = Vec::new();
    for at in ident_positions(code, "fn") {
        let after = at + 2;
        let name_start = after + (code[after..].len() - code[after..].trim_start().len());
        let name_len = b[name_start..]
            .iter()
            .take_while(|c| is_ident_byte(**c))
            .count();
        if name_len == 0 {
            continue;
        }
        let name_end = name_start + name_len;
        let mut depth = 0usize;
        let mut open = None;
        for (i, c) in b.iter().enumerate().skip(name_end) {
            match c {
                b'(' | b'[' => depth += 1,
                b')' | b']' => depth = depth.saturating_sub(1),
                b'{' if depth == 0 => {
                    open = Some(i);
                    break;
                }
                b';' if depth == 0 => break,
                _ => {}
            }
        }
        let Some(open) = open else { continue };
        if let Some(close) = closing_brace(code, open) {
            found.push((code[name_start..name_end].to_string(), open..=close));
        }
    }
    found
}

/// The body of the first `fn name` in blanked `code`.
fn fn_body(code: &str, name: &str) -> Option<RangeInclusive<usize>> {
    fn_bodies(code)
        .into_iter()
        .find(|(fn_name, _)| fn_name == name)
        .map(|(_, body)| body)
}

/// The innermost `fn` of blanked `code` whose body holds byte offset `at`.
fn innermost_fn(code: &str, at: usize) -> Option<(String, RangeInclusive<usize>)> {
    fn_bodies(code)
        .into_iter()
        .filter(|(_, body)| body.contains(&at))
        .min_by_key(|(_, body)| body.end() - body.start())
}

/// The body of `mod name { … }` in blanked `code`, braces included.
fn mod_body(code: &str, name: &str) -> Option<RangeInclusive<usize>> {
    let item = format!("mod {name}");
    let b = code.as_bytes();
    let at = code.match_indices(&item).map(|(at, _)| at).find(|at| {
        !prev_is_ident(b, *at) && !b.get(at + item.len()).copied().is_some_and(is_ident_byte)
    })?;
    let open = at + code[at..].find('{')?;
    closing_brace(code, open).map(|close| open..=close)
}

/// The attribute lines directly above the line holding byte offset `at` of
/// `with_literals` (a file blanked of comments only, so a doc comment reads as a blank
/// line and is skipped), trimmed, nearest first.
fn attributes_above(with_literals: &str, at: usize) -> Vec<&str> {
    let line_start = with_literals[..at].rfind('\n').map_or(0, |i| i + 1);
    with_literals[..line_start]
        .lines()
        .rev()
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .take_while(|line| line.starts_with("#["))
        .collect()
}