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