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
//! Shared rendering functions for documentation generation.
//!
//! This module contains standalone rendering functions that can be used by both
//! single-crate ([`ItemRenderer`](super::ItemRenderer)) and multi-crate
//! ([`MultiCrateModuleRenderer`](crate::multi_crate::generator)) renderers.
//!
//! These functions handle the core markdown generation logic without being tied
//! to a specific rendering context, avoiding code duplication between the two modes.
use std::borrow::Cow;
use std::fmt::Write;
use std::path::Path;
use rustdoc_types::{Crate, Id, Impl, Item, ItemEnum, Span, StructKind, VariantKind, Visibility};
use crate::generator::context::RenderContext;
use crate::linker::{AnchorUtils, AssocItemKind, ImplContext};
use crate::types::TypeRenderer;
// =============================================================================
// Source Location Rendering
// =============================================================================
/// Information needed to transform source paths to relative links.
///
/// When generating source location references, this config enables transforming
/// absolute cargo registry paths to relative links pointing to the local
/// `.source_{timestamp}` directory.
#[derive(Debug, Clone)]
pub struct SourcePathConfig {
/// The `.source_{timestamp}` directory name (e.g., `.source_1733660400`).
pub source_dir_name: String,
/// Depth of the current markdown file from `generated_docs/`.
/// Used to calculate the correct number of `../` prefixes.
pub depth: usize,
}
impl SourcePathConfig {
/// Create a new source path config.
///
/// # Arguments
///
/// * `source_dir` - Full path to the `.source_*` directory
/// * `current_file` - Path of the current markdown file relative to output dir
#[must_use]
pub fn new(source_dir: &Path, current_file: &str) -> Self {
let source_dir_name = source_dir
.file_name()
.and_then(|n| n.to_str())
.unwrap_or(".source")
.to_string();
// Count depth: number of '/' in current_file path
// e.g., "serde/de/index.md" has depth 2
let depth = current_file.matches('/').count();
Self {
source_dir_name,
depth,
}
}
/// Create a config with a specific depth (for file-specific configs).
#[must_use]
pub fn with_depth(&self, current_file: &str) -> Self {
Self {
source_dir_name: self.source_dir_name.clone(),
depth: current_file.matches('/').count(),
}
}
}
/// Categorized trait items for structured rendering.
#[derive(Default)]
pub struct CategorizedTraitItems<'a> {
/// Required methods (no default body)
pub required_methods: Vec<&'a Item>,
/// Provided methods (have default body)
pub provided_methods: Vec<&'a Item>,
/// Associated types
pub associated_types: Vec<&'a Item>,
/// Associated constants
pub associated_consts: Vec<&'a Item>,
}
impl<'a> CategorizedTraitItems<'a> {
/// Categorize trait items into required/provided methods, types and constants.
#[must_use]
pub fn categorize_trait_items(trait_items: &[Id], krate: &'a Crate) -> Self {
let mut result = CategorizedTraitItems::default();
for item_id in trait_items {
let Some(item) = krate.index.get(item_id) else {
continue;
};
match &item.inner {
ItemEnum::Function(f) => {
if f.has_body {
result.provided_methods.push(item);
} else {
result.required_methods.push(item);
}
},
ItemEnum::AssocType { .. } => {
result.associated_types.push(item);
},
ItemEnum::AssocConst { .. } => {
result.associated_consts.push(item);
},
_ => {},
}
}
result
}
}
/// Unit struct to organize path related utility functions related to renderer functions.
pub struct RendererUtils;
impl RendererUtils {
/// Sanitize trait paths by removing macro artifacts.
///
/// Rustdoc JSON can contain `$crate::` prefixes from macro expansions
/// which leak implementation details into documentation. This function
/// removes these artifacts for cleaner output.
///
/// Uses `Cow<str>` to avoid allocation when no changes are needed.
///
/// # Examples
///
/// ```
/// use cargo_docs_md::generator::render_shared::RendererUtils;
///
/// assert_eq!(RendererUtils::sanitize_path("$crate::clone::Clone"), "clone::Clone");
/// assert_eq!(RendererUtils::sanitize_path("std::fmt::Debug"), "std::fmt::Debug");
/// ```
#[must_use]
pub fn sanitize_path(path: &str) -> Cow<'_, str> {
if path.contains("$crate::") {
Cow::Owned(path.replace("$crate::", ""))
} else {
Cow::Borrowed(path)
}
}
/// Sanitize self parameter in function signatures.
///
/// Converts verbose self type annotations to idiomatic Rust syntax:
/// - `self: &Self` → `&self`
/// - `self: &mut Self` → `&mut self`
/// - `self: Self` → `self`
///
/// Uses `Cow<str>` to avoid allocation when no changes are needed.
///
/// # Examples
///
/// ```
/// use cargo_docs_md::generator::render_shared::RendererUtils;
///
/// assert_eq!(RendererUtils::sanitize_self_param("self: &Self"), "&self");
/// assert_eq!(RendererUtils::sanitize_self_param("self: &mut Self"), "&mut self");
/// assert_eq!(RendererUtils::sanitize_self_param("self: Self"), "self");
/// assert_eq!(RendererUtils::sanitize_self_param("x: i32"), "x: i32");
/// ```
#[must_use]
pub fn sanitize_self_param(param: &str) -> Cow<'_, str> {
match param {
"self: &Self" => Cow::Borrowed("&self"),
"self: &mut Self" => Cow::Borrowed("&mut self"),
"self: Self" => Cow::Borrowed("self"),
_ => Cow::Borrowed(param),
}
}
/// Write tuple field types directly to buffer, comma-separated.
///
/// Avoids intermediate `Vec` allocation by writing directly to the output buffer.
/// Handles `Option<Id>` fields from rustdoc's representation of tuple structs/variants
/// (where `None` indicates a private field).
///
/// # Arguments
///
/// * `out` - Output buffer to write to
/// * `fields` - Slice of optional field IDs from rustdoc
/// * `krate` - Crate containing field definitions
/// * `type_renderer` - Type renderer for field types
pub fn write_tuple_fields(
out: &mut String,
fields: &[Option<Id>],
krate: &Crate,
type_renderer: &TypeRenderer,
) {
let mut first = true;
for id in fields.iter().filter_map(|id| id.as_ref()) {
if let Some(item) = krate.index.get(id)
&& let ItemEnum::StructField(ty) = &item.inner
{
if !first {
_ = write!(out, ", ");
}
// write! is infallible for String
_ = write!(out, "{}", type_renderer.render_type(ty));
first = false;
}
}
}
/// Transform an absolute cargo registry path to a relative `.source_*` path.
///
/// Converts paths like:
/// `/home/user/.cargo/registry/src/index.crates.io-xxx/serde-1.0.228/src/lib.rs`
///
/// To:
/// `.source_1733660400/serde-1.0.228/src/lib.rs`
///
/// Returns `None` if the path doesn't match the expected cargo registry pattern.
#[must_use]
pub fn transform_cargo_path(absolute_path: &Path, source_dir_name: &str) -> Option<String> {
let path_str = absolute_path.to_str()?;
// Look for the pattern: .cargo/registry/src/{index}/
// The crate directory follows the index directory
if let Some(registry_idx) = path_str.find(".cargo/registry/src/") {
// Find the index directory end (e.g., "index.crates.io-xxx/")
let after_registry = &path_str[registry_idx + ".cargo/registry/src/".len()..];
// Skip the index directory name (find the next '/')
if let Some(slash_idx) = after_registry.find('/') {
// Everything after the index directory is the crate path
// e.g., "serde-1.0.228/src/lib.rs"
let crate_relative = &after_registry[slash_idx + 1..];
return Some(format!("{source_dir_name}/{crate_relative}"));
}
}
None
}
}
/// Unit struct to organize trait related functions.
pub struct TraitRenderer;
impl TraitRenderer {
/// Write trait bounds with `: ` prefix directly to buffer.
///
/// Avoids intermediate `Vec` allocation for trait supertrait bounds.
/// Writes nothing if bounds are empty.
///
/// # Arguments
///
/// * `out` - Output buffer to write to
/// * `bounds` - Slice of generic bounds from the trait
/// * `type_renderer` - Type renderer for bounds (passed by value as it's Copy)
fn write_trait_bounds(
out: &mut String,
bounds: &[rustdoc_types::GenericBound],
type_renderer: TypeRenderer,
) {
if bounds.is_empty() {
return;
}
_ = write!(out, ": ");
let mut first = true;
for bound in bounds {
let rendered = type_renderer.render_generic_bound(bound);
// Skip empty rendered bounds
if rendered.is_empty() {
continue;
}
if !first {
_ = write!(out, " + ");
}
_ = write!(out, "{}", &rendered);
first = false;
}
}
/// Render a trait definition code block to markdown.
///
/// Produces a heading with the trait name and generics, followed by a Rust
/// code block showing the trait signature with supertraits.
///
/// # Arguments
///
/// * `md` - Output markdown string
/// * `name` - The trait name
/// * `t` - The trait data from rustdoc
/// * `type_renderer` - Type renderer for generics and bounds
pub fn render_trait_definition(
md: &mut String,
name: &str,
t: &rustdoc_types::Trait,
type_renderer: &TypeRenderer,
) {
let generics = type_renderer.render_generics(&t.generics.params);
let where_clause = type_renderer.render_where_clause(&t.generics.where_predicates);
_ = writeln!(md, "### `{name}{generics}`\n");
_ = writeln!(md, "```rust");
_ = write!(md, "trait {name}{generics}");
Self::write_trait_bounds(md, &t.bounds, *type_renderer);
_ = writeln!(md, "{where_clause} {{ ... }}");
_ = writeln!(md, "```\n");
}
/// Render a single trait item (method, associated type, or constant).
///
/// Each item is rendered as a bullet point with its signature in backticks.
/// For methods, the first line of documentation is included.
///
/// # Arguments
///
/// * `md` - Output markdown string
/// * `item` - The trait item (function, assoc type, or assoc const)
/// * `type_renderer` - Type renderer for types
/// * `process_docs` - Closure to process documentation with intra-doc link resolution
pub fn render_trait_item<F>(
md: &mut String,
item: &Item,
type_renderer: &TypeRenderer,
process_docs: F,
) where
F: Fn(&Item) -> Option<String>,
{
let name = item.name.as_deref().unwrap_or("_");
match &item.inner {
ItemEnum::Function(f) => {
let generics = type_renderer.render_generics(&f.generics.params);
let params: Vec<String> = f
.sig
.inputs
.iter()
.map(|(param_name, ty)| {
let raw = format!("{param_name}: {}", type_renderer.render_type(ty));
RendererUtils::sanitize_self_param(&raw).into_owned()
})
.collect();
let ret = f
.sig
.output
.as_ref()
.map(|ty| format!(" -> {}", type_renderer.render_type(ty)))
.unwrap_or_default();
_ = write!(
md,
"- `fn {}{}({}){}`",
name,
generics,
params.join(", "),
ret
);
if let Some(docs) = process_docs(item)
&& let Some(first_line) = docs.lines().next()
{
_ = write!(md, "\n\n {first_line}");
}
_ = write!(md, "\n\n");
},
ItemEnum::AssocType { bounds, type_, .. } => {
let bounds_str = if bounds.is_empty() {
String::new()
} else {
format!(": {}", bounds.len())
};
let default_str = type_
.as_ref()
.map(|ty| format!(" = {}", type_renderer.render_type(ty)))
.unwrap_or_default();
_ = write!(md, "- `type {name}{bounds_str}{default_str}`\n\n");
},
ItemEnum::AssocConst { type_, .. } => {
_ = write!(
md,
"- `const {name}: {}`\n\n",
type_renderer.render_type(type_)
);
},
_ => {
_ = write!(md, "- `{name}`\n\n");
},
}
}
}
/// Unit struct containing renderer functions.
/// Helpful because free functions are annoying.
pub struct RendererInternals;
impl RendererInternals {
/// Render a struct definition code block to markdown.
///
/// Produces a heading with the struct name and generics, followed by a Rust
/// code block showing the struct definition.
///
/// # Arguments
///
/// * `md` - Output markdown string
/// * `name` - The struct name (may differ from item.name for re-exports)
/// * `s` - The struct data from rustdoc
/// * `krate` - The crate containing field definitions
/// * `type_renderer` - Type renderer for generics and field types
pub fn render_struct_definition(
md: &mut String,
name: &str,
s: &rustdoc_types::Struct,
krate: &Crate,
type_renderer: &TypeRenderer,
) {
let generics = type_renderer.render_generics(&s.generics.params);
let where_clause = type_renderer.render_where_clause(&s.generics.where_predicates);
_ = write!(md, "### `{name}{generics}`\n\n");
_ = writeln!(md, "```rust");
match &s.kind {
StructKind::Unit => {
_ = writeln!(md, "struct {name}{generics}{where_clause};");
},
StructKind::Tuple(fields) => {
_ = write!(md, "struct {name}{generics}(");
RendererUtils::write_tuple_fields(md, fields, krate, type_renderer);
_ = writeln!(md, "){where_clause};");
},
StructKind::Plain {
fields,
has_stripped_fields,
} => {
_ = writeln!(md, "struct {name}{generics}{where_clause} {{");
for field_id in fields {
if let Some(field) = krate.index.get(field_id) {
let field_name = field.name.as_deref().unwrap_or("_");
if let ItemEnum::StructField(ty) = &field.inner {
let vis = match &field.visibility {
Visibility::Public => "pub ",
_ => "",
};
_ = writeln!(
md,
" {}{}: {},",
vis,
field_name,
type_renderer.render_type(ty)
);
}
}
}
if *has_stripped_fields {
_ = writeln!(md, " // [REDACTED: Private Fields]");
}
_ = writeln!(md, "}}");
},
}
_ = writeln!(md, "```\n");
}
/// Render documented struct fields to markdown.
///
/// Produces a "Fields" section with each documented field as a bullet point
/// showing the field name, type, and documentation.
///
/// # Arguments
///
/// * `md` - Output markdown string
/// * `fields` - Field IDs from the struct
/// * `krate` - Crate containing field definitions
/// * `type_renderer` - Type renderer for field types
/// * `process_docs` - Closure to process documentation with intra-doc link resolution
pub fn render_struct_fields<F>(
md: &mut String,
fields: &[Id],
krate: &Crate,
type_renderer: &TypeRenderer,
process_docs: F,
) where
F: Fn(&Item) -> Option<String>,
{
let documented_fields: Vec<_> = fields
.iter()
.filter_map(|id| krate.index.get(id))
.filter(|f| f.docs.is_some())
.collect();
if !documented_fields.is_empty() {
_ = writeln!(md, "#### Fields\n");
for field in documented_fields {
let field_name = field.name.as_deref().unwrap_or("_");
if let ItemEnum::StructField(ty) = &field.inner {
_ = write!(
md,
"- **`{}`**: `{}`",
field_name,
type_renderer.render_type(ty)
);
if let Some(docs) = process_docs(field) {
_ = write!(md, "\n\n {}", docs.replace('\n', "\n "));
}
_ = writeln!(md, "\n");
}
}
}
}
/// Render an enum definition code block to markdown.
///
/// Produces a heading with the enum name and generics, followed by a Rust
/// code block showing the enum definition with all variants.
///
/// # Arguments
///
/// * `md` - Output markdown string
/// * `name` - The enum name (may differ from item.name for re-exports)
/// * `e` - The enum data from rustdoc
/// * `krate` - The crate containing variant definitions
/// * `type_renderer` - Type renderer for generics and variant types
pub fn render_enum_definition(
md: &mut String,
name: &str,
e: &rustdoc_types::Enum,
krate: &Crate,
type_renderer: &TypeRenderer,
) {
let generics = type_renderer.render_generics(&e.generics.params);
let where_clause = type_renderer.render_where_clause(&e.generics.where_predicates);
_ = write!(md, "### `{name}{generics}`\n\n");
_ = writeln!(md, "```rust");
_ = writeln!(md, "enum {name}{generics}{where_clause} {{");
for variant_id in &e.variants {
if let Some(variant) = krate.index.get(variant_id) {
Self::render_enum_variant(md, variant, krate, type_renderer);
}
}
_ = writeln!(md, "}}");
_ = writeln!(md, "```\n");
}
/// Render a single enum variant within the definition code block.
///
/// Handles all three variant kinds: plain, tuple, and struct variants.
pub fn render_enum_variant(
md: &mut String,
variant: &Item,
krate: &Crate,
type_renderer: &TypeRenderer,
) {
let variant_name = variant.name.as_deref().unwrap_or("_");
if let ItemEnum::Variant(v) = &variant.inner {
match &v.kind {
VariantKind::Plain => {
_ = writeln!(md, " {variant_name},");
},
VariantKind::Tuple(fields) => {
_ = write!(md, " {variant_name}(");
RendererUtils::write_tuple_fields(md, fields, krate, type_renderer);
_ = writeln!(md, "),");
},
VariantKind::Struct { fields, .. } => {
_ = writeln!(md, " {variant_name} {{");
for field_id in fields {
if let Some(field) = krate.index.get(field_id) {
let field_name = field.name.as_deref().unwrap_or("_");
if let ItemEnum::StructField(ty) = &field.inner {
_ = writeln!(
md,
" {}: {},",
field_name,
type_renderer.render_type(ty)
);
}
}
}
_ = writeln!(md, " }},");
},
}
}
}
/// Render documented enum variants to markdown.
///
/// Produces a "Variants" section with each documented variant as a bullet point.
///
/// # Arguments
///
/// * `md` - Output markdown string
/// * `variants` - Variant IDs from the enum
/// * `krate` - Crate containing variant definitions
/// * `process_docs` - Closure to process documentation with intra-doc link resolution
pub fn render_enum_variants_docs<F>(
md: &mut String,
variants: &[Id],
krate: &Crate,
process_docs: F,
) where
F: Fn(&Item) -> Option<String>,
{
let documented_variants: Vec<_> = variants
.iter()
.filter_map(|id| krate.index.get(id))
.filter(|v| v.docs.is_some())
.collect();
if !documented_variants.is_empty() {
_ = writeln!(md, "#### Variants\n");
for variant in documented_variants {
let variant_name = variant.name.as_deref().unwrap_or("_");
_ = write!(md, "- **`{variant_name}`**");
if let Some(docs) = process_docs(variant) {
_ = write!(md, "\n\n {}", docs.replace('\n', "\n "));
}
_ = writeln!(md, "\n");
}
}
}
/// Render a function definition to markdown.
///
/// Produces a heading with the function name, followed by a Rust code block
/// showing the full signature with modifiers (const, async, unsafe).
///
/// # Arguments
///
/// * `md` - Output markdown string
/// * `name` - The function name
/// * `f` - The function data from rustdoc
/// * `type_renderer` - Type renderer for parameter and return types
pub fn render_function_definition(
md: &mut String,
name: &str,
f: &rustdoc_types::Function,
type_renderer: &TypeRenderer,
) {
let generics = type_renderer.render_generics(&f.generics.params);
let where_clause = type_renderer.render_where_clause(&f.generics.where_predicates);
let params: Vec<String> = f
.sig
.inputs
.iter()
.map(|(param_name, ty)| {
let raw = format!("{param_name}: {}", type_renderer.render_type(ty));
RendererUtils::sanitize_self_param(&raw).into_owned()
})
.collect();
let ret = f
.sig
.output
.as_ref()
.map(|ty| format!(" -> {}", type_renderer.render_type(ty)))
.unwrap_or_default();
let is_async = if f.header.is_async { "async " } else { "" };
let is_const = if f.header.is_const { "const " } else { "" };
let is_unsafe = if f.header.is_unsafe { "unsafe " } else { "" };
_ = writeln!(md, "### `{name}`\n");
_ = writeln!(md, "```rust");
_ = writeln!(
md,
"{}{}{}fn {}{}({}){}{}",
is_const,
is_async,
is_unsafe,
name,
generics,
params.join(", "),
ret,
where_clause
);
_ = writeln!(md, "```\n");
}
/// Render a constant definition to markdown.
///
/// Produces a heading with the constant name, followed by a Rust code block
/// showing `const NAME: Type = value;`.
///
/// # Arguments
///
/// * `md` - Output markdown string
/// * `name` - The constant name
/// * `type_` - The constant's type
/// * `const_` - The constant data including value
/// * `type_renderer` - Type renderer for the type
pub fn render_constant_definition(
md: &mut String,
name: &str,
type_: &rustdoc_types::Type,
const_: &rustdoc_types::Constant,
type_renderer: &TypeRenderer,
) {
_ = writeln!(md, "### `{name}`");
_ = writeln!(md, "```rust");
let value = const_
.value
.as_ref()
.map(|v| format!(" = {v}"))
.unwrap_or_default();
_ = writeln!(
md,
"const {name}: {}{value};",
type_renderer.render_type(type_)
);
_ = writeln!(md, "```\n");
}
/// Render a type alias definition to markdown.
///
/// Produces a heading with the alias name and generics, followed by a Rust
/// code block showing `type Name<T> = TargetType;`.
///
/// # Arguments
///
/// * `md` - Output markdown string
/// * `name` - The type alias name
/// * `ta` - The type alias data from rustdoc
/// * `type_renderer` - Type renderer for generics and the aliased type
pub fn render_type_alias_definition(
md: &mut String,
name: &str,
ta: &rustdoc_types::TypeAlias,
type_renderer: &TypeRenderer,
) {
let generics = type_renderer.render_generics(&ta.generics.params);
let where_clause = type_renderer.render_where_clause(&ta.generics.where_predicates);
_ = write!(md, "### `{name}{generics}`\n\n");
_ = writeln!(md, "```rust");
_ = writeln!(
md,
"type {name}{generics}{where_clause} = {};",
type_renderer.render_type(&ta.type_)
);
_ = writeln!(md, "```\n");
}
/// Render a macro definition to markdown.
///
/// Produces a heading with the macro name and `!` suffix.
/// Note: We don't show macro rules since rustdoc JSON doesn't provide them.
///
/// # Arguments
///
/// * `md` - Output markdown string
/// * `name` - The macro name
pub fn render_macro_heading(md: &mut String, name: &str) {
_ = write!(md, "### `{name}!`\n\n");
}
/// Render the items within an impl block.
///
/// This renders all methods, associated constants, and associated types
/// within an impl block as bullet points.
///
/// # Arguments
///
/// * `md` - Output markdown string
/// * `impl_block` - The impl block to render items from
/// * `krate` - The crate containing item definitions
/// * `type_renderer` - Type renderer for types
/// * `process_docs` - Optional closure to process documentation
/// * `create_type_link` - Optional closure to create links for types `(id -> Option<markdown_link>)`
/// * `parent_type_name` - Optional type name for generating method anchors
/// * `impl_ctx` - Context for anchor generation (inherent vs trait impl)
#[expect(
clippy::too_many_arguments,
reason = "Internal helper with documented params"
)]
pub fn render_impl_items<F, L>(
md: &mut String,
impl_block: &Impl,
krate: &Crate,
type_renderer: &TypeRenderer,
process_docs: &Option<F>,
create_type_link: &Option<L>,
parent_type_name: Option<&str>,
impl_ctx: ImplContext<'_>,
full_method_docs: bool,
) where
F: Fn(&Item) -> Option<String>,
L: Fn(rustdoc_types::Id) -> Option<String>,
{
for item_id in &impl_block.items {
if let Some(item) = krate.index.get(item_id) {
let name = item.name.as_deref().unwrap_or("_");
match &item.inner {
ItemEnum::Function(f) => {
Self::render_impl_function(md, name, f, *type_renderer, parent_type_name, impl_ctx);
// Add type links if link creator is provided
if let Some(link_creator) = create_type_link {
Self::render_function_type_links_inline(
md,
f,
*type_renderer,
link_creator,
);
}
// Extract and render method documentation
if let Some(pf) = process_docs
&& let Some(docs) = pf(item)
{
let summary = Self::extract_method_summary(&docs, full_method_docs);
if !summary.is_empty() {
// Indent the summary for proper markdown rendering under the list item
for line in summary.lines() {
_ = write!(md, "\n\n {line}");
}
}
}
_ = writeln!(md, "\n");
},
ItemEnum::AssocConst { type_, .. } => {
// Add anchor for associated constants if parent type is known
if let Some(type_name) = parent_type_name {
let anchor = AnchorUtils::impl_item_anchor(
type_name,
name,
AssocItemKind::Const,
impl_ctx,
);
_ = writeln!(
md,
"- <span id=\"{anchor}\"></span>`const {name}: {}`\n",
type_renderer.render_type(type_)
);
} else {
_ = writeln!(
md,
"- `const {name}: {}`\n",
type_renderer.render_type(type_)
);
}
},
ItemEnum::AssocType { type_, .. } => {
// Add anchor for associated types if parent type is known
// Use impl_item_anchor to include trait name for uniqueness
let anchor_prefix = parent_type_name
.map(|tn| {
format!(
"<span id=\"{}\"></span>",
AnchorUtils::impl_item_anchor(
tn,
name,
AssocItemKind::Type,
impl_ctx
)
)
})
.unwrap_or_default();
if let Some(ty) = type_ {
_ = writeln!(
md,
"- {anchor_prefix}`type {name} = {}`\n",
type_renderer.render_type(ty)
);
} else {
_ = writeln!(md, "- {anchor_prefix}`type {name}`\n");
}
},
_ => {},
}
}
}
}
/// Extract method documentation summary for impl blocks.
///
/// The extraction strategy is:
/// 1. If `full_method_docs` is true, return the entire documentation
/// 2. If the docs contain code examples (triple-backtick blocks), return full docs to preserve them
/// 3. Otherwise, extract just the first paragraph (lines until first blank line)
///
/// This ensures important code examples are never lost while keeping summaries
/// concise for methods without examples.
fn extract_method_summary(docs: &str, full_method_docs: bool) -> String {
// If full docs requested, return everything
if full_method_docs {
return docs.to_string();
}
// Auto-expand if docs contain code examples (``` blocks)
// This preserves important usage examples that would otherwise be truncated
if docs.contains("```") {
return docs.to_string();
}
// Extract first paragraph: lines until first blank line
// This captures the essential description without examples
let first_paragraph: String = docs
.lines()
.take_while(|line| !line.trim().is_empty())
.collect::<Vec<_>>()
.join("\n");
first_paragraph
}
/// Render type links for a function signature inline (for impl methods).
///
/// This is a helper that collects types from function signatures and
/// creates links for resolvable types, outputting them on the same line.
fn render_function_type_links_inline<L>(
md: &mut String,
f: &rustdoc_types::Function,
type_renderer: TypeRenderer,
create_link: &L,
) where
L: Fn(rustdoc_types::Id) -> Option<String>,
{
use std::collections::HashSet;
let mut all_types = Vec::new();
// Collect from parameters
for (_, ty) in &f.sig.inputs {
all_types.extend(type_renderer.collect_linkable_types(ty));
}
// Collect from return type
if let Some(output) = &f.sig.output {
all_types.extend(type_renderer.collect_linkable_types(output));
}
// Deduplicate by name (keep first occurrence)
let mut seen = HashSet::new();
let unique_types: Vec<_> = all_types
.into_iter()
.filter(|(name, _)| seen.insert(name.clone()))
.collect();
// Create links for resolvable types
let links: Vec<String> = unique_types
.iter()
.filter_map(|(_, id)| create_link(*id))
.collect();
// Output inline if we have links
if !links.is_empty() {
_ = write!(md, " — {}", links.join(", "));
}
}
/// Render a function signature within an impl block.
///
/// Renders as a bullet point with the full signature including modifiers.
/// If `parent_type_name` is provided, includes a hidden anchor for deep linking.
/// The `impl_ctx` parameter ensures unique anchors when the same method name
/// appears in multiple trait implementations (e.g., `fmt` in Debug and Display).
fn render_impl_function(
md: &mut String,
name: &str,
f: &rustdoc_types::Function,
type_renderer: TypeRenderer,
parent_type_name: Option<&str>,
impl_ctx: ImplContext<'_>,
) {
let generics = type_renderer.render_generics(&f.generics.params);
let params: Vec<String> = f
.sig
.inputs
.iter()
.map(|(param_name, ty)| {
let raw = format!("{param_name}: {}", type_renderer.render_type(ty));
RendererUtils::sanitize_self_param(&raw).into_owned()
})
.collect();
let ret = f
.sig
.output
.as_ref()
.map(|ty| format!(" -> {}", type_renderer.render_type(ty)))
.unwrap_or_default();
let is_async = if f.header.is_async { "async " } else { "" };
let is_const = if f.header.is_const { "const " } else { "" };
let is_unsafe = if f.header.is_unsafe { "unsafe " } else { "" };
// Add anchor for deep linking if parent type is known
// Use impl_item_anchor to include trait name for unique anchors
let anchor_span = parent_type_name
.map(|tn| {
format!(
"<span id=\"{}\"></span>",
AnchorUtils::impl_item_anchor(tn, name, AssocItemKind::Method, impl_ctx)
)
})
.unwrap_or_default();
_ = write!(
md,
"- {anchor_span}`{}{}{}fn {}{}({}){}`",
is_const,
is_async,
is_unsafe,
name,
generics,
params.join(", "),
ret
);
}
/// Append processed documentation to markdown.
///
/// Helper function to add documentation with consistent formatting.
pub fn append_docs(md: &mut String, docs: Option<String>) {
if let Some(docs) = docs {
_ = write!(md, "{}", &docs);
_ = writeln!(md, "\n");
}
}
/// Render the opening of a collapsible `<details>` block with a summary.
///
/// Produces HTML that creates a collapsible section in markdown. Use with
/// [`render_collapsible_end`] to close the block.
///
/// # Arguments
///
/// * `summary` - The text to display in the summary line (clickable header)
///
/// # Example
///
/// ```
/// use cargo_docs_md::generator::render_shared::RendererInternals;
///
/// let start = RendererInternals::render_collapsible_start("Derived Traits (9 implementations)");
/// assert!(start.contains("<details>"));
/// assert!(start.contains("<summary>Derived Traits (9 implementations)</summary>"));
/// ```
#[must_use]
pub fn render_collapsible_start(summary: &str) -> String {
format!("<details>\n<summary>{summary}</summary>\n\n")
}
/// Render the closing of a collapsible `<details>` block.
///
/// Returns a static string to close a block opened with [`render_collapsible_start`].
///
/// # Example
///
/// ```
/// use cargo_docs_md::generator::render_shared::RendererInternals;
///
/// assert_eq!(RendererInternals::render_collapsible_end(), "\n</details>\n\n");
/// ```
#[must_use]
pub const fn render_collapsible_end() -> &'static str {
"\n</details>\n\n"
}
/// Generate a sort key for an impl block for deterministic ordering.
///
/// Combines trait name, generic params, and for-type to create a unique key.
#[must_use]
pub fn impl_sort_key(impl_block: &Impl, type_renderer: &TypeRenderer) -> String {
let trait_name = impl_block
.trait_
.as_ref()
.map(|t| t.path.clone())
.unwrap_or_default();
let for_type = type_renderer.render_type(&impl_block.for_);
let generics = type_renderer.render_generics(&impl_block.generics.params);
format!("{trait_name}{generics}::{for_type}")
}
/// Render a source location reference for an item.
///
/// Produces a small italicized line showing the source file and line range.
/// If `source_path_config` is provided, generates a clickable markdown link
/// relative to the current file's location.
///
/// # Arguments
///
/// * `span` - The source span from the item
/// * `source_path_config` - Optional configuration for path transformation
///
/// # Returns
///
/// A formatted markdown string with the source location, or empty string if span is None.
///
/// # Example Output (without config)
///
/// ```text
/// *Defined in `/home/user/.cargo/registry/src/.../serde-1.0.228/src/lib.rs:10-25`*
/// ```
///
/// # Example Output (with config, depth=2)
///
/// ```text
/// *Defined in [`serde-1.0.228/src/lib.rs:10-25`](../../.source_xxx/serde-1.0.228/src/lib.rs#L10-L25)*
/// ```
#[must_use]
pub fn render_source_location(
span: Option<&Span>,
source_path_config: Option<&SourcePathConfig>,
) -> String {
let Some(span) = span else {
return String::new();
};
let (start_line, _) = span.begin;
let (end_line, _) = span.end;
// Format line reference for display
let line_ref = if start_line == end_line {
format!("{start_line}")
} else {
format!("{start_line}-{end_line}")
};
// Try to transform the path if config is provided
if let Some(config) = source_path_config
&& let Some(relative_path) =
RendererUtils::transform_cargo_path(&span.filename, &config.source_dir_name)
{
// Build the prefix of "../" based on depth
// +1 to exit generated_docs/ directory
let prefix = "../".repeat(config.depth + 1);
// GitHub-style line fragment
let fragment = if start_line == end_line {
format!("#L{start_line}")
} else {
format!("#L{start_line}-L{end_line}")
};
// Display path without the .source_xxx prefix for cleaner look
let display_path = relative_path
.strip_prefix(&config.source_dir_name)
.map_or(relative_path.as_str(), |p| p.trim_start_matches('/'));
return format!(
"*Defined in [`{display_path}:{line_ref}`]({prefix}{relative_path}{fragment})*\n\n"
);
}
// Fallback: just display the path as-is (no link)
let filename = span.filename.display();
format!("*Defined in `{filename}:{line_ref}`*\n\n")
}
/// Render a union definition code block to markdown.
///
/// Produces a heading with the union name and generics, followed by a Rust
/// code block showing the union definition with all fields.
///
/// # Arguments
///
/// * `md` - Output markdown string
/// * `name` - The union name (may differ from item.name for re-exports)
/// * `u` - The union data from rustdoc
/// * `krate` - The crate containing field definitions
/// * `type_renderer` - Type renderer for generics and field types
pub fn render_union_definition(
md: &mut String,
name: &str,
u: &rustdoc_types::Union,
krate: &Crate,
type_renderer: &TypeRenderer,
) {
let generics = type_renderer.render_generics(&u.generics.params);
let where_clause = type_renderer.render_where_clause(&u.generics.where_predicates);
_ = writeln!(md, "### `{name}{generics}`\n");
_ = writeln!(md, "```rust");
_ = writeln!(md, "union {name}{generics}{where_clause} {{");
for field_id in &u.fields {
if let Some(field) = krate.index.get(field_id) {
let field_name = field.name.as_deref().unwrap_or("_");
if let ItemEnum::StructField(ty) = &field.inner {
let vis = match &field.visibility {
Visibility::Public => "pub ",
_ => "",
};
_ = writeln!(
md,
" {}{}: {},",
vis,
field_name,
type_renderer.render_type(ty)
);
}
}
}
if u.has_stripped_fields {
_ = writeln!(md, " // some fields omitted");
}
_ = writeln!(md, "}}\n```\n");
}
/// Render union fields documentation.
///
/// Creates a "Fields" section with each field's name, type, and documentation.
/// Only renders if at least one field has documentation.
///
/// # Arguments
///
/// * `md` - Output markdown string
/// * `fields` - Field IDs from the union
/// * `krate` - The crate containing field definitions
/// * `type_renderer` - Type renderer for field types
/// * `process_docs` - Callback to process documentation strings
pub fn render_union_fields<F>(
md: &mut String,
fields: &[Id],
krate: &Crate,
type_renderer: &TypeRenderer,
process_docs: F,
) where
F: Fn(&Item) -> Option<String>,
{
// Check if any fields have documentation
let has_documented_fields = fields
.iter()
.any(|id| krate.index.get(id).is_some_and(|item| item.docs.is_some()));
if !has_documented_fields {
return;
}
_ = write!(md, "#### Fields\n\n");
for field_id in fields {
let Some(field) = krate.index.get(field_id) else {
continue;
};
let field_name = field.name.as_deref().unwrap_or("_");
if let ItemEnum::StructField(ty) = &field.inner {
let type_str = type_renderer.render_type(ty);
_ = writeln!(md, "- **`{field_name}`**: `{type_str}`");
if let Some(docs) = process_docs(field) {
// Indent documentation under the field
for line in docs.lines() {
if line.is_empty() {
md.push('\n');
} else {
_ = writeln!(md, " {line}");
}
}
_ = writeln!(md);
}
}
}
}
/// Render a static definition code block to markdown.
///
/// Produces a heading with the static name, followed by a Rust
/// code block showing the static definition.
///
/// # Arguments
///
/// * `md` - Output markdown string
/// * `name` - The static name (may differ from item.name for re-exports)
/// * `s` - The static data from rustdoc
/// * `type_renderer` - Type renderer for the static's type
pub fn render_static_definition(
md: &mut String,
name: &str,
s: &rustdoc_types::Static,
type_renderer: &TypeRenderer,
) {
_ = write!(md, "### `{name}`\n\n");
_ = writeln!(md, "```rust");
// Build the static declaration with modifiers
let mut decl = String::new();
// Check for unsafe (extern block statics)
if s.is_unsafe {
_ = write!(decl, "unsafe ");
}
_ = write!(decl, "static ");
// Check for mutable
if s.is_mutable {
_ = write!(decl, "mut ");
}
// Add name and type
_ = write!(decl, "{name}: {}", type_renderer.render_type(&s.type_));
// Add initializer expression if not empty
if !s.expr.is_empty() {
_ = write!(decl, " = {}", s.expr);
}
_ = write!(decl, ";");
_ = writeln!(md, "{decl}");
_ = write!(md, "```\n\n");
}
}
/// Check if a render context can resolve documentation.
///
/// This trait provides a unified way to process docs from different contexts.
pub trait DocsProcessor {
/// Process documentation for an item, resolving intra-doc links.
fn process_item_docs(&self, item: &Item) -> Option<String>;
}
impl<T: RenderContext + ?Sized> DocsProcessor for (&T, &str) {
fn process_item_docs(&self, item: &Item) -> Option<String> {
self.0.process_docs(item, self.1)
}
}
#[cfg(test)]
mod tests {
use super::*;
mod sanitize_path_tests {
use super::*;
#[test]
fn removes_crate_prefix() {
assert_eq!(
RendererUtils::sanitize_path("$crate::clone::Clone"),
"clone::Clone"
);
}
#[test]
fn removes_multiple_crate_prefixes() {
assert_eq!(
RendererUtils::sanitize_path("$crate::foo::$crate::bar::Baz"),
"foo::bar::Baz"
);
}
#[test]
fn preserves_normal_paths() {
assert_eq!(
RendererUtils::sanitize_path("std::fmt::Debug"),
"std::fmt::Debug"
);
}
#[test]
fn preserves_simple_names() {
assert_eq!(RendererUtils::sanitize_path("Clone"), "Clone");
}
#[test]
fn handles_empty_string() {
assert_eq!(RendererUtils::sanitize_path(""), "");
}
#[test]
fn returns_borrowed_when_no_change() {
let result = RendererUtils::sanitize_path("std::fmt::Debug");
assert!(matches!(result, Cow::Borrowed(_)));
}
#[test]
fn returns_owned_when_changed() {
let result = RendererUtils::sanitize_path("$crate::Clone");
assert!(matches!(result, Cow::Owned(_)));
}
}
mod sanitize_self_param_tests {
use super::*;
#[test]
fn converts_ref_self() {
assert_eq!(RendererUtils::sanitize_self_param("self: &Self"), "&self");
}
#[test]
fn converts_mut_ref_self() {
assert_eq!(
RendererUtils::sanitize_self_param("self: &mut Self"),
"&mut self"
);
}
#[test]
fn converts_owned_self() {
assert_eq!(RendererUtils::sanitize_self_param("self: Self"), "self");
}
#[test]
fn preserves_regular_params() {
assert_eq!(RendererUtils::sanitize_self_param("x: i32"), "x: i32");
}
#[test]
fn preserves_complex_types() {
assert_eq!(
RendererUtils::sanitize_self_param("callback: impl Fn()"),
"callback: impl Fn()"
);
}
#[test]
fn returns_borrowed_for_all_cases() {
// All return values should be borrowed (no allocation)
assert!(matches!(
RendererUtils::sanitize_self_param("self: &Self"),
Cow::Borrowed(_)
));
assert!(matches!(
RendererUtils::sanitize_self_param("self: &mut Self"),
Cow::Borrowed(_)
));
assert!(matches!(
RendererUtils::sanitize_self_param("self: Self"),
Cow::Borrowed(_)
));
assert!(matches!(
RendererUtils::sanitize_self_param("x: i32"),
Cow::Borrowed(_)
));
}
}
mod collapsible_tests {
use super::RendererInternals;
#[test]
fn start_contains_details_tag() {
let result = RendererInternals::render_collapsible_start("Test Summary");
assert!(result.contains("<details>"));
}
#[test]
fn start_contains_summary_with_text() {
let result =
RendererInternals::render_collapsible_start("Derived Traits (9 implementations)");
assert!(result.contains("<summary>Derived Traits (9 implementations)</summary>"));
}
#[test]
fn start_has_proper_formatting() {
let result = RendererInternals::render_collapsible_start("Test");
assert_eq!(result, "<details>\n<summary>Test</summary>\n\n");
}
#[test]
fn end_closes_details_tag() {
let result = RendererInternals::render_collapsible_end();
assert!(result.contains("</details>"));
}
#[test]
fn end_has_proper_formatting() {
assert_eq!(
RendererInternals::render_collapsible_end(),
"\n</details>\n\n"
);
}
#[test]
fn start_and_end_pair_correctly() {
let start = RendererInternals::render_collapsible_start("Content");
let end = RendererInternals::render_collapsible_end();
let full = format!("{start}Some markdown content here{end}");
assert!(full.starts_with("<details>"));
assert!(full.ends_with("</details>\n\n"));
assert!(full.contains("<summary>Content</summary>"));
}
}
mod source_location_tests {
use std::path::PathBuf;
use super::*;
#[test]
fn transform_cargo_path_extracts_crate_relative() {
let path = PathBuf::from(
"/home/user/.cargo/registry/src/index.crates.io-xxx/serde-1.0.228/src/lib.rs",
);
let result = RendererUtils::transform_cargo_path(&path, ".source_12345");
assert_eq!(
result,
Some(".source_12345/serde-1.0.228/src/lib.rs".to_string())
);
}
#[test]
fn transform_cargo_path_handles_nested_paths() {
let path = PathBuf::from(
"/home/user/.cargo/registry/src/index.crates.io-abc/tokio-1.0.0/src/runtime/mod.rs",
);
let result = RendererUtils::transform_cargo_path(&path, ".source_99999");
assert_eq!(
result,
Some(".source_99999/tokio-1.0.0/src/runtime/mod.rs".to_string())
);
}
#[test]
fn transform_cargo_path_returns_none_for_non_cargo_path() {
let path = PathBuf::from("/usr/local/src/myproject/lib.rs");
let result = RendererUtils::transform_cargo_path(&path, ".source_12345");
assert_eq!(result, None);
}
#[test]
fn transform_cargo_path_returns_none_for_local_path() {
let path = PathBuf::from("src/lib.rs");
let result = RendererUtils::transform_cargo_path(&path, ".source_12345");
assert_eq!(result, None);
}
#[test]
fn source_path_config_calculates_depth() {
let source_dir = PathBuf::from("/project/.source_12345");
let config = SourcePathConfig::new(&source_dir, "index.md");
assert_eq!(config.depth, 0);
let config = SourcePathConfig::new(&source_dir, "serde/index.md");
assert_eq!(config.depth, 1);
let config = SourcePathConfig::new(&source_dir, "serde/de/visitor/index.md");
assert_eq!(config.depth, 3);
}
#[test]
fn source_path_config_extracts_dir_name() {
let source_dir = PathBuf::from("/project/.source_1733660400");
let config = SourcePathConfig::new(&source_dir, "index.md");
assert_eq!(config.source_dir_name, ".source_1733660400");
}
#[test]
fn source_path_config_with_depth_preserves_name() {
let source_dir = PathBuf::from("/project/.source_12345");
let base_config = SourcePathConfig::new(&source_dir, "");
let file_config = base_config.with_depth("crate/module/index.md");
assert_eq!(file_config.source_dir_name, ".source_12345");
assert_eq!(file_config.depth, 2);
}
#[test]
fn render_source_location_without_config_shows_absolute_path() {
let span = rustdoc_types::Span {
filename: PathBuf::from(
"/home/user/.cargo/registry/src/index/serde-1.0/src/lib.rs",
),
begin: (10, 0),
end: (25, 0),
};
let result = RendererInternals::render_source_location(Some(&span), None);
assert!(result.contains("/home/user/.cargo/registry/src/index/serde-1.0/src/lib.rs"));
assert!(result.contains("10-25"));
// Should not have a link (no [ or ])
assert!(!result.contains('['));
}
#[test]
fn render_source_location_with_config_creates_link() {
let span = rustdoc_types::Span {
filename: PathBuf::from(
"/home/user/.cargo/registry/src/index.crates.io-xxx/serde-1.0.228/src/lib.rs",
),
begin: (10, 0),
end: (25, 0),
};
let config = SourcePathConfig {
source_dir_name: ".source_12345".to_string(),
depth: 1, // e.g., "serde/index.md"
};
let result = RendererInternals::render_source_location(Some(&span), Some(&config));
// Should have markdown link
assert!(result.contains('['));
assert!(result.contains("]("));
// Should have relative prefix (depth=1 + 1 for generated_docs = ../..)
assert!(result.contains("../../.source_12345/serde-1.0.228/src/lib.rs"));
// Should have line fragment
assert!(result.contains("#L10-L25"));
// Display path should NOT have .source prefix
assert!(result.contains("[`serde-1.0.228/src/lib.rs:10-25`]"));
}
#[test]
fn render_source_location_single_line() {
let span = rustdoc_types::Span {
filename: PathBuf::from(
"/home/user/.cargo/registry/src/index.crates.io-xxx/foo-1.0.0/src/lib.rs",
),
begin: (42, 0),
end: (42, 0),
};
let config = SourcePathConfig {
source_dir_name: ".source_99999".to_string(),
depth: 0,
};
let result = RendererInternals::render_source_location(Some(&span), Some(&config));
// Single line should show just one line number
assert!(result.contains(":42`]"));
assert!(result.contains("#L42)"));
// Should NOT have range format
assert!(!result.contains("-L"));
}
#[test]
fn render_source_location_none_span_returns_empty() {
let config = SourcePathConfig {
source_dir_name: ".source_12345".to_string(),
depth: 0,
};
let result = RendererInternals::render_source_location(None, Some(&config));
assert!(result.is_empty());
}
}
mod categorized_trait_items_tests {
use std::collections::HashMap;
use rustdoc_types::{Abi, Crate, Function, FunctionHeader, FunctionSignature, Target};
use super::*;
fn make_test_crate(items: Vec<(Id, Item)>) -> Crate {
let mut index: HashMap<Id, Item> = HashMap::new();
for (id, item) in items {
index.insert(id, item);
}
Crate {
root: Id(0),
crate_version: None,
includes_private: false,
index,
paths: HashMap::new(),
external_crates: HashMap::new(),
format_version: 0,
target: Target {
triple: String::new(),
target_features: vec![],
},
}
}
fn make_function_item(name: &str, has_body: bool) -> Item {
Item {
id: Id(0),
crate_id: 0,
name: Some(name.to_string()),
attrs: vec![],
visibility: Visibility::Public,
inner: ItemEnum::Function(Function {
sig: FunctionSignature {
inputs: vec![],
output: None,
is_c_variadic: false,
},
generics: rustdoc_types::Generics {
params: vec![],
where_predicates: vec![],
},
header: FunctionHeader {
is_const: false,
is_async: false,
is_unsafe: false,
abi: Abi::Rust,
},
has_body,
}),
deprecation: None,
docs: None,
span: None,
links: HashMap::new(),
}
}
fn make_assoc_type_item(name: &str) -> Item {
Item {
id: Id(0),
crate_id: 0,
name: Some(name.to_string()),
attrs: vec![],
visibility: Visibility::Public,
inner: ItemEnum::AssocType {
generics: rustdoc_types::Generics {
params: vec![],
where_predicates: vec![],
},
bounds: vec![],
type_: None,
},
deprecation: None,
docs: None,
span: None,
links: HashMap::new(),
}
}
fn make_assoc_const_item(name: &str) -> Item {
Item {
id: Id(0),
crate_id: 0,
name: Some(name.to_string()),
attrs: vec![],
visibility: Visibility::Public,
inner: ItemEnum::AssocConst {
type_: rustdoc_types::Type::Primitive("i32".to_string()),
value: Some("42".to_string()),
},
deprecation: None,
docs: None,
span: None,
links: HashMap::new(),
}
}
#[test]
fn empty_trait_items() {
let krate = make_test_crate(vec![]);
let result = CategorizedTraitItems::categorize_trait_items(&[], &krate);
assert!(result.required_methods.is_empty());
assert!(result.provided_methods.is_empty());
assert!(result.associated_types.is_empty());
assert!(result.associated_consts.is_empty());
}
#[test]
fn categorizes_required_method() {
let id = Id(1);
let item = make_function_item("required_fn", false);
let krate = make_test_crate(vec![(id, item)]);
let result = CategorizedTraitItems::categorize_trait_items(&[id], &krate);
assert_eq!(result.required_methods.len(), 1);
assert_eq!(
result.required_methods[0].name.as_deref(),
Some("required_fn")
);
assert!(result.provided_methods.is_empty());
}
#[test]
fn categorizes_provided_method() {
let id = Id(1);
let item = make_function_item("provided_fn", true);
let krate = make_test_crate(vec![(id, item)]);
let result = CategorizedTraitItems::categorize_trait_items(&[id], &krate);
assert!(result.required_methods.is_empty());
assert_eq!(result.provided_methods.len(), 1);
assert_eq!(
result.provided_methods[0].name.as_deref(),
Some("provided_fn")
);
}
#[test]
fn categorizes_associated_type() {
let id = Id(1);
let item = make_assoc_type_item("Item");
let krate = make_test_crate(vec![(id, item)]);
let result = CategorizedTraitItems::categorize_trait_items(&[id], &krate);
assert_eq!(result.associated_types.len(), 1);
assert_eq!(result.associated_types[0].name.as_deref(), Some("Item"));
}
#[test]
fn categorizes_associated_const() {
let id = Id(1);
let item = make_assoc_const_item("CONST");
let krate = make_test_crate(vec![(id, item)]);
let result = CategorizedTraitItems::categorize_trait_items(&[id], &krate);
assert_eq!(result.associated_consts.len(), 1);
assert_eq!(result.associated_consts[0].name.as_deref(), Some("CONST"));
}
#[test]
fn categorizes_mixed_items() {
let req_id = Id(1);
let prov_id = Id(2);
let type_id = Id(3);
let const_id = Id(4);
let krate = make_test_crate(vec![
(req_id, make_function_item("req", false)),
(prov_id, make_function_item("prov", true)),
(type_id, make_assoc_type_item("Output")),
(const_id, make_assoc_const_item("MAX")),
]);
let result = CategorizedTraitItems::categorize_trait_items(
&[req_id, prov_id, type_id, const_id],
&krate,
);
assert_eq!(result.required_methods.len(), 1);
assert_eq!(result.provided_methods.len(), 1);
assert_eq!(result.associated_types.len(), 1);
assert_eq!(result.associated_consts.len(), 1);
}
#[test]
fn skips_missing_items() {
let existing_id = Id(1);
let missing_id = Id(99);
let krate = make_test_crate(vec![(existing_id, make_function_item("fn", false))]);
let result =
CategorizedTraitItems::categorize_trait_items(&[existing_id, missing_id], &krate);
// Should have one item, missing ID is skipped
assert_eq!(result.required_methods.len(), 1);
}
}
}