rustdoc/html/render/
print_item.rs

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

use itertools::Itertools;
use rinja::Template;
use rustc_abi::VariantIdx;
use rustc_data_structures::captures::Captures;
use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
use rustc_hir as hir;
use rustc_hir::def::CtorKind;
use rustc_hir::def_id::DefId;
use rustc_index::IndexVec;
use rustc_middle::ty::{self, TyCtxt};
use rustc_span::hygiene::MacroKind;
use rustc_span::symbol::{Symbol, kw, sym};
use tracing::{debug, info};

use super::type_layout::document_type_layout;
use super::{
    AssocItemLink, AssocItemRender, Context, ImplRenderingParameters, RenderMode,
    collect_paths_for_type, document, ensure_trailing_slash, get_filtered_impls_for_reference,
    item_ty_to_section, notable_traits_button, notable_traits_json, render_all_impls,
    render_assoc_item, render_assoc_items, render_attributes_in_code, render_attributes_in_pre,
    render_impl, render_rightside, render_stability_since_raw,
    render_stability_since_raw_with_extra, write_section_heading,
};
use crate::clean;
use crate::config::ModuleSorting;
use crate::formats::Impl;
use crate::formats::item_type::ItemType;
use crate::html::escape::{Escape, EscapeBodyTextWithWbr};
use crate::html::format::{
    Buffer, Ending, PrintWithSpace, display_fn, join_with_double_colon, print_abi_with_space,
    print_constness_with_space, print_where_clause, visibility_print_with_space,
};
use crate::html::markdown::{HeadingOffset, MarkdownSummaryLine};
use crate::html::render::{document_full, document_item_info};
use crate::html::url_parts_builder::UrlPartsBuilder;

/// Generates a Rinja template struct for rendering items with common methods.
///
/// Usage:
/// ```ignore (illustrative)
/// item_template!(
///     #[template(path = "<template.html>", /* additional values */)]
///     /* additional meta items */
///     struct MyItem<'a, 'cx> {
///         cx: RefCell<&'a mut Context<'cx>>,
///         it: &'a clean::Item,
///         /* additional fields */
///     },
///     methods = [ /* method names (comma separated; refer to macro definition of `item_template_methods!()`) */ ]
/// )
/// ```
///
/// NOTE: ensure that the generic lifetimes (`'a`, `'cx`) and
/// required fields (`cx`, `it`) are identical (in terms of order and definition).
macro_rules! item_template {
    (
        $(#[$meta:meta])*
        struct $name:ident<'a, 'cx> {
            cx: &'a Context<'cx>,
            it: &'a clean::Item,
            $($field_name:ident: $field_ty:ty),*,
        },
        methods = [$($methods:tt),* $(,)?]
    ) => {
        #[derive(Template)]
        $(#[$meta])*
        struct $name<'a, 'cx> {
            cx: &'a Context<'cx>,
            it: &'a clean::Item,
            $($field_name: $field_ty),*
        }

        impl<'a, 'cx: 'a> ItemTemplate<'a, 'cx> for $name<'a, 'cx> {
            fn item_and_cx(&self) -> (&'a clean::Item, &'a Context<'cx>) {
                (&self.it, &self.cx)
            }
        }

        impl<'a, 'cx: 'a> $name<'a, 'cx> {
            item_template_methods!($($methods)*);
        }
    };
}

/// Implement common methods for item template structs generated by `item_template!()`.
///
/// NOTE: this macro is intended to be used only by `item_template!()`.
macro_rules! item_template_methods {
    () => {};
    (document $($rest:tt)*) => {
        fn document<'b>(&'b self) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
            display_fn(move |f| {
                let (item, cx) = self.item_and_cx();
                let v = document(cx, item, None, HeadingOffset::H2);
                write!(f, "{v}")
            })
        }
        item_template_methods!($($rest)*);
    };
    (document_type_layout $($rest:tt)*) => {
        fn document_type_layout<'b>(&'b self) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
            display_fn(move |f| {
                let (item, cx) = self.item_and_cx();
                let def_id = item.item_id.expect_def_id();
                let v = document_type_layout(cx, def_id);
                write!(f, "{v}")
            })
        }
        item_template_methods!($($rest)*);
    };
    (render_attributes_in_pre $($rest:tt)*) => {
        fn render_attributes_in_pre<'b>(&'b self) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
            display_fn(move |f| {
                let (item, cx) = self.item_and_cx();
                let v = render_attributes_in_pre(item, "", cx);
                write!(f, "{v}")
            })
        }
        item_template_methods!($($rest)*);
    };
    (render_assoc_items $($rest:tt)*) => {
        fn render_assoc_items<'b>(&'b self) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
            display_fn(move |f| {
                let (item, cx) = self.item_and_cx();
                let def_id = item.item_id.expect_def_id();
                let v = render_assoc_items(cx, item, def_id, AssocItemRender::All);
                write!(f, "{v}")
            })
        }
        item_template_methods!($($rest)*);
    };
    ($method:ident $($rest:tt)*) => {
        compile_error!(concat!("unknown method: ", stringify!($method)));
    };
    ($token:tt $($rest:tt)*) => {
        compile_error!(concat!("unexpected token: ", stringify!($token)));
    };
}

const ITEM_TABLE_OPEN: &str = "<ul class=\"item-table\">";
const ITEM_TABLE_CLOSE: &str = "</ul>";
const ITEM_TABLE_ROW_OPEN: &str = "<li>";
const ITEM_TABLE_ROW_CLOSE: &str = "</li>";

// A component in a `use` path, like `string` in std::string::ToString
struct PathComponent {
    path: String,
    name: Symbol,
}

#[derive(Template)]
#[template(path = "print_item.html")]
struct ItemVars<'a> {
    typ: &'a str,
    name: &'a str,
    item_type: &'a str,
    path_components: Vec<PathComponent>,
    stability_since_raw: &'a str,
    src_href: Option<&'a str>,
}

/// Calls `print_where_clause` and returns `true` if a `where` clause was generated.
fn print_where_clause_and_check<'a, 'tcx: 'a>(
    buffer: &mut Buffer,
    gens: &'a clean::Generics,
    cx: &'a Context<'tcx>,
) -> bool {
    let len_before = buffer.len();
    write!(buffer, "{}", print_where_clause(gens, cx, 0, Ending::Newline));
    len_before != buffer.len()
}

pub(super) fn print_item(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) {
    debug_assert!(!item.is_stripped());
    let typ = match item.kind {
        clean::ModuleItem(_) => {
            if item.is_crate() {
                "Crate "
            } else {
                "Module "
            }
        }
        clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
        clean::TraitItem(..) => "Trait ",
        clean::StructItem(..) => "Struct ",
        clean::UnionItem(..) => "Union ",
        clean::EnumItem(..) => "Enum ",
        clean::TypeAliasItem(..) => "Type Alias ",
        clean::MacroItem(..) => "Macro ",
        clean::ProcMacroItem(ref mac) => match mac.kind {
            MacroKind::Bang => "Macro ",
            MacroKind::Attr => "Attribute Macro ",
            MacroKind::Derive => "Derive Macro ",
        },
        clean::PrimitiveItem(..) => "Primitive Type ",
        clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
        clean::ConstantItem(..) => "Constant ",
        clean::ForeignTypeItem => "Foreign Type ",
        clean::KeywordItem => "Keyword ",
        clean::TraitAliasItem(..) => "Trait Alias ",
        _ => {
            // We don't generate pages for any other type.
            unreachable!();
        }
    };
    let mut stability_since_raw = Buffer::new();
    render_stability_since_raw(
        &mut stability_since_raw,
        item.stable_since(cx.tcx()),
        item.const_stability(cx.tcx()),
    );
    let stability_since_raw: String = stability_since_raw.into_inner();

    // Write source tag
    //
    // When this item is part of a `crate use` in a downstream crate, the
    // source link in the downstream documentation will actually come back to
    // this page, and this link will be auto-clicked. The `id` attribute is
    // used to find the link to auto-click.
    let src_href =
        if cx.info.include_sources && !item.is_primitive() { cx.src_href(item) } else { None };

    let path_components = if item.is_primitive() || item.is_keyword() {
        vec![]
    } else {
        let cur = &cx.current;
        let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
        cur.iter()
            .enumerate()
            .take(amt)
            .map(|(i, component)| PathComponent {
                path: "../".repeat(cur.len() - i - 1),
                name: *component,
            })
            .collect()
    };

    let item_vars = ItemVars {
        typ,
        name: item.name.as_ref().unwrap().as_str(),
        item_type: &item.type_().to_string(),
        path_components,
        stability_since_raw: &stability_since_raw,
        src_href: src_href.as_deref(),
    };

    item_vars.render_into(buf).unwrap();

    match &item.kind {
        clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
        clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f, _) => {
            item_function(buf, cx, item, f)
        }
        clean::TraitItem(ref t) => item_trait(buf, cx, item, t),
        clean::StructItem(ref s) => item_struct(buf, cx, item, s),
        clean::UnionItem(ref s) => item_union(buf, cx, item, s),
        clean::EnumItem(ref e) => item_enum(buf, cx, item, e),
        clean::TypeAliasItem(ref t) => item_type_alias(buf, cx, item, t),
        clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
        clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
        clean::PrimitiveItem(_) => item_primitive(buf, cx, item),
        clean::StaticItem(ref i) => item_static(buf, cx, item, i, None),
        clean::ForeignStaticItem(ref i, safety) => item_static(buf, cx, item, i, Some(*safety)),
        clean::ConstantItem(ci) => item_constant(buf, cx, item, &ci.generics, &ci.type_, &ci.kind),
        clean::ForeignTypeItem => item_foreign_type(buf, cx, item),
        clean::KeywordItem => item_keyword(buf, cx, item),
        clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta),
        _ => {
            // We don't generate pages for any other type.
            unreachable!();
        }
    }

    // Render notable-traits.js used for all methods in this module.
    let mut types_with_notable_traits = cx.types_with_notable_traits.borrow_mut();
    if !types_with_notable_traits.is_empty() {
        write!(
            buf,
            r#"<script type="text/json" id="notable-traits-data">{}</script>"#,
            notable_traits_json(types_with_notable_traits.iter(), cx)
        );
        types_with_notable_traits.clear();
    }
}

