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