docextract 0.4.0

documentation extractor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
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
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
#![doc = include_str!("../README.md")]
#![allow(clippy::doc_markdown)]

mod pattern;

use crate::pattern::{Pattern, PatternError};
use std::collections::{HashMap, HashSet};
use std::io::{self, BufWriter, Read, Write};
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::rc::Rc;

/// Holds all parsed entries, their file-to-range mappings, and a global
/// tag interning pool shared across all `Docextract` instances on this thread.
struct Cache {
    /// Global tag interner. Tags are interned via `Rc<str>` so identical
    /// tag names across different parse calls share the same allocation.
    tags: HashSet<Rc<str>>,

    /// All parsed `DocEntry` records from all files, stored contiguously.
    /// A file's entries span `entries[ranges[path].start .. ranges[path].end]`.
    entries: Vec<DocEntry>,

    /// Maps a canonical path to the range of its entries in `entries`.
    /// The presence of a key is the cache-hit test — `contains_key()` is O(1).
    ranges: HashMap<PathBuf, Range<usize>>,
}

thread_local! {
    /// Thread-local global cache. Each OS thread gets its own independent
    /// cache. Within a single thread (the normal build-script case), all
    /// `Docextract` instances share this cache transparently.
    static CACHE: std::cell::RefCell<Cache> = std::cell::RefCell::new(Cache {
        tags: HashSet::new(),
        entries: Vec::new(),
        ranges: HashMap::new(),
    });
}

/// Normalize a path for use as a cache key.
///
/// Uses `canonicalize()` to resolve `.`, `..`, and symlinks.
/// The sentinel `"-"` (stdin) is returned as-is.
fn normalize_path(path: &Path) -> io::Result<PathBuf> {
    if path == Path::new("-") {
        return Ok(PathBuf::from("-"));
    }
    path.canonicalize()
}

/// Intern a tag name into the global interning pool.
fn intern_tag(pool: &mut HashSet<Rc<str>>, name: &str) -> Rc<str> {
    if let Some(existing) = pool.get(name) {
        return Rc::clone(existing);
    }
    let rc: Rc<str> = Rc::from(name.to_string());
    pool.insert(Rc::clone(&rc));
    rc
}

/// Internal enum for the output destination: file or stdout.
///
/// Implements `Write` by dispatching to the appropriate variant.
enum OutputTarget {
    File(std::fs::File),
    Stdout(std::io::Stdout),
}

impl Write for OutputTarget {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match self {
            OutputTarget::File(f) => f.write(buf),
            OutputTarget::Stdout(s) => s.write(buf),
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        match self {
            OutputTarget::File(f) => f.flush(),
            OutputTarget::Stdout(s) => s.flush(),
        }
    }
}

/// A single parsed documentation entry.
struct DocEntry {
    /// Tag name — interned via Rc<str> so identical tags share one allocation.
    tag: Rc<str>,
    /// Line content — includes trailing newline (\n or \r\n) or empty at EOF.
    text: Box<str>,
    /// `true` if this entry was created from a transient tag directive
    /// (`////tagname text`). Transient entries are skipped in unfiltered mode.
    transient: bool,
}

/// Builder for extracting `////` documentation from multiple sources into a
/// single output file.
///
/// Created via `Docextract::new(output_path)`. If the output path is `"-"`,
/// writes to stdout.
///
/// Each `.input()` call processes a file immediately via parse-then-filter.
/// Output from multiple files is concatenated in call order with no separator
/// between files.
///
/// Automatically detects build-script context: if `OUT_DIR` is set at
/// construction time, `cargo:rerun-if-changed` directives are emitted
/// for each file processed by `.input()`.
pub struct Docextract {
    output: Option<BufWriter<OutputTarget>>,
    rerun_if_changed: bool,
    output_filter: Option<Pattern>,
}

/// Extract the initial tag from a file path (filename without extension).
fn path_stem(path: &Path) -> String {
    path.file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("unknown")
        .to_string()
}

impl From<PatternError> for io::Error {
    fn from(e: PatternError) -> io::Error {
        io::Error::new(io::ErrorKind::InvalidInput, e.to_string())
    }
}

impl Docextract {
    /// Create a new builder, writing extracted documentation to `output`.
    ///
    /// If `output` is `"-"`, writes to stdout. Otherwise creates or truncates
    /// the file at the given path.
    ///
    /// The output is wrapped in a 32 KiB `BufWriter` for efficient I/O.
    ///
    /// **Auto-detection**: If `std::env::var("OUT_DIR")` is set (indicating
    /// a build script context), `rerun_if_changed` is initialized to `true`.
    pub fn new(output: impl AsRef<Path>) -> io::Result<Self> {
        let target = if output.as_ref() == Path::new("-") {
            OutputTarget::Stdout(std::io::stdout())
        } else {
            OutputTarget::File(std::fs::File::create(output.as_ref())?)
        };

        let writer = BufWriter::with_capacity(32768, target);

        let rerun_if_changed = std::env::var("OUT_DIR").is_ok();

        Ok(Docextract {
            output: Some(writer),
            rerun_if_changed,
            output_filter: None,
        })
    }

    /// Extract documentation from a file at `path`.
    ///
    /// On first access, reads the entire file, parses it into `DocEntry`
    /// records, and caches them. Subsequent accesses use the cache.
    /// Emits only persistent entries in unfiltered mode (transient skipped).
    ///
    /// # Error Handling
    ///
    /// - **File not found**: prints a warning to stderr and returns `Ok`.
    /// - **Other I/O errors**: returns `Err(io::Error)`.
    pub fn input(&mut self, path: impl AsRef<Path>) -> io::Result<&mut Self> {
        if self.output.is_none() {
            return Err(io::Error::new(
                io::ErrorKind::BrokenPipe,
                "output already closed",
            ));
        }
        self.input_impl(path.as_ref(), None)
    }

    /// Extract documentation from stdin.
    ///
    /// Reads all of stdin, parses it into `DocEntry` records, and caches them
    /// under the key `"-"`. Subsequent calls use the cache.
    ///
    /// Without filters: emits only persistent entries (transient skipped).
    pub fn stdin(&mut self) -> io::Result<&mut Self> {
        if self.output.is_none() {
            return Err(io::Error::new(
                io::ErrorKind::BrokenPipe,
                "output already closed",
            ));
        }
        self.stdin_impl()
    }

    /// Set the output filter pattern.
    ///
    /// Only doc lines whose tag matches this pattern will be emitted.
    /// Applies to all subsequent `.input()`, `.input_filtered()`, and `.stdin()` calls.
    ///
    /// Pass `None` to clear the filter.
    ///
    /// # Errors
    ///
    /// Only on the `regex`-enabled path: returns
    /// `Err(PatternError::InvalidSyntax(...))` if the pattern string is a
    /// malformed regex. On the no-regex path this method never fails.
    pub fn filter_output(&mut self, filter: Option<&str>) -> Result<&mut Self, PatternError> {
        self.output_filter = match filter {
            Some(s) => Some(Pattern::new(s)?),
            None => None,
        };
        Ok(self)
    }

    /// Extract documentation from a file at `path`, applying an input filter
    /// pattern to tag names. Only `DocEntry` items whose tag matches `filter`
    /// are emitted. Transient entries ARE included when a filter is active.
    ///
    /// On first access to a given path, reads the entire file, parses it into
    /// `Vec<DocEntry>`, and stores it in the cache. Subsequent
    /// `.input_filtered()` or `.input()` calls for the same path use the
    /// cached entries.
    ///
    /// `.input_filtered("-", filter)` is supported: reads stdin, caches under
    /// key `"-"`, and filters by tag.
    ///
    /// # Errors
    ///
    /// - Pattern compile errors are converted to `io::Error` with
    ///   `ErrorKind::InvalidInput` via `From<PatternError> for io::Error`.
    /// - File-access errors: file not found → warning to stderr + `Ok`;
    ///   other I/O errors → `Err(io::Error)`.
    /// - Invalid UTF-8 in file content → `Err(io::ErrorKind::InvalidData)`.
    pub fn input_filtered(
        &mut self,
        path: impl AsRef<Path>,
        filter: &str,
    ) -> io::Result<&mut Self> {
        if self.output.is_none() {
            return Err(io::Error::new(
                io::ErrorKind::BrokenPipe,
                "output already closed",
            ));
        }
        let pattern = Pattern::new(filter)?;
        self.input_impl(path.as_ref(), Some(&pattern))
    }

    /// Finalize extraction: flush and close the output writer.
    ///
    /// Returns `&mut self` so that the call is chainable: an idiomatic
    /// one-liner is `Docextract::new(...)?.input(...)?.done()?;`.
    ///
    /// After calling `done()`, the output is closed and further `.input()`
    /// or `.stdin()` calls will error with `BrokenPipe`. Calling `done()`
    /// multiple times is safe (idempotent — subsequent calls are no-ops).
    pub fn done(&mut self) -> io::Result<&mut Self> {
        self.close_output()?;
        Ok(self)
    }

    /// Control whether `cargo:rerun-if-changed` is emitted from `.input()`.
    pub fn rerun_if_changed(&mut self, value: bool) -> &mut Self {
        self.rerun_if_changed = value;
        self
    }

    /// Clear the thread-local global parse cache.
    ///
    /// Drops all cached `DocEntry` records, interned tags, and file-to-range
    /// mappings. Subsequent `.input()` calls will re-read and re-parse files
    /// from disk. Useful between build phases or at the end of a script to
    /// free memory.
    ///
    /// This is a free function (associated function, not a method) — no
    /// instance is required.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use docextract::Docextract;
    /// # use std::io;
    /// # fn example() -> io::Result<()> {
    /// // Phase 1: parse several files into cache
    /// Docextract::new("phase1.md")?.input("src/a.rs")?.done()?;
    ///
    /// // Clear cache between phases to free memory
    /// Docextract::clear_cache();
    ///
    /// // Phase 2: re-parse from scratch
    /// Docextract::new("phase2.md")?.input("src/b.rs")?.done()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn clear_cache() {
        CACHE.with(|c| {
            *c.borrow_mut() = Cache {
                tags: HashSet::new(),
                entries: Vec::new(),
                ranges: HashMap::new(),
            };
        });
    }

    // --- private methods ---

    /// Emit entries to the output writer, applying filters and transient exclusion.
    fn emit_entries(
        &mut self,
        entries: &[DocEntry],
        input_filter: Option<&Pattern>,
        any_filter_active: bool,
    ) -> io::Result<()> {
        let output = self.output.as_mut().expect("output not yet closed");

        for entry in entries {
            // Transient exclusion rule: skip transient entries when no filters are active
            if !any_filter_active && entry.transient {
                continue;
            }

            // Apply filters
            if let Some(f) = input_filter {
                if !f.matches(&entry.tag) {
                    continue;
                }
            }
            if let Some(ref f) = self.output_filter {
                if !f.matches(&entry.tag) {
                    continue;
                }
            }

            output.write_all(entry.text.as_bytes())?;
        }

        Ok(())
    }

    /// Core input implementation — shared by `.input()` and `.input_filtered()`.
    fn input_impl(&mut self, path: &Path, input_filter: Option<&Pattern>) -> io::Result<&mut Self> {
        let is_stdin = path == Path::new("-");

        if is_stdin {
            return self.stdin_impl_with_filter(input_filter);
        }

        let canonical = match normalize_path(path) {
            Ok(p) => p,
            Err(e) if e.kind() == io::ErrorKind::NotFound => {
                eprintln!(
                    "docextract: warning: input file not found: {}",
                    path.display()
                );
                return Ok(self);
            }
            Err(e) => return Err(e),
        };

        CACHE.with(|c| {
            let mut cache = c.borrow_mut();

            // Check cache first
            if let Some(range) = cache.ranges.get(&canonical).cloned() {
                let any_filter_active = self.output_filter.is_some() || input_filter.is_some();
                self.emit_entries(&cache.entries[range], input_filter, any_filter_active)?;
                return Ok(self);
            }

            // Cache miss — read file, parse, store
            let file = match std::fs::File::open(path) {
                Ok(f) => f,
                Err(e) if e.kind() == io::ErrorKind::NotFound => {
                    eprintln!(
                        "docextract: warning: input file not found: {}",
                        path.display()
                    );
                    return Ok(self);
                }
                Err(e) => return Err(e),
            };

            let content = {
                let mut buf = String::new();
                let mut reader = std::io::BufReader::new(file);
                reader.read_to_string(&mut buf)?;
                buf
            };

            if self.rerun_if_changed {
                println!("cargo:rerun-if-changed={}", path.display());
            }

            let initial_tag = path_stem(path);
            let new_entries = parse_doc_entries(&mut cache.tags, &content, &initial_tag);
            let start = cache.entries.len();
            cache.entries.extend(new_entries);
            let end = cache.entries.len();
            cache.ranges.insert(canonical, start..end);

            let any_filter_active = self.output_filter.is_some() || input_filter.is_some();
            self.emit_entries(&cache.entries[start..end], input_filter, any_filter_active)?;

            Ok(self)
        })
    }

    fn stdin_impl(&mut self) -> io::Result<&mut Self> {
        self.stdin_impl_with_filter(None)
    }

    fn stdin_impl_with_filter(&mut self, input_filter: Option<&Pattern>) -> io::Result<&mut Self> {
        let key = PathBuf::from("-");

        CACHE.with(|c| {
            let mut cache = c.borrow_mut();

            // Check cache first
            if let Some(range) = cache.ranges.get(&key).cloned() {
                let any_filter_active = self.output_filter.is_some() || input_filter.is_some();
                self.emit_entries(&cache.entries[range], input_filter, any_filter_active)?;
                return Ok(self);
            }

            // Read all of stdin
            let mut content = String::new();
            io::stdin().read_to_string(&mut content)?;

            let new_entries = parse_doc_entries(&mut cache.tags, &content, "-");
            let start = cache.entries.len();
            cache.entries.extend(new_entries);
            let end = cache.entries.len();
            cache.ranges.insert(key, start..end);

            let any_filter_active = self.output_filter.is_some() || input_filter.is_some();
            self.emit_entries(&cache.entries[start..end], input_filter, any_filter_active)?;

            Ok(self)
        })
    }

    /// Flush and close the output writer. Idempotent — safe to call multiple
    /// times (subsequent calls are no-ops).
    fn close_output(&mut self) -> io::Result<()> {
        match self.output.take() {
            Some(mut writer) => {
                let result = writer.flush();
                drop(writer);
                if let Err(ref e) = result {
                    eprintln!("docextract: error: output: {e}");
                }
                result
            }
            None => Ok(()),
        }
    }
}

impl Drop for Docextract {
    /// Flushes and closes the output writer via `close_output()`.
    ///
    /// Flush errors are printed to stderr inside `close_output()` — they
    /// cannot be returned from `Drop`. After `.done()` has run, the writer
    /// is `None` and this `close_output()` is a no-op.
    fn drop(&mut self) {
        let _ = self.close_output();
    }
}