/// For large structs, enums, unions, etc, determine whether to hide their fields
fn should_hide_fields(n_fields: usize) -> bool {
    n_fields > 12
}

fn toggle_open(mut w: impl fmt::Write, text: impl fmt::Display) {
    write!(
        w,
        "<details class=\"toggle type-contents-toggle\">\
            <summary class=\"hideme\">\
                <span>Show {text}</span>\
            </summary>",
    )
    .unwrap();
}

fn toggle_close(mut w: impl fmt::Write) {
    w.write_str("</details>").unwrap();
}

trait ItemTemplate<'a, 'cx: 'a>: rinja::Template + fmt::Display {
    fn item_and_cx(&self) -> (&'a clean::Item, &'a Context<'cx>);
}

fn item_module(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, items: &[clean::Item]) {
    write!(w, "{}", document(cx, item, None, HeadingOffset::H2));

    let mut not_stripped_items =
        items.iter().filter(|i| !i.is_stripped()).enumerate().collect::<Vec<_>>();

    // the order of item types in the listing
    fn reorder(ty: ItemType) -> u8 {
        match ty {
            ItemType::ExternCrate => 0,
            ItemType::Import => 1,
            ItemType::Primitive => 2,
            ItemType::Module => 3,
            ItemType::Macro => 4,
            ItemType::Struct => 5,
            ItemType::Enum => 6,
            ItemType::Constant => 7,
            ItemType::Static => 8,
            ItemType::Trait => 9,
            ItemType::Function => 10,
            ItemType::TypeAlias => 12,
            ItemType::Union => 13,
            _ => 14 + ty as u8,
        }
    }

    fn cmp(i1: &clean::Item, i2: &clean::Item, tcx: TyCtxt<'_>) -> Ordering {
        let rty1 = reorder(i1.type_());
        let rty2 = reorder(i2.type_());
        if rty1 != rty2 {
            return rty1.cmp(&rty2);
        }
        let is_stable1 = i1.stability(tcx).as_ref().map(|s| s.level.is_stable()).unwrap_or(true);
        let is_stable2 = i2.stability(tcx).as_ref().map(|s| s.level.is_stable()).unwrap_or(true);
        if is_stable1 != is_stable2 {
            // true is bigger than false in the standard bool ordering,
            // but we actually want stable items to come first
            return is_stable2.cmp(&is_stable1);
        }
        let lhs = i1.name.unwrap_or(kw::Empty);
        let rhs = i2.name.unwrap_or(kw::Empty);
        compare_names(lhs.as_str(), rhs.as_str())
    }

    let tcx = cx.tcx();

    match cx.shared.module_sorting {
        ModuleSorting::Alphabetical => {
            not_stripped_items.sort_by(|(_, i1), (_, i2)| cmp(i1, i2, tcx));
        }
        ModuleSorting::DeclarationOrder => {}
    }
    // This call is to remove re-export duplicates in cases such as:
    //
    // ```
    // pub(crate) mod foo {
    //     pub(crate) mod bar {
    //         pub(crate) trait Double { fn foo(); }
    //     }
    // }
    //
    // pub(crate) use foo::bar::*;
    // pub(crate) use foo::*;
    // ```
    //
    // `Double` will appear twice in the generated docs.
    //
    // FIXME: This code is quite ugly and could be improved. Small issue: DefId
    // can be identical even if the elements are different (mostly in imports).
    // So in case this is an import, we keep everything by adding a "unique id"
    // (which is the position in the vector).
    not_stripped_items.dedup_by_key(|(idx, i)| {
        (
            i.item_id,
            if i.name.is_some() { Some(full_path(cx, i)) } else { None },
            i.type_(),
            if i.is_import() { *idx } else { 0 },
        )
    });

    debug!("{not_stripped_items:?}");
    let mut last_section = None;

    for (_, myitem) in &not_stripped_items {
        let my_section = item_ty_to_section(myitem.type_());
        if Some(my_section) != last_section {
            if last_section.is_some() {
                w.write_str(ITEM_TABLE_CLOSE);
            }
            last_section = Some(my_section);
            write_section_heading(
                w,
                my_section.name(),
                &cx.derive_id(my_section.id()),
                None,
                ITEM_TABLE_OPEN,
            );
        }

        match myitem.kind {
            clean::ExternCrateItem { ref src } => {
                use crate::html::format::anchor;

                w.write_str(ITEM_TABLE_ROW_OPEN);
                match *src {
                    Some(src) => write!(
                        w,
                        "<div class=\"item-name\"><code>{}extern crate {} as {};",
                        visibility_print_with_space(myitem, cx),
                        anchor(myitem.item_id.expect_def_id(), src, cx),
                        EscapeBodyTextWithWbr(myitem.name.unwrap().as_str()),
                    ),
                    None => write!(
                        w,
                        "<div class=\"item-name\"><code>{}extern crate {};",
                        visibility_print_with_space(myitem, cx),
                        anchor(myitem.item_id.expect_def_id(), myitem.name.unwrap(), cx),
                    ),
                }
                w.write_str("</code></div>");
                w.write_str(ITEM_TABLE_ROW_CLOSE);
            }

            clean::ImportItem(ref import) => {
                let stab_tags = import.source.did.map_or_else(String::new, |import_def_id| {
                    extra_info_tags(tcx, myitem, item, Some(import_def_id)).to_string()
                });

                w.write_str(ITEM_TABLE_ROW_OPEN);
                let id = match import.kind {
                    clean::ImportKind::Simple(s) => {
                        format!(" id=\"{}\"", cx.derive_id(format!("reexport.{s}")))
                    }
                    clean::ImportKind::Glob => String::new(),
                };
                let (stab_tags_before, stab_tags_after) = if stab_tags.is_empty() {
                    ("", "")
                } else {
                    ("<div class=\"desc docblock-short\">", "</div>")
                };
                write!(
                    w,
                    "<div class=\"item-name\"{id}>\
                         <code>{vis}{imp}</code>\
                     </div>\
                     {stab_tags_before}{stab_tags}{stab_tags_after}",
                    vis = visibility_print_with_space(myitem, cx),
                    imp = import.print(cx),
                );
                w.write_str(ITEM_TABLE_ROW_CLOSE);
            }

            _ => {
                if myitem.name.is_none() {
                    continue;
                }

                let unsafety_flag = match myitem.kind {
                    clean::FunctionItem(_) | clean::ForeignFunctionItem(..)
                        if myitem.fn_header(tcx).unwrap().safety.is_unsafe() =>
                    {
                        "<sup title=\"unsafe function\">⚠</sup>"
                    }
                    clean::ForeignStaticItem(_, hir::Safety::Unsafe) => {
                        "<sup title=\"unsafe static\">⚠</sup>"
                    }
                    _ => "",
                };

                let visibility_and_hidden = match myitem.visibility(tcx) {
                    Some(ty::Visibility::Restricted(_)) => {
                        if myitem.is_doc_hidden() {
                            // Don't separate with a space when there are two of them
                            "<span title=\"Restricted Visibility\">&nbsp;🔒</span><span title=\"Hidden item\">👻</span> "
                        } else {
                            "<span title=\"Restricted Visibility\">&nbsp;🔒</span> "
                        }
                    }
                    _ if myitem.is_doc_hidden() => "<span title=\"Hidden item\">&nbsp;👻</span> ",
                    _ => "",
                };

                w.write_str(ITEM_TABLE_ROW_OPEN);
                let docs =
                    MarkdownSummaryLine(&myitem.doc_value(), &myitem.links(cx)).into_string();
                let (docs_before, docs_after) = if docs.is_empty() {
                    ("", "")
                } else {
                    ("<div class=\"desc docblock-short\">", "</div>")
                };
                write!(
                    w,
                    "<div class=\"item-name\">\
                        <a class=\"{class}\" href=\"{href}\" title=\"{title}\">{name}</a>\
                        {visibility_and_hidden}\
                        {unsafety_flag}\
                        {stab_tags}\
                     </div>\
                     {docs_before}{docs}{docs_after}",
                    name = EscapeBodyTextWithWbr(myitem.name.unwrap().as_str()),
                    visibility_and_hidden = visibility_and_hidden,
                    stab_tags = extra_info_tags(tcx, myitem, item, None),
                    class = myitem.type_(),
                    unsafety_flag = unsafety_flag,
                    href = item_path(myitem.type_(), myitem.name.unwrap().as_str()),
                    title = [myitem.type_().to_string(), full_path(cx, myitem)]
                        .iter()
                        .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
                        .collect::<Vec<_>>()
                        .join(" "),
                );
                w.write_str(ITEM_TABLE_ROW_CLOSE);
            }
        }
    }

    if last_section.is_some() {
        w.write_str(ITEM_TABLE_CLOSE);
    }
}

