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
#![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::path::Path;
use std::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,
// Tag-filter fields
cache: HashMap<String, Vec<DocEntry>>,
tags: HashSet<Rc<str>>,
output_filter: Option<Pattern>,
}
/// Convert a path to a cache key.
fn cache_key(path: &Path) -> String {
if path == Path::new("-") {
"-".to_string()
} else {
// Use the path's string representation
path.to_string_lossy().into_owned()
}
}
/// 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,
cache: HashMap::new(),
tags: HashSet::new(),
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
}
// --- private methods ---
/// Intern a tag name into the cross-file interning pool.
fn intern_tag(&mut self, name: &str) -> Rc<str> {
if let Some(existing) = self.tags.get(name) {
return Rc::clone(existing);
}
let rc: Rc<str> = Rc::from(name.to_string());
self.tags.insert(Rc::clone(&rc));
rc
}
/// Parse all documentation entries from raw file content.
///
/// Uses `self.tags` (the interning `HashSet` on the builder) for tag
/// interning — tags from all files share one pool.
fn parse_doc_entries(&mut self, content: &str, initial_tag: &str) -> Vec<DocEntry> {
let mut entries = Vec::new();
let initial_tag_rc = self.intern_tag(initial_tag);
let mut current_tag = Rc::clone(&initial_tag_rc);
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 {
continue;
};
let rest = &line_slice[after..];
// Step 2: Five+ slashes → ignore
if rest.as_bytes().first() == Some(&b'/') {
continue;
}
// 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(¤t_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(¤t_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(¤t_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 = self.intern_tag(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
}
/// 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 key = cache_key(path);
// Check cache first
if let Some(entries) = self.cache.get(&key) {
// Already parsed — emit from cached entries
let any_filter_active = self.output_filter.is_some() || input_filter.is_some();
// Clone the entries to avoid borrow issues
let entries_snapshot: Vec<DocEntry> = entries
.iter()
.map(|e| DocEntry {
tag: Rc::clone(&e.tag),
text: e.text.clone(),
transient: e.transient,
})
.collect();
self.emit_entries(&entries_snapshot, input_filter, any_filter_active)?;
return Ok(self);
}
// Not cached — read file, parse into DocEntry, store in cache
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 entries = self.parse_doc_entries(&content, &initial_tag);
self.cache.insert(key, entries);
// Emit entries
let any_filter_active = self.output_filter.is_some() || input_filter.is_some();
let cached_entries = self
.cache
.get(cache_key(path).as_str())
.expect("cache just populated");
// Clone to avoid borrow issues
let entries_snapshot: Vec<DocEntry> = cached_entries
.iter()
.map(|e| DocEntry {
tag: Rc::clone(&e.tag),
text: e.text.clone(),
transient: e.transient,
})
.collect();
self.emit_entries(&entries_snapshot, 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 = "-".to_string();
// Check cache first
if let Some(entries) = self.cache.get(&key) {
let any_filter_active = self.output_filter.is_some() || input_filter.is_some();
let entries_snapshot: Vec<DocEntry> = entries
.iter()
.map(|e| DocEntry {
tag: Rc::clone(&e.tag),
text: e.text.clone(),
transient: e.transient,
})
.collect();
self.emit_entries(&entries_snapshot, 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 entries = self.parse_doc_entries(&content, "-");
self.cache.insert(key, entries);
let any_filter_active = self.output_filter.is_some() || input_filter.is_some();
let cached_entries = self.cache.get("-").expect("cache just populated");
let entries_snapshot: Vec<DocEntry> = cached_entries
.iter()
.map(|e| DocEntry {
tag: Rc::clone(&e.tag),
text: e.text.clone(),
transient: e.transient,
})
.collect();
self.emit_entries(&entries_snapshot, 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();
}
}
/// 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 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)
}
}
#[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 builder's interning pool contains exactly
/// `expected` tag names.
fn assert_tags(builder: &Docextract, expected: &[&str]) {
assert_eq!(
builder.tags.len(),
expected.len(),
"interning pool size mismatch"
);
for &name in expected {
assert!(
builder.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 builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("//// Hello\n", "lib");
assert_entries(&entries, &[("lib", "Hello\n", false)]);
assert_tags(&builder, &["lib"]);
}
#[test]
fn p02_four_space_indent() {
// REQ-TAG-F-001 / P02: leading ASCII whitespace stripped before prefix match
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries(" //// Hello\n", "lib");
assert_entries(&entries, &[("lib", "Hello\n", false)]);
assert_tags(&builder, &["lib"]);
}
#[test]
fn p03_tab_indent() {
// REQ-TAG-F-001 / P03: tab indent stripped, prefix matched
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("\t//// Hello\n", "lib");
assert_entries(&entries, &[("lib", "Hello\n", false)]);
assert_tags(&builder, &["lib"]);
}
#[test]
fn p04_tab_separator() {
// REQ-TAG-F-001 / P04: tab separator stripped exactly once
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("////\tHello\n", "lib");
assert_entries(&entries, &[("lib", "Hello\n", false)]);
assert_tags(&builder, &["lib"]);
}
#[test]
fn p05_empty_doc_line_newline() {
// REQ-TAG-F-001 / P05: `////\n` → verbatim blank line entry
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("////\n", "lib");
assert_entries(&entries, &[("lib", "\n", false)]);
assert_tags(&builder, &["lib"]);
}
#[test]
fn p06_empty_doc_line_space_newline() {
// REQ-TAG-F-001 / P06: `//// \n` → separator stripped, blank line entry
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("//// \n", "lib");
assert_entries(&entries, &[("lib", "\n", false)]);
assert_tags(&builder, &["lib"]);
}
#[test]
fn p07_empty_doc_line_at_eof() {
// REQ-TAG-F-001 / P07: `////` at EOF (no newline) → empty-text entry
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("////", "lib");
assert_entries(&entries, &[("lib", "", false)]);
assert_tags(&builder, &["lib"]);
}
#[test]
fn p08_crlf_preserved() {
// REQ-TAG-F-001 / P08: CRLF ending preserved in entry text
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("//// Hello\r\n", "lib");
assert_entries(&entries, &[("lib", "Hello\r\n", false)]);
assert_tags(&builder, &["lib"]);
}
#[test]
fn p09_three_spaces_first_is_separator() {
// REQ-TAG-F-001 / P09: one separator stripped, two spaces preserved
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("//// \n", "lib");
assert_entries(&entries, &[("lib", " \n", false)]);
assert_tags(&builder, &["lib"]);
}
#[test]
fn p10_two_spaces_second_preserved() {
// REQ-TAG-F-001 / P10: one separator stripped, one space preserved
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("//// Two Spaces\n", "lib");
assert_entries(&entries, &[("lib", " Two Spaces\n", false)]);
assert_tags(&builder, &["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 builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries(&input, "myfile");
assert_entries(&entries, &[("myfile", &format!("{content}\n"), false)]);
assert_tags(&builder, &["myfile"]);
}
#[test]
fn p12_five_slashes_ignored() {
// REQ-TAG-F-001 / P12: five slashes → silently ignored
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("/////\n", "lib");
assert_entries(&entries, &[]);
assert_tags(&builder, &["lib"]);
}
#[test]
fn p13_six_slashes_ignored() {
// REQ-TAG-F-001 / P13: six slashes → silently ignored
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("//////\n", "lib");
assert_entries(&entries, &[]);
assert_tags(&builder, &["lib"]);
}
#[test]
fn p14_three_slashes_ignored() {
// REQ-TAG-F-001 / P14: `///\n` — fewer than four slashes → ignored
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("///\n", "lib");
assert_entries(&entries, &[]);
assert_tags(&builder, &["lib"]);
}
#[test]
fn p15_non_four_slash_prefix_ignored() {
// REQ-TAG-F-001 / P15: first four bytes not all slashes → ignored
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("X///\nfn main() {}\n", "lib");
assert_entries(&entries, &[]);
assert_tags(&builder, &["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 builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries(" ", "lib");
assert_entries(&entries, &[]);
assert_tags(&builder, &["lib"]);
}
#[test]
fn p17_mixed_indent() {
// REQ-TAG-F-001 / P17: mixed space+tab indent skipped
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries(" \t//// Hello\n", "lib");
assert_entries(&entries, &[("lib", "Hello\n", false)]);
assert_tags(&builder, &["lib"]);
}
#[test]
fn p18_space_separator_at_eof() {
// REQ-TAG-F-001 / P18: `//// ` at EOF → separator stripped, empty text
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("//// ", "lib");
assert_entries(&entries, &[("lib", "", false)]);
assert_tags(&builder, &["lib"]);
}
#[test]
fn p19_tab_separator_at_eof() {
// REQ-TAG-F-001 / P19: `////\t` at EOF → separator stripped, empty text
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("////\t", "lib");
assert_entries(&entries, &[("lib", "", false)]);
assert_tags(&builder, &["lib"]);
}
#[test]
fn p20_crlf_without_separator() {
// REQ-TAG-F-001 / P20: `////\r\n` → CRLF preserved, no separator to strip
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("////\r\n", "lib");
assert_entries(&entries, &[("lib", "\r\n", false)]);
assert_tags(&builder, &["lib"]);
}
#[test]
fn p21_cr_at_eof() {
// REQ-TAG-F-001 / P21: `////\r` (lone CR at EOF) → preserved
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("////\r", "lib");
assert_entries(&entries, &[("lib", "\r", false)]);
assert_tags(&builder, &["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 builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("////foo\n", "lib");
assert_entries(&entries, &[]);
assert_tags(&builder, &["lib", "foo"]);
}
#[test]
fn p23_persistent_tag_switch_chapter1() {
// REQ-TAG-F-002 / P23: `////chapter1` → persistent switch
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("////chapter1\n", "lib");
assert_entries(&entries, &[]);
assert_tags(&builder, &["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 builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("////foo bar baz\n", "lib");
assert_entries(&entries, &[("foo", "bar baz\n", true)]);
assert_tags(&builder, &["lib", "foo"]);
}
#[test]
fn p25_transient_tag_glossary() {
// REQ-TAG-F-003 / P25: `////glossary example` → transient entry
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("////glossary example\n", "lib");
assert_entries(&entries, &[("glossary", "example\n", true)]);
assert_tags(&builder, &["lib", "glossary"]);
}
#[test]
fn p26_tag_with_hyphen() {
// REQ-TAG-F-002 / P26: hyphen allowed in tag names (§6.1.3)
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("////tag-name\n", "lib");
assert_entries(&entries, &[]);
assert_tags(&builder, &["lib", "tag-name"]);
}
#[test]
fn p27_tag_with_dot() {
// REQ-TAG-F-002 / P27: dot allowed in tag names
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("////tag.name\n", "lib");
assert_entries(&entries, &[]);
assert_tags(&builder, &["lib", "tag.name"]);
}
#[test]
fn p28_hash_tag() {
// REQ-TAG-F-003 / P28: `////### Heading` → transient tag `###`
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("////### Heading\n", "lib");
assert_entries(&entries, &[("###", "Heading\n", true)]);
assert_tags(&builder, &["lib", "###"]);
}
#[test]
fn p29_numeric_tag() {
// REQ-TAG-F-002 / P29: numeric tag names allowed
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("////42\n", "lib");
assert_entries(&entries, &[]);
assert_tags(&builder, &["lib", "42"]);
}
#[test]
fn p30_indented_tag_directive() {
// REQ-TAG-F-002 / P30: tag directives may be indented
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries(" ////foo\n", "lib");
assert_entries(&entries, &[]);
assert_tags(&builder, &["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 builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("////Hello\n", "lib");
assert_entries(&entries, &[]);
assert_tags(&builder, &["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 builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("////foo\n//// bar\n", "lib");
assert_entries(&entries, &[("foo", "bar\n", false)]);
assert_tags(&builder, &["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 builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("////foo\n////baz text\n//// after\n", "lib");
assert_entries(
&entries,
&[("baz", "text\n", true), ("foo", "after\n", false)],
);
assert_tags(&builder, &["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 builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("//// 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(&builder, &["mod"]);
}
#[test]
fn p35_stdin_initial_tag() {
// REQ-TAG-F-004 / P35: stdin initial tag is the sentinel `-` (§6.3)
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("//// hello\n", "-");
assert_entries(&entries, &[("-", "hello\n", false)]);
assert_tags(&builder, &["-"]);
}
#[test]
fn p36_no_doc_lines() {
// REQ-TAG-F-001 / P36: file with no `////` lines → empty entries
let mut builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("fn main() {\n let x = 1;\n}\n", "lib");
assert_entries(&entries, &[]);
assert_tags(&builder, &["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 builder = Docextract::new("-").unwrap();
let entries = builder.parse_doc_entries("//// text\n////", "lib");
assert_entries(&entries, &[("lib", "text\n", false), ("lib", "", false)]);
assert_tags(&builder, &["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" };
content.push_str(&format!("////{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 = match builder.input_filtered(&src, "api") {
Err(e) => e,
Ok(_) => 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 = match builder.input_filtered(&src, "api") {
Err(e) => e,
Ok(_) => 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();
}
}
}