/// Parse all documentation entries from raw file content.
///
/// Uses the global tag interning pool for tag deduplication — tags
/// from all files share one pool.
#[allow(clippy::too_many_lines)]
fn parse_doc_entries(
    pool: &mut HashSet<Rc<str>>,
    content: &str,
    initial_tag: &str,
) -> Vec<DocEntry> {
    let mut entries = Vec::new();

    let initial_tag_rc = intern_tag(pool, initial_tag);
    let mut current_tag = Rc::clone(&initial_tag_rc);
    let mut capture_zone_indent: Option<usize> = None;

    for line_slice in content.split_inclusive('\n') {
        // Step 1: Try to skip leading whitespace and match four slashes
        let after_prefix = try_skip_leading_ws_and_four_slashes(line_slice);
        let Some(after) = after_prefix else {
            // Check for code-capturing line (non-//// path)
            let line_content = strip_trailing_newline(line_slice);
            if let Some((captured_code, template)) = try_split_code_capturing(line_content) {
                if let Some((tag_name, remaining, is_transient)) = parse_template_tag(template) {
                    let tag_rc = intern_tag(pool, tag_name);
                    if is_transient {
                        let resolved = resolve_placeholders(remaining, captured_code);
                        let ending = extract_line_ending(line_slice);
                        let text = format!("{resolved}{ending}");
                        entries.push(DocEntry {
                            tag: tag_rc,
                            text: Box::from(text),
                            transient: true,
                        });
                    } else {
                        current_tag = tag_rc; // persistent switch, no entry
                    }
                } else {
                    let resolved = resolve_placeholders(template, captured_code);
                    let ending = extract_line_ending(line_slice);
                    let text = format!("{resolved}{ending}");
                    entries.push(DocEntry {
                        tag: Rc::clone(&current_tag),
                        text: Box::from(text),
                        transient: false,
                    });
                }
                // Record indent of this code-capturing line for zone tracking
                let indent = line_slice
                    .bytes()
                    .take_while(|&b| b == b' ' || b == b'\t')
                    .count();
                capture_zone_indent = Some(indent);
            } else {
                capture_zone_indent = None;
            }
            continue;
        };

        let rest = &line_slice[after..];

        // Step 2: Five+ slashes → ignore
        if rest.as_bytes().first() == Some(&b'/') {
            capture_zone_indent = None;
            continue;
        }

        // Step 2a: Capture zone continuation — when a //// line
        // appears at deeper indent than the previous code-capturing
        // line, treat it as a code-capturing suffix (not a doc line).
        if let Some(zone_indent) = capture_zone_indent {
            let line_indent = after - 4; // indent = pos where //// starts
            if line_indent > zone_indent {
                // Deeper indent — treat this as code-capturing suffix.
                // Captured code is just leading whitespace → empty.
                let template = match rest.as_bytes().first() {
                    Some(&b' ' | &b'\t') => strip_trailing_newline(&rest[1..]),
                    Some(&b'\n' | &b'\r') | None => "",
                    _ => strip_trailing_newline(rest),
                };
                if let Some((tag_name, remaining, is_transient)) = parse_template_tag(template) {
                    let tag_rc = intern_tag(pool, tag_name);
                    if is_transient {
                        let resolved = resolve_placeholders(remaining, "");
                        let ending = extract_line_ending(line_slice);
                        let text = format!("{resolved}{ending}");
                        entries.push(DocEntry {
                            tag: tag_rc,
                            text: Box::from(text),
                            transient: true,
                        });
                    } else {
                        current_tag = tag_rc; // persistent switch, no entry
                    }
                } else {
                    let resolved = resolve_placeholders(template, "");
                    let ending = extract_line_ending(line_slice);
                    let text = format!("{resolved}{ending}");
                    entries.push(DocEntry {
                        tag: Rc::clone(&current_tag),
                        text: Box::from(text),
                        transient: false,
                    });
                }
                continue; // keep zone open — do NOT reset indent
            }
            capture_zone_indent = None; // not deeper — reset zone
        }

        // Step 3: Classify by byte after ////
        let Some(first_byte) = rest.as_bytes().first().copied() else {
            // "////" at EOF — handle as CASE A (empty text)
            // This matches P07/P37: empty doc line at EOF → empty-text entry
            entries.push(DocEntry {
                tag: Rc::clone(&current_tag),
                text: Box::from(""),
                transient: false,
            });
            continue;
        };

        match first_byte {
            b' ' | b'\t' => {
                // CASE B: separator → regular doc line
                let text = &rest[1..]; // strip separator, preserve \n/\r\n
                entries.push(DocEntry {
                    tag: Rc::clone(&current_tag),
                    text: Box::from(text),
                    transient: false,
                });
            }
            b'\n' | b'\r' => {
                // CASE C/D: newline after //// → regular doc line (verbatim blank)
                entries.push(DocEntry {
                    tag: Rc::clone(&current_tag),
                    text: Box::from(rest),
                    transient: false,
                });
            }
            _ => {
                // Tag directive — parse name and optional text
                let (name, text_opt) = parse_tag_directive_from_rest(rest);

                // Intern the tag name
                let tag_rc = intern_tag(pool, name);

                match text_opt {
                    None => {
                        // Persistent tag switch — update current_tag, no DocEntry
                        current_tag = tag_rc;
                    }
                    Some(text) => {
                        // Transient tag — create DocEntry, don't change current_tag
                        entries.push(DocEntry {
                            tag: tag_rc,
                            text: Box::from(text),
                            transient: true,
                        });
                    }
                }
            }
        }
    }

    entries
}

/// Try to skip leading ASCII whitespace and match exactly four slashes.
/// Returns the position after the four slashes, or `None` if not a match.
fn try_skip_leading_ws_and_four_slashes(line: &str) -> Option<usize> {
    let b = line.as_bytes();
    let mut pos: usize = 0;

    // Skip leading ASCII whitespace (space 0x20, tab 0x09)
    while pos < b.len() && (b[pos] == 0x20 || b[pos] == 0x09) {
        pos += 1;
    }

    // Require exactly four slashes (0x2F)
    if pos + 4 > b.len() {
        return None;
    }
    if b[pos] != 0x2F || b[pos + 1] != 0x2F || b[pos + 2] != 0x2F || b[pos + 3] != 0x2F {
        return None;
    }

    Some(pos + 4)
}

/// Parse a tag directive from a code-capturing template.
///
/// Returns `None` if the template starts with `{` (placeholder), `/` (five+
/// slashes), whitespace, or is empty. Otherwise scans for a space, tab, or
/// end-of-line to extract the tag name.
///
/// Returns `Some((tag_name, remaining_template, is_transient))` where
/// `is_transient` is `true` when a space or tab was found after the tag name
/// (indicating inline text follows).
fn parse_template_tag(template: &str) -> Option<(&str, &str, bool)> {
    let b = template.as_bytes();
    if b.is_empty() {
        return None;
    }
    match b[0] {
        b'{' | b'/' | b' ' | b'\t' => return None,
        _ => {}
    }
    // Scan for space, tab, or EOL to find the tag name boundary.
    for (i, &byte) in b.iter().enumerate().skip(1) {
        match byte {
            b' ' | b'\t' => {
                return Some((&template[..i], &template[i + 1..], true));
            }
            b'\n' | b'\r' => {
                return Some((&template[..i], &template[i..], false));
            }
            _ => {}
        }
    }
    // No space/tab/newline found — persistent switch with empty remaining.
    Some((template, "", false))
}

/// Parse a tag directive from the bytes after `////`.
///
/// Given `rest` = the bytes after `////` (known to start with a non-whitespace,
/// non-slash, non-newline byte), returns `(tag_name, optional_text)`.
fn parse_tag_directive_from_rest(rest: &str) -> (&str, Option<&str>) {
    // Strip trailing \n or \r\n to get the content without line ending
    let raw_tag = rest.trim_end_matches(['\n', '\r']);

    // Find first whitespace in raw_tag
    if let Some(ws_pos) = raw_tag.find(&[' ', '\t'] as &[char]) {
        let name = &raw_tag[..ws_pos];
        // text = everything after the whitespace in `rest` (preserving \n)
        let text = &rest[ws_pos + 1..];
        (name, Some(text))
    } else {
        (raw_tag, None)
    }
}

// ---------------------------------------------------------------------
// Code-lifting: placeholder-based code capture (specs/code-lifting-spec.md)
//
// Batch 1 (implemented): Leaf functions — trim helpers, try_split_code_capturing,
// resolve_placeholders, resolve_single_placeholder, unescape_delimiter,
// parse_sed_placeholder. Unit tests S01-S18, R01-R21, U01-U05 pass.
//
// Batch 2 (integration): Wiring into parse_doc_entries, integration tests
// (E01-E17, EX01-EX08, F01-F05), and D01-D11 tests for parse_sed_placeholder.
// `#[allow(dead_code)]` is required because integration wiring hasn't landed
// yet (or for cfg-gated sed-like paths).
// ---------------------------------------------------------------------

/// Return the length after stripping trailing ASCII space (0x20) and tab (0x09).
///
/// Contract: code-lifting-spec.md §6.4 (REQ-LIFT-F-003). Returns the byte
/// index of the first trailing space/tab byte — the caller slices `&bytes[..n]`
/// to get the trimmed content.
#[allow(
    dead_code,
    reason = "only used by tests and code-capturing integration (not yet wired into parse_doc_entries)"
)]
fn trim_trailing_space_tab(bytes: &[u8]) -> usize {
    let mut end = bytes.len();
    while end > 0 && (bytes[end - 1] == b' ' || bytes[end - 1] == b'\t') {
        end -= 1;
    }
    end
}

/// Strip leading ASCII space (0x20) and tab (0x09) from `s`.
///
/// Contract: code-lifting-spec.md §6.3.2 (REQ-LIFT-F-004).
/// Used only by `{{}}` resolution.
#[allow(
    dead_code,
    reason = "only used by tests and code-capturing integration"
)]
fn trim_leading_space_tab(s: &str) -> &str {
    let bytes = s.as_bytes();
    let mut start = 0;
    while start < bytes.len() && (bytes[start] == b' ' || bytes[start] == b'\t') {
        start += 1;
    }
    &s[start..]
}

/// Detect a code-capturing line and split it at the rightmost `////`
/// immediately preceded by space (0x20) or tab (0x09).
///
/// Contract: code-lifting-spec.md §6.1.2 (REQ-LIFT-F-001, REQ-LIFT-F-002,
/// REQ-LIFT-F-003). Returns `Some((captured_code, template))` where captured
/// code has trailing space/tab stripped. Returns `None` when the line has
/// no `////` preceded by space/tab.
///
/// `line` is the content without trailing `\n` or `\r\n`.
#[allow(
    dead_code,
    reason = "only used by tests and code-capturing integration"
)]
fn try_split_code_capturing(line: &str) -> Option<(&str, &str)> {
    let b = line.as_bytes();

    for i in (0..=b.len().saturating_sub(4)).rev() {
        // Guard against lines shorter than 4 bytes.
        if i + 3 >= b.len() {
            continue;
        }
        if b[i] == b'/' && b[i + 1] == b'/' && b[i + 2] == b'/' && b[i + 3] == b'/' {
            // Require separator (space or tab) before ////
            if i == 0 || (b[i - 1] != b' ' && b[i - 1] != b'\t') {
                continue;
            }

            let separator_pos = i - 1;
            let after_slashes = i + 4;

            // Captured code: trim trailing space/tab.
            let code_end = trim_trailing_space_tab(&b[..separator_pos]);
            let captured_code = &line[..code_end];

            // Doc template: consume one separator byte after //// if present.
            let template = if after_slashes >= b.len() {
                ""
            } else if b[after_slashes] == b' ' || b[after_slashes] == b'\t' {
                &line[after_slashes + 1..]
            } else {
                &line[after_slashes..]
            };

            return Some((captured_code, template));
        }
    }

    None
}

/// Replace `\<delim>` sequences with a literal `delim` byte.
///
/// Contract: code-lifting-spec.md §6.3.4.1 (REQ-LIFT-F-008). Only a backslash
/// immediately followed by the delimiter byte is unescaped; all other
/// backslash sequences pass through unchanged.
///
/// Iterates at the char level to preserve multi-byte UTF-8 sequences.
fn unescape_delimiter(s: &str, delim: u8) -> String {
    let delim_char = delim as char;
    let mut result = String::with_capacity(s.len());
    let mut iter = s.chars().peekable();
    while let Some(ch) = iter.next() {
        if ch == '\\' {
            if let Some(&next_ch) = iter.peek() {
                if next_ch == delim_char {
                    result.push(delim_char);
                    iter.next(); // consume the delimiter
                    continue;
                }
            }
        }
        result.push(ch);
    }
    result
}

/// Minimal RED scaffolding for the sed-like placeholder parse result.
///
/// Contract per code-lifting-spec.md §6.3.4 (REQ-LIFT-F-008): extract mode
/// (`{{XregexX}}`) has `subst = None`; replace mode (`{{XregexXsubstX}}`)
/// has `subst = Some(...)`. Struct form is RED scaffolding only — batch 2
/// (D01–D11 tests) will pin the exact shape when they land.
#[allow(dead_code, reason = "RED scaffolding; constructed in batch 2")]
struct SedForm {
    regex: String,
    subst: Option<String>,
}

/// Minimal RED scaffolding for sed-like parse errors.
#[allow(dead_code, reason = "RED scaffolding; constructed in batch 2")]
struct SedError(String);

/// Parse a sed-like placeholder form `XregexX` or `XregexXsubstX`.
///
/// Contract: code-lifting-spec.md §6.3.4.1 (REQ-LIFT-F-008). `content` is the
/// text between `{{` and `}}`; the first byte is the delimiter. Returns
/// extract mode when only two delimiters are found, replace mode when three
/// are found. Returns `Err(SedError)` when no closing delimiter is found.
#[allow(
    dead_code,
    reason = "only called from cfg(feature = \"regex\") code path"
)]
fn parse_sed_placeholder(content: &str) -> Result<SedForm, SedError> {
    let delim = content.as_bytes()[0];
    let inner = &content[1..];

    // Find first unescaped delimiter → regex/subst boundary.
    let mut regex_end: Option<usize> = None;
    let mut i = 0;
    while i < inner.len() {
        if inner.as_bytes()[i] == delim {
            // Escaped delimiter? Check for preceding backslash.
            if i > 0 && inner.as_bytes()[i - 1] == b'\\' {
                i += 1;
                continue;
            }
            regex_end = Some(i);
            break;
        }
        i += 1;
    }

    let Some(regex_end) = regex_end else {
        return Err(SedError("unterminated regex".to_string()));
    };

    let regex_raw = &inner[..regex_end];
    let after_regex = &inner[regex_end + 1..];

    // Unescape the regex field.
    let regex_unescaped = unescape_delimiter(regex_raw, delim);

    // Scan for third delimiter (substitution separator) or closing }}.
    let mut subst_end: Option<usize> = None;
    let mut j = 0;
    while j < after_regex.len() {
        if after_regex.as_bytes()[j] == delim {
            if j > 0 && after_regex.as_bytes()[j - 1] == b'\\' {
                j += 1;
                continue;
            }
            subst_end = Some(j);
            break;
        }
        j += 1;
    }

    match subst_end {
        Some(end) => {
            // Replace mode: three delimiters found.
            let subst_raw = &after_regex[..end];
            let subst_unescaped = unescape_delimiter(subst_raw, delim);
            Ok(SedForm {
                regex: regex_unescaped,
                subst: Some(subst_unescaped),
            })
        }
        None => {
            // Extract mode: only two delimiters found.
            Ok(SedForm {
                regex: regex_unescaped,
                subst: None,
            })
        }
    }
}

/// Check whether a byte is an ASCII punctuation character usable as a
/// sed-like placeholder delimiter.
///
/// Excludes `(`, `)`, `{`, `}` to avoid ambiguity with placeholder braces
/// and regex group syntax.
#[allow(
    dead_code,
    reason = "only used by resolve_single_placeholder (itself guarded by dead_code)"
)]
fn is_ascii_punctuation(b: u8) -> bool {
    matches!(
        b,
        b'!' | b'"'
            | b'#'
            | b'$'
            | b'%'
            | b'&'
            | b'\''
            | b'*'
            | b'+'
            | b','
            | b'-'
            | b'.'
            | b'/'
            | b':'
            | b';'
            | b'<'
            | b'='
            | b'>'
            | b'?'
            | b'@'
            | b'['
            | b'\\'
            | b']'
            | b'^'
            | b'_'
            | b'`'
            | b'|'
            | b'~'
    )
}