/// Render the stability, deprecation and portability tags that are displayed in the item's summary
/// at the module level.
fn extra_info_tags<'a, 'tcx: 'a>(
    tcx: TyCtxt<'tcx>,
    item: &'a clean::Item,
    parent: &'a clean::Item,
    import_def_id: Option<DefId>,
) -> impl fmt::Display + 'a + Captures<'tcx> {
    display_fn(move |f| {
        fn tag_html<'a>(
            class: &'a str,
            title: &'a str,
            contents: &'a str,
        ) -> impl fmt::Display + 'a {
            display_fn(move |f| {
                write!(
                    f,
                    r#"<wbr><span class="stab {class}" title="{title}">{contents}</span>"#,
                    title = Escape(title),
                )
            })
        }

        // The trailing space after each tag is to space it properly against the rest of the docs.
        let deprecation = import_def_id
            .map_or_else(|| item.deprecation(tcx), |import_did| tcx.lookup_deprecation(import_did));
        if let Some(depr) = deprecation {
            let message = if depr.is_in_effect() { "Deprecated" } else { "Deprecation planned" };
            write!(f, "{}", tag_html("deprecated", "", message))?;
        }

        // The "rustc_private" crates are permanently unstable so it makes no sense
        // to render "unstable" everywhere.
        let stability = import_def_id
            .map_or_else(|| item.stability(tcx), |import_did| tcx.lookup_stability(import_did));
        if stability.is_some_and(|s| s.is_unstable() && s.feature != sym::rustc_private) {
            write!(f, "{}", tag_html("unstable", "", "Experimental"))?;
        }

        let cfg = match (&item.cfg, parent.cfg.as_ref()) {
            (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
            (cfg, _) => cfg.as_deref().cloned(),
        };

        debug!(
            "Portability name={name:?} {cfg:?} - {parent_cfg:?} = {cfg:?}",
            name = item.name,
            cfg = item.cfg,
            parent_cfg = parent.cfg
        );
        if let Some(ref cfg) = cfg {
            write!(
                f,
                "{}",
                tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html())
            )
        } else {
            Ok(())
        }
    })
}

fn item_function(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, f: &clean::Function) {
    let tcx = cx.tcx();
    let header = it.fn_header(tcx).expect("printing a function which isn't a function");
    debug!(
        "item_function/const: {:?} {:?} {:?} {:?}",
        it.name,
        &header.constness,
        it.stable_since(tcx),
        it.const_stability(tcx),
    );
    let constness = print_constness_with_space(
        &header.constness,
        it.stable_since(tcx),
        it.const_stability(tcx),
    );
    let safety = header.safety.print_with_space();
    let abi = print_abi_with_space(header.abi).to_string();
    let asyncness = header.asyncness.print_with_space();
    let visibility = visibility_print_with_space(it, cx).to_string();
    let name = it.name.unwrap();

    let generics_len = format!("{:#}", f.generics.print(cx)).len();
    let header_len = "fn ".len()
        + visibility.len()
        + constness.len()
        + asyncness.len()
        + safety.len()
        + abi.len()
        + name.as_str().len()
        + generics_len;

    let notable_traits = notable_traits_button(&f.decl.output, cx);

    wrap_item(w, |w| {
        w.reserve(header_len);
        write!(
            w,
            "{attrs}{vis}{constness}{asyncness}{safety}{abi}fn \
                {name}{generics}{decl}{notable_traits}{where_clause}",
            attrs = render_attributes_in_pre(it, "", cx),
            vis = visibility,
            constness = constness,
            asyncness = asyncness,
            safety = safety,
            abi = abi,
            name = name,
            generics = f.generics.print(cx),
            where_clause = print_where_clause(&f.generics, cx, 0, Ending::Newline),
            decl = f.decl.full_print(header_len, 0, cx),
            notable_traits = notable_traits.unwrap_or_default(),
        );
    });
    write!(w, "{}", document(cx, it, None, HeadingOffset::H2));
}

