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