]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/render/print_item.rs
Rollup merge of #107525 - RalfJung:pointee-info, r=eddyb
[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=\"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{add}{stab}\"{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{add}{stab}\">\
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 = [myitem.type_().to_string(), full_path(cx, myitem)]
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_item(w, |w| {
534         render_attributes_in_pre(w, it, "");
535         w.reserve(header_len);
536         write!(
537             w,
538             "{vis}{constness}{asyncness}{unsafety}{abi}fn \
539                 {name}{generics}{decl}{notable_traits}{where_clause}",
540             vis = visibility,
541             constness = constness,
542             asyncness = asyncness,
543             unsafety = unsafety,
544             abi = abi,
545             name = name,
546             generics = f.generics.print(cx),
547             where_clause = print_where_clause(&f.generics, cx, 0, Ending::Newline),
548             decl = f.decl.full_print(header_len, 0, cx),
549             notable_traits = notable_traits.unwrap_or_default(),
550         );
551     });
552     document(w, cx, it, None, HeadingOffset::H2);
553 }
554
555 fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::Trait) {
556     let tcx = cx.tcx();
557     let bounds = bounds(&t.bounds, false, cx);
558     let required_types = t.items.iter().filter(|m| m.is_ty_associated_type()).collect::<Vec<_>>();
559     let provided_types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
560     let required_consts = t.items.iter().filter(|m| m.is_ty_associated_const()).collect::<Vec<_>>();
561     let provided_consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
562     let required_methods = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
563     let provided_methods = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
564     let count_types = required_types.len() + provided_types.len();
565     let count_consts = required_consts.len() + provided_consts.len();
566     let count_methods = required_methods.len() + provided_methods.len();
567     let must_implement_one_of_functions = tcx.trait_def(t.def_id).must_implement_one_of.clone();
568
569     // Output the trait definition
570     wrap_item(w, |w| {
571         render_attributes_in_pre(w, it, "");
572         write!(
573             w,
574             "{}{}{}trait {}{}{}",
575             visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
576             t.unsafety(tcx).print_with_space(),
577             if t.is_auto(tcx) { "auto " } else { "" },
578             it.name.unwrap(),
579             t.generics.print(cx),
580             bounds
581         );
582
583         if !t.generics.where_predicates.is_empty() {
584             write!(w, "{}", print_where_clause(&t.generics, cx, 0, Ending::Newline));
585         } else {
586             w.write_str(" ");
587         }
588
589         if t.items.is_empty() {
590             w.write_str("{ }");
591         } else {
592             // FIXME: we should be using a derived_id for the Anchors here
593             w.write_str("{\n");
594             let mut toggle = false;
595
596             // If there are too many associated types, hide _everything_
597             if should_hide_fields(count_types) {
598                 toggle = true;
599                 toggle_open(
600                     w,
601                     format_args!("{} associated items", count_types + count_consts + count_methods),
602                 );
603             }
604             for types in [&required_types, &provided_types] {
605                 for t in types {
606                     render_assoc_item(
607                         w,
608                         t,
609                         AssocItemLink::Anchor(None),
610                         ItemType::Trait,
611                         cx,
612                         RenderMode::Normal,
613                     );
614                     w.write_str(";\n");
615                 }
616             }
617             // If there are too many associated constants, hide everything after them
618             // We also do this if the types + consts is large because otherwise we could
619             // render a bunch of types and _then_ a bunch of consts just because both were
620             // _just_ under the limit
621             if !toggle && should_hide_fields(count_types + count_consts) {
622                 toggle = true;
623                 toggle_open(
624                     w,
625                     format_args!(
626                         "{} associated constant{} and {} method{}",
627                         count_consts,
628                         pluralize(count_consts),
629                         count_methods,
630                         pluralize(count_methods),
631                     ),
632                 );
633             }
634             if count_types != 0 && (count_consts != 0 || count_methods != 0) {
635                 w.write_str("\n");
636             }
637             for consts in [&required_consts, &provided_consts] {
638                 for c in consts {
639                     render_assoc_item(
640                         w,
641                         c,
642                         AssocItemLink::Anchor(None),
643                         ItemType::Trait,
644                         cx,
645                         RenderMode::Normal,
646                     );
647                     w.write_str(";\n");
648                 }
649             }
650             if !toggle && should_hide_fields(count_methods) {
651                 toggle = true;
652                 toggle_open(w, format_args!("{} methods", count_methods));
653             }
654             if count_consts != 0 && count_methods != 0 {
655                 w.write_str("\n");
656             }
657             for (pos, m) in required_methods.iter().enumerate() {
658                 render_assoc_item(
659                     w,
660                     m,
661                     AssocItemLink::Anchor(None),
662                     ItemType::Trait,
663                     cx,
664                     RenderMode::Normal,
665                 );
666                 w.write_str(";\n");
667
668                 if pos < required_methods.len() - 1 {
669                     w.write_str("<span class=\"item-spacer\"></span>");
670                 }
671             }
672             if !required_methods.is_empty() && !provided_methods.is_empty() {
673                 w.write_str("\n");
674             }
675             for (pos, m) in provided_methods.iter().enumerate() {
676                 render_assoc_item(
677                     w,
678                     m,
679                     AssocItemLink::Anchor(None),
680                     ItemType::Trait,
681                     cx,
682                     RenderMode::Normal,
683                 );
684                 match *m.kind {
685                     clean::MethodItem(ref inner, _)
686                         if !inner.generics.where_predicates.is_empty() =>
687                     {
688                         w.write_str(",\n    { ... }\n");
689                     }
690                     _ => {
691                         w.write_str(" { ... }\n");
692                     }
693                 }
694
695                 if pos < provided_methods.len() - 1 {
696                     w.write_str("<span class=\"item-spacer\"></span>");
697                 }
698             }
699             if toggle {
700                 toggle_close(w);
701             }
702             w.write_str("}");
703         }
704     });
705
706     // Trait documentation
707     document(w, cx, it, None, HeadingOffset::H2);
708
709     fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
710         write!(
711             w,
712             "<h2 id=\"{0}\" class=\"small-section-header\">\
713                 {1}<a href=\"#{0}\" class=\"anchor\">§</a>\
714              </h2>{2}",
715             id, title, extra_content
716         )
717     }
718
719     fn trait_item(w: &mut Buffer, cx: &mut Context<'_>, m: &clean::Item, t: &clean::Item) {
720         let name = m.name.unwrap();
721         info!("Documenting {} on {:?}", name, t.name);
722         let item_type = m.type_();
723         let id = cx.derive_id(format!("{}.{}", item_type, name));
724         let mut content = Buffer::empty_from(w);
725         document(&mut content, cx, m, Some(t), HeadingOffset::H5);
726         let toggled = !content.is_empty();
727         if toggled {
728             let method_toggle_class = if item_type.is_method() { " method-toggle" } else { "" };
729             write!(w, "<details class=\"toggle{method_toggle_class}\" open><summary>");
730         }
731         write!(w, "<section id=\"{}\" class=\"method\">", id);
732         render_rightside(w, cx, m, t, RenderMode::Normal);
733         write!(w, "<h4 class=\"code-header\">");
734         render_assoc_item(
735             w,
736             m,
737             AssocItemLink::Anchor(Some(&id)),
738             ItemType::Impl,
739             cx,
740             RenderMode::Normal,
741         );
742         w.write_str("</h4>");
743         w.write_str("</section>");
744         if toggled {
745             write!(w, "</summary>");
746             w.push_buffer(content);
747             write!(w, "</details>");
748         }
749     }
750
751     if !required_types.is_empty() {
752         write_small_section_header(
753             w,
754             "required-associated-types",
755             "Required Associated Types",
756             "<div class=\"methods\">",
757         );
758         for t in required_types {
759             trait_item(w, cx, t, it);
760         }
761         w.write_str("</div>");
762     }
763     if !provided_types.is_empty() {
764         write_small_section_header(
765             w,
766             "provided-associated-types",
767             "Provided Associated Types",
768             "<div class=\"methods\">",
769         );
770         for t in provided_types {
771             trait_item(w, cx, t, it);
772         }
773         w.write_str("</div>");
774     }
775
776     if !required_consts.is_empty() {
777         write_small_section_header(
778             w,
779             "required-associated-consts",
780             "Required Associated Constants",
781             "<div class=\"methods\">",
782         );
783         for t in required_consts {
784             trait_item(w, cx, t, it);
785         }
786         w.write_str("</div>");
787     }
788     if !provided_consts.is_empty() {
789         write_small_section_header(
790             w,
791             "provided-associated-consts",
792             "Provided Associated Constants",
793             "<div class=\"methods\">",
794         );
795         for t in provided_consts {
796             trait_item(w, cx, t, it);
797         }
798         w.write_str("</div>");
799     }
800
801     // Output the documentation for each function individually
802     if !required_methods.is_empty() || must_implement_one_of_functions.is_some() {
803         write_small_section_header(
804             w,
805             "required-methods",
806             "Required Methods",
807             "<div class=\"methods\">",
808         );
809
810         if let Some(list) = must_implement_one_of_functions.as_deref() {
811             write!(
812                 w,
813                 "<div class=\"stab must_implement\">At least one of the `{}` methods is required.</div>",
814                 list.iter().join("`, `")
815             );
816         }
817
818         for m in required_methods {
819             trait_item(w, cx, m, it);
820         }
821         w.write_str("</div>");
822     }
823     if !provided_methods.is_empty() {
824         write_small_section_header(
825             w,
826             "provided-methods",
827             "Provided Methods",
828             "<div class=\"methods\">",
829         );
830         for m in provided_methods {
831             trait_item(w, cx, m, it);
832         }
833         w.write_str("</div>");
834     }
835
836     // If there are methods directly on this trait object, render them here.
837     render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All);
838
839     let cloned_shared = Rc::clone(&cx.shared);
840     let cache = &cloned_shared.cache;
841     let mut extern_crates = FxHashSet::default();
842     if let Some(implementors) = cache.implementors.get(&it.item_id.expect_def_id()) {
843         // The DefId is for the first Type found with that name. The bool is
844         // if any Types with the same name but different DefId have been found.
845         let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();
846         for implementor in implementors {
847             if let Some(did) = implementor.inner_impl().for_.without_borrowed_ref().def_id(cache) &&
848                 !did.is_local() {
849                 extern_crates.insert(did.krate);
850             }
851             match implementor.inner_impl().for_.without_borrowed_ref() {
852                 clean::Type::Path { ref path } if !path.is_assoc_ty() => {
853                     let did = path.def_id();
854                     let &mut (prev_did, ref mut has_duplicates) =
855                         implementor_dups.entry(path.last()).or_insert((did, false));
856                     if prev_did != did {
857                         *has_duplicates = true;
858                     }
859                 }
860                 _ => {}
861             }
862         }
863
864         let (local, foreign) =
865             implementors.iter().partition::<Vec<_>, _>(|i| i.is_on_local_type(cx));
866
867         let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
868             local.iter().partition(|i| i.inner_impl().kind.is_auto());
869
870         synthetic.sort_by(|a, b| compare_impl(a, b, cx));
871         concrete.sort_by(|a, b| compare_impl(a, b, cx));
872
873         if !foreign.is_empty() {
874             write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
875
876             for implementor in foreign {
877                 let provided_methods = implementor.inner_impl().provided_trait_methods(cx.tcx());
878                 let assoc_link =
879                     AssocItemLink::GotoSource(implementor.impl_item.item_id, &provided_methods);
880                 render_impl(
881                     w,
882                     cx,
883                     implementor,
884                     it,
885                     assoc_link,
886                     RenderMode::Normal,
887                     None,
888                     &[],
889                     ImplRenderingParameters {
890                         show_def_docs: false,
891                         show_default_items: false,
892                         show_non_assoc_items: true,
893                         toggle_open_by_default: false,
894                     },
895                 );
896             }
897         }
898
899         write_small_section_header(
900             w,
901             "implementors",
902             "Implementors",
903             "<div id=\"implementors-list\">",
904         );
905         for implementor in concrete {
906             render_implementor(cx, implementor, it, w, &implementor_dups, &[]);
907         }
908         w.write_str("</div>");
909
910         if t.is_auto(cx.tcx()) {
911             write_small_section_header(
912                 w,
913                 "synthetic-implementors",
914                 "Auto implementors",
915                 "<div id=\"synthetic-implementors-list\">",
916             );
917             for implementor in synthetic {
918                 render_implementor(
919                     cx,
920                     implementor,
921                     it,
922                     w,
923                     &implementor_dups,
924                     &collect_paths_for_type(implementor.inner_impl().for_.clone(), cache),
925                 );
926             }
927             w.write_str("</div>");
928         }
929     } else {
930         // even without any implementations to write in, we still want the heading and list, so the
931         // implementors javascript file pulled in below has somewhere to write the impls into
932         write_small_section_header(
933             w,
934             "implementors",
935             "Implementors",
936             "<div id=\"implementors-list\"></div>",
937         );
938
939         if t.is_auto(cx.tcx()) {
940             write_small_section_header(
941                 w,
942                 "synthetic-implementors",
943                 "Auto implementors",
944                 "<div id=\"synthetic-implementors-list\"></div>",
945             );
946         }
947     }
948
949     // Include implementors in crates that depend on the current crate.
950     //
951     // This is complicated by the way rustdoc is invoked, which is basically
952     // the same way rustc is invoked: it gets called, one at a time, for each
953     // crate. When building the rustdocs for the current crate, rustdoc can
954     // see crate metadata for its dependencies, but cannot see metadata for its
955     // dependents.
956     //
957     // To make this work, we generate a "hook" at this stage, and our
958     // dependents can "plug in" to it when they build. For simplicity's sake,
959     // it's [JSONP]: a JavaScript file with the data we need (and can parse),
960     // surrounded by a tiny wrapper that the Rust side ignores, but allows the
961     // JavaScript side to include without having to worry about Same Origin
962     // Policy. The code for *that* is in `write_shared.rs`.
963     //
964     // This is further complicated by `#[doc(inline)]`. We want all copies
965     // of an inlined trait to reference the same JS file, to address complex
966     // dependency graphs like this one (lower crates depend on higher crates):
967     //
968     // ```text
969     //  --------------------------------------------
970     //  |            crate A: trait Foo            |
971     //  --------------------------------------------
972     //      |                               |
973     //  --------------------------------    |
974     //  | crate B: impl A::Foo for Bar |    |
975     //  --------------------------------    |
976     //      |                               |
977     //  ---------------------------------------------
978     //  | crate C: #[doc(inline)] use A::Foo as Baz |
979     //  |          impl Baz for Quux                |
980     //  ---------------------------------------------
981     // ```
982     //
983     // Basically, we want `C::Baz` and `A::Foo` to show the same set of
984     // impls, which is easier if they both treat `/implementors/A/trait.Foo.js`
985     // as the Single Source of Truth.
986     //
987     // We also want the `impl Baz for Quux` to be written to
988     // `trait.Foo.js`. However, when we generate plain HTML for `C::Baz`,
989     // we're going to want to generate plain HTML for `impl Baz for Quux` too,
990     // because that'll load faster, and it's better for SEO. And we don't want
991     // the same impl to show up twice on the same page.
992     //
993     // To make this work, the implementors JS file has a structure kinda
994     // like this:
995     //
996     // ```js
997     // JSONP({
998     // "B": {"impl A::Foo for Bar"},
999     // "C": {"impl Baz for Quux"},
1000     // });
1001     // ```
1002     //
1003     // First of all, this means we can rebuild a crate, and it'll replace its own
1004     // data if something changes. That is, `rustdoc` is idempotent. The other
1005     // advantage is that we can list the crates that get included in the HTML,
1006     // and ignore them when doing the JavaScript-based part of rendering.
1007     // So C's HTML will have something like this:
1008     //
1009     // ```html
1010     // <script src="/implementors/A/trait.Foo.js"
1011     //     data-ignore-extern-crates="A,B" async></script>
1012     // ```
1013     //
1014     // And, when the JS runs, anything in data-ignore-extern-crates is known
1015     // to already be in the HTML, and will be ignored.
1016     //
1017     // [JSONP]: https://en.wikipedia.org/wiki/JSONP
1018     let mut js_src_path: UrlPartsBuilder = std::iter::repeat("..")
1019         .take(cx.current.len())
1020         .chain(std::iter::once("implementors"))
1021         .collect();
1022     if let Some(did) = it.item_id.as_def_id() &&
1023         let get_extern = { || cache.external_paths.get(&did).map(|s| &s.0) } &&
1024         let Some(fqp) = cache.exact_paths.get(&did).or_else(get_extern) {
1025         js_src_path.extend(fqp[..fqp.len() - 1].iter().copied());
1026         js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), fqp.last().unwrap()));
1027     } else {
1028         js_src_path.extend(cx.current.iter().copied());
1029         js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), it.name.unwrap()));
1030     }
1031     let extern_crates = extern_crates
1032         .into_iter()
1033         .map(|cnum| tcx.crate_name(cnum).to_string())
1034         .collect::<Vec<_>>()
1035         .join(",");
1036     let (extern_before, extern_after) =
1037         if extern_crates.is_empty() { ("", "") } else { (" data-ignore-extern-crates=\"", "\"") };
1038     write!(
1039         w,
1040         "<script src=\"{src}\"{extern_before}{extern_crates}{extern_after} async></script>",
1041         src = js_src_path.finish(),
1042     );
1043 }
1044
1045 fn item_trait_alias(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::TraitAlias) {
1046     wrap_item(w, |w| {
1047         render_attributes_in_pre(w, it, "");
1048         write!(
1049             w,
1050             "trait {}{}{} = {};",
1051             it.name.unwrap(),
1052             t.generics.print(cx),
1053             print_where_clause(&t.generics, cx, 0, Ending::Newline),
1054             bounds(&t.bounds, true, cx)
1055         );
1056     });
1057
1058     document(w, cx, it, None, HeadingOffset::H2);
1059
1060     // Render any items associated directly to this alias, as otherwise they
1061     // won't be visible anywhere in the docs. It would be nice to also show
1062     // associated items from the aliased type (see discussion in #32077), but
1063     // we need #14072 to make sense of the generics.
1064     render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1065 }
1066
1067 fn item_opaque_ty(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::OpaqueTy) {
1068     wrap_item(w, |w| {
1069         render_attributes_in_pre(w, it, "");
1070         write!(
1071             w,
1072             "type {}{}{where_clause} = impl {bounds};",
1073             it.name.unwrap(),
1074             t.generics.print(cx),
1075             where_clause = print_where_clause(&t.generics, cx, 0, Ending::Newline),
1076             bounds = bounds(&t.bounds, false, cx),
1077         );
1078     });
1079
1080     document(w, cx, it, None, HeadingOffset::H2);
1081
1082     // Render any items associated directly to this alias, as otherwise they
1083     // won't be visible anywhere in the docs. It would be nice to also show
1084     // associated items from the aliased type (see discussion in #32077), but
1085     // we need #14072 to make sense of the generics.
1086     render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1087 }
1088
1089 fn item_typedef(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::Typedef) {
1090     fn write_content(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Typedef) {
1091         wrap_item(w, |w| {
1092             render_attributes_in_pre(w, it, "");
1093             write!(w, "{}", visibility_print_with_space(it.visibility(cx.tcx()), it.item_id, cx));
1094             write!(
1095                 w,
1096                 "type {}{}{where_clause} = {type_};",
1097                 it.name.unwrap(),
1098                 t.generics.print(cx),
1099                 where_clause = print_where_clause(&t.generics, cx, 0, Ending::Newline),
1100                 type_ = t.type_.print(cx),
1101             );
1102         });
1103     }
1104
1105     write_content(w, cx, it, t);
1106
1107     document(w, cx, it, None, HeadingOffset::H2);
1108
1109     let def_id = it.item_id.expect_def_id();
1110     // Render any items associated directly to this alias, as otherwise they
1111     // won't be visible anywhere in the docs. It would be nice to also show
1112     // associated items from the aliased type (see discussion in #32077), but
1113     // we need #14072 to make sense of the generics.
1114     render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1115     document_type_layout(w, cx, def_id);
1116 }
1117
1118 fn item_union(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Union) {
1119     wrap_item(w, |w| {
1120         render_attributes_in_pre(w, it, "");
1121         render_union(w, it, Some(&s.generics), &s.fields, "", cx);
1122     });
1123
1124     document(w, cx, it, None, HeadingOffset::H2);
1125
1126     let mut fields = s
1127         .fields
1128         .iter()
1129         .filter_map(|f| match *f.kind {
1130             clean::StructFieldItem(ref ty) => Some((f, ty)),
1131             _ => None,
1132         })
1133         .peekable();
1134     if fields.peek().is_some() {
1135         write!(
1136             w,
1137             "<h2 id=\"fields\" class=\"fields small-section-header\">\
1138                 Fields<a href=\"#fields\" class=\"anchor\">§</a>\
1139             </h2>"
1140         );
1141         for (field, ty) in fields {
1142             let name = field.name.expect("union field name");
1143             let id = format!("{}.{}", ItemType::StructField, name);
1144             write!(
1145                 w,
1146                 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
1147                      <a href=\"#{id}\" class=\"anchor field\">§</a>\
1148                      <code>{name}: {ty}</code>\
1149                  </span>",
1150                 id = id,
1151                 name = name,
1152                 shortty = ItemType::StructField,
1153                 ty = ty.print(cx),
1154             );
1155             if let Some(stability_class) = field.stability_class(cx.tcx()) {
1156                 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
1157             }
1158             document(w, cx, field, Some(it), HeadingOffset::H3);
1159         }
1160     }
1161     let def_id = it.item_id.expect_def_id();
1162     render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1163     document_type_layout(w, cx, def_id);
1164 }
1165
1166 fn print_tuple_struct_fields(w: &mut Buffer, cx: &Context<'_>, s: &[clean::Item]) {
1167     for (i, ty) in s.iter().enumerate() {
1168         if i > 0 {
1169             w.write_str(",&nbsp;");
1170         }
1171         match *ty.kind {
1172             clean::StrippedItem(box clean::StructFieldItem(_)) => w.write_str("_"),
1173             clean::StructFieldItem(ref ty) => write!(w, "{}", ty.print(cx)),
1174             _ => unreachable!(),
1175         }
1176     }
1177 }
1178
1179 fn item_enum(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, e: &clean::Enum) {
1180     let tcx = cx.tcx();
1181     let count_variants = e.variants().count();
1182     wrap_item(w, |w| {
1183         render_attributes_in_pre(w, it, "");
1184         write!(
1185             w,
1186             "{}enum {}{}",
1187             visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
1188             it.name.unwrap(),
1189             e.generics.print(cx),
1190         );
1191         if !print_where_clause_and_check(w, &e.generics, cx) {
1192             // If there wasn't a `where` clause, we add a whitespace.
1193             w.write_str(" ");
1194         }
1195
1196         let variants_stripped = e.has_stripped_entries();
1197         if count_variants == 0 && !variants_stripped {
1198             w.write_str("{}");
1199         } else {
1200             w.write_str("{\n");
1201             let toggle = should_hide_fields(count_variants);
1202             if toggle {
1203                 toggle_open(w, format_args!("{} variants", count_variants));
1204             }
1205             for v in e.variants() {
1206                 w.write_str("    ");
1207                 let name = v.name.unwrap();
1208                 match *v.kind {
1209                     // FIXME(#101337): Show discriminant
1210                     clean::VariantItem(ref var) => match var.kind {
1211                         clean::VariantKind::CLike => write!(w, "{}", name),
1212                         clean::VariantKind::Tuple(ref s) => {
1213                             write!(w, "{}(", name);
1214                             print_tuple_struct_fields(w, cx, s);
1215                             w.write_str(")");
1216                         }
1217                         clean::VariantKind::Struct(ref s) => {
1218                             render_struct(w, v, None, None, &s.fields, "    ", false, cx);
1219                         }
1220                     },
1221                     _ => unreachable!(),
1222                 }
1223                 w.write_str(",\n");
1224             }
1225
1226             if variants_stripped {
1227                 w.write_str("    // some variants omitted\n");
1228             }
1229             if toggle {
1230                 toggle_close(w);
1231             }
1232             w.write_str("}");
1233         }
1234     });
1235
1236     document(w, cx, it, None, HeadingOffset::H2);
1237
1238     if count_variants != 0 {
1239         write!(
1240             w,
1241             "<h2 id=\"variants\" class=\"variants small-section-header\">\
1242                 Variants{}<a href=\"#variants\" class=\"anchor\">§</a>\
1243             </h2>",
1244             document_non_exhaustive_header(it)
1245         );
1246         document_non_exhaustive(w, it);
1247         write!(w, "<div class=\"variants\">");
1248         for variant in e.variants() {
1249             let id = cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.unwrap()));
1250             write!(
1251                 w,
1252                 "<section id=\"{id}\" class=\"variant\">\
1253                     <a href=\"#{id}\" class=\"anchor\">§</a>",
1254                 id = id,
1255             );
1256             render_stability_since_raw_with_extra(
1257                 w,
1258                 variant.stable_since(tcx),
1259                 variant.const_stability(tcx),
1260                 it.stable_since(tcx),
1261                 it.const_stable_since(tcx),
1262                 " rightside",
1263             );
1264             write!(w, "<h3 class=\"code-header\">{name}", name = variant.name.unwrap());
1265
1266             let clean::VariantItem(variant_data) = &*variant.kind else { unreachable!() };
1267
1268             if let clean::VariantKind::Tuple(ref s) = variant_data.kind {
1269                 w.write_str("(");
1270                 print_tuple_struct_fields(w, cx, s);
1271                 w.write_str(")");
1272             }
1273             w.write_str("</h3></section>");
1274
1275             let heading_and_fields = match &variant_data.kind {
1276                 clean::VariantKind::Struct(s) => Some(("Fields", &s.fields)),
1277                 clean::VariantKind::Tuple(fields) => {
1278                     // Documentation on tuple variant fields is rare, so to reduce noise we only emit
1279                     // the section if at least one field is documented.
1280                     if fields.iter().any(|f| f.doc_value().is_some()) {
1281                         Some(("Tuple Fields", fields))
1282                     } else {
1283                         None
1284                     }
1285                 }
1286                 clean::VariantKind::CLike => None,
1287             };
1288
1289             if let Some((heading, fields)) = heading_and_fields {
1290                 let variant_id =
1291                     cx.derive_id(format!("{}.{}.fields", ItemType::Variant, variant.name.unwrap()));
1292                 write!(w, "<div class=\"sub-variant\" id=\"{id}\">", id = variant_id);
1293                 write!(w, "<h4>{heading}</h4>", heading = heading);
1294                 document_non_exhaustive(w, variant);
1295                 for field in fields {
1296                     match *field.kind {
1297                         clean::StrippedItem(box clean::StructFieldItem(_)) => {}
1298                         clean::StructFieldItem(ref ty) => {
1299                             let id = cx.derive_id(format!(
1300                                 "variant.{}.field.{}",
1301                                 variant.name.unwrap(),
1302                                 field.name.unwrap()
1303                             ));
1304                             write!(
1305                                 w,
1306                                 "<div class=\"sub-variant-field\">\
1307                                  <span id=\"{id}\" class=\"small-section-header\">\
1308                                      <a href=\"#{id}\" class=\"anchor field\">§</a>\
1309                                      <code>{f}:&nbsp;{t}</code>\
1310                                  </span>",
1311                                 id = id,
1312                                 f = field.name.unwrap(),
1313                                 t = ty.print(cx)
1314                             );
1315                             document(w, cx, field, Some(variant), HeadingOffset::H5);
1316                             write!(w, "</div>");
1317                         }
1318                         _ => unreachable!(),
1319                     }
1320                 }
1321                 w.write_str("</div>");
1322             }
1323
1324             document(w, cx, variant, Some(it), HeadingOffset::H4);
1325         }
1326         write!(w, "</div>");
1327     }
1328     let def_id = it.item_id.expect_def_id();
1329     render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1330     document_type_layout(w, cx, def_id);
1331 }
1332
1333 fn item_macro(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::Macro) {
1334     highlight::render_item_decl_with_highlighting(&t.source, w);
1335     document(w, cx, it, None, HeadingOffset::H2)
1336 }
1337
1338 fn item_proc_macro(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, m: &clean::ProcMacro) {
1339     wrap_item(w, |w| {
1340         let name = it.name.expect("proc-macros always have names");
1341         match m.kind {
1342             MacroKind::Bang => {
1343                 write!(w, "{}!() {{ /* proc-macro */ }}", name);
1344             }
1345             MacroKind::Attr => {
1346                 write!(w, "#[{}]", name);
1347             }
1348             MacroKind::Derive => {
1349                 write!(w, "#[derive({})]", name);
1350                 if !m.helpers.is_empty() {
1351                     w.push_str("\n{\n");
1352                     w.push_str("    // Attributes available to this derive:\n");
1353                     for attr in &m.helpers {
1354                         writeln!(w, "    #[{}]", attr);
1355                     }
1356                     w.push_str("}\n");
1357                 }
1358             }
1359         }
1360     });
1361     document(w, cx, it, None, HeadingOffset::H2)
1362 }
1363
1364 fn item_primitive(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item) {
1365     let def_id = it.item_id.expect_def_id();
1366     document(w, cx, it, None, HeadingOffset::H2);
1367     if it.name.map(|n| n.as_str() != "reference").unwrap_or(false) {
1368         render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1369     } else {
1370         // We handle the "reference" primitive type on its own because we only want to list
1371         // implementations on generic types.
1372         let shared = Rc::clone(&cx.shared);
1373         let (concrete, synthetic, blanket_impl) = get_filtered_impls_for_reference(&shared, it);
1374
1375         render_all_impls(w, cx, it, &concrete, &synthetic, &blanket_impl);
1376     }
1377 }
1378
1379 fn item_constant(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, c: &clean::Constant) {
1380     wrap_item(w, |w| {
1381         let tcx = cx.tcx();
1382         render_attributes_in_code(w, it);
1383
1384         write!(
1385             w,
1386             "{vis}const {name}: {typ}",
1387             vis = visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
1388             name = it.name.unwrap(),
1389             typ = c.type_.print(cx),
1390         );
1391
1392         // FIXME: The code below now prints
1393         //            ` = _; // 100i32`
1394         //        if the expression is
1395         //            `50 + 50`
1396         //        which looks just wrong.
1397         //        Should we print
1398         //            ` = 100i32;`
1399         //        instead?
1400
1401         let value = c.value(tcx);
1402         let is_literal = c.is_literal(tcx);
1403         let expr = c.expr(tcx);
1404         if value.is_some() || is_literal {
1405             write!(w, " = {expr};", expr = Escape(&expr));
1406         } else {
1407             w.write_str(";");
1408         }
1409
1410         if !is_literal {
1411             if let Some(value) = &value {
1412                 let value_lowercase = value.to_lowercase();
1413                 let expr_lowercase = expr.to_lowercase();
1414
1415                 if value_lowercase != expr_lowercase
1416                     && value_lowercase.trim_end_matches("i32") != expr_lowercase
1417                 {
1418                     write!(w, " // {value}", value = Escape(value));
1419                 }
1420             }
1421         }
1422     });
1423
1424     document(w, cx, it, None, HeadingOffset::H2)
1425 }
1426
1427 fn item_struct(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Struct) {
1428     wrap_item(w, |w| {
1429         render_attributes_in_code(w, it);
1430         render_struct(w, it, Some(&s.generics), s.ctor_kind, &s.fields, "", true, cx);
1431     });
1432
1433     document(w, cx, it, None, HeadingOffset::H2);
1434
1435     let mut fields = s
1436         .fields
1437         .iter()
1438         .filter_map(|f| match *f.kind {
1439             clean::StructFieldItem(ref ty) => Some((f, ty)),
1440             _ => None,
1441         })
1442         .peekable();
1443     if let None | Some(CtorKind::Fn) = s.ctor_kind {
1444         if fields.peek().is_some() {
1445             write!(
1446                 w,
1447                 "<h2 id=\"fields\" class=\"fields small-section-header\">\
1448                      {}{}<a href=\"#fields\" class=\"anchor\">§</a>\
1449                  </h2>",
1450                 if s.ctor_kind.is_none() { "Fields" } else { "Tuple Fields" },
1451                 document_non_exhaustive_header(it)
1452             );
1453             document_non_exhaustive(w, it);
1454             for (index, (field, ty)) in fields.enumerate() {
1455                 let field_name =
1456                     field.name.map_or_else(|| index.to_string(), |sym| sym.as_str().to_string());
1457                 let id = cx.derive_id(format!("{}.{}", ItemType::StructField, field_name));
1458                 write!(
1459                     w,
1460                     "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
1461                          <a href=\"#{id}\" class=\"anchor field\">§</a>\
1462                          <code>{name}: {ty}</code>\
1463                      </span>",
1464                     item_type = ItemType::StructField,
1465                     id = id,
1466                     name = field_name,
1467                     ty = ty.print(cx)
1468                 );
1469                 document(w, cx, field, Some(it), HeadingOffset::H3);
1470             }
1471         }
1472     }
1473     let def_id = it.item_id.expect_def_id();
1474     render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1475     document_type_layout(w, cx, def_id);
1476 }
1477
1478 fn item_static(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Static) {
1479     wrap_item(w, |w| {
1480         render_attributes_in_code(w, it);
1481         write!(
1482             w,
1483             "{vis}static {mutability}{name}: {typ}",
1484             vis = visibility_print_with_space(it.visibility(cx.tcx()), it.item_id, cx),
1485             mutability = s.mutability.print_with_space(),
1486             name = it.name.unwrap(),
1487             typ = s.type_.print(cx)
1488         );
1489     });
1490     document(w, cx, it, None, HeadingOffset::H2)
1491 }
1492
1493 fn item_foreign_type(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item) {
1494     wrap_item(w, |w| {
1495         w.write_str("extern {\n");
1496         render_attributes_in_code(w, it);
1497         write!(
1498             w,
1499             "    {}type {};\n}}",
1500             visibility_print_with_space(it.visibility(cx.tcx()), it.item_id, cx),
1501             it.name.unwrap(),
1502         );
1503     });
1504
1505     document(w, cx, it, None, HeadingOffset::H2);
1506
1507     render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1508 }
1509
1510 fn item_keyword(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item) {
1511     document(w, cx, it, None, HeadingOffset::H2)
1512 }
1513
1514 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
1515 pub(crate) fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
1516     /// Takes a non-numeric and a numeric part from the given &str.
1517     fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
1518         let i = s.find(|c: char| c.is_ascii_digit());
1519         let (a, b) = s.split_at(i.unwrap_or(s.len()));
1520         let i = b.find(|c: char| !c.is_ascii_digit());
1521         let (b, c) = b.split_at(i.unwrap_or(b.len()));
1522         *s = c;
1523         (a, b)
1524     }
1525
1526     while !lhs.is_empty() || !rhs.is_empty() {
1527         let (la, lb) = take_parts(&mut lhs);
1528         let (ra, rb) = take_parts(&mut rhs);
1529         // First process the non-numeric part.
1530         match la.cmp(ra) {
1531             Ordering::Equal => (),
1532             x => return x,
1533         }
1534         // Then process the numeric part, if both sides have one (and they fit in a u64).
1535         if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
1536             match ln.cmp(&rn) {
1537                 Ordering::Equal => (),
1538                 x => return x,
1539             }
1540         }
1541         // Then process the numeric part again, but this time as strings.
1542         match lb.cmp(rb) {
1543             Ordering::Equal => (),
1544             x => return x,
1545         }
1546     }
1547
1548     Ordering::Equal
1549 }
1550
1551 pub(super) fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
1552     let mut s = join_with_double_colon(&cx.current);
1553     s.push_str("::");
1554     s.push_str(item.name.unwrap().as_str());
1555     s
1556 }
1557
1558 pub(super) fn item_path(ty: ItemType, name: &str) -> String {
1559     match ty {
1560         ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1561         _ => format!("{}.{}.html", ty, name),
1562     }
1563 }
1564
1565 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool, cx: &Context<'_>) -> String {
1566     let mut bounds = String::new();
1567     if !t_bounds.is_empty() {
1568         if !trait_alias {
1569             bounds.push_str(": ");
1570         }
1571         for (i, p) in t_bounds.iter().enumerate() {
1572             if i > 0 {
1573                 bounds.push_str(" + ");
1574             }
1575             bounds.push_str(&p.print(cx).to_string());
1576         }
1577     }
1578     bounds
1579 }
1580
1581 fn wrap_item<F>(w: &mut Buffer, f: F)
1582 where
1583     F: FnOnce(&mut Buffer),
1584 {
1585     w.write_str(r#"<pre class="rust item-decl"><code>"#);
1586     f(w);
1587     w.write_str("</code></pre>");
1588 }
1589
1590 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl, cx: &Context<'_>) -> Ordering {
1591     let lhss = format!("{}", lhs.inner_impl().print(false, cx));
1592     let rhss = format!("{}", rhs.inner_impl().print(false, cx));
1593
1594     // lhs and rhs are formatted as HTML, which may be unnecessary
1595     compare_names(&lhss, &rhss)
1596 }
1597
1598 fn render_implementor(
1599     cx: &mut Context<'_>,
1600     implementor: &Impl,
1601     trait_: &clean::Item,
1602     w: &mut Buffer,
1603     implementor_dups: &FxHashMap<Symbol, (DefId, bool)>,
1604     aliases: &[String],
1605 ) {
1606     // If there's already another implementor that has the same abridged name, use the
1607     // full path, for example in `std::iter::ExactSizeIterator`
1608     let use_absolute = match implementor.inner_impl().for_ {
1609         clean::Type::Path { ref path, .. }
1610         | clean::BorrowedRef { type_: box clean::Type::Path { ref path, .. }, .. }
1611             if !path.is_assoc_ty() =>
1612         {
1613             implementor_dups[&path.last()].1
1614         }
1615         _ => false,
1616     };
1617     render_impl(
1618         w,
1619         cx,
1620         implementor,
1621         trait_,
1622         AssocItemLink::Anchor(None),
1623         RenderMode::Normal,
1624         Some(use_absolute),
1625         aliases,
1626         ImplRenderingParameters {
1627             show_def_docs: false,
1628             show_default_items: false,
1629             show_non_assoc_items: false,
1630             toggle_open_by_default: false,
1631         },
1632     );
1633 }
1634
1635 fn render_union(
1636     w: &mut Buffer,
1637     it: &clean::Item,
1638     g: Option<&clean::Generics>,
1639     fields: &[clean::Item],
1640     tab: &str,
1641     cx: &Context<'_>,
1642 ) {
1643     let tcx = cx.tcx();
1644     write!(
1645         w,
1646         "{}union {}",
1647         visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
1648         it.name.unwrap(),
1649     );
1650
1651     let where_displayed = g
1652         .map(|g| {
1653             write!(w, "{}", g.print(cx));
1654             print_where_clause_and_check(w, g, cx)
1655         })
1656         .unwrap_or(false);
1657
1658     // If there wasn't a `where` clause, we add a whitespace.
1659     if !where_displayed {
1660         w.write_str(" ");
1661     }
1662
1663     write!(w, "{{\n{}", tab);
1664     let count_fields =
1665         fields.iter().filter(|f| matches!(*f.kind, clean::StructFieldItem(..))).count();
1666     let toggle = should_hide_fields(count_fields);
1667     if toggle {
1668         toggle_open(w, format_args!("{} fields", count_fields));
1669     }
1670
1671     for field in fields {
1672         if let clean::StructFieldItem(ref ty) = *field.kind {
1673             write!(
1674                 w,
1675                 "    {}{}: {},\n{}",
1676                 visibility_print_with_space(field.visibility(tcx), field.item_id, cx),
1677                 field.name.unwrap(),
1678                 ty.print(cx),
1679                 tab
1680             );
1681         }
1682     }
1683
1684     if it.has_stripped_entries().unwrap() {
1685         write!(w, "    /* private fields */\n{}", tab);
1686     }
1687     if toggle {
1688         toggle_close(w);
1689     }
1690     w.write_str("}");
1691 }
1692
1693 fn render_struct(
1694     w: &mut Buffer,
1695     it: &clean::Item,
1696     g: Option<&clean::Generics>,
1697     ty: Option<CtorKind>,
1698     fields: &[clean::Item],
1699     tab: &str,
1700     structhead: bool,
1701     cx: &Context<'_>,
1702 ) {
1703     let tcx = cx.tcx();
1704     write!(
1705         w,
1706         "{}{}{}",
1707         visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
1708         if structhead { "struct " } else { "" },
1709         it.name.unwrap()
1710     );
1711     if let Some(g) = g {
1712         write!(w, "{}", g.print(cx))
1713     }
1714     match ty {
1715         None => {
1716             let where_diplayed = g.map(|g| print_where_clause_and_check(w, g, cx)).unwrap_or(false);
1717
1718             // If there wasn't a `where` clause, we add a whitespace.
1719             if !where_diplayed {
1720                 w.write_str(" {");
1721             } else {
1722                 w.write_str("{");
1723             }
1724             let count_fields =
1725                 fields.iter().filter(|f| matches!(*f.kind, clean::StructFieldItem(..))).count();
1726             let has_visible_fields = count_fields > 0;
1727             let toggle = should_hide_fields(count_fields);
1728             if toggle {
1729                 toggle_open(w, format_args!("{} fields", count_fields));
1730             }
1731             for field in fields {
1732                 if let clean::StructFieldItem(ref ty) = *field.kind {
1733                     write!(
1734                         w,
1735                         "\n{}    {}{}: {},",
1736                         tab,
1737                         visibility_print_with_space(field.visibility(tcx), field.item_id, cx),
1738                         field.name.unwrap(),
1739                         ty.print(cx),
1740                     );
1741                 }
1742             }
1743
1744             if has_visible_fields {
1745                 if it.has_stripped_entries().unwrap() {
1746                     write!(w, "\n{}    /* private fields */", tab);
1747                 }
1748                 write!(w, "\n{}", tab);
1749             } else if it.has_stripped_entries().unwrap() {
1750                 write!(w, " /* private fields */ ");
1751             }
1752             if toggle {
1753                 toggle_close(w);
1754             }
1755             w.write_str("}");
1756         }
1757         Some(CtorKind::Fn) => {
1758             w.write_str("(");
1759             for (i, field) in fields.iter().enumerate() {
1760                 if i > 0 {
1761                     w.write_str(", ");
1762                 }
1763                 match *field.kind {
1764                     clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
1765                     clean::StructFieldItem(ref ty) => {
1766                         write!(
1767                             w,
1768                             "{}{}",
1769                             visibility_print_with_space(field.visibility(tcx), field.item_id, cx),
1770                             ty.print(cx),
1771                         )
1772                     }
1773                     _ => unreachable!(),
1774                 }
1775             }
1776             w.write_str(")");
1777             if let Some(g) = g {
1778                 write!(w, "{}", print_where_clause(g, cx, 0, Ending::NoNewline));
1779             }
1780             // We only want a ";" when we are displaying a tuple struct, not a variant tuple struct.
1781             if structhead {
1782                 w.write_str(";");
1783             }
1784         }
1785         Some(CtorKind::Const) => {
1786             // Needed for PhantomData.
1787             if let Some(g) = g {
1788                 write!(w, "{}", print_where_clause(g, cx, 0, Ending::NoNewline));
1789             }
1790             w.write_str(";");
1791         }
1792     }
1793 }
1794
1795 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1796     if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1797 }
1798
1799 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1800     if item.is_non_exhaustive() {
1801         write!(
1802             w,
1803             "<details class=\"toggle non-exhaustive\">\
1804                  <summary class=\"hideme\"><span>{}</span></summary>\
1805                  <div class=\"docblock\">",
1806             {
1807                 if item.is_struct() {
1808                     "This struct is marked as non-exhaustive"
1809                 } else if item.is_enum() {
1810                     "This enum is marked as non-exhaustive"
1811                 } else if item.is_variant() {
1812                     "This variant is marked as non-exhaustive"
1813                 } else {
1814                     "This type is marked as non-exhaustive"
1815                 }
1816             }
1817         );
1818
1819         if item.is_struct() {
1820             w.write_str(
1821                 "Non-exhaustive structs could have additional fields added in future. \
1822                  Therefore, non-exhaustive structs cannot be constructed in external crates \
1823                  using the traditional <code>Struct { .. }</code> syntax; cannot be \
1824                  matched against without a wildcard <code>..</code>; and \
1825                  struct update syntax will not work.",
1826             );
1827         } else if item.is_enum() {
1828             w.write_str(
1829                 "Non-exhaustive enums could have additional variants added in future. \
1830                  Therefore, when matching against variants of non-exhaustive enums, an \
1831                  extra wildcard arm must be added to account for any future variants.",
1832             );
1833         } else if item.is_variant() {
1834             w.write_str(
1835                 "Non-exhaustive enum variants could have additional fields added in future. \
1836                  Therefore, non-exhaustive enum variants cannot be constructed in external \
1837                  crates and cannot be matched against.",
1838             );
1839         } else {
1840             w.write_str(
1841                 "This type will require a wildcard arm in any match statements or constructors.",
1842             );
1843         }
1844
1845         w.write_str("</div></details>");
1846     }
1847 }
1848
1849 fn document_type_layout(w: &mut Buffer, cx: &Context<'_>, ty_def_id: DefId) {
1850     fn write_size_of_layout(w: &mut Buffer, layout: &LayoutS<VariantIdx>, tag_size: u64) {
1851         if layout.abi.is_unsized() {
1852             write!(w, "(unsized)");
1853         } else {
1854             let bytes = layout.size.bytes() - tag_size;
1855             write!(w, "{size} byte{pl}", size = bytes, pl = if bytes == 1 { "" } else { "s" },);
1856         }
1857     }
1858
1859     if !cx.shared.show_type_layout {
1860         return;
1861     }
1862
1863     writeln!(
1864         w,
1865         "<h2 id=\"layout\" class=\"small-section-header\"> \
1866         Layout<a href=\"#layout\" class=\"anchor\">§</a></h2>"
1867     );
1868     writeln!(w, "<div class=\"docblock\">");
1869
1870     let tcx = cx.tcx();
1871     let param_env = tcx.param_env(ty_def_id);
1872     let ty = tcx.type_of(ty_def_id);
1873     match tcx.layout_of(param_env.and(ty)) {
1874         Ok(ty_layout) => {
1875             writeln!(
1876                 w,
1877                 "<div class=\"warning\"><p><strong>Note:</strong> Most layout information is \
1878                  <strong>completely unstable</strong> and may even differ between compilations. \
1879                  The only exception is types with certain <code>repr(...)</code> attributes. \
1880                  Please see the Rust Reference’s \
1881                  <a href=\"https://doc.rust-lang.org/reference/type-layout.html\">“Type Layout”</a> \
1882                  chapter for details on type layout guarantees.</p></div>"
1883             );
1884             w.write_str("<p><strong>Size:</strong> ");
1885             write_size_of_layout(w, &ty_layout.layout.0, 0);
1886             writeln!(w, "</p>");
1887             if let Variants::Multiple { variants, tag, tag_encoding, .. } =
1888                 &ty_layout.layout.variants()
1889             {
1890                 if !variants.is_empty() {
1891                     w.write_str(
1892                         "<p><strong>Size for each variant:</strong></p>\
1893                             <ul>",
1894                     );
1895
1896                     let Adt(adt, _) = ty_layout.ty.kind() else {
1897                         span_bug!(tcx.def_span(ty_def_id), "not an adt")
1898                     };
1899
1900                     let tag_size = if let TagEncoding::Niche { .. } = tag_encoding {
1901                         0
1902                     } else if let Primitive::Int(i, _) = tag.primitive() {
1903                         i.size().bytes()
1904                     } else {
1905                         span_bug!(tcx.def_span(ty_def_id), "tag is neither niche nor int")
1906                     };
1907
1908                     for (index, layout) in variants.iter_enumerated() {
1909                         let name = adt.variant(index).name;
1910                         write!(w, "<li><code>{name}</code>: ", name = name);
1911                         write_size_of_layout(w, layout, tag_size);
1912                         writeln!(w, "</li>");
1913                     }
1914                     w.write_str("</ul>");
1915                 }
1916             }
1917         }
1918         // This kind of layout error can occur with valid code, e.g. if you try to
1919         // get the layout of a generic type such as `Vec<T>`.
1920         Err(LayoutError::Unknown(_)) => {
1921             writeln!(
1922                 w,
1923                 "<p><strong>Note:</strong> Unable to compute type layout, \
1924                  possibly due to this type having generic parameters. \
1925                  Layout can only be computed for concrete, fully-instantiated types.</p>"
1926             );
1927         }
1928         // This kind of error probably can't happen with valid code, but we don't
1929         // want to panic and prevent the docs from building, so we just let the
1930         // user know that we couldn't compute the layout.
1931         Err(LayoutError::SizeOverflow(_)) => {
1932             writeln!(
1933                 w,
1934                 "<p><strong>Note:</strong> Encountered an error during type layout; \
1935                  the type was too big.</p>"
1936             );
1937         }
1938         Err(LayoutError::NormalizationFailure(_, _)) => {
1939             writeln!(
1940                 w,
1941                 "<p><strong>Note:</strong> Encountered an error during type layout; \
1942                 the type failed to be normalized.</p>"
1943             )
1944         }
1945     }
1946
1947     writeln!(w, "</div>");
1948 }
1949
1950 fn pluralize(count: usize) -> &'static str {
1951     if count > 1 { "s" } else { "" }
1952 }