fn item_trait(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Trait) {
    let tcx = cx.tcx();
    let bounds = bounds(&t.bounds, false, cx);
    let required_types =
        t.items.iter().filter(|m| m.is_required_associated_type()).collect::<Vec<_>>();
    let provided_types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
    let required_consts =
        t.items.iter().filter(|m| m.is_required_associated_const()).collect::<Vec<_>>();
    let provided_consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
    let required_methods = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
    let provided_methods = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
    let count_types = required_types.len() + provided_types.len();
    let count_consts = required_consts.len() + provided_consts.len();
    let count_methods = required_methods.len() + provided_methods.len();
    let must_implement_one_of_functions = tcx.trait_def(t.def_id).must_implement_one_of.clone();

    // Output the trait definition
    wrap_item(w, |mut w| {
        write!(
            w,
            "{attrs}{vis}{safety}{is_auto}trait {name}{generics}{bounds}",
            attrs = render_attributes_in_pre(it, "", cx),
            vis = visibility_print_with_space(it, cx),
            safety = t.safety(tcx).print_with_space(),
            is_auto = if t.is_auto(tcx) { "auto " } else { "" },
            name = it.name.unwrap(),
            generics = t.generics.print(cx),
        );

        if !t.generics.where_predicates.is_empty() {
            write!(w, "{}", print_where_clause(&t.generics, cx, 0, Ending::Newline));
        } else {
            w.write_str(" ");
        }

        if t.items.is_empty() {
            w.write_str("{ }");
        } else {
            // FIXME: we should be using a derived_id for the Anchors here
            w.write_str("{\n");
            let mut toggle = false;

            // If there are too many associated types, hide _everything_
            if should_hide_fields(count_types) {
                toggle = true;
                toggle_open(
                    &mut w,
                    format_args!("{} associated items", count_types + count_consts + count_methods),
                );
            }
            for types in [&required_types, &provided_types] {
                for t in types {
                    render_assoc_item(
                        w,
                        t,
                        AssocItemLink::Anchor(None),
                        ItemType::Trait,
                        cx,
                        RenderMode::Normal,
                    );
                    w.write_str(";\n");
                }
            }
            // If there are too many associated constants, hide everything after them
            // We also do this if the types + consts is large because otherwise we could
            // render a bunch of types and _then_ a bunch of consts just because both were
            // _just_ under the limit
            if !toggle && should_hide_fields(count_types + count_consts) {
                toggle = true;
                toggle_open(
                    &mut w,
                    format_args!(
                        "{count_consts} associated constant{plural_const} and \
                         {count_methods} method{plural_method}",
                        plural_const = pluralize(count_consts),
                        plural_method = pluralize(count_methods),
                    ),
                );
            }
            if count_types != 0 && (count_consts != 0 || count_methods != 0) {
                w.write_str("\n");
            }
            for consts in [&required_consts, &provided_consts] {
                for c in consts {
                    render_assoc_item(
                        w,
                        c,
                        AssocItemLink::Anchor(None),
                        ItemType::Trait,
                        cx,
                        RenderMode::Normal,
                    );
                    w.write_str(";\n");
                }
            }
            if !toggle && should_hide_fields(count_methods) {
                toggle = true;
                toggle_open(&mut w, format_args!("{count_methods} methods"));
            }
            if count_consts != 0 && count_methods != 0 {
                w.write_str("\n");
            }

            if !required_methods.is_empty() {
                writeln!(w, "    // Required method{}", pluralize(required_methods.len()));
            }
            for (pos, m) in required_methods.iter().enumerate() {
                render_assoc_item(
                    w,
                    m,
                    AssocItemLink::Anchor(None),
                    ItemType::Trait,
                    cx,
                    RenderMode::Normal,
                );
                w.write_str(";\n");

                if pos < required_methods.len() - 1 {
                    w.write_str("<span class=\"item-spacer\"></span>");
                }
            }
            if !required_methods.is_empty() && !provided_methods.is_empty() {
                w.write_str("\n");
            }

            if !provided_methods.is_empty() {
                writeln!(w, "    // Provided method{}", pluralize(provided_methods.len()));
            }
            for (pos, m) in provided_methods.iter().enumerate() {
                render_assoc_item(
                    w,
                    m,
                    AssocItemLink::Anchor(None),
                    ItemType::Trait,
                    cx,
                    RenderMode::Normal,
                );

                w.write_str(" { ... }\n");

                if pos < provided_methods.len() - 1 {
                    w.write_str("<span class=\"item-spacer\"></span>");
                }
            }
            if toggle {
                toggle_close(&mut w);
            }
            w.write_str("}");
        }
    });

    // Trait documentation
    write!(w, "{}", document(cx, it, None, HeadingOffset::H2));

    fn trait_item(w: &mut Buffer, cx: &Context<'_>, m: &clean::Item, t: &clean::Item) {
        let name = m.name.unwrap();
        info!("Documenting {name} on {ty_name:?}", ty_name = t.name);
        let item_type = m.type_();
        let id = cx.derive_id(format!("{item_type}.{name}"));

        let mut content = Buffer::empty_from(w);
        write!(content, "{}", document_full(m, cx, HeadingOffset::H5));

        let toggled = !content.is_empty();
        if toggled {
            let method_toggle_class = if item_type.is_method() { " method-toggle" } else { "" };
            write!(w, "<details class=\"toggle{method_toggle_class}\" open><summary>");
        }
        write!(w, "<section id=\"{id}\" class=\"method\">");
        render_rightside(w, cx, m, RenderMode::Normal);
        write!(w, "<h4 class=\"code-header\">");
        render_assoc_item(
            w,
            m,
            AssocItemLink::Anchor(Some(&id)),
            ItemType::Impl,
            cx,
            RenderMode::Normal,
        );
        w.write_str("</h4></section>");
        document_item_info(cx, m, Some(t)).render_into(w).unwrap();
        if toggled {
            write!(w, "</summary>");
            w.push_buffer(content);
            write!(w, "</details>");
        }
    }

    if !required_consts.is_empty() {
        write_section_heading(
            w,
            "Required Associated Constants",
            "required-associated-consts",
            None,
            "<div class=\"methods\">",
        );
        for t in required_consts {
            trait_item(w, cx, t, it);
        }
        w.write_str("</div>");
    }
    if !provided_consts.is_empty() {
        write_section_heading(
            w,
            "Provided Associated Constants",
            "provided-associated-consts",
            None,
            "<div class=\"methods\">",
        );
        for t in provided_consts {
            trait_item(w, cx, t, it);
        }
        w.write_str("</div>");
    }

    if !required_types.is_empty() {
        write_section_heading(
            w,
            "Required Associated Types",
            "required-associated-types",
            None,
            "<div class=\"methods\">",
        );
        for t in required_types {
            trait_item(w, cx, t, it);
        }
        w.write_str("</div>");
    }
    if !provided_types.is_empty() {
        write_section_heading(
            w,
            "Provided Associated Types",
            "provided-associated-types",
            None,
            "<div class=\"methods\">",
        );
        for t in provided_types {
            trait_item(w, cx, t, it);
        }
        w.write_str("</div>");
    }

    // Output the documentation for each function individually
    if !required_methods.is_empty() || must_implement_one_of_functions.is_some() {
        write_section_heading(
            w,
            "Required Methods",
            "required-methods",
            None,
            "<div class=\"methods\">",
        );

        if let Some(list) = must_implement_one_of_functions.as_deref() {
            write!(
                w,
                "<div class=\"stab must_implement\">At least one of the `{}` methods is required.</div>",
                list.iter().join("`, `")
            );
        }

        for m in required_methods {
            trait_item(w, cx, m, it);
        }
        w.write_str("</div>");
    }
    if !provided_methods.is_empty() {
        write_section_heading(
            w,
            "Provided Methods",
            "provided-methods",
            None,
            "<div class=\"methods\">",
        );
        for m in provided_methods {
            trait_item(w, cx, m, it);
        }
        w.write_str("</div>");
    }

    // If there are methods directly on this trait object, render them here.
    write!(w, "{}", render_assoc_items(cx, it, it.item_id.expect_def_id(), AssocItemRender::All));

    let mut extern_crates = FxIndexSet::default();

    if !t.is_dyn_compatible(cx.tcx()) {
        // FIXME(dyn_compat_renaming): Update the URL once the Reference is updated.
        write_section_heading(
            w,
            "Dyn Compatibility",
            "dyn-compatibility",
            None,
            format!(
                "<div class=\"dyn-compatibility-info\"><p>This trait is <b>not</b> \
                <a href=\"{base}/reference/items/traits.html#object-safety\">dyn compatible</a>.</p>\
                <p><i>In older versions of Rust, dyn compatibility was called \"object safety\", \
                so this trait is not object safe.</i></p></div>",
                base = crate::clean::utils::DOC_RUST_LANG_ORG_CHANNEL
            ),
        );
    }

    if let Some(implementors) = cx.shared.cache.implementors.get(&it.item_id.expect_def_id()) {
        // The DefId is for the first Type found with that name. The bool is
        // if any Types with the same name but different DefId have been found.
        let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();
        for implementor in implementors {
            if let Some(did) =
                implementor.inner_impl().for_.without_borrowed_ref().def_id(&cx.shared.cache)
                && !did.is_local()
            {
                extern_crates.insert(did.krate);
            }
            match implementor.inner_impl().for_.without_borrowed_ref() {
                clean::Type::Path { ref path } if !path.is_assoc_ty() => {
                    let did = path.def_id();
                    let &mut (prev_did, ref mut has_duplicates) =
                        implementor_dups.entry(path.last()).or_insert((did, false));
                    if prev_did != did {
                        *has_duplicates = true;
                    }
                }
                _ => {}
            }
        }

        let (local, mut foreign) =
            implementors.iter().partition::<Vec<_>, _>(|i| i.is_on_local_type(cx));

        let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
            local.iter().partition(|i| i.inner_impl().kind.is_auto());

        synthetic.sort_by_cached_key(|i| ImplString::new(i, cx));
        concrete.sort_by_cached_key(|i| ImplString::new(i, cx));
        foreign.sort_by_cached_key(|i| ImplString::new(i, cx));

        if !foreign.is_empty() {
            write_section_heading(w, "Implementations on Foreign Types", "foreign-impls", None, "");

            for implementor in foreign {
                let provided_methods = implementor.inner_impl().provided_trait_methods(tcx);
                let assoc_link =
                    AssocItemLink::GotoSource(implementor.impl_item.item_id, &provided_methods);
                render_impl(
                    w,
                    cx,
                    implementor,
                    it,
                    assoc_link,
                    RenderMode::Normal,
                    None,
                    &[],
                    ImplRenderingParameters {
                        show_def_docs: false,
                        show_default_items: false,
                        show_non_assoc_items: true,
                        toggle_open_by_default: false,
                    },
                );
            }
        }

        write_section_heading(
            w,
            "Implementors",
            "implementors",
            None,
            "<div id=\"implementors-list\">",
        );
        for implementor in concrete {
            render_implementor(cx, implementor, it, w, &implementor_dups, &[]);
        }
        w.write_str("</div>");

        if t.is_auto(tcx) {
            write_section_heading(
                w,
                "Auto implementors",
                "synthetic-implementors",
                None,
                "<div id=\"synthetic-implementors-list\">",
            );
            for implementor in synthetic {
                render_implementor(
                    cx,
                    implementor,
                    it,
                    w,
                    &implementor_dups,
                    &collect_paths_for_type(
                        implementor.inner_impl().for_.clone(),
                        &cx.shared.cache,
                    ),
                );
            }
            w.write_str("</div>");
        }
    } else {
        // even without any implementations to write in, we still want the heading and list, so the
        // implementors javascript file pulled in below has somewhere to write the impls into
        write_section_heading(
            w,
            "Implementors",
            "implementors",
            None,
            "<div id=\"implementors-list\"></div>",
        );

        if t.is_auto(tcx) {
            write_section_heading(
                w,
                "Auto implementors",
                "synthetic-implementors",
                None,
                "<div id=\"synthetic-implementors-list\"></div>",
            );
        }
    }

    // [RUSTDOCIMPL] trait.impl
    //
    // Include implementors in crates that depend on the current crate.
    //
    // This is complicated by the way rustdoc is invoked, which is basically
    // the same way rustc is invoked: it gets called, one at a time, for each
    // crate. When building the rustdocs for the current crate, rustdoc can
    // see crate metadata for its dependencies, but cannot see metadata for its
    // dependents.
    //
    // To make this work, we generate a "hook" at this stage, and our
    // dependents can "plug in" to it when they build. For simplicity's sake,
    // it's [JSONP]: a JavaScript file with the data we need (and can parse),
    // surrounded by a tiny wrapper that the Rust side ignores, but allows the
    // JavaScript side to include without having to worry about Same Origin
    // Policy. The code for *that* is in `write_shared.rs`.
    //
    // This is further complicated by `#[doc(inline)]`. We want all copies
    // of an inlined trait to reference the same JS file, to address complex
    // dependency graphs like this one (lower crates depend on higher crates):
    //
    // ```text
    //  --------------------------------------------
    //  |            crate A: trait Foo            |
    //  --------------------------------------------
    //      |                               |
    //  --------------------------------    |
    //  | crate B: impl A::Foo for Bar |    |
    //  --------------------------------    |
    //      |                               |
    //  ---------------------------------------------
    //  | crate C: #[doc(inline)] use A::Foo as Baz |
    //  |          impl Baz for Quux                |
    //  ---------------------------------------------
    // ```
    //
    // Basically, we want `C::Baz` and `A::Foo` to show the same set of
    // impls, which is easier if they both treat `/trait.impl/A/trait.Foo.js`
    // as the Single Source of Truth.
    //
    // We also want the `impl Baz for Quux` to be written to
    // `trait.Foo.js`. However, when we generate plain HTML for `C::Baz`,
    // we're going to want to generate plain HTML for `impl Baz for Quux` too,
    // because that'll load faster, and it's better for SEO. And we don't want
    // the same impl to show up twice on the same page.
    //
    // To make this work, the trait.impl/A/trait.Foo.js JS file has a structure kinda
    // like this:
    //
    // ```js
    // JSONP({
    // "B": {"impl A::Foo for Bar"},
    // "C": {"impl Baz for Quux"},
    // });
    // ```
    //
    // First of all, this means we can rebuild a crate, and it'll replace its own
    // data if something changes. That is, `rustdoc` is idempotent. The other
    // advantage is that we can list the crates that get included in the HTML,
    // and ignore them when doing the JavaScript-based part of rendering.
    // So C's HTML will have something like this:
    //
    // ```html
    // <script src="/trait.impl/A/trait.Foo.js"
    //     data-ignore-extern-crates="A,B" async></script>
    // ```
    //
    // And, when the JS runs, anything in data-ignore-extern-crates is known
    // to already be in the HTML, and will be ignored.
    //
    // [JSONP]: https://en.wikipedia.org/wiki/JSONP
    let mut js_src_path: UrlPartsBuilder = std::iter::repeat("..")
        .take(cx.current.len())
        .chain(std::iter::once("trait.impl"))
        .collect();
    if let Some(did) = it.item_id.as_def_id()
        && let get_extern = { || cx.shared.cache.external_paths.get(&did).map(|s| &s.0) }
        && let Some(fqp) = cx.shared.cache.exact_paths.get(&did).or_else(get_extern)
    {
        js_src_path.extend(fqp[..fqp.len() - 1].iter().copied());
        js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), fqp.last().unwrap()));
    } else {
        js_src_path.extend(cx.current.iter().copied());
        js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), it.name.unwrap()));
    }
    let extern_crates = extern_crates
        .into_iter()
        .map(|cnum| tcx.crate_name(cnum).to_string())
        .collect::<Vec<_>>()
        .join(",");
    let (extern_before, extern_after) =
        if extern_crates.is_empty() { ("", "") } else { (" data-ignore-extern-crates=\"", "\"") };
    write!(
        w,
        "<script src=\"{src}\"{extern_before}{extern_crates}{extern_after} async></script>",
        src = js_src_path.finish(),
    );
}

fn item_trait_alias(
    w: &mut impl fmt::Write,
    cx: &Context<'_>,
    it: &clean::Item,
    t: &clean::TraitAlias,
) {
    wrap_item(w, |w| {
        write!(
            w,
            "{attrs}trait {name}{generics}{where_b} = {bounds};",
            attrs = render_attributes_in_pre(it, "", cx),
            name = it.name.unwrap(),
            generics = t.generics.print(cx),
            where_b = print_where_clause(&t.generics, cx, 0, Ending::Newline),
            bounds = bounds(&t.bounds, true, cx),
        )
        .unwrap();
    });

    write!(w, "{}", document(cx, it, None, HeadingOffset::H2)).unwrap();
    // Render any items associated directly to this alias, as otherwise they
    // won't be visible anywhere in the docs. It would be nice to also show
    // associated items from the aliased type (see discussion in #32077), but
    // we need #14072 to make sense of the generics.
    write!(w, "{}", render_assoc_items(cx, it, it.item_id.expect_def_id(), AssocItemRender::All))
        .unwrap();
}

