]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/render/print_item.rs
Rollup merge of #106354 - aDotInTheVoid:rdj-always-discr, r=GuillaumeGomez
[rust.git] / src / librustdoc / html / render / print_item.rs
1 use clean::AttributesExt;
2
3 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
4 use rustc_hir as hir;
5 use rustc_hir::def::CtorKind;
6 use rustc_hir::def_id::DefId;
7 use rustc_middle::middle::stability;
8 use rustc_middle::span_bug;
9 use rustc_middle::ty::layout::LayoutError;
10 use rustc_middle::ty::{self, Adt, TyCtxt};
11 use rustc_span::hygiene::MacroKind;
12 use rustc_span::symbol::{kw, sym, Symbol};
13 use rustc_target::abi::{LayoutS, Primitive, TagEncoding, VariantIdx, Variants};
14 use std::cmp::Ordering;
15 use std::fmt;
16 use std::rc::Rc;
17
18 use super::{
19     collect_paths_for_type, document, ensure_trailing_slash, get_filtered_impls_for_reference,
20     item_ty_to_section, notable_traits_button, notable_traits_json, render_all_impls,
21     render_assoc_item, render_assoc_items, render_attributes_in_code, render_attributes_in_pre,
22     render_impl, render_rightside, render_stability_since_raw,
23     render_stability_since_raw_with_extra, AssocItemLink, Context, ImplRenderingParameters,
24 };
25 use crate::clean;
26 use crate::config::ModuleSorting;
27 use crate::formats::item_type::ItemType;
28 use crate::formats::{AssocItemRender, Impl, RenderMode};
29 use crate::html::escape::Escape;
30 use crate::html::format::{
31     join_with_double_colon, print_abi_with_space, print_constness_with_space, print_where_clause,
32     visibility_print_with_space, Buffer, Ending, PrintWithSpace,
33 };
34 use crate::html::layout::Page;
35 use crate::html::markdown::{HeadingOffset, MarkdownSummaryLine};
36 use crate::html::url_parts_builder::UrlPartsBuilder;
37 use crate::html::{highlight, static_files};
38
39 use askama::Template;
40 use itertools::Itertools;
41
42 const ITEM_TABLE_OPEN: &str = "<div class=\"item-table\">";
43 const ITEM_TABLE_CLOSE: &str = "</div>";
44 const ITEM_TABLE_ROW_OPEN: &str = "<div class=\"item-row\">";
45 const ITEM_TABLE_ROW_CLOSE: &str = "</div>";
46
47 // A component in a `use` path, like `string` in std::string::ToString
48 struct PathComponent {
49     path: String,
50     name: Symbol,
51 }
52
53 #[derive(Template)]
54 #[template(path = "print_item.html")]
55 struct ItemVars<'a> {
56     static_root_path: &'a str,
57     clipboard_svg: &'static static_files::StaticFile,
58     typ: &'a str,
59     name: &'a str,
60     item_type: &'a str,
61     path_components: Vec<PathComponent>,
62     stability_since_raw: &'a str,
63     src_href: Option<&'a str>,
64 }
65
66 /// Calls `print_where_clause` and returns `true` if a `where` clause was generated.
67 fn print_where_clause_and_check<'a, 'tcx: 'a>(
68     buffer: &mut Buffer,
69     gens: &'a clean::Generics,
70     cx: &'a Context<'tcx>,
71 ) -> bool {
72     let len_before = buffer.len();
73     write!(buffer, "{}", print_where_clause(gens, cx, 0, Ending::Newline));
74     len_before != buffer.len()
75 }
76
77 pub(super) fn print_item(
78     cx: &mut Context<'_>,
79     item: &clean::Item,
80     buf: &mut Buffer,
81     page: &Page<'_>,
82 ) {
83     debug_assert!(!item.is_stripped());
84     let typ = match *item.kind {
85         clean::ModuleItem(_) => {
86             if item.is_crate() {
87                 "Crate "
88             } else {
89                 "Module "
90             }
91         }
92         clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
93         clean::TraitItem(..) => "Trait ",
94         clean::StructItem(..) => "Struct ",
95         clean::UnionItem(..) => "Union ",
96         clean::EnumItem(..) => "Enum ",
97         clean::TypedefItem(..) => "Type Definition ",
98         clean::MacroItem(..) => "Macro ",
99         clean::ProcMacroItem(ref mac) => match mac.kind {
100             MacroKind::Bang => "Macro ",
101             MacroKind::Attr => "Attribute Macro ",
102             MacroKind::Derive => "Derive Macro ",
103         },
104         clean::PrimitiveItem(..) => "Primitive Type ",
105         clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
106         clean::ConstantItem(..) => "Constant ",
107         clean::ForeignTypeItem => "Foreign Type ",
108         clean::KeywordItem => "Keyword ",
109         clean::OpaqueTyItem(..) => "Opaque Type ",
110         clean::TraitAliasItem(..) => "Trait Alias ",
111         _ => {
112             // We don't generate pages for any other type.
113             unreachable!();
114         }
115     };
116     let mut stability_since_raw = Buffer::new();
117     render_stability_since_raw(
118         &mut stability_since_raw,
119         item.stable_since(cx.tcx()),
120         item.const_stability(cx.tcx()),
121         None,
122         None,
123     );
124     let stability_since_raw: String = stability_since_raw.into_inner();
125
126     // Write source tag
127     //
128     // When this item is part of a `crate use` in a downstream crate, the
129     // source link in the downstream documentation will actually come back to
130     // this page, and this link will be auto-clicked. The `id` attribute is
131     // used to find the link to auto-click.
132     let src_href =
133         if cx.include_sources && !item.is_primitive() { cx.src_href(item) } else { None };
134
135     let path_components = if item.is_primitive() || item.is_keyword() {
136         vec![]
137     } else {
138         let cur = &cx.current;
139         let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
140         cur.iter()
141             .enumerate()
142             .take(amt)
143             .map(|(i, component)| PathComponent {
144                 path: "../".repeat(cur.len() - i - 1),
145                 name: *component,
146             })
147             .collect()
148     };
149
150     let item_vars = ItemVars {
151         static_root_path: &page.get_static_root_path(),
152         clipboard_svg: &static_files::STATIC_FILES.clipboard_svg,
153         typ,
154         name: item.name.as_ref().unwrap().as_str(),
155         item_type: &item.type_().to_string(),
156         path_components,
157         stability_since_raw: &stability_since_raw,
158         src_href: src_href.as_deref(),
159     };
160
161     item_vars.render_into(buf).unwrap();
162
163     match &*item.kind {
164         clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
165         clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
166             item_function(buf, cx, item, f)
167         }
168         clean::TraitItem(ref t) => item_trait(buf, cx, item, t),
169         clean::StructItem(ref s) => item_struct(buf, cx, item, s),
170         clean::UnionItem(ref s) => item_union(buf, cx, item, s),
171         clean::EnumItem(ref e) => item_enum(buf, cx, item, e),
172         clean::TypedefItem(ref t) => item_typedef(buf, cx, item, t),
173         clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
174         clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
175         clean::PrimitiveItem(_) => item_primitive(buf, cx, item),
176         clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
177         clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
178         clean::ForeignTypeItem => item_foreign_type(buf, cx, item),
179         clean::KeywordItem => item_keyword(buf, cx, item),
180         clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e),
181         clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta),
182         _ => {
183             // We don't generate pages for any other type.
184             unreachable!();
185         }
186     }
187
188     // Render notable-traits.js used for all methods in this module.
189     if !cx.types_with_notable_traits.is_empty() {
190         write!(
191             buf,
192             r#"<script type="text/json" id="notable-traits-data">{}</script>"#,
193             notable_traits_json(cx.types_with_notable_traits.iter(), cx)
194         );
195         cx.types_with_notable_traits.clear();
196     }
197 }
198
199 /// For large structs, enums, unions, etc, determine whether to hide their fields
200 fn should_hide_fields(n_fields: usize) -> bool {
201     n_fields > 12
202 }
203
204 fn toggle_open(w: &mut Buffer, text: impl fmt::Display) {
205     write!(
206         w,
207         "<details class=\"rustdoc-toggle type-contents-toggle\">\
208             <summary class=\"hideme\">\
209                 <span>Show {}</span>\
210             </summary>",
211         text
212     );
213 }
214
215 fn toggle_close(w: &mut Buffer) {
216     w.write_str("</details>");
217 }
218
219 fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items: &[clean::Item]) {
220     document(w, cx, item, None, HeadingOffset::H2);
221
222     let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
223
224     // the order of item types in the listing
225     fn reorder(ty: ItemType) -> u8 {
226         match ty {
227             ItemType::ExternCrate => 0,
228             ItemType::Import => 1,
229             ItemType::Primitive => 2,
230             ItemType::Module => 3,
231             ItemType::Macro => 4,
232             ItemType::Struct => 5,
233             ItemType::Enum => 6,
234             ItemType::Constant => 7,
235             ItemType::Static => 8,
236             ItemType::Trait => 9,
237             ItemType::Function => 10,
238             ItemType::Typedef => 12,
239             ItemType::Union => 13,
240             _ => 14 + ty as u8,
241         }
242     }
243
244     fn cmp(
245         i1: &clean::Item,
246         i2: &clean::Item,
247         idx1: usize,
248         idx2: usize,
249         tcx: TyCtxt<'_>,
250     ) -> Ordering {
251         let ty1 = i1.type_();
252         let ty2 = i2.type_();
253         if item_ty_to_section(ty1) != item_ty_to_section(ty2)
254             || (ty1 != ty2 && (ty1 == ItemType::ExternCrate || ty2 == ItemType::ExternCrate))
255         {
256             return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
257         }
258         let s1 = i1.stability(tcx).as_ref().map(|s| s.level);
259         let s2 = i2.stability(tcx).as_ref().map(|s| s.level);
260         if let (Some(a), Some(b)) = (s1, s2) {
261             match (a.is_stable(), b.is_stable()) {
262                 (true, true) | (false, false) => {}
263                 (false, true) => return Ordering::Less,
264                 (true, false) => return Ordering::Greater,
265             }
266         }
267         let lhs = i1.name.unwrap_or(kw::Empty);
268         let rhs = i2.name.unwrap_or(kw::Empty);
269         compare_names(lhs.as_str(), rhs.as_str())
270     }
271
272     match cx.shared.module_sorting {
273         ModuleSorting::Alphabetical => {
274             indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2, cx.tcx()));
275         }
276         ModuleSorting::DeclarationOrder => {}
277     }
278     // This call is to remove re-export duplicates in cases such as:
279     //
280     // ```
281     // pub(crate) mod foo {
282     //     pub(crate) mod bar {
283     //         pub(crate) trait Double { fn foo(); }
284     //     }
285     // }
286     //
287     // pub(crate) use foo::bar::*;
288     // pub(crate) use foo::*;
289     // ```
290     //
291     // `Double` will appear twice in the generated docs.
292     //
293     // FIXME: This code is quite ugly and could be improved. Small issue: DefId
294     // can be identical even if the elements are different (mostly in imports).
295     // So in case this is an import, we keep everything by adding a "unique id"
296     // (which is the position in the vector).
297     indices.dedup_by_key(|i| {
298         (
299             items[*i].item_id,
300             if items[*i].name.is_some() { Some(full_path(cx, &items[*i])) } else { None },
301             items[*i].type_(),
302             if items[*i].is_import() { *i } else { 0 },
303         )
304     });
305
306     debug!("{:?}", indices);
307     let mut last_section = None;
308
309     for &idx in &indices {
310         let myitem = &items[idx];
311         if myitem.is_stripped() {
312             continue;
313         }
314
315         let my_section = item_ty_to_section(myitem.type_());
316         if Some(my_section) != last_section {
317             if last_section.is_some() {
318                 w.write_str(ITEM_TABLE_CLOSE);
319             }
320             last_section = Some(my_section);
321             write!(
322                 w,
323                 "<h2 id=\"{id}\" class=\"small-section-header\">\
324                     <a href=\"#{id}\">{name}</a>\
325                  </h2>{}",
326                 ITEM_TABLE_OPEN,
327                 id = cx.derive_id(my_section.id().to_owned()),
328                 name = my_section.name(),
329             );
330         }
331
332         let tcx = cx.tcx();
333         match *myitem.kind {
334             clean::ExternCrateItem { ref src } => {
335                 use crate::html::format::anchor;
336
337                 w.write_str(ITEM_TABLE_ROW_OPEN);
338                 match *src {
339                     Some(src) => write!(
340                         w,
341                         "<div class=\"item-left\"><code>{}extern crate {} as {};",
342                         visibility_print_with_space(myitem.visibility(tcx), myitem.item_id, cx),
343                         anchor(myitem.item_id.expect_def_id(), src, cx),
344                         myitem.name.unwrap(),
345                     ),
346                     None => write!(
347                         w,
348                         "<div class=\"item-left\"><code>{}extern crate {};",
349                         visibility_print_with_space(myitem.visibility(tcx), myitem.item_id, cx),
350                         anchor(myitem.item_id.expect_def_id(), myitem.name.unwrap(), cx),
351                     ),
352                 }
353                 w.write_str("</code></div>");
354                 w.write_str(ITEM_TABLE_ROW_CLOSE);
355             }
356
357             clean::ImportItem(ref import) => {
358                 let (stab, stab_tags) = if let Some(import_def_id) = import.source.did {
359                     let ast_attrs = cx.tcx().get_attrs_unchecked(import_def_id);
360                     let import_attrs = Box::new(clean::Attributes::from_ast(ast_attrs));
361
362                     // Just need an item with the correct def_id and attrs
363                     let import_item = clean::Item {
364                         item_id: import_def_id.into(),
365                         attrs: import_attrs,
366                         cfg: ast_attrs.cfg(cx.tcx(), &cx.cache().hidden_cfg),
367                         ..myitem.clone()
368                     };
369
370                     let stab = import_item.stability_class(cx.tcx());
371                     let stab_tags = Some(extra_info_tags(&import_item, item, cx.tcx()));
372                     (stab, stab_tags)
373                 } else {
374                     (None, None)
375                 };
376
377                 let add = if stab.is_some() { " " } else { "" };
378
379                 w.write_str(ITEM_TABLE_ROW_OPEN);
380                 let id = match import.kind {
381                     clean::ImportKind::Simple(s) => {
382                         format!(" id=\"{}\"", cx.derive_id(format!("reexport.{}", s)))
383                     }
384                     clean::ImportKind::Glob => String::new(),
385                 };
386                 let stab_tags = stab_tags.unwrap_or_default();
387                 let (stab_tags_before, stab_tags_after) = if stab_tags.is_empty() {
388                     ("", "")
389                 } else {
390                     ("<div class=\"item-right docblock-short\">", "</div>")
391                 };
392                 write!(
393                     w,
394                     "<div class=\"item-left {stab}{add}import-item\"{id}>\
395                          <code>{vis}{imp}</code>\
396                      </div>\
397                      {stab_tags_before}{stab_tags}{stab_tags_after}",
398                     stab = stab.unwrap_or_default(),
399                     vis = visibility_print_with_space(myitem.visibility(tcx), myitem.item_id, cx),
400                     imp = import.print(cx),
401                 );
402                 w.write_str(ITEM_TABLE_ROW_CLOSE);
403             }
404
405             _ => {
406                 if myitem.name.is_none() {
407                     continue;
408                 }
409
410                 let unsafety_flag = match *myitem.kind {
411                     clean::FunctionItem(_) | clean::ForeignFunctionItem(_)
412                         if myitem.fn_header(cx.tcx()).unwrap().unsafety
413                             == hir::Unsafety::Unsafe =>
414                     {
415                         "<sup title=\"unsafe function\">⚠</sup>"
416                     }
417                     _ => "",
418                 };
419
420                 let stab = myitem.stability_class(cx.tcx());
421                 let add = if stab.is_some() { " " } else { "" };
422
423                 let visibility_emoji = match myitem.visibility(tcx) {
424                     Some(ty::Visibility::Restricted(_)) => {
425                         "<span title=\"Restricted Visibility\">&nbsp;🔒</span> "
426                     }
427                     _ => "",
428                 };
429
430                 let doc_value = myitem.doc_value().unwrap_or_default();
431                 w.write_str(ITEM_TABLE_ROW_OPEN);
432                 let docs = MarkdownSummaryLine(&doc_value, &myitem.links(cx)).into_string();
433                 let (docs_before, docs_after) = if docs.is_empty() {
434                     ("", "")
435                 } else {
436                     ("<div class=\"item-right docblock-short\">", "</div>")
437                 };
438                 write!(
439                     w,
440                     "<div class=\"item-left {stab}{add}module-item\">\
441                         <a class=\"{class}\" href=\"{href}\" title=\"{title}\">{name}</a>\
442                         {visibility_emoji}\
443                         {unsafety_flag}\
444                         {stab_tags}\
445                      </div>\
446                      {docs_before}{docs}{docs_after}",
447                     name = myitem.name.unwrap(),
448                     visibility_emoji = visibility_emoji,
449                     stab_tags = extra_info_tags(myitem, item, cx.tcx()),
450                     class = myitem.type_(),
451                     add = add,
452                     stab = stab.unwrap_or_default(),
453                     unsafety_flag = unsafety_flag,
454                     href = item_path(myitem.type_(), myitem.name.unwrap().as_str()),
455                     title = [full_path(cx, myitem), myitem.type_().to_string()]
456                         .iter()
457                         .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
458                         .collect::<Vec<_>>()
459                         .join(" "),
460                 );
461                 w.write_str(ITEM_TABLE_ROW_CLOSE);
462             }
463         }
464     }
465
466     if last_section.is_some() {
467         w.write_str(ITEM_TABLE_CLOSE);
468     }
469 }
470
471 /// Render the stability, deprecation and portability tags that are displayed in the item's summary
472 /// at the module level.
473 fn extra_info_tags(item: &clean::Item, parent: &clean::Item, tcx: TyCtxt<'_>) -> String {
474     let mut tags = String::new();
475
476     fn tag_html(class: &str, title: &str, contents: &str) -> String {
477         format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
478     }
479
480     // The trailing space after each tag is to space it properly against the rest of the docs.
481     if let Some(depr) = &item.deprecation(tcx) {
482         let mut message = "Deprecated";
483         if !stability::deprecation_in_effect(depr) {
484             message = "Deprecation planned";
485         }
486         tags += &tag_html("deprecated", "", message);
487     }
488
489     // The "rustc_private" crates are permanently unstable so it makes no sense
490     // to render "unstable" everywhere.
491     if item.stability(tcx).as_ref().map(|s| s.is_unstable() && s.feature != sym::rustc_private)
492         == Some(true)
493     {
494         tags += &tag_html("unstable", "", "Experimental");
495     }
496
497     let cfg = match (&item.cfg, parent.cfg.as_ref()) {
498         (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
499         (cfg, _) => cfg.as_deref().cloned(),
500     };
501
502     debug!("Portability name={:?} {:?} - {:?} = {:?}", item.name, item.cfg, parent.cfg, cfg);
503     if let Some(ref cfg) = cfg {
504         tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
505     }
506
507     tags
508 }
509
510 fn item_function(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, f: &clean::Function) {
511     let tcx = cx.tcx();
512     let header = it.fn_header(tcx).expect("printing a function which isn't a function");
513     let constness = print_constness_with_space(&header.constness, it.const_stability(tcx));
514     let unsafety = header.unsafety.print_with_space();
515     let abi = print_abi_with_space(header.abi).to_string();
516     let asyncness = header.asyncness.print_with_space();
517     let visibility = visibility_print_with_space(it.visibility(tcx), it.item_id, cx).to_string();
518     let name = it.name.unwrap();
519
520     let generics_len = format!("{:#}", f.generics.print(cx)).len();
521     let header_len = "fn ".len()
522         + visibility.len()
523         + constness.len()
524         + asyncness.len()
525         + unsafety.len()
526         + abi.len()
527         + name.as_str().len()
528         + generics_len;
529
530     let notable_traits =
531         f.decl.output.as_return().and_then(|output| notable_traits_button(output, cx));
532
533     wrap_into_item_decl(w, |w| {
534         wrap_item(w, "fn", |w| {
535             render_attributes_in_pre(w, it, "");
536             w.reserve(header_len);
537             write!(
538                 w,
539                 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
540                  {name}{generics}{decl}{notable_traits}{where_clause}",
541                 vis = visibility,
542                 constness = constness,
543                 asyncness = asyncness,
544                 unsafety = unsafety,
545                 abi = abi,
546                 name = name,
547                 generics = f.generics.print(cx),
548                 where_clause = print_where_clause(&f.generics, cx, 0, Ending::Newline),
549                 decl = f.decl.full_print(header_len, 0, cx),
550                 notable_traits = notable_traits.unwrap_or_default(),
551             );
552         });
553     });
554     document(w, cx, it, None, HeadingOffset::H2);
555 }
556
557 fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::Trait) {
558     let tcx = cx.tcx();
559     let bounds = bounds(&t.bounds, false, cx);
560     let required_types = t.items.iter().filter(|m| m.is_ty_associated_type()).collect::<Vec<_>>();
561     let provided_types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
562     let required_consts = t.items.iter().filter(|m| m.is_ty_associated_const()).collect::<Vec<_>>();
563     let provided_consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
564     let required_methods = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
565     let provided_methods = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
566     let count_types = required_types.len() + provided_types.len();
567     let count_consts = required_consts.len() + provided_consts.len();
568     let count_methods = required_methods.len() + provided_methods.len();
569     let must_implement_one_of_functions = tcx.trait_def(t.def_id).must_implement_one_of.clone();
570
571     // Output the trait definition
572     wrap_into_item_decl(w, |w| {
573         wrap_item(w, "trait", |w| {
574             render_attributes_in_pre(w, it, "");
575             write!(
576                 w,
577                 "{}{}{}trait {}{}{}",
578                 visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
579                 t.unsafety(tcx).print_with_space(),
580                 if t.is_auto(tcx) { "auto " } else { "" },
581                 it.name.unwrap(),
582                 t.generics.print(cx),
583                 bounds
584             );
585
586             if !t.generics.where_predicates.is_empty() {
587                 write!(w, "{}", print_where_clause(&t.generics, cx, 0, Ending::Newline));
588             } else {
589                 w.write_str(" ");
590             }
591
592             if t.items.is_empty() {
593                 w.write_str("{ }");
594             } else {
595                 // FIXME: we should be using a derived_id for the Anchors here
596                 w.write_str("{\n");
597                 let mut toggle = false;
598
599                 // If there are too many associated types, hide _everything_
600                 if should_hide_fields(count_types) {
601                     toggle = true;
602                     toggle_open(
603                         w,
604                         format_args!(
605                             "{} associated items",
606                             count_types + count_consts + count_methods
607                         ),
608                     );
609                 }
610                 for types in [&required_types, &provided_types] {
611                     for t in types {
612                         render_assoc_item(
613                             w,
614                             t,
615                             AssocItemLink::Anchor(None),
616                             ItemType::Trait,
617                             cx,
618                             RenderMode::Normal,
619                         );
620                         w.write_str(";\n");
621                     }
622                 }
623                 // If there are too many associated constants, hide everything after them
624                 // We also do this if the types + consts is large because otherwise we could
625                 // render a bunch of types and _then_ a bunch of consts just because both were
626                 // _just_ under the limit
627                 if !toggle && should_hide_fields(count_types + count_consts) {
628                     toggle = true;
629                     toggle_open(
630                         w,
631                         format_args!(
632                             "{} associated constant{} and {} method{}",
633                             count_consts,
634                             pluralize(count_consts),
635                             count_methods,
636                             pluralize(count_methods),
637                         ),
638                     );
639                 }
640                 if count_types != 0 && (count_consts != 0 || count_methods != 0) {
641                     w.write_str("\n");
642                 }
643                 for consts in [&required_consts, &provided_consts] {
644                     for c in consts {
645                         render_assoc_item(
646                             w,
647                             c,
648                             AssocItemLink::Anchor(None),
649                             ItemType::Trait,
650                             cx,
651                             RenderMode::Normal,
652                         );
653                         w.write_str(";\n");
654                     }
655                 }
656                 if !toggle && should_hide_fields(count_methods) {
657                     toggle = true;
658                     toggle_open(w, format_args!("{} methods", count_methods));
659                 }
660                 if count_consts != 0 && count_methods != 0 {
661                     w.write_str("\n");
662                 }
663                 for (pos, m) in required_methods.iter().enumerate() {
664                     render_assoc_item(
665                         w,
666                         m,
667                         AssocItemLink::Anchor(None),
668                         ItemType::Trait,
669                         cx,
670                         RenderMode::Normal,
671                     );
672                     w.write_str(";\n");
673
674                     if pos < required_methods.len() - 1 {
675                         w.write_str("<span class=\"item-spacer\"></span>");
676                     }
677                 }
678                 if !required_methods.is_empty() && !provided_methods.is_empty() {
679                     w.write_str("\n");
680                 }
681                 for (pos, m) in provided_methods.iter().enumerate() {
682                     render_assoc_item(
683                         w,
684                         m,
685                         AssocItemLink::Anchor(None),
686                         ItemType::Trait,
687                         cx,
688                         RenderMode::Normal,
689                     );
690                     match *m.kind {
691                         clean::MethodItem(ref inner, _)
692                             if !inner.generics.where_predicates.is_empty() =>
693                         {
694                             w.write_str(",\n    { ... }\n");
695                         }
696                         _ => {
697                             w.write_str(" { ... }\n");
698                         }
699                     }
700
701                     if pos < provided_methods.len() - 1 {
702                         w.write_str("<span class=\"item-spacer\"></span>");
703                     }
704                 }
705                 if toggle {
706                     toggle_close(w);
707                 }
708                 w.write_str("}");
709             }
710         });
711     });
712
713     // Trait documentation
714     document(w, cx, it, None, HeadingOffset::H2);
715
716     fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
717         write!(
718             w,
719             "<h2 id=\"{0}\" class=\"small-section-header\">\
720                 {1}<a href=\"#{0}\" class=\"anchor\">§</a>\
721              </h2>{2}",
722             id, title, extra_content
723         )
724     }
725
726     fn trait_item(w: &mut Buffer, cx: &mut Context<'_>, m: &clean::Item, t: &clean::Item) {
727         let name = m.name.unwrap();
728         info!("Documenting {} on {:?}", name, t.name);
729         let item_type = m.type_();
730         let id = cx.derive_id(format!("{}.{}", item_type, name));
731         let mut content = Buffer::empty_from(w);
732         document(&mut content, cx, m, Some(t), HeadingOffset::H5);
733         let toggled = !content.is_empty();
734         if toggled {
735             let method_toggle_class = if item_type.is_method() { " method-toggle" } else { "" };
736             write!(w, "<details class=\"rustdoc-toggle{method_toggle_class}\" open><summary>");
737         }
738         write!(w, "<section id=\"{}\" class=\"method has-srclink\">", id);
739         render_rightside(w, cx, m, t, RenderMode::Normal);
740         write!(w, "<h4 class=\"code-header\">");
741         render_assoc_item(
742             w,
743             m,
744             AssocItemLink::Anchor(Some(&id)),
745             ItemType::Impl,
746             cx,
747             RenderMode::Normal,
748         );
749         w.write_str("</h4>");
750         w.write_str("</section>");
751         if toggled {
752             write!(w, "</summary>");
753             w.push_buffer(content);
754             write!(w, "</details>");
755         }
756     }
757
758     if !required_types.is_empty() {
759         write_small_section_header(
760             w,
761             "required-associated-types",
762             "Required Associated Types",
763             "<div class=\"methods\">",
764         );
765         for t in required_types {
766             trait_item(w, cx, t, it);
767         }
768         w.write_str("</div>");
769     }
770     if !provided_types.is_empty() {
771         write_small_section_header(
772             w,
773             "provided-associated-types",
774             "Provided Associated Types",
775             "<div class=\"methods\">",
776         );
777         for t in provided_types {
778             trait_item(w, cx, t, it);
779         }
780         w.write_str("</div>");
781     }
782
783     if !required_consts.is_empty() {
784         write_small_section_header(
785             w,
786             "required-associated-consts",
787             "Required Associated Constants",
788             "<div class=\"methods\">",
789         );
790         for t in required_consts {
791             trait_item(w, cx, t, it);
792         }
793         w.write_str("</div>");
794     }
795     if !provided_consts.is_empty() {
796         write_small_section_header(
797             w,
798             "provided-associated-consts",
799             "Provided Associated Constants",
800             "<div class=\"methods\">",
801         );
802         for t in provided_consts {
803             trait_item(w, cx, t, it);
804         }
805         w.write_str("</div>");
806     }
807
808     // Output the documentation for each function individually
809     if !required_methods.is_empty() || must_implement_one_of_functions.is_some() {
810         write_small_section_header(
811             w,
812             "required-methods",
813             "Required Methods",
814             "<div class=\"methods\">",
815         );
816
817         if let Some(list) = must_implement_one_of_functions.as_deref() {
818             write!(
819                 w,
820                 "<div class=\"stab must_implement\">At least one of the `{}` methods is required.</div>",
821                 list.iter().join("`, `")
822             );
823         }
824
825         for m in required_methods {
826             trait_item(w, cx, m, it);
827         }
828         w.write_str("</div>");
829     }
830     if !provided_methods.is_empty() {
831         write_small_section_header(
832             w,
833             "provided-methods",
834             "Provided Methods",
835             "<div class=\"methods\">",
836         );
837         for m in provided_methods {
838             trait_item(w, cx, m, it);
839         }
840         w.write_str("</div>");
841     }
842
843     // If there are methods directly on this trait object, render them here.
844     render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All);
845
846     let cloned_shared = Rc::clone(&cx.shared);
847     let cache = &cloned_shared.cache;
848     let mut extern_crates = FxHashSet::default();
849     if let Some(implementors) = cache.implementors.get(&it.item_id.expect_def_id()) {
850         // The DefId is for the first Type found with that name. The bool is
851         // if any Types with the same name but different DefId have been found.
852         let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();
853         for implementor in implementors {
854             if let Some(did) = implementor.inner_impl().for_.without_borrowed_ref().def_id(cache) &&
855                 !did.is_local() {
856                 extern_crates.insert(did.krate);
857             }
858             match implementor.inner_impl().for_.without_borrowed_ref() {
859                 clean::Type::Path { ref path } if !path.is_assoc_ty() => {
860                     let did = path.def_id();
861                     let &mut (prev_did, ref mut has_duplicates) =
862                         implementor_dups.entry(path.last()).or_insert((did, false));
863                     if prev_did != did {
864                         *has_duplicates = true;
865                     }
866                 }
867                 _ => {}
868             }
869         }
870
871         let (local, foreign) =
872             implementors.iter().partition::<Vec<_>, _>(|i| i.is_on_local_type(cx));
873
874         let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
875             local.iter().partition(|i| i.inner_impl().kind.is_auto());
876
877         synthetic.sort_by(|a, b| compare_impl(a, b, cx));
878         concrete.sort_by(|a, b| compare_impl(a, b, cx));
879
880         if !foreign.is_empty() {
881             write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
882
883             for implementor in foreign {
884                 let provided_methods = implementor.inner_impl().provided_trait_methods(cx.tcx());
885                 let assoc_link =
886                     AssocItemLink::GotoSource(implementor.impl_item.item_id, &provided_methods);
887                 render_impl(
888                     w,
889                     cx,
890                     implementor,
891                     it,
892                     assoc_link,
893                     RenderMode::Normal,
894                     None,
895                     &[],
896                     ImplRenderingParameters {
897                         show_def_docs: false,
898                         show_default_items: false,
899                         show_non_assoc_items: true,
900                         toggle_open_by_default: false,
901                     },
902                 );
903             }
904         }
905
906         write_small_section_header(
907             w,
908             "implementors",
909             "Implementors",
910             "<div id=\"implementors-list\">",
911         );
912         for implementor in concrete {
913             render_implementor(cx, implementor, it, w, &implementor_dups, &[]);
914         }
915         w.write_str("</div>");
916
917         if t.is_auto(cx.tcx()) {
918             write_small_section_header(
919                 w,
920                 "synthetic-implementors",
921                 "Auto implementors",
922                 "<div id=\"synthetic-implementors-list\">",
923             );
924             for implementor in synthetic {
925                 render_implementor(
926                     cx,
927                     implementor,
928                     it,
929                     w,
930                     &implementor_dups,
931                     &collect_paths_for_type(implementor.inner_impl().for_.clone(), cache),
932                 );
933             }
934             w.write_str("</div>");
935         }
936     } else {
937         // even without any implementations to write in, we still want the heading and list, so the
938         // implementors javascript file pulled in below has somewhere to write the impls into
939         write_small_section_header(
940             w,
941             "implementors",
942             "Implementors",
943             "<div id=\"implementors-list\"></div>",
944         );
945
946         if t.is_auto(cx.tcx()) {
947             write_small_section_header(
948                 w,
949                 "synthetic-implementors",
950                 "Auto implementors",
951                 "<div id=\"synthetic-implementors-list\"></div>",
952             );
953         }
954     }
955
956     // Include implementors in crates that depend on the current crate.
957     //
958     // This is complicated by the way rustdoc is invoked, which is basically
959     // the same way rustc is invoked: it gets called, one at a time, for each
960     // crate. When building the rustdocs for the current crate, rustdoc can
961     // see crate metadata for its dependencies, but cannot see metadata for its
962     // dependents.
963     //
964     // To make this work, we generate a "hook" at this stage, and our
965     // dependents can "plug in" to it when they build. For simplicity's sake,
966     // it's [JSONP]: a JavaScript file with the data we need (and can parse),
967     // surrounded by a tiny wrapper that the Rust side ignores, but allows the
968     // JavaScript side to include without having to worry about Same Origin
969     // Policy. The code for *that* is in `write_shared.rs`.
970     //
971     // This is further complicated by `#[doc(inline)]`. We want all copies
972     // of an inlined trait to reference the same JS file, to address complex
973     // dependency graphs like this one (lower crates depend on higher crates):
974     //
975     // ```text
976     //  --------------------------------------------
977     //  |            crate A: trait Foo            |
978     //  --------------------------------------------
979     //      |                               |
980     //  --------------------------------    |
981     //  | crate B: impl A::Foo for Bar |    |
982     //  --------------------------------    |
983     //      |                               |
984     //  ---------------------------------------------
985     //  | crate C: #[doc(inline)] use A::Foo as Baz |
986     //  |          impl Baz for Quux                |
987     //  ---------------------------------------------
988     // ```
989     //
990     // Basically, we want `C::Baz` and `A::Foo` to show the same set of
991     // impls, which is easier if they both treat `/implementors/A/trait.Foo.js`
992     // as the Single Source of Truth.
993     //
994     // We also want the `impl Baz for Quux` to be written to
995     // `trait.Foo.js`. However, when we generate plain HTML for `C::Baz`,
996     // we're going to want to generate plain HTML for `impl Baz for Quux` too,
997     // because that'll load faster, and it's better for SEO. And we don't want
998     // the same impl to show up twice on the same page.
999     //
1000     // To make this work, the implementors JS file has a structure kinda
1001     // like this:
1002     //
1003     // ```js
1004     // JSONP({
1005     // "B": {"impl A::Foo for Bar"},
1006     // "C": {"impl Baz for Quux"},
1007     // });
1008     // ```
1009     //
1010     // First of all, this means we can rebuild a crate, and it'll replace its own
1011     // data if something changes. That is, `rustdoc` is idempotent. The other
1012     // advantage is that we can list the crates that get included in the HTML,
1013     // and ignore them when doing the JavaScript-based part of rendering.
1014     // So C's HTML will have something like this:
1015     //
1016     // ```html
1017     // <script src="/implementors/A/trait.Foo.js"
1018     //     data-ignore-extern-crates="A,B" async></script>
1019     // ```
1020     //
1021     // And, when the JS runs, anything in data-ignore-extern-crates is known
1022     // to already be in the HTML, and will be ignored.
1023     //
1024     // [JSONP]: https://en.wikipedia.org/wiki/JSONP
1025     let mut js_src_path: UrlPartsBuilder = std::iter::repeat("..")
1026         .take(cx.current.len())
1027         .chain(std::iter::once("implementors"))
1028         .collect();
1029     if let Some(did) = it.item_id.as_def_id() &&
1030         let get_extern = { || cache.external_paths.get(&did).map(|s| s.0.clone()) } &&
1031         let Some(fqp) = cache.exact_paths.get(&did).cloned().or_else(get_extern) {
1032         js_src_path.extend(fqp[..fqp.len() - 1].iter().copied());
1033         js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), fqp.last().unwrap()));
1034     } else {
1035         js_src_path.extend(cx.current.iter().copied());
1036         js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), it.name.unwrap()));
1037     }
1038     let extern_crates = extern_crates
1039         .into_iter()
1040         .map(|cnum| tcx.crate_name(cnum).to_string())
1041         .collect::<Vec<_>>()
1042         .join(",");
1043     let (extern_before, extern_after) =
1044         if extern_crates.is_empty() { ("", "") } else { (" data-ignore-extern-crates=\"", "\"") };
1045     write!(
1046         w,
1047         "<script src=\"{src}\"{extern_before}{extern_crates}{extern_after} async></script>",
1048         src = js_src_path.finish(),
1049     );
1050 }
1051
1052 fn item_trait_alias(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::TraitAlias) {
1053     wrap_into_item_decl(w, |w| {
1054         wrap_item(w, "trait-alias", |w| {
1055             render_attributes_in_pre(w, it, "");
1056             write!(
1057                 w,
1058                 "trait {}{}{} = {};",
1059                 it.name.unwrap(),
1060                 t.generics.print(cx),
1061                 print_where_clause(&t.generics, cx, 0, Ending::Newline),
1062                 bounds(&t.bounds, true, cx)
1063             );
1064         });
1065     });
1066
1067     document(w, cx, it, None, HeadingOffset::H2);
1068
1069     // Render any items associated directly to this alias, as otherwise they
1070     // won't be visible anywhere in the docs. It would be nice to also show
1071     // associated items from the aliased type (see discussion in #32077), but
1072     // we need #14072 to make sense of the generics.
1073     render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1074 }
1075
1076 fn item_opaque_ty(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::OpaqueTy) {
1077     wrap_into_item_decl(w, |w| {
1078         wrap_item(w, "opaque", |w| {
1079             render_attributes_in_pre(w, it, "");
1080             write!(
1081                 w,
1082                 "type {}{}{where_clause} = impl {bounds};",
1083                 it.name.unwrap(),
1084                 t.generics.print(cx),
1085                 where_clause = print_where_clause(&t.generics, cx, 0, Ending::Newline),
1086                 bounds = bounds(&t.bounds, false, cx),
1087             );
1088         });
1089     });
1090
1091     document(w, cx, it, None, HeadingOffset::H2);
1092
1093     // Render any items associated directly to this alias, as otherwise they
1094     // won't be visible anywhere in the docs. It would be nice to also show
1095     // associated items from the aliased type (see discussion in #32077), but
1096     // we need #14072 to make sense of the generics.
1097     render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1098 }
1099
1100 fn item_typedef(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::Typedef) {
1101     fn write_content(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Typedef) {
1102         wrap_item(w, "typedef", |w| {
1103             render_attributes_in_pre(w, it, "");
1104             write!(w, "{}", visibility_print_with_space(it.visibility(cx.tcx()), it.item_id, cx));
1105             write!(
1106                 w,
1107                 "type {}{}{where_clause} = {type_};",
1108                 it.name.unwrap(),
1109                 t.generics.print(cx),
1110                 where_clause = print_where_clause(&t.generics, cx, 0, Ending::Newline),
1111                 type_ = t.type_.print(cx),
1112             );
1113         });
1114     }
1115
1116     wrap_into_item_decl(w, |w| write_content(w, cx, it, t));
1117
1118     document(w, cx, it, None, HeadingOffset::H2);
1119
1120     let def_id = it.item_id.expect_def_id();
1121     // Render any items associated directly to this alias, as otherwise they
1122     // won't be visible anywhere in the docs. It would be nice to also show
1123     // associated items from the aliased type (see discussion in #32077), but
1124     // we need #14072 to make sense of the generics.
1125     render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1126     document_type_layout(w, cx, def_id);
1127 }
1128
1129 fn item_union(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Union) {
1130     wrap_into_item_decl(w, |w| {
1131         wrap_item(w, "union", |w| {
1132             render_attributes_in_pre(w, it, "");
1133             render_union(w, it, Some(&s.generics), &s.fields, "", cx);
1134         });
1135     });
1136
1137     document(w, cx, it, None, HeadingOffset::H2);
1138
1139     let mut fields = s
1140         .fields
1141         .iter()
1142         .filter_map(|f| match *f.kind {
1143             clean::StructFieldItem(ref ty) => Some((f, ty)),
1144             _ => None,
1145         })
1146         .peekable();
1147     if fields.peek().is_some() {
1148         write!(
1149             w,
1150             "<h2 id=\"fields\" class=\"fields small-section-header\">\
1151                 Fields<a href=\"#fields\" class=\"anchor\">§</a>\
1152             </h2>"
1153         );
1154         for (field, ty) in fields {
1155             let name = field.name.expect("union field name");
1156             let id = format!("{}.{}", ItemType::StructField, name);
1157             write!(
1158                 w,
1159                 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
1160                      <a href=\"#{id}\" class=\"anchor field\">§</a>\
1161                      <code>{name}: {ty}</code>\
1162                  </span>",
1163                 id = id,
1164                 name = name,
1165                 shortty = ItemType::StructField,
1166                 ty = ty.print(cx),
1167             );
1168             if let Some(stability_class) = field.stability_class(cx.tcx()) {
1169                 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
1170             }
1171             document(w, cx, field, Some(it), HeadingOffset::H3);
1172         }
1173     }
1174     let def_id = it.item_id.expect_def_id();
1175     render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1176     document_type_layout(w, cx, def_id);
1177 }
1178
1179 fn print_tuple_struct_fields(w: &mut Buffer, cx: &Context<'_>, s: &[clean::Item]) {
1180     for (i, ty) in s.iter().enumerate() {
1181         if i > 0 {
1182             w.write_str(",&nbsp;");
1183         }
1184         match *ty.kind {
1185             clean::StrippedItem(box clean::StructFieldItem(_)) => w.write_str("_"),
1186             clean::StructFieldItem(ref ty) => write!(w, "{}", ty.print(cx)),
1187             _ => unreachable!(),
1188         }
1189     }
1190 }
1191
1192 fn item_enum(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, e: &clean::Enum) {
1193     let tcx = cx.tcx();
1194     let count_variants = e.variants().count();
1195     wrap_into_item_decl(w, |w| {
1196         wrap_item(w, "enum", |w| {
1197             render_attributes_in_pre(w, it, "");
1198             write!(
1199                 w,
1200                 "{}enum {}{}",
1201                 visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
1202                 it.name.unwrap(),
1203                 e.generics.print(cx),
1204             );
1205             if !print_where_clause_and_check(w, &e.generics, cx) {
1206                 // If there wasn't a `where` clause, we add a whitespace.
1207                 w.write_str(" ");
1208             }
1209
1210             let variants_stripped = e.has_stripped_entries();
1211             if count_variants == 0 && !variants_stripped {
1212                 w.write_str("{}");
1213             } else {
1214                 w.write_str("{\n");
1215                 let toggle = should_hide_fields(count_variants);
1216                 if toggle {
1217                     toggle_open(w, format_args!("{} variants", count_variants));
1218                 }
1219                 for v in e.variants() {
1220                     w.write_str("    ");
1221                     let name = v.name.unwrap();
1222                     match *v.kind {
1223                         // FIXME(#101337): Show discriminant
1224                         clean::VariantItem(ref var) => match var.kind {
1225                             clean::VariantKind::CLike => write!(w, "{}", name),
1226                             clean::VariantKind::Tuple(ref s) => {
1227                                 write!(w, "{}(", name);
1228                                 print_tuple_struct_fields(w, cx, s);
1229                                 w.write_str(")");
1230                             }
1231                             clean::VariantKind::Struct(ref s) => {
1232                                 render_struct(
1233                                     w,
1234                                     v,
1235                                     None,
1236                                     s.ctor_kind,
1237                                     &s.fields,
1238                                     "    ",
1239                                     false,
1240                                     cx,
1241                                 );
1242                             }
1243                         },
1244                         _ => unreachable!(),
1245                     }
1246                     w.write_str(",\n");
1247                 }
1248
1249                 if variants_stripped {
1250                     w.write_str("    // some variants omitted\n");
1251                 }
1252                 if toggle {
1253                     toggle_close(w);
1254                 }
1255                 w.write_str("}");
1256             }
1257         });
1258     });
1259
1260     document(w, cx, it, None, HeadingOffset::H2);
1261
1262     if count_variants != 0 {
1263         write!(
1264             w,
1265             "<h2 id=\"variants\" class=\"variants small-section-header\">\
1266                 Variants{}<a href=\"#variants\" class=\"anchor\">§</a>\
1267             </h2>",
1268             document_non_exhaustive_header(it)
1269         );
1270         document_non_exhaustive(w, it);
1271         write!(w, "<div class=\"variants\">");
1272         for variant in e.variants() {
1273             let id = cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.unwrap()));
1274             write!(
1275                 w,
1276                 "<section id=\"{id}\" class=\"variant\">\
1277                     <a href=\"#{id}\" class=\"anchor\">§</a>",
1278                 id = id,
1279             );
1280             render_stability_since_raw_with_extra(
1281                 w,
1282                 variant.stable_since(tcx),
1283                 variant.const_stability(tcx),
1284                 it.stable_since(tcx),
1285                 it.const_stable_since(tcx),
1286                 " rightside",
1287             );
1288             write!(w, "<h3 class=\"code-header\">{name}", name = variant.name.unwrap());
1289
1290             let clean::VariantItem(variant_data) = &*variant.kind else { unreachable!() };
1291
1292             if let clean::VariantKind::Tuple(ref s) = variant_data.kind {
1293                 w.write_str("(");
1294                 print_tuple_struct_fields(w, cx, s);
1295                 w.write_str(")");
1296             }
1297             w.write_str("</h3></section>");
1298
1299             let heading_and_fields = match &variant_data.kind {
1300                 clean::VariantKind::Struct(s) => Some(("Fields", &s.fields)),
1301                 clean::VariantKind::Tuple(fields) => {
1302                     // Documentation on tuple variant fields is rare, so to reduce noise we only emit
1303                     // the section if at least one field is documented.
1304                     if fields.iter().any(|f| f.doc_value().is_some()) {
1305                         Some(("Tuple Fields", fields))
1306                     } else {
1307                         None
1308                     }
1309                 }
1310                 clean::VariantKind::CLike => None,
1311             };
1312
1313             if let Some((heading, fields)) = heading_and_fields {
1314                 let variant_id =
1315                     cx.derive_id(format!("{}.{}.fields", ItemType::Variant, variant.name.unwrap()));
1316                 write!(w, "<div class=\"sub-variant\" id=\"{id}\">", id = variant_id);
1317                 write!(w, "<h4>{heading}</h4>", heading = heading);
1318                 document_non_exhaustive(w, variant);
1319                 for field in fields {
1320                     match *field.kind {
1321                         clean::StrippedItem(box clean::StructFieldItem(_)) => {}
1322                         clean::StructFieldItem(ref ty) => {
1323                             let id = cx.derive_id(format!(
1324                                 "variant.{}.field.{}",
1325                                 variant.name.unwrap(),
1326                                 field.name.unwrap()
1327                             ));
1328                             write!(
1329                                 w,
1330                                 "<div class=\"sub-variant-field\">\
1331                                  <span id=\"{id}\" class=\"small-section-header\">\
1332                                      <a href=\"#{id}\" class=\"anchor field\">§</a>\
1333                                      <code>{f}:&nbsp;{t}</code>\
1334                                  </span>",
1335                                 id = id,
1336                                 f = field.name.unwrap(),
1337                                 t = ty.print(cx)
1338                             );
1339                             document(w, cx, field, Some(variant), HeadingOffset::H5);
1340                             write!(w, "</div>");
1341                         }
1342                         _ => unreachable!(),
1343                     }
1344                 }
1345                 w.write_str("</div>");
1346             }
1347
1348             document(w, cx, variant, Some(it), HeadingOffset::H4);
1349         }
1350         write!(w, "</div>");
1351     }
1352     let def_id = it.item_id.expect_def_id();
1353     render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1354     document_type_layout(w, cx, def_id);
1355 }
1356
1357 fn item_macro(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::Macro) {
1358     wrap_into_item_decl(w, |w| {
1359         highlight::render_macro_with_highlighting(&t.source, w);
1360     });
1361     document(w, cx, it, None, HeadingOffset::H2)
1362 }
1363
1364 fn item_proc_macro(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, m: &clean::ProcMacro) {
1365     wrap_into_item_decl(w, |w| {
1366         let name = it.name.expect("proc-macros always have names");
1367         match m.kind {
1368             MacroKind::Bang => {
1369                 wrap_item(w, "macro", |w| {
1370                     write!(w, "{}!() {{ /* proc-macro */ }}", name);
1371                 });
1372             }
1373             MacroKind::Attr => {
1374                 wrap_item(w, "attr", |w| {
1375                     write!(w, "#[{}]", name);
1376                 });
1377             }
1378             MacroKind::Derive => {
1379                 wrap_item(w, "derive", |w| {
1380                     write!(w, "#[derive({})]", name);
1381                     if !m.helpers.is_empty() {
1382                         w.push_str("\n{\n");
1383                         w.push_str("    // Attributes available to this derive:\n");
1384                         for attr in &m.helpers {
1385                             writeln!(w, "    #[{}]", attr);
1386                         }
1387                         w.push_str("}\n");
1388                     }
1389                 });
1390             }
1391         }
1392     });
1393     document(w, cx, it, None, HeadingOffset::H2)
1394 }
1395
1396 fn item_primitive(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item) {
1397     let def_id = it.item_id.expect_def_id();
1398     document(w, cx, it, None, HeadingOffset::H2);
1399     if it.name.map(|n| n.as_str() != "reference").unwrap_or(false) {
1400         render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1401     } else {
1402         // We handle the "reference" primitive type on its own because we only want to list
1403         // implementations on generic types.
1404         let shared = Rc::clone(&cx.shared);
1405         let (concrete, synthetic, blanket_impl) = get_filtered_impls_for_reference(&shared, it);
1406
1407         render_all_impls(w, cx, it, &concrete, &synthetic, &blanket_impl);
1408     }
1409 }
1410
1411 fn item_constant(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, c: &clean::Constant) {
1412     wrap_into_item_decl(w, |w| {
1413         wrap_item(w, "const", |w| {
1414             let tcx = cx.tcx();
1415             render_attributes_in_code(w, it);
1416
1417             write!(
1418                 w,
1419                 "{vis}const {name}: {typ}",
1420                 vis = visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
1421                 name = it.name.unwrap(),
1422                 typ = c.type_.print(cx),
1423             );
1424
1425             // FIXME: The code below now prints
1426             //            ` = _; // 100i32`
1427             //        if the expression is
1428             //            `50 + 50`
1429             //        which looks just wrong.
1430             //        Should we print
1431             //            ` = 100i32;`
1432             //        instead?
1433
1434             let value = c.value(tcx);
1435             let is_literal = c.is_literal(tcx);
1436             let expr = c.expr(tcx);
1437             if value.is_some() || is_literal {
1438                 write!(w, " = {expr};", expr = Escape(&expr));
1439             } else {
1440                 w.write_str(";");
1441             }
1442
1443             if !is_literal {
1444                 if let Some(value) = &value {
1445                     let value_lowercase = value.to_lowercase();
1446                     let expr_lowercase = expr.to_lowercase();
1447
1448                     if value_lowercase != expr_lowercase
1449                         && value_lowercase.trim_end_matches("i32") != expr_lowercase
1450                     {
1451                         write!(w, " // {value}", value = Escape(value));
1452                     }
1453                 }
1454             }
1455         });
1456     });
1457
1458     document(w, cx, it, None, HeadingOffset::H2)
1459 }
1460
1461 fn item_struct(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Struct) {
1462     wrap_into_item_decl(w, |w| {
1463         wrap_item(w, "struct", |w| {
1464             render_attributes_in_code(w, it);
1465             render_struct(w, it, Some(&s.generics), s.ctor_kind, &s.fields, "", true, cx);
1466         });
1467     });
1468
1469     document(w, cx, it, None, HeadingOffset::H2);
1470
1471     let mut fields = s
1472         .fields
1473         .iter()
1474         .filter_map(|f| match *f.kind {
1475             clean::StructFieldItem(ref ty) => Some((f, ty)),
1476             _ => None,
1477         })
1478         .peekable();
1479     if let None | Some(CtorKind::Fn) = s.ctor_kind {
1480         if fields.peek().is_some() {
1481             write!(
1482                 w,
1483                 "<h2 id=\"fields\" class=\"fields small-section-header\">\
1484                      {}{}<a href=\"#fields\" class=\"anchor\">§</a>\
1485                  </h2>",
1486                 if s.ctor_kind.is_none() { "Fields" } else { "Tuple Fields" },
1487                 document_non_exhaustive_header(it)
1488             );
1489             document_non_exhaustive(w, it);
1490             for (index, (field, ty)) in fields.enumerate() {
1491                 let field_name =
1492                     field.name.map_or_else(|| index.to_string(), |sym| sym.as_str().to_string());
1493                 let id = cx.derive_id(format!("{}.{}", ItemType::StructField, field_name));
1494                 write!(
1495                     w,
1496                     "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
1497                          <a href=\"#{id}\" class=\"anchor field\">§</a>\
1498                          <code>{name}: {ty}</code>\
1499                      </span>",
1500                     item_type = ItemType::StructField,
1501                     id = id,
1502                     name = field_name,
1503                     ty = ty.print(cx)
1504                 );
1505                 document(w, cx, field, Some(it), HeadingOffset::H3);
1506             }
1507         }
1508     }
1509     let def_id = it.item_id.expect_def_id();
1510     render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1511     document_type_layout(w, cx, def_id);
1512 }
1513
1514 fn item_static(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Static) {
1515     wrap_into_item_decl(w, |w| {
1516         wrap_item(w, "static", |w| {
1517             render_attributes_in_code(w, it);
1518             write!(
1519                 w,
1520                 "{vis}static {mutability}{name}: {typ}",
1521                 vis = visibility_print_with_space(it.visibility(cx.tcx()), it.item_id, cx),
1522                 mutability = s.mutability.print_with_space(),
1523                 name = it.name.unwrap(),
1524                 typ = s.type_.print(cx)
1525             );
1526         });
1527     });
1528     document(w, cx, it, None, HeadingOffset::H2)
1529 }
1530
1531 fn item_foreign_type(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item) {
1532     wrap_into_item_decl(w, |w| {
1533         wrap_item(w, "foreigntype", |w| {
1534             w.write_str("extern {\n");
1535             render_attributes_in_code(w, it);
1536             write!(
1537                 w,
1538                 "    {}type {};\n}}",
1539                 visibility_print_with_space(it.visibility(cx.tcx()), it.item_id, cx),
1540                 it.name.unwrap(),
1541             );
1542         });
1543     });
1544
1545     document(w, cx, it, None, HeadingOffset::H2);
1546
1547     render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1548 }
1549
1550 fn item_keyword(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item) {
1551     document(w, cx, it, None, HeadingOffset::H2)
1552 }
1553
1554 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
1555 pub(crate) fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
1556     /// Takes a non-numeric and a numeric part from the given &str.
1557     fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
1558         let i = s.find(|c: char| c.is_ascii_digit());
1559         let (a, b) = s.split_at(i.unwrap_or(s.len()));
1560         let i = b.find(|c: char| !c.is_ascii_digit());
1561         let (b, c) = b.split_at(i.unwrap_or(b.len()));
1562         *s = c;
1563         (a, b)
1564     }
1565
1566     while !lhs.is_empty() || !rhs.is_empty() {
1567         let (la, lb) = take_parts(&mut lhs);
1568         let (ra, rb) = take_parts(&mut rhs);
1569         // First process the non-numeric part.
1570         match la.cmp(ra) {
1571             Ordering::Equal => (),
1572             x => return x,
1573         }
1574         // Then process the numeric part, if both sides have one (and they fit in a u64).
1575         if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
1576             match ln.cmp(&rn) {
1577                 Ordering::Equal => (),
1578                 x => return x,
1579             }
1580         }
1581         // Then process the numeric part again, but this time as strings.
1582         match lb.cmp(rb) {
1583             Ordering::Equal => (),
1584             x => return x,
1585         }
1586     }
1587
1588     Ordering::Equal
1589 }
1590
1591 pub(super) fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
1592     let mut s = join_with_double_colon(&cx.current);
1593     s.push_str("::");
1594     s.push_str(item.name.unwrap().as_str());
1595     s
1596 }
1597
1598 pub(super) fn item_path(ty: ItemType, name: &str) -> String {
1599     match ty {
1600         ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1601         _ => format!("{}.{}.html", ty, name),
1602     }
1603 }
1604
1605 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool, cx: &Context<'_>) -> String {
1606     let mut bounds = String::new();
1607     if !t_bounds.is_empty() {
1608         if !trait_alias {
1609             bounds.push_str(": ");
1610         }
1611         for (i, p) in t_bounds.iter().enumerate() {
1612             if i > 0 {
1613                 bounds.push_str(" + ");
1614             }
1615             bounds.push_str(&p.print(cx).to_string());
1616         }
1617     }
1618     bounds
1619 }
1620
1621 fn wrap_into_item_decl<F>(w: &mut Buffer, f: F)
1622 where
1623     F: FnOnce(&mut Buffer),
1624 {
1625     w.write_str("<div class=\"item-decl\">");
1626     f(w);
1627     w.write_str("</div>")
1628 }
1629
1630 fn wrap_item<F>(w: &mut Buffer, item_name: &str, f: F)
1631 where
1632     F: FnOnce(&mut Buffer),
1633 {
1634     w.write_fmt(format_args!("<pre class=\"rust {}\"><code>", item_name));
1635     f(w);
1636     w.write_str("</code></pre>");
1637 }
1638
1639 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl, cx: &Context<'_>) -> Ordering {
1640     let lhss = format!("{}", lhs.inner_impl().print(false, cx));
1641     let rhss = format!("{}", rhs.inner_impl().print(false, cx));
1642
1643     // lhs and rhs are formatted as HTML, which may be unnecessary
1644     compare_names(&lhss, &rhss)
1645 }
1646
1647 fn render_implementor(
1648     cx: &mut Context<'_>,
1649     implementor: &Impl,
1650     trait_: &clean::Item,
1651     w: &mut Buffer,
1652     implementor_dups: &FxHashMap<Symbol, (DefId, bool)>,
1653     aliases: &[String],
1654 ) {
1655     // If there's already another implementor that has the same abridged name, use the
1656     // full path, for example in `std::iter::ExactSizeIterator`
1657     let use_absolute = match implementor.inner_impl().for_ {
1658         clean::Type::Path { ref path, .. }
1659         | clean::BorrowedRef { type_: box clean::Type::Path { ref path, .. }, .. }
1660             if !path.is_assoc_ty() =>
1661         {
1662             implementor_dups[&path.last()].1
1663         }
1664         _ => false,
1665     };
1666     render_impl(
1667         w,
1668         cx,
1669         implementor,
1670         trait_,
1671         AssocItemLink::Anchor(None),
1672         RenderMode::Normal,
1673         Some(use_absolute),
1674         aliases,
1675         ImplRenderingParameters {
1676             show_def_docs: false,
1677             show_default_items: false,
1678             show_non_assoc_items: false,
1679             toggle_open_by_default: false,
1680         },
1681     );
1682 }
1683
1684 fn render_union(
1685     w: &mut Buffer,
1686     it: &clean::Item,
1687     g: Option<&clean::Generics>,
1688     fields: &[clean::Item],
1689     tab: &str,
1690     cx: &Context<'_>,
1691 ) {
1692     let tcx = cx.tcx();
1693     write!(
1694         w,
1695         "{}union {}",
1696         visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
1697         it.name.unwrap(),
1698     );
1699
1700     let where_displayed = g
1701         .map(|g| {
1702             write!(w, "{}", g.print(cx));
1703             print_where_clause_and_check(w, g, cx)
1704         })
1705         .unwrap_or(false);
1706
1707     // If there wasn't a `where` clause, we add a whitespace.
1708     if !where_displayed {
1709         w.write_str(" ");
1710     }
1711
1712     write!(w, "{{\n{}", tab);
1713     let count_fields =
1714         fields.iter().filter(|f| matches!(*f.kind, clean::StructFieldItem(..))).count();
1715     let toggle = should_hide_fields(count_fields);
1716     if toggle {
1717         toggle_open(w, format_args!("{} fields", count_fields));
1718     }
1719
1720     for field in fields {
1721         if let clean::StructFieldItem(ref ty) = *field.kind {
1722             write!(
1723                 w,
1724                 "    {}{}: {},\n{}",
1725                 visibility_print_with_space(field.visibility(tcx), field.item_id, cx),
1726                 field.name.unwrap(),
1727                 ty.print(cx),
1728                 tab
1729             );
1730         }
1731     }
1732
1733     if it.has_stripped_entries().unwrap() {
1734         write!(w, "    /* private fields */\n{}", tab);
1735     }
1736     if toggle {
1737         toggle_close(w);
1738     }
1739     w.write_str("}");
1740 }
1741
1742 fn render_struct(
1743     w: &mut Buffer,
1744     it: &clean::Item,
1745     g: Option<&clean::Generics>,
1746     ty: Option<CtorKind>,
1747     fields: &[clean::Item],
1748     tab: &str,
1749     structhead: bool,
1750     cx: &Context<'_>,
1751 ) {
1752     let tcx = cx.tcx();
1753     write!(
1754         w,
1755         "{}{}{}",
1756         visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
1757         if structhead { "struct " } else { "" },
1758         it.name.unwrap()
1759     );
1760     if let Some(g) = g {
1761         write!(w, "{}", g.print(cx))
1762     }
1763     match ty {
1764         None => {
1765             let where_diplayed = g.map(|g| print_where_clause_and_check(w, g, cx)).unwrap_or(false);
1766
1767             // If there wasn't a `where` clause, we add a whitespace.
1768             if !where_diplayed {
1769                 w.write_str(" {");
1770             } else {
1771                 w.write_str("{");
1772             }
1773             let count_fields =
1774                 fields.iter().filter(|f| matches!(*f.kind, clean::StructFieldItem(..))).count();
1775             let has_visible_fields = count_fields > 0;
1776             let toggle = should_hide_fields(count_fields);
1777             if toggle {
1778                 toggle_open(w, format_args!("{} fields", count_fields));
1779             }
1780             for field in fields {
1781                 if let clean::StructFieldItem(ref ty) = *field.kind {
1782                     write!(
1783                         w,
1784                         "\n{}    {}{}: {},",
1785                         tab,
1786                         visibility_print_with_space(field.visibility(tcx), field.item_id, cx),
1787                         field.name.unwrap(),
1788                         ty.print(cx),
1789                     );
1790                 }
1791             }
1792
1793             if has_visible_fields {
1794                 if it.has_stripped_entries().unwrap() {
1795                     write!(w, "\n{}    /* private fields */", tab);
1796                 }
1797                 write!(w, "\n{}", tab);
1798             } else if it.has_stripped_entries().unwrap() {
1799                 write!(w, " /* private fields */ ");
1800             }
1801             if toggle {
1802                 toggle_close(w);
1803             }
1804             w.write_str("}");
1805         }
1806         Some(CtorKind::Fn) => {
1807             w.write_str("(");
1808             for (i, field) in fields.iter().enumerate() {
1809                 if i > 0 {
1810                     w.write_str(", ");
1811                 }
1812                 match *field.kind {
1813                     clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
1814                     clean::StructFieldItem(ref ty) => {
1815                         write!(
1816                             w,
1817                             "{}{}",
1818                             visibility_print_with_space(field.visibility(tcx), field.item_id, cx),
1819                             ty.print(cx),
1820                         )
1821                     }
1822                     _ => unreachable!(),
1823                 }
1824             }
1825             w.write_str(")");
1826             if let Some(g) = g {
1827                 write!(w, "{}", print_where_clause(g, cx, 0, Ending::NoNewline));
1828             }
1829             // We only want a ";" when we are displaying a tuple struct, not a variant tuple struct.
1830             if structhead {
1831                 w.write_str(";");
1832             }
1833         }
1834         Some(CtorKind::Const) => {
1835             // Needed for PhantomData.
1836             if let Some(g) = g {
1837                 write!(w, "{}", print_where_clause(g, cx, 0, Ending::NoNewline));
1838             }
1839             w.write_str(";");
1840         }
1841     }
1842 }
1843
1844 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1845     if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1846 }
1847
1848 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1849     if item.is_non_exhaustive() {
1850         write!(
1851             w,
1852             "<details class=\"rustdoc-toggle non-exhaustive\">\
1853                  <summary class=\"hideme\"><span>{}</span></summary>\
1854                  <div class=\"docblock\">",
1855             {
1856                 if item.is_struct() {
1857                     "This struct is marked as non-exhaustive"
1858                 } else if item.is_enum() {
1859                     "This enum is marked as non-exhaustive"
1860                 } else if item.is_variant() {
1861                     "This variant is marked as non-exhaustive"
1862                 } else {
1863                     "This type is marked as non-exhaustive"
1864                 }
1865             }
1866         );
1867
1868         if item.is_struct() {
1869             w.write_str(
1870                 "Non-exhaustive structs could have additional fields added in future. \
1871                  Therefore, non-exhaustive structs cannot be constructed in external crates \
1872                  using the traditional <code>Struct { .. }</code> syntax; cannot be \
1873                  matched against without a wildcard <code>..</code>; and \
1874                  struct update syntax will not work.",
1875             );
1876         } else if item.is_enum() {
1877             w.write_str(
1878                 "Non-exhaustive enums could have additional variants added in future. \
1879                  Therefore, when matching against variants of non-exhaustive enums, an \
1880                  extra wildcard arm must be added to account for any future variants.",
1881             );
1882         } else if item.is_variant() {
1883             w.write_str(
1884                 "Non-exhaustive enum variants could have additional fields added in future. \
1885                  Therefore, non-exhaustive enum variants cannot be constructed in external \
1886                  crates and cannot be matched against.",
1887             );
1888         } else {
1889             w.write_str(
1890                 "This type will require a wildcard arm in any match statements or constructors.",
1891             );
1892         }
1893
1894         w.write_str("</div></details>");
1895     }
1896 }
1897
1898 fn document_type_layout(w: &mut Buffer, cx: &Context<'_>, ty_def_id: DefId) {
1899     fn write_size_of_layout(w: &mut Buffer, layout: &LayoutS<VariantIdx>, tag_size: u64) {
1900         if layout.abi.is_unsized() {
1901             write!(w, "(unsized)");
1902         } else {
1903             let bytes = layout.size.bytes() - tag_size;
1904             write!(w, "{size} byte{pl}", size = bytes, pl = if bytes == 1 { "" } else { "s" },);
1905         }
1906     }
1907
1908     if !cx.shared.show_type_layout {
1909         return;
1910     }
1911
1912     writeln!(
1913         w,
1914         "<h2 id=\"layout\" class=\"small-section-header\"> \
1915         Layout<a href=\"#layout\" class=\"anchor\">§</a></h2>"
1916     );
1917     writeln!(w, "<div class=\"docblock\">");
1918
1919     let tcx = cx.tcx();
1920     let param_env = tcx.param_env(ty_def_id);
1921     let ty = tcx.type_of(ty_def_id);
1922     match tcx.layout_of(param_env.and(ty)) {
1923         Ok(ty_layout) => {
1924             writeln!(
1925                 w,
1926                 "<div class=\"warning\"><p><strong>Note:</strong> Most layout information is \
1927                  <strong>completely unstable</strong> and may even differ between compilations. \
1928                  The only exception is types with certain <code>repr(...)</code> attributes. \
1929                  Please see the Rust Reference’s \
1930                  <a href=\"https://doc.rust-lang.org/reference/type-layout.html\">“Type Layout”</a> \
1931                  chapter for details on type layout guarantees.</p></div>"
1932             );
1933             w.write_str("<p><strong>Size:</strong> ");
1934             write_size_of_layout(w, &ty_layout.layout.0, 0);
1935             writeln!(w, "</p>");
1936             if let Variants::Multiple { variants, tag, tag_encoding, .. } =
1937                 &ty_layout.layout.variants()
1938             {
1939                 if !variants.is_empty() {
1940                     w.write_str(
1941                         "<p><strong>Size for each variant:</strong></p>\
1942                             <ul>",
1943                     );
1944
1945                     let Adt(adt, _) = ty_layout.ty.kind() else {
1946                         span_bug!(tcx.def_span(ty_def_id), "not an adt")
1947                     };
1948
1949                     let tag_size = if let TagEncoding::Niche { .. } = tag_encoding {
1950                         0
1951                     } else if let Primitive::Int(i, _) = tag.primitive() {
1952                         i.size().bytes()
1953                     } else {
1954                         span_bug!(tcx.def_span(ty_def_id), "tag is neither niche nor int")
1955                     };
1956
1957                     for (index, layout) in variants.iter_enumerated() {
1958                         let name = adt.variant(index).name;
1959                         write!(w, "<li><code>{name}</code>: ", name = name);
1960                         write_size_of_layout(w, layout, tag_size);
1961                         writeln!(w, "</li>");
1962                     }
1963                     w.write_str("</ul>");
1964                 }
1965             }
1966         }
1967         // This kind of layout error can occur with valid code, e.g. if you try to
1968         // get the layout of a generic type such as `Vec<T>`.
1969         Err(LayoutError::Unknown(_)) => {
1970             writeln!(
1971                 w,
1972                 "<p><strong>Note:</strong> Unable to compute type layout, \
1973                  possibly due to this type having generic parameters. \
1974                  Layout can only be computed for concrete, fully-instantiated types.</p>"
1975             );
1976         }
1977         // This kind of error probably can't happen with valid code, but we don't
1978         // want to panic and prevent the docs from building, so we just let the
1979         // user know that we couldn't compute the layout.
1980         Err(LayoutError::SizeOverflow(_)) => {
1981             writeln!(
1982                 w,
1983                 "<p><strong>Note:</strong> Encountered an error during type layout; \
1984                  the type was too big.</p>"
1985             );
1986         }
1987         Err(LayoutError::NormalizationFailure(_, _)) => {
1988             writeln!(
1989                 w,
1990                 "<p><strong>Note:</strong> Encountered an error during type layout; \
1991                 the type failed to be normalized.</p>"
1992             )
1993         }
1994     }
1995
1996     writeln!(w, "</div>");
1997 }
1998
1999 fn pluralize(count: usize) -> &'static str {
2000     if count > 1 { "s" } else { "" }
2001 }