1 use clean::AttributesExt;
3 use std::cmp::Ordering;
6 use rustc_data_structures::fx::FxHashMap;
8 use rustc_hir::def::CtorKind;
9 use rustc_hir::def_id::DefId;
10 use rustc_middle::middle::stability;
11 use rustc_middle::span_bug;
12 use rustc_middle::ty::layout::LayoutError;
13 use rustc_middle::ty::{Adt, TyCtxt};
14 use rustc_span::hygiene::MacroKind;
15 use rustc_span::symbol::{kw, sym, Symbol};
16 use rustc_target::abi::{Layout, Primitive, TagEncoding, Variants};
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,
25 use crate::formats::item_type::ItemType;
26 use crate::formats::{AssocItemRender, Impl, RenderMode};
27 use crate::html::escape::Escape;
28 use crate::html::format::{
29 join_with_double_colon, print_abi_with_space, print_constness_with_space, print_where_clause,
30 Buffer, PrintWithSpace,
32 use crate::html::highlight;
33 use crate::html::layout::Page;
34 use crate::html::markdown::{HeadingOffset, MarkdownSummaryLine};
35 use crate::html::url_parts_builder::UrlPartsBuilder;
39 const ITEM_TABLE_OPEN: &str = "<div class=\"item-table\">";
40 const ITEM_TABLE_CLOSE: &str = "</div>";
41 const ITEM_TABLE_ROW_OPEN: &str = "<div class=\"item-row\">";
42 const ITEM_TABLE_ROW_CLOSE: &str = "</div>";
44 // A component in a `use` path, like `string` in std::string::ToString
45 struct PathComponent {
51 #[template(path = "print_item.html")]
54 static_root_path: &'a str,
58 path_components: Vec<PathComponent>,
59 stability_since_raw: &'a str,
60 src_href: Option<&'a str>,
63 pub(super) fn print_item(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer, page: &Page<'_>) {
64 debug_assert!(!item.is_stripped());
65 let typ = match *item.kind {
66 clean::ModuleItem(_) => {
73 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
74 clean::TraitItem(..) => "Trait ",
75 clean::StructItem(..) => "Struct ",
76 clean::UnionItem(..) => "Union ",
77 clean::EnumItem(..) => "Enum ",
78 clean::TypedefItem(..) => "Type Definition ",
79 clean::MacroItem(..) => "Macro ",
80 clean::ProcMacroItem(ref mac) => match mac.kind {
81 MacroKind::Bang => "Macro ",
82 MacroKind::Attr => "Attribute Macro ",
83 MacroKind::Derive => "Derive Macro ",
85 clean::PrimitiveItem(..) => "Primitive Type ",
86 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
87 clean::ConstantItem(..) => "Constant ",
88 clean::ForeignTypeItem => "Foreign Type ",
89 clean::KeywordItem(..) => "Keyword ",
90 clean::OpaqueTyItem(..) => "Opaque Type ",
91 clean::TraitAliasItem(..) => "Trait Alias ",
93 // We don't generate pages for any other type.
97 let mut stability_since_raw = Buffer::new();
98 render_stability_since_raw(
99 &mut stability_since_raw,
100 item.stable_since(cx.tcx()),
101 item.const_stability(cx.tcx()),
105 let stability_since_raw: String = stability_since_raw.into_inner();
109 // When this item is part of a `crate use` in a downstream crate, the
110 // source link in the downstream documentation will actually come back to
111 // this page, and this link will be auto-clicked. The `id` attribute is
112 // used to find the link to auto-click.
114 if cx.include_sources && !item.is_primitive() { cx.src_href(item) } else { None };
116 let path_components = if item.is_primitive() || item.is_keyword() {
119 let cur = &cx.current;
120 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
124 .map(|(i, component)| PathComponent {
125 path: "../".repeat(cur.len() - i - 1),
131 let item_vars = ItemVars {
133 static_root_path: page.get_static_root_path(),
135 name: item.name.as_ref().unwrap().as_str(),
136 item_type: &item.type_().to_string(),
138 stability_since_raw: &stability_since_raw,
139 src_href: src_href.as_deref(),
142 item_vars.render_into(buf).unwrap();
145 clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
146 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
147 item_function(buf, cx, item, f)
149 clean::TraitItem(ref t) => item_trait(buf, cx, item, t),
150 clean::StructItem(ref s) => item_struct(buf, cx, item, s),
151 clean::UnionItem(ref s) => item_union(buf, cx, item, s),
152 clean::EnumItem(ref e) => item_enum(buf, cx, item, e),
153 clean::TypedefItem(ref t, is_associated) => item_typedef(buf, cx, item, t, is_associated),
154 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
155 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
156 clean::PrimitiveItem(_) => item_primitive(buf, cx, item),
157 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
158 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
159 clean::ForeignTypeItem => item_foreign_type(buf, cx, item),
160 clean::KeywordItem(_) => item_keyword(buf, cx, item),
161 clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e),
162 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta),
164 // We don't generate pages for any other type.
170 /// For large structs, enums, unions, etc, determine whether to hide their fields
171 fn should_hide_fields(n_fields: usize) -> bool {
175 fn toggle_open(w: &mut Buffer, text: impl fmt::Display) {
178 "<details class=\"rustdoc-toggle type-contents-toggle\">\
179 <summary class=\"hideme\">\
180 <span>Show {}</span>\
186 fn toggle_close(w: &mut Buffer) {
187 w.write_str("</details>");
190 fn item_module(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, items: &[clean::Item]) {
191 document(w, cx, item, None, HeadingOffset::H2);
193 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
195 // the order of item types in the listing
196 fn reorder(ty: ItemType) -> u8 {
198 ItemType::ExternCrate => 0,
199 ItemType::Import => 1,
200 ItemType::Primitive => 2,
201 ItemType::Module => 3,
202 ItemType::Macro => 4,
203 ItemType::Struct => 5,
205 ItemType::Constant => 7,
206 ItemType::Static => 8,
207 ItemType::Trait => 9,
208 ItemType::Function => 10,
209 ItemType::Typedef => 12,
210 ItemType::Union => 13,
222 let ty1 = i1.type_();
223 let ty2 = i2.type_();
224 if item_ty_to_section(ty1) != item_ty_to_section(ty2)
225 || (ty1 != ty2 && (ty1 == ItemType::ExternCrate || ty2 == ItemType::ExternCrate))
227 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
229 let s1 = i1.stability(tcx).as_ref().map(|s| s.level);
230 let s2 = i2.stability(tcx).as_ref().map(|s| s.level);
231 if let (Some(a), Some(b)) = (s1, s2) {
232 match (a.is_stable(), b.is_stable()) {
233 (true, true) | (false, false) => {}
234 (false, true) => return Ordering::Less,
235 (true, false) => return Ordering::Greater,
238 let lhs = i1.name.unwrap_or(kw::Empty);
239 let rhs = i2.name.unwrap_or(kw::Empty);
240 compare_names(lhs.as_str(), rhs.as_str())
243 if cx.shared.sort_modules_alphabetically {
244 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2, cx.tcx()));
246 // This call is to remove re-export duplicates in cases such as:
251 // crate trait Double { fn foo(); }
255 // crate use foo::bar::*;
259 // `Double` will appear twice in the generated docs.
261 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
262 // can be identical even if the elements are different (mostly in imports).
263 // So in case this is an import, we keep everything by adding a "unique id"
264 // (which is the position in the vector).
265 indices.dedup_by_key(|i| {
268 if items[*i].name.is_some() { Some(full_path(cx, &items[*i])) } else { None },
270 if items[*i].is_import() { *i } else { 0 },
274 debug!("{:?}", indices);
275 let mut last_section = None;
277 for &idx in &indices {
278 let myitem = &items[idx];
279 if myitem.is_stripped() {
283 let my_section = item_ty_to_section(myitem.type_());
284 if Some(my_section) != last_section {
285 if last_section.is_some() {
286 w.write_str(ITEM_TABLE_CLOSE);
288 last_section = Some(my_section);
291 "<h2 id=\"{id}\" class=\"small-section-header\">\
292 <a href=\"#{id}\">{name}</a>\
295 id = cx.derive_id(my_section.id().to_owned()),
296 name = my_section.name(),
301 clean::ExternCrateItem { ref src } => {
302 use crate::html::format::anchor;
304 w.write_str(ITEM_TABLE_ROW_OPEN);
308 "<div class=\"item-left\"><code>{}extern crate {} as {};",
309 myitem.visibility.print_with_space(myitem.def_id, cx),
310 anchor(myitem.def_id.expect_def_id(), src, cx),
311 myitem.name.unwrap(),
315 "<div class=\"item-left\"><code>{}extern crate {};",
316 myitem.visibility.print_with_space(myitem.def_id, cx),
317 anchor(myitem.def_id.expect_def_id(), myitem.name.unwrap(), cx),
320 w.write_str("</code></div>");
321 w.write_str(ITEM_TABLE_ROW_CLOSE);
324 clean::ImportItem(ref import) => {
325 let (stab, stab_tags) = if let Some(import_def_id) = import.source.did {
326 let ast_attrs = cx.tcx().get_attrs(import_def_id);
327 let import_attrs = Box::new(clean::Attributes::from_ast(ast_attrs, None));
329 // Just need an item with the correct def_id and attrs
330 let import_item = clean::Item {
331 def_id: import_def_id.into(),
333 cfg: ast_attrs.cfg(cx.tcx(), &cx.cache().hidden_cfg),
337 let stab = import_item.stability_class(cx.tcx());
338 let stab_tags = Some(extra_info_tags(&import_item, item, cx.tcx()));
344 let add = if stab.is_some() { " " } else { "" };
346 w.write_str(ITEM_TABLE_ROW_OPEN);
349 "<div class=\"item-left {stab}{add}import-item\">\
350 <code>{vis}{imp}</code>\
352 <div class=\"item-right docblock-short\">{stab_tags}</div>",
353 stab = stab.unwrap_or_default(),
355 vis = myitem.visibility.print_with_space(myitem.def_id, cx),
356 imp = import.print(cx),
357 stab_tags = stab_tags.unwrap_or_default(),
359 w.write_str(ITEM_TABLE_ROW_CLOSE);
363 if myitem.name.is_none() {
367 let unsafety_flag = match *myitem.kind {
368 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
369 if func.header.unsafety == hir::Unsafety::Unsafe =>
371 "<a title=\"unsafe function\" href=\"#\"><sup>⚠</sup></a>"
376 let stab = myitem.stability_class(cx.tcx());
377 let add = if stab.is_some() { " " } else { "" };
379 let doc_value = myitem.doc_value().unwrap_or_default();
380 w.write_str(ITEM_TABLE_ROW_OPEN);
383 "<div class=\"item-left {stab}{add}module-item\">\
384 <a class=\"{class}\" href=\"{href}\" title=\"{title}\">{name}</a>\
388 <div class=\"item-right docblock-short\">{docs}</div>",
389 name = myitem.name.unwrap(),
390 stab_tags = extra_info_tags(myitem, item, cx.tcx()),
391 docs = MarkdownSummaryLine(&doc_value, &myitem.links(cx)).into_string(),
392 class = myitem.type_(),
394 stab = stab.unwrap_or_default(),
395 unsafety_flag = unsafety_flag,
396 href = item_path(myitem.type_(), myitem.name.unwrap().as_str()),
397 title = [full_path(cx, myitem), myitem.type_().to_string()]
399 .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
403 w.write_str(ITEM_TABLE_ROW_CLOSE);
408 if last_section.is_some() {
409 w.write_str(ITEM_TABLE_CLOSE);
413 /// Render the stability, deprecation and portability tags that are displayed in the item's summary
414 /// at the module level.
415 fn extra_info_tags(item: &clean::Item, parent: &clean::Item, tcx: TyCtxt<'_>) -> String {
416 let mut tags = String::new();
418 fn tag_html(class: &str, title: &str, contents: &str) -> String {
419 format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
422 // The trailing space after each tag is to space it properly against the rest of the docs.
423 if let Some(depr) = &item.deprecation(tcx) {
424 let mut message = "Deprecated";
425 if !stability::deprecation_in_effect(depr) {
426 message = "Deprecation planned";
428 tags += &tag_html("deprecated", "", message);
431 // The "rustc_private" crates are permanently unstable so it makes no sense
432 // to render "unstable" everywhere.
436 .map(|s| s.level.is_unstable() && s.feature != sym::rustc_private)
439 tags += &tag_html("unstable", "", "Experimental");
442 let cfg = match (&item.cfg, parent.cfg.as_ref()) {
443 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
444 (cfg, _) => cfg.as_deref().cloned(),
447 debug!("Portability {:?} - {:?} = {:?}", item.cfg, parent.cfg, cfg);
448 if let Some(ref cfg) = cfg {
449 tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
455 fn item_function(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, f: &clean::Function) {
456 let vis = it.visibility.print_with_space(it.def_id, cx).to_string();
457 let constness = print_constness_with_space(&f.header.constness, it.const_stability(cx.tcx()));
458 let asyncness = f.header.asyncness.print_with_space();
459 let unsafety = f.header.unsafety.print_with_space();
460 let abi = print_abi_with_space(f.header.abi).to_string();
461 let name = it.name.unwrap();
463 let generics_len = format!("{:#}", f.generics.print(cx)).len();
464 let header_len = "fn ".len()
470 + name.as_str().len()
473 wrap_into_docblock(w, |w| {
474 wrap_item(w, "fn", |w| {
475 render_attributes_in_pre(w, it, "");
476 w.reserve(header_len);
479 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
480 {name}{generics}{decl}{notable_traits}{where_clause}",
482 constness = constness,
483 asyncness = asyncness,
487 generics = f.generics.print(cx),
488 where_clause = print_where_clause(&f.generics, cx, 0, true),
489 decl = f.decl.full_print(header_len, 0, f.header.asyncness, cx),
490 notable_traits = notable_traits_decl(&f.decl, cx),
494 document(w, cx, it, None, HeadingOffset::H2)
497 fn item_trait(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Trait) {
498 let bounds = bounds(&t.bounds, false, cx);
499 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
500 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
501 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
502 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
503 let count_types = types.len();
504 let count_consts = consts.len();
505 let count_methods = required.len() + provided.len();
507 // Output the trait definition
508 wrap_into_docblock(w, |w| {
509 wrap_item(w, "trait", |w| {
510 render_attributes_in_pre(w, it, "");
513 "{}{}{}trait {}{}{}",
514 it.visibility.print_with_space(it.def_id, cx),
515 t.unsafety.print_with_space(),
516 if t.is_auto { "auto " } else { "" },
518 t.generics.print(cx),
522 if !t.generics.where_predicates.is_empty() {
523 write!(w, "{}", print_where_clause(&t.generics, cx, 0, true));
528 if t.items.is_empty() {
531 // FIXME: we should be using a derived_id for the Anchors here
533 let mut toggle = false;
535 // If there are too many associated types, hide _everything_
536 if should_hide_fields(count_types) {
541 "{} associated items",
542 count_types + count_consts + count_methods
550 AssocItemLink::Anchor(None),
557 // If there are too many associated constants, hide everything after them
558 // We also do this if the types + consts is large because otherwise we could
559 // render a bunch of types and _then_ a bunch of consts just because both were
560 // _just_ under the limit
561 if !toggle && should_hide_fields(count_types + count_consts) {
566 "{} associated constant{} and {} method{}",
568 pluralize(count_consts),
570 pluralize(count_methods),
574 if !types.is_empty() && !consts.is_empty() {
581 AssocItemLink::Anchor(None),
588 if !toggle && should_hide_fields(count_methods) {
590 toggle_open(w, format_args!("{} methods", count_methods));
592 if !consts.is_empty() && !required.is_empty() {
595 for (pos, m) in required.iter().enumerate() {
599 AssocItemLink::Anchor(None),
606 if pos < required.len() - 1 {
607 w.write_str("<div class=\"item-spacer\"></div>");
610 if !required.is_empty() && !provided.is_empty() {
613 for (pos, m) in provided.iter().enumerate() {
617 AssocItemLink::Anchor(None),
623 clean::MethodItem(ref inner, _)
624 if !inner.generics.where_predicates.is_empty() =>
626 w.write_str(",\n { ... }\n");
629 w.write_str(" { ... }\n");
632 if pos < provided.len() - 1 {
633 w.write_str("<div class=\"item-spacer\"></div>");
644 // Trait documentation
645 document(w, cx, it, None, HeadingOffset::H2);
647 fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
650 "<h2 id=\"{0}\" class=\"small-section-header\">\
651 {1}<a href=\"#{0}\" class=\"anchor\"></a>\
653 id, title, extra_content
657 fn trait_item(w: &mut Buffer, cx: &Context<'_>, m: &clean::Item, t: &clean::Item) {
658 let name = m.name.unwrap();
659 info!("Documenting {} on {:?}", name, t.name);
660 let item_type = m.type_();
661 let id = cx.derive_id(format!("{}.{}", item_type, name));
662 let mut content = Buffer::empty_from(w);
663 document(&mut content, cx, m, Some(t), HeadingOffset::H5);
664 let toggled = !content.is_empty();
666 write!(w, "<details class=\"rustdoc-toggle\" open><summary>");
668 write!(w, "<div id=\"{}\" class=\"method has-srclink\">", id);
669 write!(w, "<div class=\"rightside\">");
671 let has_stability = render_stability_since(w, m, t, cx.tcx());
675 write_srclink(cx, m, w);
677 write!(w, "<h4 class=\"code-header\">");
681 AssocItemLink::Anchor(Some(&id)),
686 w.write_str("</h4>");
687 w.write_str("</div>");
689 write!(w, "</summary>");
690 w.push_buffer(content);
691 write!(w, "</details>");
695 if !types.is_empty() {
696 write_small_section_header(
700 "<div class=\"methods\">",
703 trait_item(w, cx, t, it);
705 w.write_str("</div>");
708 if !consts.is_empty() {
709 write_small_section_header(
712 "Associated Constants",
713 "<div class=\"methods\">",
716 trait_item(w, cx, t, it);
718 w.write_str("</div>");
721 // Output the documentation for each function individually
722 if !required.is_empty() {
723 write_small_section_header(
727 "<div class=\"methods\">",
730 trait_item(w, cx, m, it);
732 w.write_str("</div>");
734 if !provided.is_empty() {
735 write_small_section_header(
739 "<div class=\"methods\">",
742 trait_item(w, cx, m, it);
744 w.write_str("</div>");
747 // If there are methods directly on this trait object, render them here.
748 render_assoc_items(w, cx, it, it.def_id.expect_def_id(), AssocItemRender::All);
750 let cache = cx.cache();
751 if let Some(implementors) = cache.implementors.get(&it.def_id.expect_def_id()) {
752 // The DefId is for the first Type found with that name. The bool is
753 // if any Types with the same name but different DefId have been found.
754 let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();
755 for implementor in implementors {
756 match implementor.inner_impl().for_ {
757 clean::Type::Path { ref path }
758 | clean::BorrowedRef { type_: box clean::Type::Path { ref path }, .. }
759 if !path.is_assoc_ty() =>
761 let did = path.def_id();
762 let &mut (prev_did, ref mut has_duplicates) =
763 implementor_dups.entry(path.last()).or_insert((did, false));
765 *has_duplicates = true;
772 let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| {
773 i.inner_impl().for_.def_id(cache).map_or(true, |d| cache.paths.contains_key(&d))
776 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
777 local.iter().partition(|i| i.inner_impl().kind.is_auto());
779 synthetic.sort_by(|a, b| compare_impl(a, b, cx));
780 concrete.sort_by(|a, b| compare_impl(a, b, cx));
782 if !foreign.is_empty() {
783 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
785 for implementor in foreign {
786 let provided_methods = implementor.inner_impl().provided_trait_methods(cx.tcx());
788 AssocItemLink::GotoSource(implementor.impl_item.def_id, &provided_methods);
798 ImplRenderingParameters {
799 show_def_docs: false,
800 is_on_foreign_type: true,
801 show_default_items: false,
802 show_non_assoc_items: true,
803 toggle_open_by_default: false,
809 write_small_section_header(
813 "<div class=\"item-list\" id=\"implementors-list\">",
815 for implementor in concrete {
816 render_implementor(cx, implementor, it, w, &implementor_dups, &[]);
818 w.write_str("</div>");
821 write_small_section_header(
823 "synthetic-implementors",
825 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
827 for implementor in synthetic {
834 &collect_paths_for_type(implementor.inner_impl().for_.clone(), cache),
837 w.write_str("</div>");
840 // even without any implementations to write in, we still want the heading and list, so the
841 // implementors javascript file pulled in below has somewhere to write the impls into
842 write_small_section_header(
846 "<div class=\"item-list\" id=\"implementors-list\"></div>",
850 write_small_section_header(
852 "synthetic-implementors",
854 "<div class=\"item-list\" id=\"synthetic-implementors-list\"></div>",
859 let mut js_src_path: UrlPartsBuilder = std::iter::repeat("..")
860 .take(cx.current.len())
861 .chain(std::iter::once("implementors"))
863 if it.def_id.is_local() {
864 js_src_path.extend(cx.current.iter().copied());
866 let (ref path, _) = cache.external_paths[&it.def_id.expect_def_id()];
867 js_src_path.extend(path[..path.len() - 1].iter().copied());
869 js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), it.name.unwrap()));
872 "<script type=\"text/javascript\" src=\"{src}\" async></script>",
873 src = js_src_path.finish(),
877 fn item_trait_alias(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::TraitAlias) {
878 wrap_into_docblock(w, |w| {
879 wrap_item(w, "trait-alias", |w| {
880 render_attributes_in_pre(w, it, "");
883 "trait {}{}{} = {};",
885 t.generics.print(cx),
886 print_where_clause(&t.generics, cx, 0, true),
887 bounds(&t.bounds, true, cx)
892 document(w, cx, it, None, HeadingOffset::H2);
894 // Render any items associated directly to this alias, as otherwise they
895 // won't be visible anywhere in the docs. It would be nice to also show
896 // associated items from the aliased type (see discussion in #32077), but
897 // we need #14072 to make sense of the generics.
898 render_assoc_items(w, cx, it, it.def_id.expect_def_id(), AssocItemRender::All)
901 fn item_opaque_ty(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::OpaqueTy) {
902 wrap_into_docblock(w, |w| {
903 wrap_item(w, "opaque", |w| {
904 render_attributes_in_pre(w, it, "");
907 "type {}{}{where_clause} = impl {bounds};",
909 t.generics.print(cx),
910 where_clause = print_where_clause(&t.generics, cx, 0, true),
911 bounds = bounds(&t.bounds, false, cx),
916 document(w, cx, it, None, HeadingOffset::H2);
918 // Render any items associated directly to this alias, as otherwise they
919 // won't be visible anywhere in the docs. It would be nice to also show
920 // associated items from the aliased type (see discussion in #32077), but
921 // we need #14072 to make sense of the generics.
922 render_assoc_items(w, cx, it, it.def_id.expect_def_id(), AssocItemRender::All)
939 wrap_item(w, "typedef", |w| {
940 render_attributes_in_pre(w, it, "");
942 write!(w, "{}", it.visibility.print_with_space(it.def_id, cx));
946 "type {}{}{where_clause} = {type_};",
948 t.generics.print(cx),
949 where_clause = print_where_clause(&t.generics, cx, 0, true),
950 type_ = t.type_.print(cx),
955 // If this is an associated typedef, we don't want to wrap it into a docblock.
957 write_content(w, cx, it, t, is_associated);
959 wrap_into_docblock(w, |w| {
960 write_content(w, cx, it, t, is_associated);
964 document(w, cx, it, None, HeadingOffset::H2);
966 let def_id = it.def_id.expect_def_id();
967 // Render any items associated directly to this alias, as otherwise they
968 // won't be visible anywhere in the docs. It would be nice to also show
969 // associated items from the aliased type (see discussion in #32077), but
970 // we need #14072 to make sense of the generics.
971 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
972 document_type_layout(w, cx, def_id);
975 fn item_union(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Union) {
976 wrap_into_docblock(w, |w| {
977 wrap_item(w, "union", |w| {
978 render_attributes_in_pre(w, it, "");
979 render_union(w, it, Some(&s.generics), &s.fields, "", cx);
983 document(w, cx, it, None, HeadingOffset::H2);
988 .filter_map(|f| match *f.kind {
989 clean::StructFieldItem(ref ty) => Some((f, ty)),
993 if fields.peek().is_some() {
996 "<h2 id=\"fields\" class=\"fields small-section-header\">\
997 Fields<a href=\"#fields\" class=\"anchor\"></a></h2>"
999 for (field, ty) in fields {
1000 let name = field.name.expect("union field name");
1001 let id = format!("{}.{}", ItemType::StructField, name);
1004 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
1005 <a href=\"#{id}\" class=\"anchor field\"></a>\
1006 <code>{name}: {ty}</code>\
1010 shortty = ItemType::StructField,
1013 if let Some(stability_class) = field.stability_class(cx.tcx()) {
1014 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
1016 document(w, cx, field, Some(it), HeadingOffset::H3);
1019 let def_id = it.def_id.expect_def_id();
1020 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1021 document_type_layout(w, cx, def_id);
1024 fn print_tuple_struct_fields(w: &mut Buffer, cx: &Context<'_>, s: &[clean::Item]) {
1025 for (i, ty) in s.iter().enumerate() {
1027 w.write_str(", ");
1030 clean::StrippedItem(box clean::StructFieldItem(_)) => w.write_str("_"),
1031 clean::StructFieldItem(ref ty) => write!(w, "{}", ty.print(cx)),
1032 _ => unreachable!(),
1037 fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum) {
1038 wrap_into_docblock(w, |w| {
1039 wrap_item(w, "enum", |w| {
1040 render_attributes_in_pre(w, it, "");
1044 it.visibility.print_with_space(it.def_id, cx),
1046 e.generics.print(cx),
1047 print_where_clause(&e.generics, cx, 0, true),
1049 if e.variants.is_empty() && !e.variants_stripped {
1052 w.write_str(" {\n");
1053 let count_variants = e.variants.len();
1054 let toggle = should_hide_fields(count_variants);
1056 toggle_open(w, format_args!("{} variants", count_variants));
1058 for v in &e.variants {
1060 let name = v.name.unwrap();
1062 clean::VariantItem(ref var) => match var {
1063 clean::Variant::CLike => write!(w, "{}", name),
1064 clean::Variant::Tuple(ref s) => {
1065 write!(w, "{}(", name);
1066 print_tuple_struct_fields(w, cx, s);
1069 clean::Variant::Struct(ref s) => {
1082 _ => unreachable!(),
1087 if e.variants_stripped {
1088 w.write_str(" // some variants omitted\n");
1098 document(w, cx, it, None, HeadingOffset::H2);
1100 if !e.variants.is_empty() {
1103 "<h2 id=\"variants\" class=\"variants small-section-header\">\
1104 Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>",
1105 document_non_exhaustive_header(it)
1107 document_non_exhaustive(w, it);
1108 for variant in &e.variants {
1109 let id = cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.unwrap()));
1112 "<h3 id=\"{id}\" class=\"variant small-section-header\">\
1113 <a href=\"#{id}\" class=\"anchor field\"></a>\
1116 name = variant.name.unwrap()
1118 if let clean::VariantItem(clean::Variant::Tuple(ref s)) = *variant.kind {
1120 print_tuple_struct_fields(w, cx, s);
1123 w.write_str("</code>");
1124 render_stability_since(w, variant, it, cx.tcx());
1125 w.write_str("</h3>");
1127 use crate::clean::Variant;
1129 let heading_and_fields = match &*variant.kind {
1130 clean::VariantItem(Variant::Struct(s)) => Some(("Fields", &s.fields)),
1131 // Documentation on tuple variant fields is rare, so to reduce noise we only emit
1132 // the section if at least one field is documented.
1133 clean::VariantItem(Variant::Tuple(fields))
1134 if fields.iter().any(|f| f.doc_value().is_some()) =>
1136 Some(("Tuple Fields", fields))
1141 if let Some((heading, fields)) = heading_and_fields {
1143 cx.derive_id(format!("{}.{}.fields", ItemType::Variant, variant.name.unwrap()));
1144 write!(w, "<div class=\"sub-variant\" id=\"{id}\">", id = variant_id);
1145 write!(w, "<h4>{heading}</h4>", heading = heading);
1146 document_non_exhaustive(w, variant);
1147 for field in fields {
1149 clean::StrippedItem(box clean::StructFieldItem(_)) => {}
1150 clean::StructFieldItem(ref ty) => {
1151 let id = cx.derive_id(format!(
1152 "variant.{}.field.{}",
1153 variant.name.unwrap(),
1158 "<div class=\"sub-variant-field\">\
1159 <span id=\"{id}\" class=\"variant small-section-header\">\
1160 <a href=\"#{id}\" class=\"anchor field\"></a>\
1161 <code>{f}: {t}</code>\
1164 f = field.name.unwrap(),
1167 document(w, cx, field, Some(variant), HeadingOffset::H5);
1168 write!(w, "</div>");
1170 _ => unreachable!(),
1173 w.write_str("</div>");
1176 document(w, cx, variant, Some(it), HeadingOffset::H4);
1179 let def_id = it.def_id.expect_def_id();
1180 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1181 document_type_layout(w, cx, def_id);
1184 fn item_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Macro) {
1185 wrap_into_docblock(w, |w| {
1186 highlight::render_with_highlighting(
1192 it.span(cx.tcx()).inner().edition(),
1198 document(w, cx, it, None, HeadingOffset::H2)
1201 fn item_proc_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, m: &clean::ProcMacro) {
1202 wrap_into_docblock(w, |w| {
1203 let name = it.name.expect("proc-macros always have names");
1205 MacroKind::Bang => {
1206 wrap_item(w, "macro", |w| {
1207 write!(w, "{}!() {{ /* proc-macro */ }}", name);
1210 MacroKind::Attr => {
1211 wrap_item(w, "attr", |w| {
1212 write!(w, "#[{}]", name);
1215 MacroKind::Derive => {
1216 wrap_item(w, "derive", |w| {
1217 write!(w, "#[derive({})]", name);
1218 if !m.helpers.is_empty() {
1219 w.push_str("\n{\n");
1220 w.push_str(" // Attributes available to this derive:\n");
1221 for attr in &m.helpers {
1222 writeln!(w, " #[{}]", attr);
1230 document(w, cx, it, None, HeadingOffset::H2)
1233 fn item_primitive(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
1234 document(w, cx, it, None, HeadingOffset::H2);
1235 render_assoc_items(w, cx, it, it.def_id.expect_def_id(), AssocItemRender::All)
1238 fn item_constant(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, c: &clean::Constant) {
1239 wrap_into_docblock(w, |w| {
1240 wrap_item(w, "const", |w| {
1241 render_attributes_in_code(w, it);
1245 "{vis}const {name}: {typ}",
1246 vis = it.visibility.print_with_space(it.def_id, cx),
1247 name = it.name.unwrap(),
1248 typ = c.type_.print(cx),
1251 let value = c.value(cx.tcx());
1252 let is_literal = c.is_literal(cx.tcx());
1253 let expr = c.expr(cx.tcx());
1254 if value.is_some() || is_literal {
1255 write!(w, " = {expr};", expr = Escape(&expr));
1261 if let Some(value) = &value {
1262 let value_lowercase = value.to_lowercase();
1263 let expr_lowercase = expr.to_lowercase();
1265 if value_lowercase != expr_lowercase
1266 && value_lowercase.trim_end_matches("i32") != expr_lowercase
1268 write!(w, " // {value}", value = Escape(value));
1275 document(w, cx, it, None, HeadingOffset::H2)
1278 fn item_struct(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Struct) {
1279 wrap_into_docblock(w, |w| {
1280 wrap_item(w, "struct", |w| {
1281 render_attributes_in_code(w, it);
1282 render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true, cx);
1286 document(w, cx, it, None, HeadingOffset::H2);
1291 .filter_map(|f| match *f.kind {
1292 clean::StructFieldItem(ref ty) => Some((f, ty)),
1296 if let CtorKind::Fictive | CtorKind::Fn = s.struct_type {
1297 if fields.peek().is_some() {
1300 "<h2 id=\"fields\" class=\"fields small-section-header\">\
1301 {}{}<a href=\"#fields\" class=\"anchor\"></a>\
1303 if let CtorKind::Fictive = s.struct_type { "Fields" } else { "Tuple Fields" },
1304 document_non_exhaustive_header(it)
1306 document_non_exhaustive(w, it);
1307 for (index, (field, ty)) in fields.enumerate() {
1309 field.name.map_or_else(|| index.to_string(), |sym| sym.as_str().to_string());
1310 let id = cx.derive_id(format!("{}.{}", ItemType::StructField, field_name));
1313 "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
1314 <a href=\"#{id}\" class=\"anchor field\"></a>\
1315 <code>{name}: {ty}</code>\
1317 item_type = ItemType::StructField,
1322 document(w, cx, field, Some(it), HeadingOffset::H3);
1326 let def_id = it.def_id.expect_def_id();
1327 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1328 document_type_layout(w, cx, def_id);
1331 fn item_static(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Static) {
1332 wrap_into_docblock(w, |w| {
1333 wrap_item(w, "static", |w| {
1334 render_attributes_in_code(w, it);
1337 "{vis}static {mutability}{name}: {typ}",
1338 vis = it.visibility.print_with_space(it.def_id, cx),
1339 mutability = s.mutability.print_with_space(),
1340 name = it.name.unwrap(),
1341 typ = s.type_.print(cx)
1345 document(w, cx, it, None, HeadingOffset::H2)
1348 fn item_foreign_type(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
1349 wrap_into_docblock(w, |w| {
1350 wrap_item(w, "foreigntype", |w| {
1351 w.write_str("extern {\n");
1352 render_attributes_in_code(w, it);
1356 it.visibility.print_with_space(it.def_id, cx),
1362 document(w, cx, it, None, HeadingOffset::H2);
1364 render_assoc_items(w, cx, it, it.def_id.expect_def_id(), AssocItemRender::All)
1367 fn item_keyword(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
1368 document(w, cx, it, None, HeadingOffset::H2)
1371 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
1372 crate fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
1373 /// Takes a non-numeric and a numeric part from the given &str.
1374 fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
1375 let i = s.find(|c: char| c.is_ascii_digit());
1376 let (a, b) = s.split_at(i.unwrap_or(s.len()));
1377 let i = b.find(|c: char| !c.is_ascii_digit());
1378 let (b, c) = b.split_at(i.unwrap_or(b.len()));
1383 while !lhs.is_empty() || !rhs.is_empty() {
1384 let (la, lb) = take_parts(&mut lhs);
1385 let (ra, rb) = take_parts(&mut rhs);
1386 // First process the non-numeric part.
1388 Ordering::Equal => (),
1391 // Then process the numeric part, if both sides have one (and they fit in a u64).
1392 if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
1394 Ordering::Equal => (),
1398 // Then process the numeric part again, but this time as strings.
1400 Ordering::Equal => (),
1408 pub(super) fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
1409 let mut s = join_with_double_colon(&cx.current);
1411 s.push_str(item.name.unwrap().as_str());
1415 pub(super) fn item_path(ty: ItemType, name: &str) -> String {
1417 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1418 _ => format!("{}.{}.html", ty, name),
1422 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool, cx: &Context<'_>) -> String {
1423 let mut bounds = String::new();
1424 if !t_bounds.is_empty() {
1426 bounds.push_str(": ");
1428 for (i, p) in t_bounds.iter().enumerate() {
1430 bounds.push_str(" + ");
1432 bounds.push_str(&p.print(cx).to_string());
1438 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1440 F: FnOnce(&mut Buffer),
1442 w.write_str("<div class=\"docblock item-decl\">");
1444 w.write_str("</div>")
1447 fn wrap_item<F>(w: &mut Buffer, item_name: &str, f: F)
1449 F: FnOnce(&mut Buffer),
1451 w.write_fmt(format_args!("<pre class=\"rust {}\"><code>", item_name));
1453 w.write_str("</code></pre>");
1456 fn render_stability_since(
1459 containing_item: &clean::Item,
1462 render_stability_since_raw(
1464 item.stable_since(tcx),
1465 item.const_stability(tcx),
1466 containing_item.stable_since(tcx),
1467 containing_item.const_stable_since(tcx),
1471 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl, cx: &Context<'_>) -> Ordering {
1472 let lhss = format!("{}", lhs.inner_impl().print(false, cx));
1473 let rhss = format!("{}", rhs.inner_impl().print(false, cx));
1475 // lhs and rhs are formatted as HTML, which may be unnecessary
1476 compare_names(&lhss, &rhss)
1479 fn render_implementor(
1482 trait_: &clean::Item,
1484 implementor_dups: &FxHashMap<Symbol, (DefId, bool)>,
1487 // If there's already another implementor that has the same abridged name, use the
1488 // full path, for example in `std::iter::ExactSizeIterator`
1489 let use_absolute = match implementor.inner_impl().for_ {
1490 clean::Type::Path { ref path, .. }
1491 | clean::BorrowedRef { type_: box clean::Type::Path { ref path, .. }, .. }
1492 if !path.is_assoc_ty() =>
1494 implementor_dups[&path.last()].1
1503 AssocItemLink::Anchor(None),
1507 ImplRenderingParameters {
1508 show_def_docs: false,
1509 is_on_foreign_type: false,
1510 show_default_items: false,
1511 show_non_assoc_items: false,
1512 toggle_open_by_default: false,
1520 g: Option<&clean::Generics>,
1521 fields: &[clean::Item],
1525 write!(w, "{}union {}", it.visibility.print_with_space(it.def_id, cx), it.name.unwrap());
1526 if let Some(g) = g {
1527 write!(w, "{}", g.print(cx));
1528 write!(w, "{}", print_where_clause(g, cx, 0, true));
1531 write!(w, " {{\n{}", tab);
1533 fields.iter().filter(|f| matches!(*f.kind, clean::StructFieldItem(..))).count();
1534 let toggle = should_hide_fields(count_fields);
1536 toggle_open(w, format_args!("{} fields", count_fields));
1539 for field in fields {
1540 if let clean::StructFieldItem(ref ty) = *field.kind {
1544 field.visibility.print_with_space(field.def_id, cx),
1545 field.name.unwrap(),
1552 if it.has_stripped_fields().unwrap() {
1553 write!(w, " /* private fields */\n{}", tab);
1564 g: Option<&clean::Generics>,
1566 fields: &[clean::Item],
1574 it.visibility.print_with_space(it.def_id, cx),
1575 if structhead { "struct " } else { "" },
1578 if let Some(g) = g {
1579 write!(w, "{}", g.print(cx))
1582 CtorKind::Fictive => {
1583 if let Some(g) = g {
1584 write!(w, "{}", print_where_clause(g, cx, 0, true),)
1588 fields.iter().filter(|f| matches!(*f.kind, clean::StructFieldItem(..))).count();
1589 let has_visible_fields = count_fields > 0;
1590 let toggle = should_hide_fields(count_fields);
1592 toggle_open(w, format_args!("{} fields", count_fields));
1594 for field in fields {
1595 if let clean::StructFieldItem(ref ty) = *field.kind {
1600 field.visibility.print_with_space(field.def_id, cx),
1601 field.name.unwrap(),
1607 if has_visible_fields {
1608 if it.has_stripped_fields().unwrap() {
1609 write!(w, "\n{} /* private fields */", tab);
1611 write!(w, "\n{}", tab);
1612 } else if it.has_stripped_fields().unwrap() {
1613 write!(w, " /* private fields */ ");
1622 for (i, field) in fields.iter().enumerate() {
1627 clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
1628 clean::StructFieldItem(ref ty) => {
1632 field.visibility.print_with_space(field.def_id, cx),
1636 _ => unreachable!(),
1640 if let Some(g) = g {
1641 write!(w, "{}", print_where_clause(g, cx, 0, false),)
1643 // We only want a ";" when we are displaying a tuple struct, not a variant tuple struct.
1648 CtorKind::Const => {
1649 // Needed for PhantomData.
1650 if let Some(g) = g {
1651 write!(w, "{}", print_where_clause(g, cx, 0, false),)
1658 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1659 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1662 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1663 if item.is_non_exhaustive() {
1666 "<details class=\"rustdoc-toggle non-exhaustive\">\
1667 <summary class=\"hideme\"><span>{}</span></summary>\
1668 <div class=\"docblock\">",
1670 if item.is_struct() {
1671 "This struct is marked as non-exhaustive"
1672 } else if item.is_enum() {
1673 "This enum is marked as non-exhaustive"
1674 } else if item.is_variant() {
1675 "This variant is marked as non-exhaustive"
1677 "This type is marked as non-exhaustive"
1682 if item.is_struct() {
1684 "Non-exhaustive structs could have additional fields added in future. \
1685 Therefore, non-exhaustive structs cannot be constructed in external crates \
1686 using the traditional <code>Struct { .. }</code> syntax; cannot be \
1687 matched against without a wildcard <code>..</code>; and \
1688 struct update syntax will not work.",
1690 } else if item.is_enum() {
1692 "Non-exhaustive enums could have additional variants added in future. \
1693 Therefore, when matching against variants of non-exhaustive enums, an \
1694 extra wildcard arm must be added to account for any future variants.",
1696 } else if item.is_variant() {
1698 "Non-exhaustive enum variants could have additional fields added in future. \
1699 Therefore, non-exhaustive enum variants cannot be constructed in external \
1700 crates and cannot be matched against.",
1704 "This type will require a wildcard arm in any match statements or constructors.",
1708 w.write_str("</div></details>");
1712 fn document_type_layout(w: &mut Buffer, cx: &Context<'_>, ty_def_id: DefId) {
1713 fn write_size_of_layout(w: &mut Buffer, layout: &Layout, tag_size: u64) {
1714 if layout.abi.is_unsized() {
1715 write!(w, "(unsized)");
1717 let bytes = layout.size.bytes() - tag_size;
1718 write!(w, "{size} byte{pl}", size = bytes, pl = if bytes == 1 { "" } else { "s" },);
1722 if !cx.shared.show_type_layout {
1726 writeln!(w, "<h2 class=\"small-section-header\">Layout</h2>");
1727 writeln!(w, "<div class=\"docblock\">");
1730 let param_env = tcx.param_env(ty_def_id);
1731 let ty = tcx.type_of(ty_def_id);
1732 match tcx.layout_of(param_env.and(ty)) {
1736 "<div class=\"warning\"><p><strong>Note:</strong> Most layout information is \
1737 <strong>completely unstable</strong> and may even differ between compilations. \
1738 The only exception is types with certain <code>repr(...)</code> attributes. \
1739 Please see the Rust Reference’s \
1740 <a href=\"https://doc.rust-lang.org/reference/type-layout.html\">“Type Layout”</a> \
1741 chapter for details on type layout guarantees.</p></div>"
1743 w.write_str("<p><strong>Size:</strong> ");
1744 write_size_of_layout(w, ty_layout.layout, 0);
1745 writeln!(w, "</p>");
1746 if let Variants::Multiple { variants, tag, tag_encoding, .. } =
1747 &ty_layout.layout.variants
1749 if !variants.is_empty() {
1751 "<p><strong>Size for each variant:</strong></p>\
1755 let Adt(adt, _) = ty_layout.ty.kind() else {
1756 span_bug!(tcx.def_span(ty_def_id), "not an adt")
1759 let tag_size = if let TagEncoding::Niche { .. } = tag_encoding {
1761 } else if let Primitive::Int(i, _) = tag.value {
1764 span_bug!(tcx.def_span(ty_def_id), "tag is neither niche nor int")
1767 for (index, layout) in variants.iter_enumerated() {
1768 let name = adt.variants[index].name;
1769 write!(w, "<li><code>{name}</code>: ", name = name);
1770 write_size_of_layout(w, layout, tag_size);
1771 writeln!(w, "</li>");
1773 w.write_str("</ul>");
1777 // This kind of layout error can occur with valid code, e.g. if you try to
1778 // get the layout of a generic type such as `Vec<T>`.
1779 Err(LayoutError::Unknown(_)) => {
1782 "<p><strong>Note:</strong> Unable to compute type layout, \
1783 possibly due to this type having generic parameters. \
1784 Layout can only be computed for concrete, fully-instantiated types.</p>"
1787 // This kind of error probably can't happen with valid code, but we don't
1788 // want to panic and prevent the docs from building, so we just let the
1789 // user know that we couldn't compute the layout.
1790 Err(LayoutError::SizeOverflow(_)) => {
1793 "<p><strong>Note:</strong> Encountered an error during type layout; \
1794 the type was too big.</p>"
1797 Err(LayoutError::NormalizationFailure(_, _)) => {
1800 "<p><strong>Note:</strong> Encountered an error during type layout; \
1801 the type failed to be normalized.</p>"
1806 writeln!(w, "</div>");
1809 fn pluralize(count: usize) -> &'static str {
1810 if count > 1 { "s" } else { "" }