fn item_type_alias(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::TypeAlias) {
    wrap_item(w, |w| {
        write!(
            w,
            "{attrs}{vis}type {name}{generics}{where_clause} = {type_};",
            attrs = render_attributes_in_pre(it, "", cx),
            vis = visibility_print_with_space(it, cx),
            name = it.name.unwrap(),
            generics = t.generics.print(cx),
            where_clause = print_where_clause(&t.generics, cx, 0, Ending::Newline),
            type_ = t.type_.print(cx),
        );
    });

    write!(w, "{}", document(cx, it, None, HeadingOffset::H2));

    if let Some(inner_type) = &t.inner_type {
        write_section_heading(w, "Aliased Type", "aliased-type", None, "");

        match inner_type {
            clean::TypeAliasInnerType::Enum { variants, is_non_exhaustive } => {
                let variants_iter = || variants.iter().filter(|i| !i.is_stripped());
                let ty = cx.tcx().type_of(it.def_id().unwrap()).instantiate_identity();
                let enum_def_id = ty.ty_adt_def().unwrap().did();

                wrap_item(w, |w| {
                    let variants_len = variants.len();
                    let variants_count = variants_iter().count();
                    let has_stripped_entries = variants_len != variants_count;

                    write!(w, "enum {}{}", it.name.unwrap(), t.generics.print(cx));
                    render_enum_fields(
                        w,
                        cx,
                        Some(&t.generics),
                        variants,
                        variants_count,
                        has_stripped_entries,
                        *is_non_exhaustive,
                        enum_def_id,
                    )
                });
                item_variants(w, cx, it, variants, enum_def_id);
            }
            clean::TypeAliasInnerType::Union { fields } => {
                wrap_item(w, |w| {
                    let fields_count = fields.iter().filter(|i| !i.is_stripped()).count();
                    let has_stripped_fields = fields.len() != fields_count;

                    write!(w, "union {}{}", it.name.unwrap(), t.generics.print(cx));
                    render_struct_fields(
                        w,
                        Some(&t.generics),
                        None,
                        fields,
                        "",
                        true,
                        has_stripped_fields,
                        cx,
                    );
                });
                item_fields(w, cx, it, fields, None);
            }
            clean::TypeAliasInnerType::Struct { ctor_kind, fields } => {
                wrap_item(w, |w| {
                    let fields_count = fields.iter().filter(|i| !i.is_stripped()).count();
                    let has_stripped_fields = fields.len() != fields_count;

                    write!(w, "struct {}{}", it.name.unwrap(), t.generics.print(cx));
                    render_struct_fields(
                        w,
                        Some(&t.generics),
                        *ctor_kind,
                        fields,
                        "",
                        true,
                        has_stripped_fields,
                        cx,
                    );
                });
                item_fields(w, cx, it, fields, None);
            }
        }
    }

    let def_id = it.item_id.expect_def_id();
    // Render any items associated directly to this alias, as otherwise they
    // won't be visible anywhere in the docs. It would be nice to also show
    // associated items from the aliased type (see discussion in #32077), but
    // we need #14072 to make sense of the generics.
    write!(w, "{}", render_assoc_items(cx, it, def_id, AssocItemRender::All));
    write!(w, "{}", document_type_layout(cx, def_id));

    // [RUSTDOCIMPL] type.impl
    //
    // Include type definitions from the alias target type.
    //
    // Earlier versions of this code worked by having `render_assoc_items`
    // include this data directly. That generates *O*`(types*impls)` of HTML
    // text, and some real crates have a lot of types and impls.
    //
    // To create the same UX without generating half a gigabyte of HTML for a
    // crate that only contains 20 megabytes of actual documentation[^115718],
    // rustdoc stashes these type-alias-inlined docs in a [JSONP]
    // "database-lite". The file itself is generated in `write_shared.rs`,
    // and hooks into functions provided by `main.js`.
    //
    // The format of `trait.impl` and `type.impl` JS files are superficially
    // similar. Each line, except the JSONP wrapper itself, belongs to a crate,
    // and they are otherwise separate (rustdoc should be idempotent). The
    // "meat" of the file is HTML strings, so the frontend code is very simple.
    // Links are relative to the doc root, though, so the frontend needs to fix
    // that up, and inlined docs can reuse these files.
    //
    // However, there are a few differences, caused by the sophisticated
    // features that type aliases have. Consider this crate graph:
    //
    // ```text
    //  ---------------------------------
    //  | crate A: struct Foo<T>        |
    //  |          type Bar = Foo<i32>  |
    //  |          impl X for Foo<i8>   |
    //  |          impl Y for Foo<i32>  |
    //  ---------------------------------
    //      |
    //  ----------------------------------
    //  | crate B: type Baz = A::Foo<i8> |
    //  |          type Xyy = A::Foo<i8> |
    //  |          impl Z for Xyy        |
    //  ----------------------------------
    // ```
    //
    // The type.impl/A/struct.Foo.js JS file has a structure kinda like this:
    //
    // ```js
    // JSONP({
    // "A": [["impl Y for Foo<i32>", "Y", "A::Bar"]],
    // "B": [["impl X for Foo<i8>", "X", "B::Baz", "B::Xyy"], ["impl Z for Xyy", "Z", "B::Baz"]],
    // });
    // ```
    //
    // When the type.impl file is loaded, only the current crate's docs are
    // actually used. The main reason to bundle them together is that there's
    // enough duplication in them for DEFLATE to remove the redundancy.
    //
    // The contents of a crate are a list of impl blocks, themselves
    // represented as lists. The first item in the sublist is the HTML block,
    // the second item is the name of the trait (which goes in the sidebar),
    // and all others are the names of type aliases that successfully match.
    //
    // This way:
    //
    // - There's no need to generate these files for types that have no aliases
    //   in the current crate. If a dependent crate makes a type alias, it'll
    //   take care of generating its own docs.
    // - There's no need to reimplement parts of the type checker in
    //   JavaScript. The Rust backend does the checking, and includes its
    //   results in the file.
    // - Docs defined directly on the type alias are dropped directly in the
    //   HTML by `render_assoc_items`, and are accessible without JavaScript.
    //   The JSONP file will not list impl items that are known to be part
    //   of the main HTML file already.
    //
    // [JSONP]: https://en.wikipedia.org/wiki/JSONP
    // [^115718]: https://github.com/rust-lang/rust/issues/115718
    let cache = &cx.shared.cache;
    if let Some(target_did) = t.type_.def_id(cache) &&
        let get_extern = { || cache.external_paths.get(&target_did) } &&
        let Some(&(ref target_fqp, target_type)) = cache.paths.get(&target_did).or_else(get_extern) &&
        target_type.is_adt() && // primitives cannot be inlined
        let Some(self_did) = it.item_id.as_def_id() &&
        let get_local = { || cache.paths.get(&self_did).map(|(p, _)| p) } &&
        let Some(self_fqp) = cache.exact_paths.get(&self_did).or_else(get_local)
    {
        let mut js_src_path: UrlPartsBuilder = std::iter::repeat("..")
            .take(cx.current.len())
            .chain(std::iter::once("type.impl"))
            .collect();
        js_src_path.extend(target_fqp[..target_fqp.len() - 1].iter().copied());
        js_src_path.push_fmt(format_args!("{target_type}.{}.js", target_fqp.last().unwrap()));
        let self_path = self_fqp.iter().map(Symbol::as_str).collect::<Vec<&str>>().join("::");
        write!(
            w,
            "<script src=\"{src}\" data-self-path=\"{self_path}\" async></script>",
            src = js_src_path.finish(),
        );
    }
}

fn item_union(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Union) {
    item_template!(
        #[template(path = "item_union.html")]
        struct ItemUnion<'a, 'cx> {
            cx: &'a Context<'cx>,
            it: &'a clean::Item,
            s: &'a clean::Union,
        },
        methods = [document, document_type_layout, render_attributes_in_pre, render_assoc_items]
    );

    impl<'a, 'cx: 'a> ItemUnion<'a, 'cx> {
        fn render_union<'b>(&'b self) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
            display_fn(move |f| {
                let v = render_union(self.it, Some(&self.s.generics), &self.s.fields, self.cx);
                write!(f, "{v}")
            })
        }

        fn document_field<'b>(
            &'b self,
            field: &'a clean::Item,
        ) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
            display_fn(move |f| {
                let v = document(self.cx, field, Some(self.it), HeadingOffset::H3);
                write!(f, "{v}")
            })
        }

        fn stability_field(&self, field: &clean::Item) -> Option<String> {
            field.stability_class(self.cx.tcx())
        }

        fn print_ty<'b>(
            &'b self,
            ty: &'a clean::Type,
        ) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
            display_fn(move |f| {
                let v = ty.print(&self.cx);
                write!(f, "{v}")
            })
        }

        fn fields_iter(
            &self,
        ) -> std::iter::Peekable<impl Iterator<Item = (&'a clean::Item, &'a clean::Type)>> {
            self.s
                .fields
                .iter()
                .filter_map(|f| match f.kind {
                    clean::StructFieldItem(ref ty) => Some((f, ty)),
                    _ => None,
                })
                .peekable()
        }
    }

    ItemUnion { cx, it, s }.render_into(w).unwrap();
}