/// Resolve a single `{{...}}` placeholder against captured code.
///
/// First-byte dispatch per code-lifting-spec.md §6.3: empty content →
/// `{{}}` double-trim; digit → `{{N}}` character removal; ASCII punctuation
/// → sed-like form; anything else → reserved-form panic.
#[allow(
    dead_code,
    reason = "only used by tests and resolve_placeholders (not yet wired into parse_doc_entries)"
)]
fn resolve_single_placeholder(content: &str, captured_code: &str) -> String {
    // {{}} — content is empty because the scanner found "}}" immediately
    // after "{{". Apply double-trim: trailing already stripped by split,
    // now strip leading space/tab.
    if content.is_empty() {
        return trim_leading_space_tab(captured_code).to_string();
    }

    let first_byte = content.as_bytes()[0];

    // {{N}} — first byte is '0'..='9'.
    if first_byte.is_ascii_digit() {
        let n: usize = content.parse().unwrap_or(usize::MAX);
        let char_count = captured_code.chars().count();
        if n >= char_count {
            return String::new();
        }
        return captured_code.chars().skip(n).collect();
    }

    // Sed-like form — first byte is ASCII punctuation.
    if is_ascii_punctuation(first_byte) {
        #[cfg(feature = "regex")]
        {
            let form = parse_sed_placeholder(content)
                .unwrap_or_else(|e| panic!("docextract: invalid sed placeholder: {}", e.0));

            return match form.subst {
                None => {
                    // Extract mode
                    let re = regex_lite::Regex::new(&form.regex).unwrap_or_else(|e| {
                        eprintln!("docextract: warning: invalid regex '{}': {}", form.regex, e);
                        regex_lite::Regex::new("\\b\\B").expect("\\b\\B is a valid regex pattern")
                    });
                    match re.find(captured_code) {
                        Some(m) => m.as_str().to_string(),
                        None => String::new(),
                    }
                }
                Some(subst) => {
                    // Replace mode — output only the expanded substitution
                    // of the first match; discard non-matched text.
                    let re = regex_lite::Regex::new(&form.regex).unwrap_or_else(|e| {
                        eprintln!("docextract: warning: invalid regex '{}': {}", form.regex, e);
                        regex_lite::Regex::new("\\b\\B").expect("\\b\\B is a valid regex pattern")
                    });
                    if let Some(m) = re.find(captured_code) {
                        re.replace(m.as_str(), subst.as_str()).into_owned()
                    } else {
                        String::new()
                    }
                }
            };
        }
        #[cfg(not(feature = "regex"))]
        {
            panic!(
                "docextract: sed-like placeholder '{{{{{content}}}}}' requires the `regex` feature.\n\
                 Rebuild with default features (cargo build) or use only {{{{}}}} and {{{{N}}}} placeholders."
            );
        }
    }

    // Reserved form — anything else.
    panic!(
        "docextract: reserved placeholder form '{{{{{content}}}}}'.\n\
         Use {{{{}}}}, {{{{N}}}}, or a sed-like form {{{{X...X}}}}."
    );
}

/// Resolve all `{{...}}` placeholders in a template against captured code.
///
/// Scanner per code-lifting-spec.md §6.5. Unterminated `{{` (no closing `}}`)
/// is emitted literally.
///
/// `captured_code` must already have trailing space/tab stripped.
#[allow(
    dead_code,
    reason = "only used by tests and code-capturing integration"
)]
fn resolve_placeholders(template: &str, captured_code: &str) -> String {
    let mut result = String::new();
    let mut pos = 0;

    while pos < template.len() {
        if template[pos..].starts_with("{{") {
            let search_from = pos + 2;
            if let Some(close_offset) = template[search_from..].find("}}") {
                let close_pos = search_from + close_offset;
                let content = &template[search_from..close_pos];
                let replacement = resolve_single_placeholder(content, captured_code);
                result.push_str(&replacement);
                pos = close_pos + 2;
            } else {
                // No closing }} — emit {{ literally.
                result.push_str("{{");
                pos += 2;
            }
        } else {
            let ch = template[pos..]
                .chars()
                .next()
                .expect("pos < template.len() guarantees at least one char");
            result.push(ch);
            pos += ch.len_utf8();
        }
    }

    result
}

/// Strip a trailing `\n` or `\r\n` from `s`, returning the content
/// without the line ending.
///
/// At EOF (no trailing newline), returns `s` unchanged.
fn strip_trailing_newline(s: &str) -> &str {
    if let Some(stripped) = s.strip_suffix("\r\n") {
        stripped
    } else if let Some(stripped) = s.strip_suffix('\n') {
        stripped
    } else {
        s
    }
}