fn print_tuple_struct_fields<'a, 'cx: 'a>(
    cx: &'a Context<'cx>,
    s: &'a [clean::Item],
) -> impl fmt::Display + 'a + Captures<'cx> {
    display_fn(|f| {
        if !s.is_empty()
            && s.iter().all(|field| {
                matches!(field.kind, clean::StrippedItem(box clean::StructFieldItem(..)))
            })
        {
            return f.write_str("<span class=\"comment\">/* private fields */</span>");
        }

        for (i, ty) in s.iter().enumerate() {
            if i > 0 {
                f.write_str(", ")?;
            }
            match ty.kind {
                clean::StrippedItem(box clean::StructFieldItem(_)) => f.write_str("_")?,
                clean::StructFieldItem(ref ty) => write!(f, "{}", ty.print(cx))?,
                _ => unreachable!(),
            }
        }
        Ok(())
    })
}

fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum) {
    let count_variants = e.variants().count();
    wrap_item(w, |w| {
        render_attributes_in_code(w, it, cx);
        write!(
            w,
            "{}enum {}{}",
            visibility_print_with_space(it, cx),
            it.name.unwrap(),
            e.generics.print(cx),
        );

        render_enum_fields(
            w,
            cx,
            Some(&e.generics),
            &e.variants,
            count_variants,
            e.has_stripped_entries(),
            it.is_non_exhaustive(),
            it.def_id().unwrap(),
        );
    });

    write!(w, "{}", document(cx, it, None, HeadingOffset::H2));

    if count_variants != 0 {
        item_variants(w, cx, it, &e.variants, it.def_id().unwrap());
    }
    let def_id = it.item_id.expect_def_id();
    write!(w, "{}", render_assoc_items(cx, it, def_id, AssocItemRender::All));
    write!(w, "{}", document_type_layout(cx, def_id));
}

/// It'll return false if any variant is not a C-like variant. Otherwise it'll return true if at
/// least one of them has an explicit discriminant or if the enum has `#[repr(C)]` or an integer
/// `repr`.
fn should_show_enum_discriminant(
    cx: &Context<'_>,
    enum_def_id: DefId,
    variants: &IndexVec<VariantIdx, clean::Item>,
) -> bool {
    let mut has_variants_with_value = false;
    for variant in variants {
        if let clean::VariantItem(ref var) = variant.kind
            && matches!(var.kind, clean::VariantKind::CLike)
        {
            has_variants_with_value |= var.discriminant.is_some();
        } else {
            return false;
        }
    }
    if has_variants_with_value {
        return true;
    }
    let repr = cx.tcx().adt_def(enum_def_id).repr();
    repr.c() || repr.int.is_some()
}

fn display_c_like_variant(
    w: &mut Buffer,
    cx: &Context<'_>,
    item: &clean::Item,
    variant: &clean::Variant,
    index: VariantIdx,
    should_show_enum_discriminant: bool,
    enum_def_id: DefId,
) {
    let name = item.name.unwrap();
    if let Some(ref value) = variant.discriminant {
        write!(w, "{} = {}", name.as_str(), value.value(cx.tcx(), true));
    } else if should_show_enum_discriminant {
        let adt_def = cx.tcx().adt_def(enum_def_id);
        let discr = adt_def.discriminant_for_variant(cx.tcx(), index);
        if discr.ty.is_signed() {
            write!(w, "{} = {}", name.as_str(), discr.val as i128);
        } else {
            write!(w, "{} = {}", name.as_str(), discr.val);
        }
    } else {
        w.write_str(name.as_str());
    }
}

fn render_enum_fields(
    mut w: &mut Buffer,
    cx: &Context<'_>,
    g: Option<&clean::Generics>,
    variants: &IndexVec<VariantIdx, clean::Item>,
    count_variants: usize,
    has_stripped_entries: bool,
    is_non_exhaustive: bool,
    enum_def_id: DefId,
) {
    let should_show_enum_discriminant = should_show_enum_discriminant(cx, enum_def_id, variants);
    if !g.is_some_and(|g| print_where_clause_and_check(w, g, cx)) {
        // If there wasn't a `where` clause, we add a whitespace.
        w.write_str(" ");
    }

    let variants_stripped = has_stripped_entries;
    if count_variants == 0 && !variants_stripped {
        w.write_str("{}");
    } else {
        w.write_str("{\n");
        let toggle = should_hide_fields(count_variants);
        if toggle {
            toggle_open(&mut w, format_args!("{count_variants} variants"));
        }
        const TAB: &str = "    ";
        for (index, v) in variants.iter_enumerated() {
            if v.is_stripped() {
                continue;
            }
            w.write_str(TAB);
            match v.kind {
                clean::VariantItem(ref var) => match var.kind {
                    clean::VariantKind::CLike => display_c_like_variant(
                        w,
                        cx,
                        v,
                        var,
                        index,
                        should_show_enum_discriminant,
                        enum_def_id,
                    ),
                    clean::VariantKind::Tuple(ref s) => {
                        write!(w, "{}({})", v.name.unwrap(), print_tuple_struct_fields(cx, s));
                    }
                    clean::VariantKind::Struct(ref s) => {
                        render_struct(w, v, None, None, &s.fields, TAB, false, cx);
                    }
                },
                _ => unreachable!(),
            }
            w.write_str(",\n");
        }

        if variants_stripped && !is_non_exhaustive {
            w.write_str("    <span class=\"comment\">// some variants omitted</span>\n");
        }
        if toggle {
            toggle_close(&mut w);
        }
        w.write_str("}");
    }
}

fn item_variants(
    w: &mut Buffer,
    cx: &Context<'_>,
    it: &clean::Item,
    variants: &IndexVec<VariantIdx, clean::Item>,
    enum_def_id: DefId,
) {
    let tcx = cx.tcx();
    write_section_heading(
        w,
        &format!("Variants{}", document_non_exhaustive_header(it)),
        "variants",
        Some("variants"),
        format!("{}<div class=\"variants\">", document_non_exhaustive(it)),
    );

    let should_show_enum_discriminant = should_show_enum_discriminant(cx, enum_def_id, variants);
    for (index, variant) in variants.iter_enumerated() {
        if variant.is_stripped() {
            continue;
        }
        let id = cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.unwrap()));
        write!(
            w,
            "<section id=\"{id}\" class=\"variant\">\
                <a href=\"#{id}\" class=\"anchor\">§</a>",
        );
        render_stability_since_raw_with_extra(
            w,
            variant.stable_since(tcx),
            variant.const_stability(tcx),
            " rightside",
        );
        w.write_str("<h3 class=\"code-header\">");
        if let clean::VariantItem(ref var) = variant.kind
            && let clean::VariantKind::CLike = var.kind
        {
            display_c_like_variant(
                w,
                cx,
                variant,
                var,
                index,
                should_show_enum_discriminant,
                enum_def_id,
            );
        } else {
            w.write_str(variant.name.unwrap().as_str());
        }

        let clean::VariantItem(variant_data) = &variant.kind else { unreachable!() };

        if let clean::VariantKind::Tuple(ref s) = variant_data.kind {
            write!(w, "({})", print_tuple_struct_fields(cx, s));
        }
        w.write_str("</h3></section>");

        write!(w, "{}", document(cx, variant, Some(it), HeadingOffset::H4));

        let heading_and_fields = match &variant_data.kind {
            clean::VariantKind::Struct(s) => {
                // If there is no field to display, no need to add the heading.
                if s.fields.iter().any(|f| !f.is_doc_hidden()) {
                    Some(("Fields", &s.fields))
                } else {
                    None
                }
            }
            clean::VariantKind::Tuple(fields) => {
                // Documentation on tuple variant fields is rare, so to reduce noise we only emit
                // the section if at least one field is documented.
                if fields.iter().any(|f| !f.doc_value().is_empty()) {
                    Some(("Tuple Fields", fields))
                } else {
                    None
                }
            }
            clean::VariantKind::CLike => None,
        };

        if let Some((heading, fields)) = heading_and_fields {
            let variant_id =
                cx.derive_id(format!("{}.{}.fields", ItemType::Variant, variant.name.unwrap()));
            write!(
                w,
                "<div class=\"sub-variant\" id=\"{variant_id}\">\
                    <h4>{heading}</h4>\
                    {}",
                document_non_exhaustive(variant)
            );
            for field in fields {
                match field.kind {
                    clean::StrippedItem(box clean::StructFieldItem(_)) => {}
                    clean::StructFieldItem(ref ty) => {
                        let id = cx.derive_id(format!(
                            "variant.{}.field.{}",
                            variant.name.unwrap(),
                            field.name.unwrap()
                        ));
                        write!(
                            w,
                            "<div class=\"sub-variant-field\">\
                                 <span id=\"{id}\" class=\"section-header\">\
                                     <a href=\"#{id}\" class=\"anchor field\">§</a>\
                                     <code>{f}: {t}</code>\
                                 </span>",
                            f = field.name.unwrap(),
                            t = ty.print(cx),
                        );
                        write!(
                            w,
                            "{}</div>",
                            document(cx, field, Some(variant), HeadingOffset::H5)
                        );
                    }
                    _ => unreachable!(),
                }
            }
            w.write_str("</div>");
        }
    }
    write!(w, "</div>");
}

fn item_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Macro) {
    wrap_item(w, |w| {
        // FIXME: Also print `#[doc(hidden)]` for `macro_rules!` if it `is_doc_hidden`.
        if !t.macro_rules {
            write!(w, "{}", visibility_print_with_space(it, cx));
        }
        write!(w, "{}", Escape(&t.source));
    });
    write!(w, "{}", document(cx, it, None, HeadingOffset::H2))
}

fn item_proc_macro(
    w: &mut impl fmt::Write,
    cx: &Context<'_>,
    it: &clean::Item,
    m: &clean::ProcMacro,
) {
    wrap_item(w, |buffer| {
        let name = it.name.expect("proc-macros always have names");
        match m.kind {
            MacroKind::Bang => {
                write!(buffer, "{name}!() {{ <span class=\"comment\">/* proc-macro */</span> }}")
                    .unwrap();
            }
            MacroKind::Attr => {
                write!(buffer, "#[{name}]").unwrap();
            }
            MacroKind::Derive => {
                write!(buffer, "#[derive({name})]").unwrap();
                if !m.helpers.is_empty() {
                    buffer
                        .write_str(
                            "\n{\n    \
                        <span class=\"comment\">// Attributes available to this derive:</span>\n",
                        )
                        .unwrap();
                    for attr in &m.helpers {
                        writeln!(buffer, "    #[{attr}]").unwrap();
                    }
                    buffer.write_str("}\n").unwrap();
                }
            }
        }
    });
    write!(w, "{}", document(cx, it, None, HeadingOffset::H2)).unwrap();
}

fn item_primitive(w: &mut impl fmt::Write, cx: &Context<'_>, it: &clean::Item) {
    let def_id = it.item_id.expect_def_id();
    write!(w, "{}", document(cx, it, None, HeadingOffset::H2)).unwrap();
    if it.name.map(|n| n.as_str() != "reference").unwrap_or(false) {
        write!(w, "{}", render_assoc_items(cx, it, def_id, AssocItemRender::All)).unwrap();
    } else {
        // We handle the "reference" primitive type on its own because we only want to list
        // implementations on generic types.
        let (concrete, synthetic, blanket_impl) = get_filtered_impls_for_reference(&cx.shared, it);

        render_all_impls(w, cx, it, &concrete, &synthetic, &blanket_impl);
    }
}

fn item_constant(
    w: &mut Buffer,
    cx: &Context<'_>,
    it: &clean::Item,
    generics: &clean::Generics,
    ty: &clean::Type,
    c: &clean::ConstantKind,
) {
    wrap_item(w, |w| {
        let tcx = cx.tcx();
        render_attributes_in_code(w, it, cx);

        write!(
            w,
            "{vis}const {name}{generics}: {typ}{where_clause}",
            vis = visibility_print_with_space(it, cx),
            name = it.name.unwrap(),
            generics = generics.print(cx),
            typ = ty.print(cx),
            where_clause = print_where_clause(generics, cx, 0, Ending::NoNewline),
        );

        // FIXME: The code below now prints
        //            ` = _; // 100i32`
        //        if the expression is
        //            `50 + 50`
        //        which looks just wrong.
        //        Should we print
        //            ` = 100i32;`
        //        instead?

        let value = c.value(tcx);
        let is_literal = c.is_literal(tcx);
        let expr = c.expr(tcx);
        if value.is_some() || is_literal {
            write!(w, " = {expr};", expr = Escape(&expr));
        } else {
            w.write_str(";");
        }

        if !is_literal {
            if let Some(value) = &value {
                let value_lowercase = value.to_lowercase();
                let expr_lowercase = expr.to_lowercase();

                if value_lowercase != expr_lowercase
                    && value_lowercase.trim_end_matches("i32") != expr_lowercase
                {
                    write!(w, " // {value}", value = Escape(value));
                }
            }
        }
    });

    write!(w, "{}", document(cx, it, None, HeadingOffset::H2))
}

fn item_struct(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Struct) {
    wrap_item(w, |w| {
        render_attributes_in_code(w, it, cx);
        render_struct(w, it, Some(&s.generics), s.ctor_kind, &s.fields, "", true, cx);
    });

    write!(w, "{}", document(cx, it, None, HeadingOffset::H2));

    item_fields(w, cx, it, &s.fields, s.ctor_kind);

    let def_id = it.item_id.expect_def_id();
    write!(w, "{}", render_assoc_items(cx, it, def_id, AssocItemRender::All));
    write!(w, "{}", document_type_layout(cx, def_id));
}

fn item_fields(
    w: &mut Buffer,
    cx: &Context<'_>,
    it: &clean::Item,
    fields: &[clean::Item],
    ctor_kind: Option<CtorKind>,
) {
    let mut fields = fields
        .iter()
        .filter_map(|f| match f.kind {
            clean::StructFieldItem(ref ty) => Some((f, ty)),
            _ => None,
        })
        .peekable();
    if let None | Some(CtorKind::Fn) = ctor_kind {
        if fields.peek().is_some() {
            let title = format!(
                "{}{}",
                if ctor_kind.is_none() { "Fields" } else { "Tuple Fields" },
                document_non_exhaustive_header(it),
            );
            write_section_heading(w, &title, "fields", Some("fields"), document_non_exhaustive(it));
            for (index, (field, ty)) in fields.enumerate() {
                let field_name =
                    field.name.map_or_else(|| index.to_string(), |sym| sym.as_str().to_string());
                let id = cx.derive_id(format!("{typ}.{field_name}", typ = ItemType::StructField));
                write!(
                    w,
                    "<span id=\"{id}\" class=\"{item_type} section-header\">\
                         <a href=\"#{id}\" class=\"anchor field\">§</a>\
                         <code>{field_name}: {ty}</code>\
                     </span>",
                    item_type = ItemType::StructField,
                    ty = ty.print(cx)
                );
                write!(w, "{}", document(cx, field, Some(it), HeadingOffset::H3));
            }
        }
    }
}

fn item_static(
    w: &mut impl fmt::Write,
    cx: &Context<'_>,
    it: &clean::Item,
    s: &clean::Static,
    safety: Option<hir::Safety>,
) {
    wrap_item(w, |buffer| {
        render_attributes_in_code(buffer, it, cx);
        write!(
            buffer,
            "{vis}{safe}static {mutability}{name}: {typ}",
            vis = visibility_print_with_space(it, cx),
            safe = safety.map(|safe| safe.prefix_str()).unwrap_or(""),
            mutability = s.mutability.print_with_space(),
            name = it.name.unwrap(),
            typ = s.type_.print(cx)
        )
        .unwrap();
    });

    write!(w, "{}", document(cx, it, None, HeadingOffset::H2)).unwrap();
}

fn item_foreign_type(w: &mut impl fmt::Write, cx: &Context<'_>, it: &clean::Item) {
    wrap_item(w, |buffer| {
        buffer.write_str("extern {\n").unwrap();
        render_attributes_in_code(buffer, it, cx);
        write!(
            buffer,
            "    {}type {};\n}}",
            visibility_print_with_space(it, cx),
            it.name.unwrap(),
        )
        .unwrap();
    });

    write!(w, "{}", document(cx, it, None, HeadingOffset::H2)).unwrap();
    write!(w, "{}", render_assoc_items(cx, it, it.item_id.expect_def_id(), AssocItemRender::All))
        .unwrap();
}

fn item_keyword(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
    write!(w, "{}", document(cx, it, None, HeadingOffset::H2))
}

/// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
///
/// This code is copied from [`rustfmt`], and should probably be released as a crate at some point.
///
/// [`rustfmt`]:https://github.com/rust-lang/rustfmt/blob/rustfmt-2.0.0-rc.2/src/formatting/reorder.rs#L32
pub(crate) fn compare_names(left: &str, right: &str) -> Ordering {
    let mut left = left.chars().peekable();
    let mut right = right.chars().peekable();

    loop {
        // The strings are equal so far and not inside a number in both sides
        let (l, r) = match (left.next(), right.next()) {
            // Is this the end of both strings?
            (None, None) => return Ordering::Equal,
            // If for one, the shorter one is considered smaller
            (None, Some(_)) => return Ordering::Less,
            (Some(_), None) => return Ordering::Greater,
            (Some(l), Some(r)) => (l, r),
        };
        let next_ordering = match (l.to_digit(10), r.to_digit(10)) {
            // If neither is a digit, just compare them
            (None, None) => Ord::cmp(&l, &r),
            // The one with shorter non-digit run is smaller
            // For `strverscmp` it's smaller iff next char in longer is greater than digits
            (None, Some(_)) => Ordering::Greater,
            (Some(_), None) => Ordering::Less,
            // If both start numbers, we have to compare the numbers
            (Some(l), Some(r)) => {
                if l == 0 || r == 0 {
                    // Fraction mode: compare as if there was leading `0.`
                    let ordering = Ord::cmp(&l, &r);
                    if ordering != Ordering::Equal {
                        return ordering;
                    }
                    loop {
                        // Get next pair
                        let (l, r) = match (left.peek(), right.peek()) {
                            // Is this the end of both strings?
                            (None, None) => return Ordering::Equal,
                            // If for one, the shorter one is considered smaller
                            (None, Some(_)) => return Ordering::Less,
                            (Some(_), None) => return Ordering::Greater,
                            (Some(l), Some(r)) => (l, r),
                        };
                        // Are they digits?
                        match (l.to_digit(10), r.to_digit(10)) {
                            // If out of digits, use the stored ordering due to equal length
                            (None, None) => break Ordering::Equal,
                            // If one is shorter, it's smaller
                            (None, Some(_)) => return Ordering::Less,
                            (Some(_), None) => return Ordering::Greater,
                            // If both are digits, consume them and take into account
                            (Some(l), Some(r)) => {
                                left.next();
                                right.next();
                                let ordering = Ord::cmp(&l, &r);
                                if ordering != Ordering::Equal {
                                    return ordering;
                                }
                            }
                        }
                    }
                } else {
                    // Integer mode
                    let mut same_length_ordering = Ord::cmp(&l, &r);
                    loop {
                        // Get next pair
                        let (l, r) = match (left.peek(), right.peek()) {
                            // Is this the end of both strings?
                            (None, None) => return same_length_ordering,
                            // If for one, the shorter one is considered smaller
                            (None, Some(_)) => return Ordering::Less,
                            (Some(_), None) => return Ordering::Greater,
                            (Some(l), Some(r)) => (l, r),
                        };
                        // Are they digits?
                        match (l.to_digit(10), r.to_digit(10)) {
                            // If out of digits, use the stored ordering due to equal length
                            (None, None) => break same_length_ordering,
                            // If one is shorter, it's smaller
                            (None, Some(_)) => return Ordering::Less,
                            (Some(_), None) => return Ordering::Greater,
                            // If both are digits, consume them and take into account
                            (Some(l), Some(r)) => {
                                left.next();
                                right.next();
                                same_length_ordering = same_length_ordering.then(Ord::cmp(&l, &r));
                            }
                        }
                    }
                }
            }
        };
        if next_ordering != Ordering::Equal {
            return next_ordering;
        }
    }
}