/// Return the line ending of `s`: `"\r\n"`, `"\n"`, or `""` (EOF).
fn extract_line_ending(s: &str) -> &str {
    if s.ends_with("\r\n") {
        "\r\n"
    } else if s.ends_with('\n') {
        "\n"
    } else {
        ""
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used)]

    // --- B01-B28: Docextract builder API tests (lib-spec.md §11.2) ---

    use super::*;
    use std::fmt::Write as FmtWrite;
    use std::fs;
    use std::path::PathBuf;
    use std::sync::{Mutex, MutexGuard};

    /// Unique per-test temp directory; removed on drop (also on panic).
    struct TempDir(PathBuf);

    impl TempDir {
        fn new(name: &str) -> TempDir {
            let dir = std::env::temp_dir().join(format!(
                "docextract-test-{}-pid{}-{:?}",
                name,
                std::process::id(),
                std::thread::current().id(),
            ));
            fs::create_dir_all(&dir).unwrap();
            TempDir(dir)
        }

        fn file(&self, name: &str) -> PathBuf {
            self.0.join(name)
        }

        fn write(&self, name: &str, content: &str) -> PathBuf {
            let path = self.file(name);
            fs::write(&path, content).unwrap();
            path
        }

        fn write_bytes(&self, name: &str, content: &[u8]) -> PathBuf {
            let path = self.file(name);
            fs::write(&path, content).unwrap();
            path
        }
    }

    impl Drop for TempDir {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.0);
        }
    }

    fn read_str(path: &Path) -> String {
        fs::read_to_string(path).unwrap()
    }

    /// Serializes `OUT_DIR` mutation: env vars are process-global and tests run
    /// in parallel, so tests that read `OUT_DIR` must not race each other.
    static OUT_DIR_LOCK: Mutex<()> = Mutex::new(());

    /// RAII guard: sets/removes `OUT_DIR` for the duration of the guard and
    /// restores the previous value on drop.
    struct OutDirGuard {
        prev: Option<std::ffi::OsString>,
        _lock: MutexGuard<'static, ()>,
    }

    impl OutDirGuard {
        fn with(value: Option<&std::ffi::OsStr>) -> OutDirGuard {
            let lock = OUT_DIR_LOCK.lock().unwrap();
            let prev = std::env::var_os("OUT_DIR");
            match value {
                Some(v) => unsafe { std::env::set_var("OUT_DIR", v) },
                None => unsafe { std::env::remove_var("OUT_DIR") },
            }
            OutDirGuard { prev, _lock: lock }
        }
    }

    impl Drop for OutDirGuard {
        fn drop(&mut self) {
            match &self.prev {
                Some(v) => unsafe { std::env::set_var("OUT_DIR", v) },
                None => unsafe { std::env::remove_var("OUT_DIR") },
            }
        }
    }

    #[test]
    fn b01_single_file_extraction() {
        // BUILDER-F-001: `.input("valid.rs")` → output file contains extracted docs.
        // No interspersed non-doc code means no block break → no auto-separator.
        // (The tag-filter model removes auto inter-block separators; entries are
        // concatenated back-to-back per tag-filter-spec.md §6.2.4.)
        let tmp = TempDir::new("b01");
        let src = tmp.write(
            "valid.rs",
            "//// Hello World\nfn main() {}\n//// Second line\n",
        );
        let out = tmp.file("out.md");
        Docextract::new(&out)
            .unwrap()
            .input(&src)
            .unwrap()
            .done()
            .unwrap();
        // Entries are concatenated without separators in the cache-first model
        assert_eq!(read_str(&out), "Hello World\nSecond line\n");
    }

    #[test]
    fn b02_multiple_files_concatenated() {
        // BUILDER-F-002: two files → docs concatenated, no inter-file separator (§5.1)
        let tmp = TempDir::new("b02");
        let a = tmp.write("a.rs", "//// From A\n");
        let b = tmp.write("b.rs", "//// From B\n");
        let out = tmp.file("out.md");
        Docextract::new(&out)
            .unwrap()
            .input(&a)
            .unwrap()
            .input(&b)
            .unwrap()
            .done()
            .unwrap();
        assert_eq!(read_str(&out), "From A\nFrom B\n");
    }

    #[test]
    fn b03_missing_file_warns_and_continues() {
        // BUILDER-F-010: file not found → warning to stderr, returns Ok, continues
        let tmp = TempDir::new("b03");
        let src = tmp.write("valid.rs", "//// From Valid\n");
        let out = tmp.file("out.md");
        let mut builder = Docextract::new(&out).unwrap();
        // Missing input: Ok returned (warning goes to stderr, not captured here).
        assert!(builder.input(tmp.file("missing.rs")).is_ok());
        // Processing continues with the remaining input.
        builder.input(&src).unwrap();
        builder.done().unwrap();
        assert_eq!(read_str(&out), "From Valid\n");
    }

    #[test]
    fn b04_zero_inputs_empty_output() {
        // BUILDER-F-003: `.done()` with zero inputs → empty output file, Ok
        let tmp = TempDir::new("b04");
        let out = tmp.file("out.md");
        Docextract::new(&out).unwrap().done().unwrap();
        assert!(out.exists());
        assert_eq!(read_str(&out), "");
    }

    #[test]
    fn b05_stdin_input() {
        // BUILDER-F-004: extraction from a stream source.
        let tmp = TempDir::new("b05");
        let src = tmp.write("stdin-content.txt", "//// From stdin\n");
        let out = tmp.file("out.md");
        Docextract::new(&out)
            .unwrap()
            .input(&src)
            .unwrap()
            .done()
            .unwrap();
        assert_eq!(read_str(&out), "From stdin\n");
    }

    #[test]
    fn b06_stdin_and_file_combined() {
        // BUILDER-F-005: mix `.input("file.rs")` + `.stdin()` → both sources
        let tmp = TempDir::new("b06");
        let file = tmp.write("file.rs", "//// From File\n");
        let stdin_content = tmp.write("stdin.txt", "//// From stdin\n");
        let out = tmp.file("out.md");
        Docextract::new(&out)
            .unwrap()
            .input(&file)
            .unwrap()
            .input(&stdin_content)
            .unwrap()
            .done()
            .unwrap();
        assert_eq!(read_str(&out), "From File\nFrom stdin\n");
    }

    #[test]
    fn b07_mixed_valid_and_invalid_inputs() {
        // BUILDER-F-001/016: doc-bearing file + file with only non-doc lines
        let tmp = TempDir::new("b07");
        let docs = tmp.write("docs.rs", "//// Kept\n");
        let no_docs = tmp.write(
            "code.rs",
            "fn main() {\n    // not a doc\n}\n////Bad\n///// five\n////### Heading\n",
        );
        let out = tmp.file("out.md");
        Docextract::new(&out)
            .unwrap()
            .input(&docs)
            .unwrap()
            .input(&no_docs)
            .unwrap()
            .done()
            .unwrap();
        // Non-doc lines silently ignored; `////Bad` is a tag directive (no entry);
        // only `docs.rs` contributes.
        assert_eq!(read_str(&out), "Kept\n");
    }

    #[test]
    fn b08_read_error_returns_err() {
        // BUILDER-F-011: read error (mid-stream) → Err(io::Error).
        let tmp = TempDir::new("b08");
        let dir = tmp.file("a_directory");
        fs::create_dir_all(&dir).unwrap();
        let out = tmp.file("out.md");
        assert!(Docextract::new(&out).unwrap().input(&dir).is_err());
    }

    #[test]
    fn b09_output_file_created() {
        // BUILDER-F-014-adjacent: new() creates (and truncates) the output file
        let tmp = TempDir::new("b09");
        let out = tmp.file("out.md");
        assert!(!out.exists());
        let mut builder = Docextract::new(&out).unwrap();
        assert!(out.exists(), "output file must be created by new()");
        builder.done().unwrap();
        // Truncation: pre-existing content is wiped.
        let out2 = tmp.file("pre.md");
        fs::write(&out2, "stale content").unwrap();
        Docextract::new(&out2).unwrap().done().unwrap();
        assert_eq!(read_str(&out2), "");
    }

    #[test]
    fn b10_stdout_output_path() {
        // BUILDER-F-022: `new("-")` targets stdout — no file named "-" is created.
        let tmp = TempDir::new("b10");
        Docextract::new("-")
            .unwrap()
            .input(tmp.write("in.rs", "//// To stdout\n"))
            .unwrap()
            .done()
            .unwrap();
        assert!(
            !std::path::Path::new("-").exists(),
            "no file named '-' should be created in the working directory"
        );
    }

    #[test]
    fn b11_rerun_if_changed_false_suppresses() {
        // BUILDER-F-007: `.rerun_if_changed(false)` suppresses cargo: directives.
        let tmp = TempDir::new("b11");
        let src = tmp.write("in.rs", "//// Doc\n");
        let out = tmp.file("out.md");
        let mut builder = Docextract::new(&out).unwrap();
        builder.rerun_if_changed(false);
        builder.input(&src).unwrap();
        builder.done().unwrap();
        assert_eq!(read_str(&out), "Doc\n");
    }

    #[test]
    fn b12_last_toggle_wins() {
        // BUILDER-F-008: repeated toggles — the last call wins.
        let tmp = TempDir::new("b12");
        let src = tmp.write("in.rs", "//// Doc\n");
        let out = tmp.file("out.md");
        let mut builder = Docextract::new(&out).unwrap();
        builder.rerun_if_changed(true);
        builder.rerun_if_changed(false);
        builder.rerun_if_changed(true);
        builder.input(&src).unwrap();
        builder.done().unwrap();
        assert_eq!(read_str(&out), "Doc\n");
    }

    #[test]
    fn b13_out_dir_set_auto_detects() {
        // BUILDER-F-006: with OUT_DIR set, new() auto-enables rerun-if-changed
        let tmp = TempDir::new("b13");
        let src = tmp.write("in.rs", "//// Doc\n");
        let out = tmp.file("out.md");
        let _guard = OutDirGuard::with(Some(tmp.file("out_dir").as_os_str()));
        let mut builder = Docextract::new(&out).unwrap();
        builder.input(&src).unwrap();
        builder.done().unwrap();
        assert_eq!(read_str(&out), "Doc\n");
    }

    #[test]
    fn b14_out_dir_unset_default_false() {
        // BUILDER-F-024: with OUT_DIR unset, rerun_if_changed defaults to false.
        let tmp = TempDir::new("b14");
        let src = tmp.write("in.rs", "//// Doc\n");
        let out = tmp.file("out.md");
        let _guard = OutDirGuard::with(None);
        let mut builder = Docextract::new(&out).unwrap();
        builder.input(&src).unwrap();
        builder.done().unwrap();
        assert_eq!(read_str(&out), "Doc\n");
    }

    #[test]
    fn b15_done_then_drop_no_double_close() {
        // BUILDER-F-009 + §6.1: `.done()` is chainable and idempotent
        let tmp = TempDir::new("b15");
        let src = tmp.write("in.rs", "//// Doc\n");
        let out = tmp.file("out.md");
        let mut builder = Docextract::new(&out).unwrap();
        builder.input(&src).unwrap();
        builder.done().unwrap();
        builder.done().unwrap();
        assert_eq!(read_str(&out), "Doc\n");
    }

    #[test]
    fn b16_drop_without_done_flushes() {
        // BUILDER-F-023: Drop flushes and closes the output via close_output().
        let tmp = TempDir::new("b16");
        let src = tmp.write("in.rs", "//// Doc\n");
        let out = tmp.file("out.md");
        {
            let mut builder = Docextract::new(&out).unwrap();
            builder.input(&src).unwrap();
            // No .done() — Drop must flush the writer.
        }
        assert_eq!(read_str(&out), "Doc\n");
    }

    #[test]
    fn b17_empty_file_no_output() {
        // BUILDER-F-015: empty input file → no output, no error
        let tmp = TempDir::new("b17");
        let src = tmp.write("empty.rs", "");
        let out = tmp.file("out.md");
        Docextract::new(&out)
            .unwrap()
            .input(&src)
            .unwrap()
            .done()
            .unwrap();
        assert_eq!(read_str(&out), "");
    }

    #[test]
    fn b18_no_doc_lines_empty_output() {
        // BUILDER-F-016: file with only non-doc lines → empty output, no error.
        // In the cache-first model, `////Bad`, `///// five` are all handled:
        // `////Bad` is a persistent tag directive (no entry), `/////` is ignored.
        let tmp = TempDir::new("b18");
        let src = tmp.write(
            "code.rs",
            "fn main() {\n    println!(\"hi\");\n}\n// regular\n/// rustdoc\n////Bad\n///// five\n",
        );
        let out = tmp.file("out.md");
        Docextract::new(&out)
            .unwrap()
            .input(&src)
            .unwrap()
            .done()
            .unwrap();
        assert_eq!(read_str(&out), "");
    }

    #[test]
    fn b19_crlf_preserved() {
        // BUILDER-F-017: CRLF line endings preserved in output.
        // Cache-first model: no auto inter-block separators.
        let tmp = TempDir::new("b19");
        let src = tmp.write(
            "crlf.rs",
            "//// First\r\n//// Second\r\nlet x = 1;\r\n//// Third\r\n",
        );
        let out = tmp.file("out.md");
        Docextract::new(&out)
            .unwrap()
            .input(&src)
            .unwrap()
            .done()
            .unwrap();
        assert_eq!(read_str(&out), "First\r\nSecond\r\nThird\r\n");
    }

    #[test]
    fn b20_invalid_utf8_errors() {
        // BUILDER-F-013 / task B20: invalid UTF-8 input → error.
        let tmp = TempDir::new("b20");
        let src = tmp.write_bytes("binary.rs", b"//// \xFF\xFE not utf8\n");
        let out = tmp.file("out.md");
        let mut builder = Docextract::new(&out).unwrap();
        assert!(builder.input(&src).is_err());
        builder.done().unwrap();
    }

    #[test]
    fn b21_large_file_processing() {
        // BUILDER-F-018: ~1 MiB source with 20k doc lines + interspersed code;
        // all doc lines extracted, none lost, code lines never leaked.
        // Cache-first model: no auto inter-block separators → 20,000 lines.
        let tmp = TempDir::new("b21");
        let mut content = String::new();
        for i in 0..20_000 {
            let _ = write!(content, "//// line {i} {}", "x".repeat(40));
            content.push('\n');
            if i % 5 == 0 {
                content.push_str("fn f() {}\n");
            }
        }
        assert!(content.len() >= 1_000_000, "source should be ~1 MiB");
        let src = tmp.write("large.rs", &content);
        let out = tmp.file("out.md");
        Docextract::new(&out)
            .unwrap()
            .input(&src)
            .unwrap()
            .done()
            .unwrap();
        let output = read_str(&out);
        assert!(output.starts_with("line 0 "));
        assert!(output.ends_with(&format!("line 19999 {}\n", "x".repeat(40))));
        // Cache-first: no auto-separators — 20,000 lines total
        assert_eq!(output.lines().count(), 20_000);
        // Every non-empty line is a doc line — no "fn f()" code leaked.
        assert!(
            output
                .lines()
                .filter(|l| !l.is_empty())
                .all(|l| l.starts_with("line "))
        );
        assert!(output.len() > 800_000, "all 20k doc lines must be present");
    }

    #[test]
    fn b22_multiple_inputs_in_loop() {
        // BUILDER-F-002: many `.input()` calls (loop style) → all files processed.
        let tmp = TempDir::new("b22");
        let out = tmp.file("out.md");
        let mut builder = Docextract::new(&out).unwrap();
        let mut expected = String::new();
        for i in 0..10 {
            let src = tmp.write(&format!("m{i}.rs"), &format!("//// File {i}\n"));
            builder.input(&src).unwrap();
            let _ = writeln!(expected, "File {i}");
        }
        builder.done().unwrap();
        assert_eq!(read_str(&out), expected);
    }

    #[test]
    fn b23_done_ok_on_empty_builder() {
        // BUILDER-F-003: `.done()` on a builder with no inputs returns Ok(&mut self)
        let tmp = TempDir::new("b23");
        let out = tmp.file("out.md");
        let mut builder = Docextract::new(&out).unwrap();
        let result = builder.done();
        assert!(result.is_ok());
        assert_eq!(read_str(&out), "");
    }

    #[test]
    fn b24_stdin_called_twice_second_noop() {
        // BUILDER-F-021: the second source (non-doc lines only, the file analog of
        // an exhausted stream) contributes nothing.
        let tmp = TempDir::new("b24");
        let first = tmp.write("first.txt", "//// Only once\n");
        let second = tmp.write("second.txt", "fn main() {\n    let x = 1;\n}\n");
        let out = tmp.file("out.md");
        Docextract::new(&out)
            .unwrap()
            .input(&first)
            .unwrap()
            .input(&second)
            .unwrap()
            .done()
            .unwrap();
        assert_eq!(read_str(&out), "Only once\n");
    }

    #[test]
    fn b25_empty_output_path_errors() {
        // CLI "missing output argument" analogue at the library level.
        let result = Docextract::new("");
        assert!(result.is_err());
    }

    #[test]
    fn b26_file_vs_stdout_output_paths() {
        // BUILDER-F-001/022: file path creates a real file; "-" path targets stdout.
        let tmp = TempDir::new("b26");
        let src = tmp.write("in.rs", "//// Doc\n");
        let out = tmp.file("out.md");
        {
            Docextract::new(&out)
                .unwrap()
                .input(&src)
                .unwrap()
                .done()
                .unwrap();
        }
        assert!(out.exists());
        assert_eq!(read_str(&out), "Doc\n");
        let string_path: String = tmp
            .write("str.rs", "//// String Doc\n")
            .to_string_lossy()
            .into_owned();
        let out2 = tmp.file("out2.md");
        {
            Docextract::new(&out2)
                .unwrap()
                .input(string_path)
                .unwrap()
                .done()
                .unwrap();
        }
        assert_eq!(read_str(&out2), "String Doc\n");
        {
            Docextract::new("-")
                .unwrap()
                .input(&src)
                .unwrap()
                .done()
                .unwrap();
        }
        assert!(
            !std::path::Path::new("-").exists(),
            "stdout target must not create a file named '-' in the working directory"
        );
    }

    #[test]
    fn b27_mid_stream_error_preserves_earlier_output() {
        // §9.4 non-atomic output: when a later input fails, output written by
        // earlier inputs is preserved.
        let tmp = TempDir::new("b27");
        let good = tmp.write("good.rs", "//// From Good\n");
        let bad_dir = tmp.file("bad");
        fs::create_dir_all(&bad_dir).unwrap();
        let out = tmp.file("out.md");
        let mut builder = Docextract::new(&out).unwrap();
        builder.input(&good).unwrap();
        assert!(builder.input(&bad_dir).is_err());
        builder.done().unwrap();
        assert_eq!(read_str(&out), "From Good\n");
    }

    #[test]
    fn b28_all_doc_line_types_in_one_file() {
        // BUILDER-F-001: every valid doc-line form in one file — space separator,
        // tab separator, indented, verbatim blank (////), tab indent, two-space
        // content, EOF "////" — with directives and ignored lines between.
        // Cache-first model: no auto inter-block separators.
        let tmp = TempDir::new("b28");
        let src = tmp.write(
            "all.rs",
            "//// First\n////\n//// Second\nlet x = 1;\n\t//// Tab Sep\n////\tTab Content\n////  Two Spaces\n////Bad\n///// five\n////",
        );
        let out = tmp.file("out.md");
        Docextract::new(&out)
            .unwrap()
            .input(&src)
            .unwrap()
            .done()
            .unwrap();
        // `////Bad` is a tag directive (persistent switch, no entry).
        // Entries: First, blank, Second, Tab Sep, Tab Content, Two Spaces, EOF empty
        // All concatenated without auto-separators.
        assert_eq!(
            read_str(&out),
            "First\n\nSecond\nTab Sep\nTab Content\n Two Spaces\n"
        );
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn b29_done_flush_error_returns_err() {
        // BUILDER-F-012: `.done()` must surface a flush/write failure as Err(io::Error).
        let tmp = TempDir::new("b29");
        let src = tmp.write("in.rs", "//// Doc\n");
        let mut builder = Docextract::new("/dev/full").unwrap();
        builder.input(&src).unwrap();
        assert!(builder.done().is_err());
    }

    #[test]
    fn b30_all_inputs_missing_warns_and_creates_empty_output() {
        // BUILDER-F-020: all inputs missing → one warning per file to stderr.
        let tmp = TempDir::new("b30");
        let out = tmp.file("out.md");
        let mut builder = Docextract::new(&out).unwrap();
        assert!(builder.input(tmp.file("m1.rs")).is_ok());
        assert!(builder.input(tmp.file("m2.rs")).is_ok());
        builder.done().unwrap();
        assert!(out.exists());
        assert_eq!(read_str(&out), "");
    }

    #[test]
    fn b31_out_dir_auto_detect_set_and_clear() {
        // BUILDER-F-006 + BUILDER-F-024: auto-detection via OUT_DIR.
        let tmp = TempDir::new("b31");
        let src = tmp.write("in.rs", "//// Doc\n");
        let out_set = tmp.file("out-set.md");
        {
            let _guard = OutDirGuard::with(Some(tmp.file("out_dir").as_os_str()));
            Docextract::new(&out_set)
                .unwrap()
                .input(&src)
                .unwrap()
                .done()
                .unwrap();
        }
        let out_clear = tmp.file("out-clear.md");
        {
            let _guard = OutDirGuard::with(None);
            Docextract::new(&out_clear)
                .unwrap()
                .input(&src)
                .unwrap()
                .done()
                .unwrap();
        }
        assert_eq!(read_str(&out_set), "Doc\n");
        assert_eq!(read_str(&out_clear), "Doc\n");
        assert_eq!(read_str(&out_set), read_str(&out_clear));
    }

    #[test]
    fn b32_non_notfound_open_error_returns_err() {
        // BUILDER-F-011 (open-error branch): non-NotFound open errors propagate as Err.
        let tmp = TempDir::new("b32");
        let out = tmp.file("out.md");
        let mut builder = Docextract::new(&out).unwrap();
        let nul_path = PathBuf::from("docextract-nul\0path");
        assert!(builder.input(nul_path).is_err());
        builder.done().unwrap();
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn b33_drop_flush_error_reports_to_stderr() {
        // §6.1: when `.done()` is never called, Drop's close_output() must flush
        // and print a flush failure to stderr.
        if std::env::var_os("DOCEXTRACT_SUBPROCESS").is_some() {
            // Child: extract a doc line into /dev/full, drop without .done().
            let tmp = TempDir::new("b33-child");
            let src = tmp.write("in.rs", "//// Doc\n");
            let mut builder = Docextract::new("/dev/full").unwrap();
            builder.input(&src).unwrap();
            // Builder drops here — Drop must flush and print the ENOSPC error.
            return;
        }
        // Parent: run the child and assert the flush error reached stderr.
        let exe = std::env::current_exe().unwrap();
        let output = std::process::Command::new(&exe)
            .env("DOCEXTRACT_SUBPROCESS", "1")
            .arg("--exact")
            .arg("tests::b33_drop_flush_error_reports_to_stderr")
            .arg("--nocapture")
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "child test binary must exit 0, got {:?}",
            output.status
        );
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains("docextract: error: output:"),
            "Drop flush error must be printed to stderr, got: {stderr}"
        );
    }

    // ---------------------------------------------------------------------
    // Tag-filter feature tests — specs/tag-filter-spec.md §7 (RED phase).
    //
    // These tests target the tag-filter API specified in tag-filter-spec.md
    // §6 (`DocEntry`, `Docextract::parse_doc_entries`, `Pattern`/
    // `PatternError` from `crate::pattern`, `filter_output`,
    // `input_filtered`).
    // ---------------------------------------------------------------------
    mod tag_filter {
        use super::*;
        use crate::pattern::Pattern;
        #[cfg(feature = "regex")]
        use crate::pattern::PatternError;
        use std::rc::Rc;

        /// Assert that `actual` entries match the expected
        /// `(tag, text, transient)` triples.
        fn assert_entries(actual: &[DocEntry], expected: &[(&str, &str, bool)]) {
            assert_eq!(
                actual.len(),
                expected.len(),
                "entry count mismatch: got {} expected {}",
                actual.len(),
                expected.len()
            );
            for (entry, (tag, text, transient)) in actual.iter().zip(expected) {
                assert_eq!(&*entry.tag, *tag, "tag mismatch");
                assert_eq!(&*entry.text, *text, "text mismatch");
                assert_eq!(entry.transient, *transient, "transient mismatch");
            }
        }

        /// Assert that the interning pool contains exactly `expected` tag names.
        fn assert_tags(tags: &HashSet<Rc<str>>, expected: &[&str]) {
            assert_eq!(tags.len(), expected.len(), "interning pool size mismatch");
            for &name in expected {
                assert!(tags.contains(name), "tag {name:?} missing from pool");
            }
        }

        // --- §7.1 parse_doc_entries tests (P01-P37, tag-filter-spec.md) ---

        #[test]
        fn p01_simple_doc_line() {
            // REQ-TAG-F-001 / P01: `//// Hello\n` → one persistent entry under the initial tag
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "//// Hello\n", "lib");
            assert_entries(&entries, &[("lib", "Hello\n", false)]);
            assert_tags(&tags, &["lib"]);
        }

        #[test]
        fn p02_four_space_indent() {
            // REQ-TAG-F-001 / P02: leading ASCII whitespace stripped before prefix match
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "    //// Hello\n", "lib");
            assert_entries(&entries, &[("lib", "Hello\n", false)]);
            assert_tags(&tags, &["lib"]);
        }

        #[test]
        fn p03_tab_indent() {
            // REQ-TAG-F-001 / P03: tab indent stripped, prefix matched
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "\t//// Hello\n", "lib");
            assert_entries(&entries, &[("lib", "Hello\n", false)]);
            assert_tags(&tags, &["lib"]);
        }

        #[test]
        fn p04_tab_separator() {
            // REQ-TAG-F-001 / P04: tab separator stripped exactly once
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "////\tHello\n", "lib");
            assert_entries(&entries, &[("lib", "Hello\n", false)]);
            assert_tags(&tags, &["lib"]);
        }

        #[test]
        fn p05_empty_doc_line_newline() {
            // REQ-TAG-F-001 / P05: `////\n` → verbatim blank line entry
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "////\n", "lib");
            assert_entries(&entries, &[("lib", "\n", false)]);
            assert_tags(&tags, &["lib"]);
        }

        #[test]
        fn p06_empty_doc_line_space_newline() {
            // REQ-TAG-F-001 / P06: `//// \n` → separator stripped, blank line entry
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "//// \n", "lib");
            assert_entries(&entries, &[("lib", "\n", false)]);
            assert_tags(&tags, &["lib"]);
        }

        #[test]
        fn p07_empty_doc_line_at_eof() {
            // REQ-TAG-F-001 / P07: `////` at EOF (no newline) → empty-text entry
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "////", "lib");
            assert_entries(&entries, &[("lib", "", false)]);
            assert_tags(&tags, &["lib"]);
        }

        #[test]
        fn p08_crlf_preserved() {
            // REQ-TAG-F-001 / P08: CRLF ending preserved in entry text
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "//// Hello\r\n", "lib");
            assert_entries(&entries, &[("lib", "Hello\r\n", false)]);
            assert_tags(&tags, &["lib"]);
        }

        #[test]
        fn p09_three_spaces_first_is_separator() {
            // REQ-TAG-F-001 / P09: one separator stripped, two spaces preserved
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "////   \n", "lib");
            assert_entries(&entries, &[("lib", "  \n", false)]);
            assert_tags(&tags, &["lib"]);
        }

        #[test]
        fn p10_two_spaces_second_preserved() {
            // REQ-TAG-F-001 / P10: one separator stripped, one space preserved
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "////  Two Spaces\n", "lib");
            assert_entries(&entries, &[("lib", " Two Spaces\n", false)]);
            assert_tags(&tags, &["lib"]);
        }

        #[test]
        fn p11_long_doc_line_preserved_verbatim() {
            // REQ-TAG-F-001 / P11: long doc line (> 256 chars) preserved verbatim
            let content = "x".repeat(300);
            let input = format!("//// {content}\n");
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, &input, "myfile");
            assert_entries(&entries, &[("myfile", &format!("{content}\n"), false)]);
            assert_tags(&tags, &["myfile"]);
        }

        #[test]
        fn p12_five_slashes_ignored() {
            // REQ-TAG-F-001 / P12: five slashes → silently ignored
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "/////\n", "lib");
            assert_entries(&entries, &[]);
            assert_tags(&tags, &["lib"]);
        }

        #[test]
        fn p13_six_slashes_ignored() {
            // REQ-TAG-F-001 / P13: six slashes → silently ignored
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "//////\n", "lib");
            assert_entries(&entries, &[]);
            assert_tags(&tags, &["lib"]);
        }

        #[test]
        fn p14_three_slashes_ignored() {
            // REQ-TAG-F-001 / P14: `///\n` — fewer than four slashes → ignored
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "///\n", "lib");
            assert_entries(&entries, &[]);
            assert_tags(&tags, &["lib"]);
        }

        #[test]
        fn p15_non_four_slash_prefix_ignored() {
            // REQ-TAG-F-001 / P15: first four bytes not all slashes → ignored
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "X///\nfn main() {}\n", "lib");
            assert_entries(&entries, &[]);
            assert_tags(&tags, &["lib"]);
        }

        #[test]
        fn p16_whitespace_only_line_at_eof_ignored() {
            // REQ-TAG-F-001 / P16: whitespace-only line at EOF → fewer than
            // four bytes remain after whitespace skip → ignored
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "    ", "lib");
            assert_entries(&entries, &[]);
            assert_tags(&tags, &["lib"]);
        }

        #[test]
        fn p17_mixed_indent() {
            // REQ-TAG-F-001 / P17: mixed space+tab indent skipped
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, " \t//// Hello\n", "lib");
            assert_entries(&entries, &[("lib", "Hello\n", false)]);
            assert_tags(&tags, &["lib"]);
        }

        #[test]
        fn p18_space_separator_at_eof() {
            // REQ-TAG-F-001 / P18: `//// ` at EOF → separator stripped, empty text
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "//// ", "lib");
            assert_entries(&entries, &[("lib", "", false)]);
            assert_tags(&tags, &["lib"]);
        }

        #[test]
        fn p19_tab_separator_at_eof() {
            // REQ-TAG-F-001 / P19: `////\t` at EOF → separator stripped, empty text
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "////\t", "lib");
            assert_entries(&entries, &[("lib", "", false)]);
            assert_tags(&tags, &["lib"]);
        }

        #[test]
        fn p20_crlf_without_separator() {
            // REQ-TAG-F-001 / P20: `////\r\n` → CRLF preserved, no separator to strip
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "////\r\n", "lib");
            assert_entries(&entries, &[("lib", "\r\n", false)]);
            assert_tags(&tags, &["lib"]);
        }

        #[test]
        fn p21_cr_at_eof() {
            // REQ-TAG-F-001 / P21: `////\r` (lone CR at EOF) → preserved
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "////\r", "lib");
            assert_entries(&entries, &[("lib", "\r", false)]);
            assert_tags(&tags, &["lib"]);
        }

        #[test]
        fn p22_persistent_tag_switch() {
            // REQ-TAG-F-002 / P22: `////foo` is a persistent switch — no
            // DocEntry emitted, tag added to pool
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "////foo\n", "lib");
            assert_entries(&entries, &[]);
            assert_tags(&tags, &["lib", "foo"]);
        }

        #[test]
        fn p23_persistent_tag_switch_chapter1() {
            // REQ-TAG-F-002 / P23: `////chapter1` → persistent switch
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "////chapter1\n", "lib");
            assert_entries(&entries, &[]);
            assert_tags(&tags, &["lib", "chapter1"]);
        }

        #[test]
        fn p24_transient_tag_with_text() {
            // REQ-TAG-F-003 / P24: `////foo bar baz` → transient entry with
            // tag `foo`, text `bar baz\n`, transient=true
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "////foo bar baz\n", "lib");
            assert_entries(&entries, &[("foo", "bar baz\n", true)]);
            assert_tags(&tags, &["lib", "foo"]);
        }

        #[test]
        fn p25_transient_tag_glossary() {
            // REQ-TAG-F-003 / P25: `////glossary example` → transient entry
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "////glossary example\n", "lib");
            assert_entries(&entries, &[("glossary", "example\n", true)]);
            assert_tags(&tags, &["lib", "glossary"]);
        }

        #[test]
        fn p26_tag_with_hyphen() {
            // REQ-TAG-F-002 / P26: hyphen allowed in tag names (§6.1.3)
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "////tag-name\n", "lib");
            assert_entries(&entries, &[]);
            assert_tags(&tags, &["lib", "tag-name"]);
        }

        #[test]
        fn p27_tag_with_dot() {
            // REQ-TAG-F-002 / P27: dot allowed in tag names
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "////tag.name\n", "lib");
            assert_entries(&entries, &[]);
            assert_tags(&tags, &["lib", "tag.name"]);
        }

        #[test]
        fn p28_hash_tag() {
            // REQ-TAG-F-003 / P28: `////### Heading` → transient tag `###`
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "////### Heading\n", "lib");
            assert_entries(&entries, &[("###", "Heading\n", true)]);
            assert_tags(&tags, &["lib", "###"]);
        }

        #[test]
        fn p29_numeric_tag() {
            // REQ-TAG-F-002 / P29: numeric tag names allowed
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "////42\n", "lib");
            assert_entries(&entries, &[]);
            assert_tags(&tags, &["lib", "42"]);
        }

        #[test]
        fn p30_indented_tag_directive() {
            // REQ-TAG-F-002 / P30: tag directives may be indented
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "    ////foo\n", "lib");
            assert_entries(&entries, &[]);
            assert_tags(&tags, &["lib", "foo"]);
        }

        #[test]
        fn p31_hello_repurposed_case_e() {
            // REQ-TAG-F-002 / P31: `////Hello` (old CASE E) is now a
            // persistent tag switch — no DocEntry, no output
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "////Hello\n", "lib");
            assert_entries(&entries, &[]);
            assert_tags(&tags, &["lib", "Hello"]);
        }

        #[test]
        fn p32_persistent_switch_then_doc_line() {
            // REQ-TAG-F-002 / P32: doc line after persistent switch uses the
            // new tag
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "////foo\n//// bar\n", "lib");
            assert_entries(&entries, &[("foo", "bar\n", false)]);
            assert_tags(&tags, &["lib", "foo"]);
        }

        #[test]
        fn p33_transient_does_not_change_current_tag() {
            // REQ-TAG-F-003 / P33: transient entry does NOT change the
            // current tag; following doc line keeps the pre-transient tag
            let mut tags = HashSet::new();
            let entries =
                parse_doc_entries(&mut tags, "////foo\n////baz text\n//// after\n", "lib");
            assert_entries(
                &entries,
                &[("baz", "text\n", true), ("foo", "after\n", false)],
            );
            assert_tags(&tags, &["lib", "foo", "baz"]);
        }

        #[test]
        fn p34_tag_interning_shared_rc() {
            // REQ-TAG-F-001 / P34: identical tags share ONE Rc<str>
            // allocation via the interning pool (§6.2.1)
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "//// a\n//// b\n//// c\n", "mod");
            assert_eq!(entries.len(), 3);
            assert!(Rc::ptr_eq(&entries[0].tag, &entries[1].tag));
            assert!(Rc::ptr_eq(&entries[1].tag, &entries[2].tag));
            assert_tags(&tags, &["mod"]);
        }

        #[test]
        fn p35_stdin_initial_tag() {
            // REQ-TAG-F-004 / P35: stdin initial tag is the sentinel `-` (§6.3)
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "//// hello\n", "-");
            assert_entries(&entries, &[("-", "hello\n", false)]);
            assert_tags(&tags, &["-"]);
        }

        #[test]
        fn p36_no_doc_lines() {
            // REQ-TAG-F-001 / P36: file with no `////` lines → empty entries
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "fn main() {\n    let x = 1;\n}\n", "lib");
            assert_entries(&entries, &[]);
            assert_tags(&tags, &["lib"]);
        }

        #[test]
        fn p37_doc_at_eof_without_newline() {
            // REQ-TAG-F-001 / P37: `////` as the last line at EOF (no
            // trailing newline) → empty-text entry
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, "//// text\n////", "lib");
            assert_entries(&entries, &[("lib", "text\n", false), ("lib", "", false)]);
            assert_tags(&tags, &["lib"]);
        }

        // --- §7.2 Pattern matcher — hand-rolled backend (G01-G32) ---

        #[cfg(not(feature = "regex"))]
        mod simple_matcher {
            use super::*;

            /// Compile `pattern` (infallible on the hand-rolled path) and
            /// test it against `target`.
            fn m(pattern: &str, target: &str) -> bool {
                Pattern::new(pattern).unwrap().matches(target)
            }

            #[test]
            fn g01_star_matches_everything() {
                assert!(m(".*", "anything"));
            }

            #[test]
            fn g02_star_matches_empty() {
                assert!(m(".*", ""));
            }

            #[test]
            fn g03_literal_exact_match() {
                assert!(m("foo", "foo"));
            }

            #[test]
            fn g04_literal_no_match() {
                assert!(!m("foo", "bar"));
            }

            #[test]
            fn g05_prefix_then_star() {
                assert!(m("foo.*", "foobar"));
            }

            #[test]
            fn g06_prefix_then_star_wrong_target() {
                assert!(!m("foo.*", "barfoo"));
            }

            #[test]
            fn g07_star_then_suffix() {
                assert!(m(".*foo", "barfoo"));
            }

            #[test]
            fn g08_star_sandwich() {
                assert!(m(".*foo.*", "barfoobaz"));
            }

            #[test]
            fn g09_optional_any_single_char() {
                assert!(m(".?", "a"));
            }

            #[test]
            fn g10_optional_any_empty() {
                assert!(m(".?", ""));
            }

            #[test]
            fn g11_optional_any_two_chars() {
                assert!(!m(".?", "ab"));
            }

            #[test]
            fn g12_optional_any_middle_filled() {
                assert!(m("f.?o", "foo"));
            }

            #[test]
            fn g13_optional_any_middle_other() {
                assert!(m("f.?o", "fao"));
            }

            #[test]
            fn g14_optional_any_middle_omitted() {
                assert!(m("f.?o", "fo"));
            }

            #[test]
            fn g15_chapter_optional_digit() {
                assert!(m("chapter.?", "chapter1"));
            }

            #[test]
            fn g16_chapter_optional_omitted() {
                assert!(m("chapter.?", "chapter"));
            }

            #[test]
            fn g17_character_class_member() {
                assert!(m("[abc]", "a"));
            }

            #[test]
            fn g18_character_class_non_member() {
                assert!(!m("[abc]", "d"));
            }

            #[test]
            fn g19_character_class_range() {
                assert!(m("[a-z]", "m"));
            }

            #[test]
            fn g20_character_class_range_case_sensitive() {
                assert!(!m("[a-z]", "M"));
            }

            #[test]
            fn g21_negated_class_matches_outside() {
                assert!(m("[^abc]", "d"));
            }

            #[test]
            fn g22_negated_class_rejects_member() {
                assert!(!m("[^abc]", "a"));
            }

            #[test]
            fn g23_escaped_dot_matches_dot() {
                assert!(m("\\.", "."));
            }

            #[test]
            fn g24_escaped_dot_rejects_other() {
                assert!(!m("\\.", "a"));
            }

            #[test]
            fn g25_escaped_backslash_matches_backslash() {
                assert!(m("\\\\", "\\"));
            }

            #[test]
            fn g26_empty_pattern_empty_target() {
                assert!(m("", ""));
            }

            #[test]
            fn g27_empty_pattern_nonempty_target() {
                assert!(!m("", "a"));
            }

            #[test]
            fn g28_multiple_stars() {
                assert!(m(".*.*", "abc"));
            }

            #[test]
            fn g29_unclosed_bracket_matches_literal() {
                assert!(m("[", "["));
            }

            #[test]
            fn g30_unclosed_range_literal_fallback() {
                assert!(!m("[a", "["));
            }

            #[test]
            fn g31_star_then_optional() {
                assert!(m(".*.?", "a"));
            }

            #[test]
            fn g32_optional_then_star() {
                assert!(m(".?.*", "abc"));
            }

            #[test]
            fn g33_unquantified_class_not_empty() {
                assert!(!m("[abc]", ""));
            }
        }

        // --- §7.2a Pattern matcher — regex backend (R01-R21) ---

        #[cfg(feature = "regex")]
        mod regex_matcher {
            use super::*;

            /// Compile `pattern` (regex path — valid patterns must compile)
            /// and test it against `target`.
            fn m(pattern: &str, target: &str) -> bool {
                Pattern::new(pattern).unwrap().matches(target)
            }

            #[test]
            fn r01_posix_alpha_matches_letter() {
                assert!(m("[[:alpha:]]", "a"));
            }

            #[test]
            fn r02_posix_alpha_rejects_digit() {
                assert!(!m("[[:alpha:]]", "9"));
            }

            #[test]
            fn r03_alpha_alnum_star_bar() {
                assert!(m("[[:alpha:]][[:alnum:]]*_bar", "a1_bar"));
            }

            #[test]
            fn r04_alpha_alnum_star_bar_long() {
                assert!(m("[[:alpha:]][[:alnum:]]*_bar", "a123foo_bar"));
            }

            #[test]
            fn r05_alpha_alnum_star_bar_short() {
                assert!(m("[[:alpha:]][[:alnum:]]*_bar", "a_bar"));
            }

            #[test]
            fn r06_alpha_alnum_star_bar_digit_start() {
                assert!(!m("[[:alpha:]][[:alnum:]]*_bar", "1_bar"));
            }

            #[test]
            fn r07_alpha_alnum_star_bar_wrong_suffix() {
                assert!(!m("[[:alpha:]][[:alnum:]]*_bar", "a_baz"));
            }

            #[test]
            fn r08_group_plus_repeated() {
                assert!(m("(foo)+", "foofoofoo"));
            }

            #[test]
            fn r09_group_plus_single() {
                assert!(m("(foo)+", "foo"));
            }

            #[test]
            fn r10_group_plus_empty() {
                assert!(!m("(foo)+", ""));
            }

            #[test]
            fn r11_alternation_first_branch() {
                assert!(m("foo|bar", "foo"));
            }

            #[test]
            fn r12_alternation_second_branch() {
                assert!(m("foo|bar", "bar"));
            }

            #[test]
            fn r13_alternation_no_branch() {
                assert!(!m("foo|bar", "baz"));
            }

            #[test]
            fn r14_digit_plus() {
                assert!(m("\\d+", "123"));
            }

            #[test]
            fn r15_digit_plus_rejects_letters() {
                assert!(!m("\\d+", "abc"));
            }

            #[test]
            fn r16_word_plus() {
                assert!(m("\\w+", "hello_world"));
            }

            #[test]
            fn r17_exact_count_quantifier() {
                assert!(m("a{3}", "aaa"));
            }

            #[test]
            fn r18_exact_count_quantifier_short() {
                assert!(!m("a{3}", "aa"));
            }

            #[test]
            fn r19_non_capturing_group() {
                assert!(m("(?:foo)", "foo"));
            }

            #[test]
            fn r20_unclosed_bracket_is_compile_error() {
                let result = Pattern::new("[");
                assert!(
                    matches!(result, Err(PatternError::InvalidSyntax(_))),
                    "unclosed character class must be a compile error"
                );
            }

            #[test]
            fn r21_unclosed_paren_is_compile_error() {
                let result = Pattern::new("(");
                assert!(
                    matches!(result, Err(PatternError::InvalidSyntax(_))),
                    "unclosed group must be a compile error"
                );
            }
        }

        // --- §7.3 Library API filtering tests (F01-F26) ---

        #[test]
        fn f01_input_filtered_matches_tag() {
            // REQ-TAG-F-005 / F01: `.input_filtered("file.rs", "api")`
            // emits only api-tagged lines (transient included — filter active)
            let tmp = TempDir::new("f01");
            let src = tmp.write("file.rs", "////api intro\n//// core\n////api detail\n");
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .input_filtered(&src, "api")
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "intro\ndetail\n");
        }

        #[test]
        fn f02_input_filtered_no_matching_tag() {
            // REQ-TAG-F-005 / F02: no api-tagged lines → empty output, no error
            let tmp = TempDir::new("f02");
            let src = tmp.write("file.rs", "//// core\n");
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .input_filtered(&src, "api")
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "");
        }

        #[test]
        fn f03_output_filter_with_unfiltered_input() {
            // REQ-TAG-F-006 / F03: `.filter_output(Some("chapter.*"))` +
            // `.input()` → only chapter.*-tagged lines
            let tmp = TempDir::new("f03");
            let src = tmp.write("file.rs", "////chapter1 a\n//// intro\n////chapter2 b\n");
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .filter_output(Some("chapter.*"))
                .unwrap()
                .input(&src)
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "a\nb\n");
        }

        #[test]
        fn f04_output_and_input_filter_and_combine() {
            // REQ-TAG-F-006 / F04: output filter chapter.* AND input filter
            // chapter1 → only chapter1 lines (§8.7 AND semantics)
            let tmp = TempDir::new("f04");
            let src = tmp.write("file.rs", "////chapter1 a\n////chapter2 b\n//// plain\n");
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .filter_output(Some("chapter.*"))
                .unwrap()
                .input_filtered(&src, "chapter1")
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "a\n");
        }

        #[test]
        fn f05_reordering_via_multiple_filtered_reads() {
            // REQ-TAG-F-007 / F05: ch1, ch1, ch2 reads → ch1 lines then ch2
            // lines; the file is read/parsed once (cache — rewrite proves it)
            let tmp = TempDir::new("f05");
            let src = tmp.write("f.rs", "////ch1 one\n////ch2 two\n////ch1 three\n");
            let out = tmp.file("out.md");
            let mut builder = Docextract::new(&out).unwrap();
            builder.input_filtered(&src, "ch1").unwrap();
            // Cache proof: a rewritten file must NOT be re-read on cache hit.
            fs::write(&src, "////ch1 REWRITTEN\n").unwrap();
            builder.input_filtered(&src, "ch1").unwrap();
            builder.input_filtered(&src, "ch2").unwrap();
            builder.done().unwrap();
            assert_eq!(read_str(&out), "one\nthree\none\nthree\ntwo\n");
        }

        #[test]
        fn f06_filtered_then_unfiltered_rerun() {
            // REQ-TAG-F-008 / F06: filtered read then unfiltered `.input()`
            // → ch1 lines, then all PERSISTENT lines (cache used on 2nd call;
            // transient `ch1` entry skipped in unfiltered mode)
            let tmp = TempDir::new("f06");
            let src = tmp.write("f.rs", "////ch1 one\n//// plain\n");
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .input_filtered(&src, "ch1")
                .unwrap()
                .input(&src)
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "one\nplain\n");
        }

        #[test]
        fn f07_unfiltered_backward_compat() {
            // REQ-TAG-F-010 / F07: `.input()` without filters on a file with
            // no tag directives → output identical to the pre-tag-filter
            // version
            let tmp = TempDir::new("f07");
            let src = tmp.write("file.rs", "//// hello\n//// world\n");
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .input(&src)
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "hello\nworld\n");
        }

        #[test]
        fn f08_stdin_unfiltered_backward_compat() {
            // REQ-TAG-F-010 / F08: stdin parses into cache, emits only
            // persistent entries.
            let tmp = TempDir::new("f08");
            let src = tmp.write("stdin-content.txt", "//// persistent\n////t transient\n");
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .input(&src)
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "persistent\n");
        }

        #[test]
        fn f09_rerun_if_changed_emitted_once() {
            // REQ-TAG-F-006 / F09: with a cached file, `cargo:rerun-if-changed`
            // is emitted only on the FIRST access (cache miss).
            if std::env::var_os("DOCEXTRACT_F09_SUBPROCESS").is_some() {
                // Child: OUT_DIR set (auto-enables rerun-if-changed), access
                // the same file twice → exactly one directive on stdout.
                let tmp = TempDir::new("f09-child");
                let src = tmp.write("in.rs", "////api doc\n");
                let out = tmp.file("out.md");
                let _guard = OutDirGuard::with(Some(tmp.file("out_dir").as_os_str()));
                let mut builder = Docextract::new(&out).unwrap();
                builder.input_filtered(&src, "api").unwrap(); // cache miss → directive
                builder.input_filtered(&src, "api").unwrap(); // cache hit → no directive
                builder.done().unwrap();
                return;
            }
            // Parent: run the child and count directive emissions on stdout.
            let exe = std::env::current_exe().unwrap();
            let output = std::process::Command::new(&exe)
                .env("DOCEXTRACT_F09_SUBPROCESS", "1")
                .arg("--exact")
                .arg("tests::tag_filter::f09_rerun_if_changed_emitted_once")
                .arg("--nocapture")
                .output()
                .unwrap();
            assert!(
                output.status.success(),
                "child test binary must exit 0, got {:?}",
                output.status
            );
            let stdout = String::from_utf8_lossy(&output.stdout);
            let directive_count = stdout.matches("cargo:rerun-if-changed=").count();
            assert_eq!(
                directive_count, 1,
                "rerun-if-changed must be emitted exactly once (first access only), got: {stdout}"
            );
        }

        #[test]
        fn f10_persistent_tag_switch_mid_file() {
            // REQ-TAG-F-002 / F10: lines before the switch carry the initial
            // tag, lines after carry the new tag
            let tmp = TempDir::new("f10");
            let src = tmp.write("f.rs", "//// first\n////sec\n//// second\n");
            let out = tmp.file("out.md");
            let mut builder = Docextract::new(&out).unwrap();
            builder.input(&src).unwrap(); // unfiltered: both persistent lines
            builder.input_filtered(&src, "sec").unwrap(); // proves the 2nd line's tag
            builder.done().unwrap();
            assert_eq!(read_str(&out), "first\nsecond\nsecond\n");
        }

        #[test]
        fn f11_transient_skipped_when_unfiltered() {
            // REQ-TAG-F-003 / F11: transient entry skipped in unfiltered mode
            let tmp = TempDir::new("f11");
            let src = tmp.write("f.rs", "////t text\n//// regular\n");
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .input(&src)
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "regular\n");
        }

        #[test]
        fn f11a_transient_included_when_filter_matches() {
            // REQ-TAG-F-003 / F11a: transient entry IS emitted when a filter
            // matches its tag
            let tmp = TempDir::new("f11a");
            let src = tmp.write("f.rs", "////t text\n//// regular\n");
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .input_filtered(&src, "t")
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "text\n");
        }

        #[test]
        fn f12_initial_tag_from_filename_stem() {
            // REQ-TAG-F-004 / F12: initial tag = filename without extension
            let tmp = TempDir::new("f12");
            let src = tmp.write("lib.rs", "//// hello\n");
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .input_filtered(&src, "lib")
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "hello\n");
        }

        #[test]
        fn f13_nonmatching_filter_empty_output() {
            // REQ-TAG-F-005 / F13: filter matching nothing → empty output
            let tmp = TempDir::new("f13");
            let src = tmp.write("f.rs", "//// hello\n");
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .input_filtered(&src, "nonexistent")
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "");
        }

        #[test]
        fn f14_filter_output_none_clears_filter() {
            // REQ-TAG-F-006 / F14: `.filter_output(None)` clears the output filter
            let tmp = TempDir::new("f14");
            let src = tmp.write("f.rs", "////api a\n//// plain\n");
            let out = tmp.file("out.md");
            let mut builder = Docextract::new(&out).unwrap();
            builder.filter_output(Some("api")).unwrap();
            builder.input(&src).unwrap();
            builder.filter_output(None).unwrap();
            builder.input(&src).unwrap();
            builder.done().unwrap();
            assert_eq!(read_str(&out), "a\nplain\n");
        }

        #[test]
        fn f15_empty_file_with_filter() {
            // REQ-TAG-F-005 / F15: empty file + filter → empty output, no error
            let tmp = TempDir::new("f15");
            let src = tmp.write("empty.rs", "");
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .input_filtered(&src, "api")
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "");
        }

        #[test]
        fn f16_only_tag_directives_no_output() {
            // REQ-TAG-F-002 / F16: file with only persistent tag switches → empty output
            let tmp = TempDir::new("f16");
            let src = tmp.write("f.rs", "////api\n////chapter1\n");
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .input(&src)
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "");
        }

        #[test]
        fn f17_tag_with_special_chars() {
            // REQ-TAG-F-009 / F17: tag `my-tag.v2!` matched by pattern `my-tag.*`
            let tmp = TempDir::new("f17");
            let src = tmp.write("f.rs", "////my-tag.v2! entry\n//// plain\n");
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .input_filtered(&src, "my-tag.*")
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "entry\n");
        }

        #[test]
        fn f18_consecutive_tag_switches_no_output() {
            // REQ-TAG-F-002 / F18: consecutive persistent switches with no
            // doc lines between them → no output
            let tmp = TempDir::new("f18");
            let src = tmp.write("f.rs", "////a\n////b\n////c\n");
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .input(&src)
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "");
        }

        #[test]
        fn f19_transient_then_transient_current_tag_unchanged() {
            // REQ-TAG-F-003 / F19: two consecutive transients each create a
            // DocEntry with their own tag; current_tag is unchanged between
            // them — the trailing persistent line keeps the initial tag
            let tmp = TempDir::new("f19");
            let src = tmp.write("f.rs", "////t1 one\n////t2 two\n//// final\n");
            let out = tmp.file("out.md");
            let mut builder = Docextract::new(&out).unwrap();
            builder.input_filtered(&src, "f").unwrap(); // current tag stayed `f`
            builder.input_filtered(&src, ".*").unwrap(); // all entries
            builder.done().unwrap();
            assert_eq!(read_str(&out), "final\none\ntwo\nfinal\n");
        }

        #[test]
        fn f20_no_separator_between_tag_changes() {
            // REQ-TAG-F-002 / F20: entries with different tags are emitted
            // back-to-back — no blank line is auto-inserted (§8.6)
            let tmp = TempDir::new("f20");
            let src = tmp.write("f.rs", "////a one\n////b two\n");
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .input_filtered(&src, ".*")
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "one\ntwo\n");
        }

        #[test]
        fn f21_explicit_blank_doc_line() {
            // REQ-TAG-F-001 / F21: explicit `////` produces a verbatim blank line
            let tmp = TempDir::new("f21");
            let src = tmp.write("f.rs", "//// one\n////\n//// two\n");
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .input(&src)
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "one\n\ntwo\n");
        }

        #[test]
        fn f22_large_file_filtered_extraction() {
            // REQ-TAG-NF-002 / F22: ~1 MiB source alternating a/b tags;
            // filtering on `a` emits exactly the a-tagged lines
            let tmp = TempDir::new("f22");
            let mut content = String::new();
            let mut expected = String::new();
            for i in 0..20_000 {
                let text = format!("line {i} {}\n", "x".repeat(40));
                let tag = if i % 2 == 0 { "a" } else { "b" };
                let _ = write!(content, "////{tag} {text}");
                if tag == "a" {
                    expected.push_str(&text);
                }
            }
            assert!(content.len() >= 1_000_000, "source should be ~1 MiB");
            let src = tmp.write("big.rs", &content);
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .input_filtered(&src, "a")
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), expected);
        }

        #[test]
        fn f23_operation_after_done_returns_broken_pipe() {
            // REQ-TAG-F-008 / F23: `.input_filtered()` after `.done()` →
            // Err(BrokenPipe)
            let tmp = TempDir::new("f23");
            let src = tmp.write("f.rs", "////api a\n");
            let out = tmp.file("out.md");
            let mut builder = Docextract::new(&out).unwrap();
            builder.done().unwrap();
            let Err(err) = builder.input_filtered(&src, "api") else {
                panic!("expected error after done()");
            };
            assert_eq!(err.kind(), std::io::ErrorKind::BrokenPipe);
        }

        #[test]
        fn f24_blank_line_tagged_with_current_tag() {
            // REQ-TAG-F-001 / F24: a `////` verbatim blank line is created
            // with the current tag and emitted if that tag matches the filter
            let tmp = TempDir::new("f24");
            let src = tmp.write("f.rs", "////\n////api\n////\n");
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .input_filtered(&src, "api")
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "\n");
        }

        #[test]
        fn f25_missing_file_warns_and_continues() {
            // REQ-TAG-F-005 / F25: missing file with `.input_filtered()` →
            // warning to stderr, returns Ok, processing continues
            let tmp = TempDir::new("f25");
            let valid = tmp.write("valid.rs", "////api kept\n");
            let out = tmp.file("out.md");
            let mut builder = Docextract::new(&out).unwrap();
            assert!(
                builder
                    .input_filtered(tmp.file("missing.rs"), "api")
                    .is_ok()
            );
            builder.input_filtered(&valid, "api").unwrap();
            builder.done().unwrap();
            assert_eq!(read_str(&out), "kept\n");
        }

        #[test]
        fn f26_invalid_utf8_errors() {
            // REQ-TAG-F-005 / F26: invalid UTF-8 content →
            // Err(io::ErrorKind::InvalidData)
            let tmp = TempDir::new("f26");
            let src = tmp.write_bytes("binary.rs", b"//// \xFF\xFE not utf8\n");
            let out = tmp.file("out.md");
            let mut builder = Docextract::new(&out).unwrap();
            let Err(err) = builder.input_filtered(&src, "api") else {
                panic!("expected error for invalid UTF-8");
            };
            assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
            // The builder must remain usable after the error.
            builder.done().unwrap();
        }
    }

    // -----------------------------------------------------------------
    // Code-lifting tests — specs/code-lifting-spec.md §8.1–8.7
    // Batch 1: S01-S18 (split), R01-R21 (resolve_placeholders),
    // U01-U05 (UTF-8 char counting) — leaf function tests.
    // Batch 2: E01-E18 (end-to-end + capture zone), EX01-EX08 (sed-like e2e),
    // F01-F06 (filter interaction), D01-D11 (parse_sed_placeholder).
    // -----------------------------------------------------------------
    mod code_lifting {
        use super::*;

        // --- §8.1 try_split_code_capturing (S01–S10) ---

        #[test]
        fn s01_basic_split() {
            // S01 (REQ-LIFT-F-001, F-002): simple split at `////`
            assert_eq!(
                try_split_code_capturing("code;  //// {{}}"),
                Some(("code;", "{{}}"))
            );
        }

        #[test]
        fn s02_trailing_spaces_stripped_from_code() {
            // S02 (REQ-LIFT-F-001, F-003): trailing spaces before `////`
            // are NOT part of the captured code
            assert_eq!(
                try_split_code_capturing("    let x = 5;      //// {{}}"),
                Some(("    let x = 5;", "{{}}"))
            );
        }

        #[test]
        fn s03_single_space_is_separator() {
            // S03 (REQ-LIFT-F-001, F-003): one space before `////` IS
            // the separator — not part of the captured code
            assert_eq!(
                try_split_code_capturing("fn foo() { //// {{}}"),
                Some(("fn foo() {", "{{}}"))
            );
        }

        #[test]
        fn s04_tab_separator() {
            // S04 (REQ-LIFT-F-001): tab before `////` is the separator
            assert_eq!(
                try_split_code_capturing("code\t//// {{}}"),
                Some(("code", "{{}}"))
            );
        }

        #[test]
        fn s05_empty_template() {
            // S05 (REQ-LIFT-F-002): no template after `////`
            assert_eq!(try_split_code_capturing("code  ////"), Some(("code", "")));
        }

        #[test]
        fn s06_no_separator_after_slashes() {
            // S06 (REQ-LIFT-F-002): text directly after `////` (no space)
            // is the template
            assert_eq!(
                try_split_code_capturing("code  ////text"),
                Some(("code", "text"))
            );
        }

        #[test]
        fn s07_rightmost_double_slash_wins() {
            // S07 (REQ-LIFT-F-001): two `////` — the rightmost preceded
            // by space/tab is the split point
            assert_eq!(
                try_split_code_capturing("code //// inner //// {{}}"),
                Some(("code //// inner", "{{}}"))
            );
        }

        #[test]
        fn s08_double_slash_inside_string_literal() {
            // S08 (REQ-LIFT-F-001): `////` inside a string literal is
            // not the split point — the rightmost one wins
            assert_eq!(
                try_split_code_capturing("    let x = \"////\";  //// {{}}"),
                Some(("    let x = \"////\";", "{{}}"))
            );
        }

        #[test]
        fn s09_many_trailing_spaces_stripped() {
            // S09 (REQ-LIFT-F-003): multiple trailing spaces before
            // `////` are all stripped from the captured code
            assert_eq!(
                try_split_code_capturing("code;      //// {{}}"),
                Some(("code;", "{{}}"))
            );
        }

        #[test]
        fn s10_no_separator_before_slashes() {
            // S10 (REQ-LIFT-F-001): no space/tab before `////` — not a
            // code-capturing line
            assert_eq!(try_split_code_capturing("code////no-separator"), None);
        }

        // --- §8.2 resolve_placeholders — `{{}}` and `{{N}}` (R01–R10) ---

        #[test]
        fn r01_full_substitution_double_trim() {
            // R01 (REQ-LIFT-F-004): `{{}}` strips leading AND trailing
            // whitespace
            assert_eq!(resolve_placeholders("{{}}", "    let x = 5;"), "let x = 5;");
        }

        #[test]
        fn r02_full_substitution_plain_code() {
            // R02 (REQ-LIFT-F-004): `{{}}` on code with no whitespace
            assert_eq!(resolve_placeholders("{{}}", "code"), "code");
        }

        #[test]
        fn r03_full_substitution_empty_code() {
            // R03 (REQ-LIFT-F-004): `{{}}` with empty captured code
            assert_eq!(resolve_placeholders("{{}}", ""), "");
        }

        #[test]
        fn r04_zero_removal() {
            // R04 (REQ-LIFT-F-005): `{{0}}` removes nothing
            assert_eq!(resolve_placeholders("{{0}}", "code"), "code");
        }

        #[test]
        fn r05_remove_four_chars() {
            // R05 (REQ-LIFT-F-005): `{{4}}` removes the first 4 chars
            // (the 4 leading spaces)
            assert_eq!(resolve_placeholders("{{4}}", "    code"), "code");
        }

        #[test]
        fn r06_remove_one_char() {
            // R06 (REQ-LIFT-F-005): `{{1}}` removes the first char
            assert_eq!(resolve_placeholders("{{1}}", "abc"), "bc");
        }

        #[test]
        fn r07_n_greater_than_code_length() {
            // R07 (REQ-LIFT-F-005): `{{3}}` on 2-char code → empty
            assert_eq!(resolve_placeholders("{{3}}", "ab"), "");
        }

        #[test]
        fn r08_n_much_greater_than_code_length() {
            // R08 (REQ-LIFT-F-005): `{{100}}` on 5-char code → empty
            assert_eq!(resolve_placeholders("{{100}}", "short"), "");
        }

        #[test]
        fn r09_placeholder_with_surrounding_text() {
            // R09 (REQ-LIFT-F-004): placeholder embedded in template text
            assert_eq!(
                resolve_placeholders("prefix {{}} suffix", "code"),
                "prefix code suffix"
            );
        }

        #[test]
        fn r10_same_code_multiple_placeholders() {
            // R10 (REQ-LIFT-F-004): same captured code substituted twice
            assert_eq!(resolve_placeholders("{{}} and {{}}", "X"), "X and X");
        }

        // --- §8.3 UTF-8 character counting for `{{N}}` (U01–U05) ---

        #[test]
        fn u01_multibyte_char_removed_by_count() {
            // U01 (REQ-LIFT-NF-002): é is 2 bytes but 1 char — `{{1}}`
            // removes it entirely
            assert_eq!(resolve_placeholders("{{1}}", "éabc"), "abc");
        }

        #[test]
        fn u02_two_multibyte_chars_removed() {
            // U02 (REQ-LIFT-NF-002): é + à = 4 bytes but 2 chars
            assert_eq!(resolve_placeholders("{{2}}", "éàbc"), "bc");
        }

        #[test]
        fn u03_astral_char_counts_once() {
            // U03 (REQ-LIFT-NF-002): 😀 is 4 bytes but 1 char; a+😀+b =
            // 3 chars — `{{3}}` removes all
            assert_eq!(resolve_placeholders("{{3}}", "a😀b"), "");
        }

        #[test]
        fn u04_zero_removal_multibyte_unchanged() {
            // U04 (REQ-LIFT-NF-002): `{{0}}` leaves multibyte code intact
            assert_eq!(resolve_placeholders("{{0}}", "éabc"), "éabc");
        }

        #[test]
        fn u05_n_greater_than_char_count() {
            // U05 (REQ-LIFT-NF-002): `{{4}}` on 3-char code → empty
            // (char counting, not bytes: a+😀+b = 3 chars)
            assert_eq!(resolve_placeholders("{{4}}", "a😀b"), "");
        }

        // --- Helper-function scaffolding tests (contract pinning) ---

        #[test]
        fn trim_leading_space_tab_strips_only_leading_ws() {
            // REQ-LIFT-F-004: leading space/tab stripped, empty stays empty
            assert_eq!(trim_leading_space_tab("  code"), "code");
            assert_eq!(trim_leading_space_tab("\tcode"), "code");
            assert_eq!(trim_leading_space_tab("code"), "code");
            assert_eq!(trim_leading_space_tab(""), "");
        }

        // NOTE: D01/D02/D10 (parse_sed_placeholder extract/replace/unterminated)
        // are DEFERRED to batch 2. trim_trailing_space_tab is tested indirectly
        // via S02/S03/S09 (through try_split_code_capturing); {{N}} char removal
        // is covered by U01-U05 via resolve_placeholders. count_utf8_chars_prefix
        // is not in the spec ({{N}} uses captured_code.chars().skip(n).collect()).

        #[test]
        fn unescape_delimiter_unescapes_only_delimiter() {
            // REQ-LIFT-F-008: `\` + delimiter → literal delimiter;
            // other backslash sequences pass through unchanged
            assert_eq!(unescape_delimiter("foo\\/bar", b'/'), "foo/bar");
            assert_eq!(unescape_delimiter("baz/qux", b'/'), "baz/qux");
        }

        // --- §8.5 End-to-end extraction tests (E01–E17) ---
        //
        // Helper: parse a single-line input and assert entries match
        // `(tag, text, transient)` triples.
        fn assert_parse(input: &str, initial_tag: &str, expected: &[(&str, &str, bool)]) {
            let mut tags = HashSet::new();
            let entries = parse_doc_entries(&mut tags, input, initial_tag);
            assert_eq!(entries.len(), expected.len(), "entry count mismatch");
            for (entry, (tag, text, transient)) in entries.iter().zip(expected) {
                assert_eq!(&*entry.tag, *tag, "tag mismatch");
                assert_eq!(&*entry.text, *text, "text mismatch");
                assert_eq!(entry.transient, *transient, "transient mismatch");
            }
        }

        #[test]
        fn e01_basic_substitution_with_double_trim() {
            // E01 (REQ-LIFT-F-001,F-002,F-004,F-010): {{}} double-trim.
            // Template "value: {{}}" starts with 'v' → tag directive
            // "value:" (transient), text from {{}} resolution.
            assert_parse(
                "    let x = 5;      //// value: {{}}\n",
                "lib",
                &[("value:", "let x = 5;\n", true)],
            );
        }

        #[test]
        fn e02_n_placeholder_character_removal() {
            // E02 (REQ-LIFT-F-005): {{8}} removes first 8 UTF-8 chars
            assert_parse(
                "    let x = 5;      //// {{8}}\n",
                "lib",
                &[("lib", "x = 5;\n", false)],
            );
        }

        #[test]
        fn e03_n_exceeds_code_length() {
            // E03 (REQ-LIFT-F-005): {{100}} on short code → empty
            assert_parse(
                "    let x = 5;      //// {{100}}\n",
                "lib",
                &[("lib", "\n", false)],
            );
        }

        #[test]
        fn e04_code_capture_between_doc_lines() {
            // E04 (REQ-LIFT-F-004,F-010): code capture between doc lines
            assert_parse(
                "//// # Before\n    code;  //// {{}}\n//// # After\n",
                "lib",
                &[
                    ("lib", "# Before\n", false),
                    ("lib", "code;\n", false),
                    ("lib", "# After\n", false),
                ],
            );
        }

        #[test]
        fn e05_back_to_back_code_captures() {
            // E05 (REQ-LIFT-F-004): multiple code-capturing lines
            assert_parse(
                "    a;  //// {{}}\n    b;  //// {{}}\n",
                "lib",
                &[("lib", "a;\n", false), ("lib", "b;\n", false)],
            );
        }

        #[test]
        fn e06_template_with_no_placeholder() {
            // E06 (REQ-LIFT-F-010): template with no {{}}.
            // Template "just text" starts with 'j' → tag directive
            // "just" (transient), text is "text\n".
            assert_parse(
                "    code;  //// just text\n",
                "lib",
                &[("just", "text\n", true)],
            );
        }

        #[test]
        fn e07_empty_template() {
            // E07 (REQ-LIFT-F-010): empty template — just the line ending
            assert_parse("    code;  ////\n", "lib", &[("lib", "\n", false)]);
        }

        #[test]
        fn e08_multiple_placeholders() {
            // E08 (REQ-LIFT-F-004): template "a{{}}b{{}}c" starts with 'a',
            // no space/tab → persistent switch to tag "a{{}}b{{}}c", no entry.
            assert_parse("    X;  //// a{{}}b{{}}c\n", "lib", &[]);
        }

        #[test]
        fn e09_unterminated_double_brace() {
            // E09 (REQ-LIFT-F-004): unterminated {{ emitted literally.
            // Template "text {{ oops" starts with 't' → tag directive
            // "text" (transient), text is "{{ oops\n".
            assert_parse(
                "    X;  //// text {{ oops\n",
                "lib",
                &[("text", "{{ oops\n", true)],
            );
        }

        #[test]
        fn e10_code_capture_with_tag_directive() {
            // E10 (REQ-LIFT-F-010): code capture under tag directive
            assert_parse(
                "////foo\n    code;  //// {{}}\n",
                "lib",
                &[("foo", "code;\n", false)],
            );
        }

        #[test]
        fn e11_backward_compat_doc_lines_only() {
            // E11 (REQ-LIFT-C-004): only doc lines — output unchanged
            assert_parse(
                "//// Hello\n//// World\n",
                "lib",
                &[("lib", "Hello\n", false), ("lib", "World\n", false)],
            );
        }

        #[test]
        fn e12_backward_compat_doc_with_code() {
            // E12 (REQ-LIFT-C-004): doc lines + regular code (non-capturing)
            assert_parse(
                "//// Doc\nlet x = 5;\n//// More\n",
                "lib",
                &[("lib", "Doc\n", false), ("lib", "More\n", false)],
            );
        }

        #[test]
        fn e13_doc_line_with_trailing_slashes_not_code_capture() {
            // E13 (REQ-LIFT-C-004): //// line with trailing //// is a doc line
            assert_parse(
                "//// This text ends with ////\n",
                "lib",
                &[("lib", "This text ends with ////\n", false)],
            );
        }

        #[test]
        fn e14_tag_directive_not_code_capture() {
            // E14 (REQ-LIFT-C-004): tag directive not treated as code capture
            assert_parse("////foo bar\n", "lib", &[("foo", "bar\n", true)]);
        }

        #[test]
        fn e15_crlf_preserved() {
            // E15 (REQ-LIFT-F-010): CRLF preserved in code-capturing entry
            assert_parse(
                "code;  //// {{}}\r\n",
                "lib",
                &[("lib", "code;\r\n", false)],
            );
        }

        #[test]
        fn e16_no_separator_before_slashes() {
            // E16 (REQ-LIFT-F-001): no space/tab before //// → skipped
            assert_parse("code////no-separator\n", "lib", &[]);
        }

        #[test]
        #[should_panic(expected = "reserved placeholder form")]
        fn e17_reserved_form_panics() {
            // E17 (REQ-LIFT-F-009): reserved form {{abc}} panics
            let mut tags = HashSet::new();
            let _entries = parse_doc_entries(&mut tags, "code;  //// {{abc}}\n", "lib");
        }

        // --- §8.5a Capture zone continuation (E18) ---

        #[test]
        fn e18_capture_zone_continuation() {
            // E18: deeper-indented //// line inside a capture zone is
            // treated as code-capturing suffix, not a doc line.
            // Captured code is empty (whitespace before ////);
            // placeholders resolve with empty code.
            //
            // Input mimics the user's example: a code block inside
            // ``` fences with code-capturing lines and a continuation.
            assert_parse(
                concat!(
                    "//// lets show the internal code\n",
                    "//// ```\n",
                    "    code  //// {{}}\n",
                    "        //// {{4}} suffix\n",
                    "    more  //// {{}}\n",
                    "//// ```\n",
                ),
                "lib",
                &[
                    ("lib", "lets show the internal code\n", false),
                    ("lib", "```\n", false),
                    ("lib", "code\n", false),
                    // continuation: {{4}} on empty → empty, then " suffix"
                    ("lib", " suffix\n", false),
                    ("lib", "more\n", false),
                    ("lib", "```\n", false),
                ],
            );
        }

        // --- §8.5b Tag-directive on code-capturing templates (E19–E22) ---

        #[test]
        fn e19_transient_tag_on_code_capture() {
            // E19: user's exact example — transient tag on code-capturing
            // template with {{}} placeholder resolution.
            // `constants code: {{}}` → tag="constants", transient, text="code: <captured>\n"
            assert_parse(
                concat!(
                    "//// lets show the internal code\n",
                    "//// ```\n",
                    "fn foo() {\n",
                    "    const FOO:i32=0;   ////constants code: {{}}\n",
                    "    let x=1;                     //// {{4}}\n",
                    "                                     //// {{4}}\n",
                    "    println!(\"{x}\");        //// {{4}}\n",
                    "}\n",
                    "//// ```\n",
                ),
                "lib",
                &[
                    ("lib", "lets show the internal code\n", false),
                    ("lib", "```\n", false),
                    // template "constants code: {{}}" → tag="constants", transient, text="code: const FOO:i32=0;\n"
                    ("constants", "code: const FOO:i32=0;\n", true),
                    // "    let x=1;" → {{4}} removes first 4 chars → "let x=1;\n"
                    ("lib", "let x=1;\n", false),
                    // continuation: "    //// {{4}}" → {{4}} on empty → "" → just newline
                    ("lib", "\n", false),
                    // "    println!(\"{x}\");" → {{4}} → "println!(\"{x}\");\n"
                    ("lib", "println!(\"{x}\");\n", false),
                    ("lib", "```\n", false),
                ],
            );
        }

        #[test]
        fn e20_persistent_tag_on_code_capture() {
            // E20: persistent tag switch on code-capture template.
            // `////mytag` (no space after tag) → persistent switch, no entry.
            // The next line captures under the new tag.
            assert_parse(
                concat!(
                    "//// before\n",
                    "    code;  ////mytag\n", // persistent switch → mytag
                    "    more;  //// {{}}\n", // now under tag "mytag"
                ),
                "lib",
                &[
                    ("lib", "before\n", false),
                    // "////mytag" (no space after tag) → persistent switch, no entry
                    // "more;  //// {{}}" → tag="mytag", text="more;\n"
                    ("mytag", "more;\n", false),
                ],
            );
        }

        #[test]
        fn e21_transient_then_persistent_on_code_capture() {
            // E21: transient tag then persistent switch sequence on code-capture.
            assert_parse(
                concat!(
                    "    a;  ////tag1 {{}}\n", // transient: tag=tag1, text="a;\n"
                    "    b;  ////tag2\n",      // persistent switch → tag2 (no entry)
                    "    c;  //// {{}}\n",     // under tag2: text="c;\n"
                ),
                "lib",
                &[
                    ("tag1", "a;\n", true),
                    // persistent switch "tag2" → no entry
                    ("tag2", "c;\n", false),
                ],
            );
        }

        #[test]
        fn e22_continuation_with_persistent_tag() {
            // E22: continuation line with persistent tag switch.
            assert_parse(
                concat!(
                    "    code;  //// {{}}\n", // zone at indent 4
                    "        ////mytag\n",    // deeper indent → continuation, persistent switch
                    "        //// {{}}\n",    // continuation under mytag: {{}} on empty → ""
                ),
                "lib",
                &[
                    ("lib", "code;\n", false),
                    // persistent switch "mytag" → no entry
                    // continuation {{}} on empty → empty
                    ("mytag", "\n", false),
                ],
            );
        }

        // --- §8.7 Filter interaction tests (F01–F05) ---

        #[test]
        fn f01_code_capture_matches_output_filter() {
            // F01 (REQ-LIFT-F-010): code-capture entry tagged chapter1,
            // matches output filter chapter1
            let tmp = TempDir::new("lift_f01");
            let src = tmp.write("f.rs", "////chapter1\n    code;  //// {{}}\n");
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .filter_output(Some("chapter1"))
                .unwrap()
                .input(&src)
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "code;\n");
        }

        #[test]
        fn f02_code_capture_filtered_out_by_tag() {
            // F02 (REQ-LIFT-F-010): code-capture entry tagged chapter2,
            // filter chapter1 → filtered out
            let tmp = TempDir::new("lift_f02");
            let src = tmp.write("f.rs", "////chapter2\n    code;  //// {{}}\n");
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .filter_output(Some("chapter1"))
                .unwrap()
                .input(&src)
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "");
        }

        #[test]
        fn f03_unfiltered_emits_both() {
            // F03 (REQ-LIFT-F-010): no filters — both doc and code-capture
            // entries emitted
            let tmp = TempDir::new("lift_f03");
            let src = tmp.write("f.rs", "//// Doc\n    code;  //// {{}}\n");
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .input(&src)
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "Doc\ncode;\n");
        }

        #[test]
        fn f04_input_filtered_code_capture() {
            // F04 (REQ-LIFT-F-010): input_filtered(api) — only api-tagged
            // entries emitted. Use persistent tag switch ////api (no text)
            // so subsequent lines carry the api tag.
            // "    code;  //// captured": template "captured" → persistent
            // switch to tag "captured" (no entry), then ////core text is
            // transient — filtered out by "api".
            let tmp = TempDir::new("lift_f04");
            let src = tmp.write(
                "f.rs",
                "////api\n//// doc\n    code;  //// captured\n////core text\n",
            );
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .input_filtered(&src, "api")
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "doc\n");
        }

        #[test]
        fn f05_code_capture_is_persistent() {
            // F05 (REQ-LIFT-F-010): templates starting with non-`{` characters
            // are now parsed as tag directives. "captured" → persistent switch
            // (no entry). The transient "t" entry is skipped in unfiltered mode.
            // Result: empty output.
            let tmp = TempDir::new("lift_f05");
            let src = tmp.write("f.rs", "////t transient\n    code;  //// captured\n");
            let out = tmp.file("out.md");
            Docextract::new(&out)
                .unwrap()
                .input(&src)
                .unwrap()
                .done()
                .unwrap();
            // transient "t" entry skipped; no other entries → empty
            assert_eq!(read_str(&out), "");
        }

        #[test]
        fn f06_code_capture_carries_tag_and_responds_to_filter() {
            // F06: verify that tag directives on code-capturing templates
            // respond to output filtering. Template "captured" → persistent
            // switch to tag "captured" (no entry), followed by doc line.
            let tmp = TempDir::new("lift_f06");
            let src = tmp.write(
                "f.rs",
                concat!("////detail\n", "    code;  //// captured\n", "//// doc\n"),
            );
            let out = tmp.file("out.md");
            // Unfiltered: persistent switch "captured", then doc line
            // "doc" under "captured" tag → emitted
            Docextract::new(&out)
                .unwrap()
                .input(&src)
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out), "doc\n");
            // Filtered for "detail": the doc line under "captured" is filtered out
            let out2 = tmp.file("out2.md");
            Docextract::new(&out2)
                .unwrap()
                .filter_output(Some("detail"))
                .unwrap()
                .input(&src)
                .unwrap()
                .done()
                .unwrap();
            assert_eq!(read_str(&out2), "");
        }

        // --- §8.2a Sed-like resolve_placeholders (EX01–EX03) ---

        #[cfg(feature = "regex")]
        #[test]
        fn ex01_replace_outputs_only_substitution() {
            // EX01 (REQ-LIFT-F-007): {{/regex/subst/}} outputs only the
            // expanded substitution. Non-matched text ("pub " in
            // "pub fn new;") is discarded.
            assert_eq!(
                resolve_placeholders("{{/fn (.*);/$1/}}", "pub fn new;"),
                "new"
            );
        }

        #[cfg(feature = "regex")]
        #[test]
        fn ex02_replace_no_match_returns_empty() {
            // EX02 (REQ-LIFT-F-007): no regex match → empty string.
            assert_eq!(resolve_placeholders("{{/xxx/$1/}}", "pub fn new;"), "");
        }

        #[cfg(feature = "regex")]
        #[test]
        fn ex03_extract_still_outputs_match() {
            // EX03 (REQ-LIFT-F-006): extract mode unchanged — outputs the
            // match text.
            assert_eq!(
                resolve_placeholders("{{/fn .*;/}}", "pub fn new;"),
                "fn new;"
            );
        }
    }

    // -----------------------------------------------------------------
    // Global cache tests — specs/global-cache-spec.md §5
    //
    // RED phase: tests that exercise the thread-local global cache.
    // Expected to fail until the global cache implementation lands.
    // -----------------------------------------------------------------
    mod global_cache {
        use super::*;
        use std::rc::Rc;

        // --- TC-01: Cache sharing across instances ---

        /// Subprocess helper: runs the test binary with the given env var set,
        /// executing the same test function as the child.
        fn run_cache_sharing_subprocess(child_env: &str, test_name: &str) -> std::process::Output {
            let exe = std::env::current_exe().unwrap();
            std::process::Command::new(&exe)
                .env(child_env, "1")
                .arg("--exact")
                .arg(test_name)
                .arg("--nocapture")
                .output()
                .unwrap()
        }

        #[test]
        fn tc01_cache_sharing_two_instances() {
            // REQ-CACHE-F-001, REQ-CACHE-F-005, REQ-CACHE-C-004
            if std::env::var_os("DOCEXTRACT_TC01_SUBPROCESS").is_some() {
                // Child: run the actual cache-sharing logic
                let tmp = TempDir::new("tc01");
                let src = tmp.write("in.rs", "////api doc\n");
                let out1 = tmp.file("out1.md");
                let out2 = tmp.file("out2.md");
                let _guard = OutDirGuard::with(Some(tmp.file("out_dir").as_os_str()));

                Docextract::new(&out1)
                    .unwrap()
                    .input_filtered(&src, "api")
                    .unwrap()
                    .done()
                    .unwrap();
                Docextract::new(&out2)
                    .unwrap()
                    .input_filtered(&src, "api")
                    .unwrap()
                    .done()
                    .unwrap();

                assert_eq!(read_str(&out1), "doc\n");
                assert_eq!(read_str(&out2), "doc\n");
                return;
            }
            let output = run_cache_sharing_subprocess(
                "DOCEXTRACT_TC01_SUBPROCESS",
                "tests::global_cache::tc01_cache_sharing_two_instances",
            );
            assert!(output.status.success(), "child failed: {:?}", output.status);
            let stdout = String::from_utf8_lossy(&output.stdout);
            let directive_count = stdout.matches("cargo:rerun-if-changed=").count();
            assert_eq!(
                directive_count, 1,
                "rerun-if-changed must be emitted exactly once across two instances, got: {stdout}"
            );
            assert!(
                String::from_utf8_lossy(&output.stderr).is_empty(),
                "no warnings expected"
            );
        }

        #[test]
        fn tc01_cache_sharing_three_instances() {
            if std::env::var_os("DOCEXTRACT_TC01B_SUBPROCESS").is_some() {
                let tmp = TempDir::new("tc01b");
                let src = tmp.write("in.rs", "////api a\n");
                let out1 = tmp.file("out1.md");
                let out2 = tmp.file("out2.md");
                let out3 = tmp.file("out3.md");
                let _guard = OutDirGuard::with(Some(tmp.file("out_dir").as_os_str()));

                Docextract::new(&out1)
                    .unwrap()
                    .input_filtered(&src, "api")
                    .unwrap()
                    .done()
                    .unwrap();
                Docextract::new(&out2)
                    .unwrap()
                    .input_filtered(&src, "api")
                    .unwrap()
                    .done()
                    .unwrap();
                Docextract::new(&out3)
                    .unwrap()
                    .input_filtered(&src, "api")
                    .unwrap()
                    .done()
                    .unwrap();

                assert_eq!(read_str(&out1), "a\n");
                assert_eq!(read_str(&out2), "a\n");
                assert_eq!(read_str(&out3), "a\n");
                return;
            }
            let output = run_cache_sharing_subprocess(
                "DOCEXTRACT_TC01B_SUBPROCESS",
                "tests::global_cache::tc01_cache_sharing_three_instances",
            );
            assert!(output.status.success(), "child failed: {:?}", output.status);
            let stdout = String::from_utf8_lossy(&output.stdout);
            let directive_count = stdout.matches("cargo:rerun-if-changed=").count();
            assert_eq!(
                directive_count, 1,
                "rerun-if-changed must be emitted exactly once across three instances, got: {stdout}"
            );
        }

        // --- TC-02: clear_cache ---

        #[test]
        fn tc02_clear_cache_then_reparse() {
            if std::env::var_os("DOCEXTRACT_TC02_SUBPROCESS").is_some() {
                let tmp = TempDir::new("tc02");
                let src = tmp.write("in.rs", "////api doc\n");
                let out1 = tmp.file("out1.md");
                let out2 = tmp.file("out2.md");
                let _guard = OutDirGuard::with(Some(tmp.file("out_dir").as_os_str()));

                Docextract::new(&out1)
                    .unwrap()
                    .input_filtered(&src, "api")
                    .unwrap()
                    .done()
                    .unwrap();
                Docextract::clear_cache();
                Docextract::new(&out2)
                    .unwrap()
                    .input_filtered(&src, "api")
                    .unwrap()
                    .done()
                    .unwrap();

                assert_eq!(read_str(&out1), "doc\n");
                assert_eq!(read_str(&out2), "doc\n");
                return;
            }
            let output = run_cache_sharing_subprocess(
                "DOCEXTRACT_TC02_SUBPROCESS",
                "tests::global_cache::tc02_clear_cache_then_reparse",
            );
            assert!(output.status.success(), "child failed: {:?}", output.status);
            let stdout = String::from_utf8_lossy(&output.stdout);
            let directive_count = stdout.matches("cargo:rerun-if-changed=").count();
            assert_eq!(
                directive_count, 2,
                "rerun-if-changed must be emitted twice: before and after clear_cache, got: {stdout}"
            );
        }

        #[test]
        fn tc02_clear_cache_on_empty_cache_noop() {
            // clear_cache() on empty cache → no panic, no error.
            Docextract::clear_cache();
            Docextract::clear_cache();
            // Multiple clears are idempotent.
        }

        #[test]
        fn tc02_clear_cache_between_inputs_on_same_instance() {
            // clear_cache() between .input() calls on same instance
            // forces re-parse on second call.
            let tmp = TempDir::new("tc02c");
            let src = tmp.write("in.rs", "//// doc\n");
            let out = tmp.file("out.md");

            let mut builder = Docextract::new(&out).unwrap();
            builder.input(&src).unwrap();

            // Rewrite file to verify re-parse happens
            fs::write(&src, "//// new\n").unwrap();

            // Clear cache — next input must re-read
            Docextract::clear_cache();
            builder.input(&src).unwrap();
            builder.done().unwrap();

            // Since we re-read after clear, we get "new" not "doc"
            assert_eq!(read_str(&out), "doc\nnew\n");
        }

        // --- TC-03: Path normalization ---

        #[test]
        fn tc03_equivalent_paths_share_cache() {
            // REQ-CACHE-F-002
            // Same file accessed via canonical and original path shares cache.
            let tmp = TempDir::new("tc03");
            let src = tmp.write("file.rs", "//// hello\n");
            let out = tmp.file("out.md");

            let mut builder = Docextract::new(&out).unwrap();

            // First access: canonical path
            let canonical = std::fs::canonicalize(&src).unwrap();
            builder.input(&canonical).unwrap();

            // Second access: original path — must be cache hit
            builder.input(&src).unwrap();
            builder.done().unwrap();

            assert_eq!(read_str(&out), "hello\nhello\n");
        }

        #[test]
        fn tc03_dot_slash_path_resolves() {
            // REQ-CACHE-F-002
            // `./path/to/file.rs` and `path/to/file.rs` share cache.
            let tmp = TempDir::new("tc03b");
            let subdir = tmp.file("subdir");
            fs::create_dir_all(&subdir).unwrap();
            let file_in_sub = subdir.join("file.rs");
            fs::write(&file_in_sub, "//// data\n").unwrap();

            let out = tmp.file("out.md");
            let mut builder = Docextract::new(&out).unwrap();

            // Change to the tmp directory so `./subdir/file.rs` resolves
            let orig_cwd = std::env::current_dir().unwrap();
            std::env::set_current_dir(tmp.0.as_path()).unwrap();

            // First access with ./ prefix
            builder.input("./subdir/file.rs").unwrap();

            // Second access without ./ prefix — must be cache hit
            builder.input("subdir/file.rs").unwrap();
            builder.done().unwrap();

            // Restore CWD
            std::env::set_current_dir(orig_cwd).unwrap();

            assert_eq!(read_str(&out), "data\ndata\n");
        }

        // --- TC-04: Stdin caching ---

        #[test]
        fn tc04_stdin_twice_on_same_instance() {
            // REQ-CACHE-F-007
            // Calling .stdin() twice should cache the second call (no re-read).
            // But in-process, .stdin() reads from the real stdin — this test
            // verifies that caching under the "-" key works. We use
            // .input_filtered("-", ...) which is the same code path.
            //
            // Since we can't inject stdin in a unit test, we verify
            // that the cache key "-" is recognized. We test via the
            // subprocess approach (TC-05 covers this via CLI).
        }

        #[test]
        fn tc04_repeated_filtered_stdin_uses_cache() {
            // REQ-CACHE-F-007
            // Two reads of the same file via input_filtered — second is cache hit.
            let tmp = TempDir::new("tc04");
            let src = tmp.write("in.txt", "////api a\n////b b\n");
            let out = tmp.file("out.md");

            let mut builder = Docextract::new(&out).unwrap();
            builder.input_filtered(&src, "api").unwrap();
            builder.input_filtered(&src, "b").unwrap();
            builder.done().unwrap();

            assert_eq!(read_str(&out), "a\nb\n");
        }

        // --- TC-06: Tag interning across instances ---

        #[test]
        fn tc06_tag_interning_across_instances() {
            // REQ-CACHE-F-004
            // Tags from different parse calls across instances share the
            // same Rc<str> allocation via the global pool.
            let tmp = TempDir::new("tc06");
            let src1 = tmp.write("a.rs", "////foo bar\n");
            let src2 = tmp.write("b.rs", "////foo baz\n");

            // Parse both files — entries from both should share tag "foo"
            // We need to access parsed entries to check Rc::ptr_eq.
            // Use parse_doc_entries directly.
            let content1 = fs::read_to_string(&src1).unwrap();
            let content2 = fs::read_to_string(&src2).unwrap();
            let mut tags = HashSet::new();
            let entries1 = parse_doc_entries(&mut tags, &content1, "a");
            let entries2 = parse_doc_entries(&mut tags, &content2, "b");

            assert_eq!(entries1.len(), 1);
            assert_eq!(entries2.len(), 1);
            assert_eq!(&*entries1[0].tag, "foo");
            assert_eq!(&*entries2[0].tag, "foo");
            // Cross-instance: tags from two parse calls must share allocation
            assert!(
                Rc::ptr_eq(&entries1[0].tag, &entries2[0].tag),
                "tag 'foo' from two different parse calls must share the same Rc<str> allocation"
            );
        }

        // --- TC-09: Error propagation (missing file) ---

        #[test]
        fn tc09_missing_file_returns_ok_on_both_instances() {
            // REQ-CACHE-C-003
            // Missing file → canonicalize() fails → NotFound propagated.
            // Two instances both calling .input() on a missing file must
            // return Ok (warning to stderr) and not panic.
            let tmp = TempDir::new("tc09");
            let out1 = tmp.file("out1.md");
            let out2 = tmp.file("out2.md");
            let missing = tmp.file("does_not_exist.rs");

            let mut builder1 = Docextract::new(&out1).unwrap();
            assert!(
                builder1.input(&missing).is_ok(),
                "missing file must return Ok (warning to stderr)"
            );

            let mut builder2 = Docextract::new(&out2).unwrap();
            assert!(
                builder2.input(&missing).is_ok(),
                "second instance with missing file must also return Ok"
            );

            builder1.done().unwrap();
            builder2.done().unwrap();
        }

        // --- Backward compatibility: all existing tests pass ---

        #[test]
        fn tc08_single_instance_output_unchanged() {
            // REQ-CACHE-C-001, REQ-CACHE-NF-002
            // Single-instance usage produces identical output to pre-cache.
            let tmp = TempDir::new("tc08");
            let src = tmp.write("in.rs", "//// Hello\n//// World\n");
            let out = tmp.file("out.md");

            Docextract::new(&out)
                .unwrap()
                .input(&src)
                .unwrap()
                .done()
                .unwrap();

            assert_eq!(read_str(&out), "Hello\nWorld\n");
        }
    }
}