pub(super) fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
    let mut s = join_with_double_colon(&cx.current);
    s.push_str("::");
    s.push_str(item.name.unwrap().as_str());
    s
}

pub(super) fn item_path(ty: ItemType, name: &str) -> String {
    match ty {
        ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
        _ => format!("{ty}.{name}.html"),
    }
}

fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool, cx: &Context<'_>) -> String {
    let mut bounds = String::new();
    if t_bounds.is_empty() {
        return bounds;
    }
    let has_lots_of_bounds = t_bounds.len() > 2;
    let inter_str = if has_lots_of_bounds { "\n    + " } else { " + " };
    if !trait_alias {
        if has_lots_of_bounds {
            bounds.push_str(":\n    ");
        } else {
            bounds.push_str(": ");
        }
    }
    for (i, p) in t_bounds.iter().enumerate() {
        if i > 0 {
            bounds.push_str(inter_str);
        }
        bounds.push_str(&p.print(cx).to_string());
    }
    bounds
}

fn wrap_item<W, F>(w: &mut W, f: F)
where
    W: fmt::Write,
    F: FnOnce(&mut W),
{
    write!(w, r#"<pre class="rust item-decl"><code>"#).unwrap();
    f(w);
    write!(w, "</code></pre>").unwrap();
}

#[derive(PartialEq, Eq)]
struct ImplString(String);

impl ImplString {
    fn new(i: &Impl, cx: &Context<'_>) -> ImplString {
        ImplString(format!("{}", i.inner_impl().print(false, cx)))
    }
}

impl PartialOrd for ImplString {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(Ord::cmp(self, other))
    }
}

impl Ord for ImplString {
    fn cmp(&self, other: &Self) -> Ordering {
        compare_names(&self.0, &other.0)
    }
}

fn render_implementor(
    cx: &Context<'_>,
    implementor: &Impl,
    trait_: &clean::Item,
    w: &mut Buffer,
    implementor_dups: &FxHashMap<Symbol, (DefId, bool)>,
    aliases: &[String],
) {
    // If there's already another implementor that has the same abridged name, use the
    // full path, for example in `std::iter::ExactSizeIterator`
    let use_absolute = match implementor.inner_impl().for_ {
        clean::Type::Path { ref path, .. }
        | clean::BorrowedRef { type_: box clean::Type::Path { ref path, .. }, .. }
            if !path.is_assoc_ty() =>
        {
            implementor_dups[&path.last()].1
        }
        _ => false,
    };
    render_impl(
        w,
        cx,
        implementor,
        trait_,
        AssocItemLink::Anchor(None),
        RenderMode::Normal,
        Some(use_absolute),
        aliases,
        ImplRenderingParameters {
            show_def_docs: false,
            show_default_items: false,
            show_non_assoc_items: false,
            toggle_open_by_default: false,
        },
    );
}

fn render_union<'a, 'cx: 'a>(
    it: &'a clean::Item,
    g: Option<&'a clean::Generics>,
    fields: &'a [clean::Item],
    cx: &'a Context<'cx>,
) -> impl fmt::Display + 'a + Captures<'cx> {
    display_fn(move |mut f| {
        write!(f, "{}union {}", visibility_print_with_space(it, cx), it.name.unwrap(),)?;

        let where_displayed = g
            .map(|g| {
                let mut buf = Buffer::html();
                write!(buf, "{}", g.print(cx));
                let where_displayed = print_where_clause_and_check(&mut buf, g, cx);
                write!(f, "{buf}", buf = buf.into_inner()).unwrap();
                where_displayed
            })
            .unwrap_or(false);

        // If there wasn't a `where` clause, we add a whitespace.
        if !where_displayed {
            f.write_str(" ")?;
        }

        writeln!(f, "{{")?;
        let count_fields =
            fields.iter().filter(|field| matches!(field.kind, clean::StructFieldItem(..))).count();
        let toggle = should_hide_fields(count_fields);
        if toggle {
            toggle_open(&mut f, format_args!("{count_fields} fields"));
        }

        for field in fields {
            if let clean::StructFieldItem(ref ty) = field.kind {
                writeln!(
                    f,
                    "    {}{}: {},",
                    visibility_print_with_space(field, cx),
                    field.name.unwrap(),
                    ty.print(cx)
                )?;
            }
        }

        if it.has_stripped_entries().unwrap() {
            writeln!(f, "    <span class=\"comment\">/* private fields */</span>")?;
        }
        if toggle {
            toggle_close(&mut f);
        }
        f.write_str("}").unwrap();
        Ok(())
    })
}

fn render_struct(
    w: &mut Buffer,
    it: &clean::Item,
    g: Option<&clean::Generics>,
    ty: Option<CtorKind>,
    fields: &[clean::Item],
    tab: &str,
    structhead: bool,
    cx: &Context<'_>,
) {
    write!(
        w,
        "{}{}{}",
        visibility_print_with_space(it, cx),
        if structhead { "struct " } else { "" },
        it.name.unwrap()
    );
    if let Some(g) = g {
        write!(w, "{}", g.print(cx))
    }
    render_struct_fields(
        w,
        g,
        ty,
        fields,
        tab,
        structhead,
        it.has_stripped_entries().unwrap_or(false),
        cx,
    )
}

fn render_struct_fields(
    mut w: &mut Buffer,
    g: Option<&clean::Generics>,
    ty: Option<CtorKind>,
    fields: &[clean::Item],
    tab: &str,
    structhead: bool,
    has_stripped_entries: bool,
    cx: &Context<'_>,
) {
    match ty {
        None => {
            let where_displayed =
                g.map(|g| print_where_clause_and_check(w, g, cx)).unwrap_or(false);

            // If there wasn't a `where` clause, we add a whitespace.
            if !where_displayed {
                w.write_str(" {");
            } else {
                w.write_str("{");
            }
            let count_fields =
                fields.iter().filter(|f| matches!(f.kind, clean::StructFieldItem(..))).count();
            let has_visible_fields = count_fields > 0;
            let toggle = should_hide_fields(count_fields);
            if toggle {
                toggle_open(&mut w, format_args!("{count_fields} fields"));
            }
            for field in fields {
                if let clean::StructFieldItem(ref ty) = field.kind {
                    write!(
                        w,
                        "\n{tab}    {vis}{name}: {ty},",
                        vis = visibility_print_with_space(field, cx),
                        name = field.name.unwrap(),
                        ty = ty.print(cx),
                    );
                }
            }

            if has_visible_fields {
                if has_stripped_entries {
                    write!(w, "\n{tab}    <span class=\"comment\">/* private fields */</span>");
                }
                write!(w, "\n{tab}");
            } else if has_stripped_entries {
                write!(w, " <span class=\"comment\">/* private fields */</span> ");
            }
            if toggle {
                toggle_close(&mut w);
            }
            w.write_str("}");
        }
        Some(CtorKind::Fn) => {
            w.write_str("(");
            if !fields.is_empty()
                && fields.iter().all(|field| {
                    matches!(field.kind, clean::StrippedItem(box clean::StructFieldItem(..)))
                })
            {
                write!(w, "<span class=\"comment\">/* private fields */</span>");
            } else {
                for (i, field) in fields.iter().enumerate() {
                    if i > 0 {
                        w.write_str(", ");
                    }
                    match field.kind {
                        clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
                        clean::StructFieldItem(ref ty) => {
                            write!(w, "{}{}", visibility_print_with_space(field, cx), ty.print(cx),)
                        }
                        _ => unreachable!(),
                    }
                }
            }
            w.write_str(")");
            if let Some(g) = g {
                write!(w, "{}", print_where_clause(g, cx, 0, Ending::NoNewline));
            }
            // We only want a ";" when we are displaying a tuple struct, not a variant tuple struct.
            if structhead {
                w.write_str(";");
            }
        }
        Some(CtorKind::Const) => {
            // Needed for PhantomData.
            if let Some(g) = g {
                write!(w, "{}", print_where_clause(g, cx, 0, Ending::NoNewline));
            }
            w.write_str(";");
        }
    }
}

fn document_non_exhaustive_header(item: &clean::Item) -> &str {
    if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
}

fn document_non_exhaustive(item: &clean::Item) -> impl fmt::Display + '_ {
    display_fn(|f| {
        if item.is_non_exhaustive() {
            write!(
                f,
                "<details class=\"toggle non-exhaustive\">\
                    <summary class=\"hideme\"><span>{}</span></summary>\
                    <div class=\"docblock\">",
                {
                    if item.is_struct() {
                        "This struct is marked as non-exhaustive"
                    } else if item.is_enum() {
                        "This enum is marked as non-exhaustive"
                    } else if item.is_variant() {
                        "This variant is marked as non-exhaustive"
                    } else {
                        "This type is marked as non-exhaustive"
                    }
                }
            )?;

            if item.is_struct() {
                f.write_str(
                    "Non-exhaustive structs could have additional fields added in future. \
                    Therefore, non-exhaustive structs cannot be constructed in external crates \
                    using the traditional <code>Struct { .. }</code> syntax; cannot be \
                    matched against without a wildcard <code>..</code>; and \
                    struct update syntax will not work.",
                )?;
            } else if item.is_enum() {
                f.write_str(
                    "Non-exhaustive enums could have additional variants added in future. \
                    Therefore, when matching against variants of non-exhaustive enums, an \
                    extra wildcard arm must be added to account for any future variants.",
                )?;
            } else if item.is_variant() {
                f.write_str(
                    "Non-exhaustive enum variants could have additional fields added in future. \
                    Therefore, non-exhaustive enum variants cannot be constructed in external \
                    crates and cannot be matched against.",
                )?;
            } else {
                f.write_str(
                    "This type will require a wildcard arm in any match statements or constructors.",
                )?;
            }

            f.write_str("</div></details>")?;
        }
        Ok(())
    })
}

fn pluralize(count: usize) -> &'static str {
    if count > 1 { "s" } else { "" }
}