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_strs, notable_traits_decl,
20 render_assoc_item, render_assoc_items, render_attributes_in_code, render_attributes_in_pre,
21 render_impl, render_stability_since_raw, write_srclink, AssocItemLink, Context,
22 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 print_abi_with_space, print_constness_with_space, print_where_clause, Buffer, PrintWithSpace,
31 use crate::html::highlight;
32 use crate::html::layout::Page;
33 use crate::html::markdown::{HeadingOffset, MarkdownSummaryLine};
37 const ITEM_TABLE_OPEN: &str = "<div class=\"item-table\">";
38 const ITEM_TABLE_CLOSE: &str = "</div>";
39 const ITEM_TABLE_ROW_OPEN: &str = "<div class=\"item-row\">";
40 const ITEM_TABLE_ROW_CLOSE: &str = "</div>";
42 // A component in a `use` path, like `string` in std::string::ToString
44 struct PathComponent<'a> {
52 static_root_path: &'a str,
56 path_components: Vec<PathComponent<'a>>,
57 stability_since_raw: &'a str,
58 src_href: Option<&'a str>,
61 pub(super) fn print_item(
63 templates: &tera::Tera,
68 debug_assert!(!item.is_stripped());
69 let typ = match *item.kind {
70 clean::ModuleItem(_) => {
77 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
78 clean::TraitItem(..) => "Trait ",
79 clean::StructItem(..) => "Struct ",
80 clean::UnionItem(..) => "Union ",
81 clean::EnumItem(..) => "Enum ",
82 clean::TypedefItem(..) => "Type Definition ",
83 clean::MacroItem(..) => "Macro ",
84 clean::ProcMacroItem(ref mac) => match mac.kind {
85 MacroKind::Bang => "Macro ",
86 MacroKind::Attr => "Attribute Macro ",
87 MacroKind::Derive => "Derive Macro ",
89 clean::PrimitiveItem(..) => "Primitive Type ",
90 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
91 clean::ConstantItem(..) => "Constant ",
92 clean::ForeignTypeItem => "Foreign Type ",
93 clean::KeywordItem(..) => "Keyword ",
94 clean::OpaqueTyItem(..) => "Opaque Type ",
95 clean::TraitAliasItem(..) => "Trait Alias ",
97 // We don't generate pages for any other type.
101 let mut stability_since_raw = Buffer::new();
102 render_stability_since_raw(
103 &mut stability_since_raw,
104 item.stable_since(cx.tcx()).as_deref(),
105 item.const_stability(cx.tcx()),
109 let stability_since_raw: String = stability_since_raw.into_inner();
113 // When this item is part of a `crate use` in a downstream crate, the
114 // [src] link in the downstream documentation will actually come back to
115 // this page, and this link will be auto-clicked. The `id` attribute is
116 // used to find the link to auto-click.
118 if cx.include_sources && !item.is_primitive() { cx.src_href(item) } else { None };
120 let path_components = if item.is_primitive() || item.is_keyword() {
123 let cur = &cx.current;
124 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
128 .map(|(i, component)| PathComponent {
129 path: "../".repeat(cur.len() - i - 1),
135 let item_vars = ItemVars {
137 static_root_path: page.get_static_root_path(),
139 name: &item.name.as_ref().unwrap().as_str(),
140 item_type: &item.type_().to_string(),
141 path_components: path_components,
142 stability_since_raw: &stability_since_raw,
143 src_href: src_href.as_deref(),
146 let teractx = tera::Context::from_serialize(item_vars).unwrap();
147 let heading = templates.render("print_item.html", &teractx).unwrap();
148 buf.write_str(&heading);
151 clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
152 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
153 item_function(buf, cx, item, f)
155 clean::TraitItem(ref t) => item_trait(buf, cx, item, t),
156 clean::StructItem(ref s) => item_struct(buf, cx, item, s),
157 clean::UnionItem(ref s) => item_union(buf, cx, item, s),
158 clean::EnumItem(ref e) => item_enum(buf, cx, item, e),
159 clean::TypedefItem(ref t, is_associated) => item_typedef(buf, cx, item, t, is_associated),
160 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
161 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
162 clean::PrimitiveItem(_) => item_primitive(buf, cx, item),
163 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
164 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
165 clean::ForeignTypeItem => item_foreign_type(buf, cx, item),
166 clean::KeywordItem(_) => item_keyword(buf, cx, item),
167 clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e),
168 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta),
170 // We don't generate pages for any other type.
176 /// For large structs, enums, unions, etc, determine whether to hide their fields
177 fn should_hide_fields(n_fields: usize) -> bool {
181 fn toggle_open(w: &mut Buffer, text: impl fmt::Display) {
184 "<details class=\"rustdoc-toggle type-contents-toggle\">\
185 <summary class=\"hideme\">\
186 <span>Show {}</span>\
192 fn toggle_close(w: &mut Buffer) {
193 w.write_str("</details>");
196 fn item_module(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, items: &[clean::Item]) {
197 document(w, cx, item, None, HeadingOffset::H2);
199 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
201 // the order of item types in the listing
202 fn reorder(ty: ItemType) -> u8 {
204 ItemType::ExternCrate => 0,
205 ItemType::Import => 1,
206 ItemType::Primitive => 2,
207 ItemType::Module => 3,
208 ItemType::Macro => 4,
209 ItemType::Struct => 5,
211 ItemType::Constant => 7,
212 ItemType::Static => 8,
213 ItemType::Trait => 9,
214 ItemType::Function => 10,
215 ItemType::Typedef => 12,
216 ItemType::Union => 13,
228 let ty1 = i1.type_();
229 let ty2 = i2.type_();
231 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
233 let s1 = i1.stability(tcx).as_ref().map(|s| s.level);
234 let s2 = i2.stability(tcx).as_ref().map(|s| s.level);
235 if let (Some(a), Some(b)) = (s1, s2) {
236 match (a.is_stable(), b.is_stable()) {
237 (true, true) | (false, false) => {}
238 (false, true) => return Ordering::Less,
239 (true, false) => return Ordering::Greater,
242 let lhs = i1.name.unwrap_or(kw::Empty).as_str();
243 let rhs = i2.name.unwrap_or(kw::Empty).as_str();
244 compare_names(&lhs, &rhs)
247 if cx.shared.sort_modules_alphabetically {
248 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2, cx.tcx()));
250 // This call is to remove re-export duplicates in cases such as:
255 // crate trait Double { fn foo(); }
259 // crate use foo::bar::*;
263 // `Double` will appear twice in the generated docs.
265 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
266 // can be identical even if the elements are different (mostly in imports).
267 // So in case this is an import, we keep everything by adding a "unique id"
268 // (which is the position in the vector).
269 indices.dedup_by_key(|i| {
272 if items[*i].name.as_ref().is_some() { Some(full_path(cx, &items[*i])) } else { None },
274 if items[*i].is_import() { *i } else { 0 },
278 debug!("{:?}", indices);
279 let mut curty = None;
281 for &idx in &indices {
282 let myitem = &items[idx];
283 if myitem.is_stripped() {
287 let myty = Some(myitem.type_());
288 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
289 // Put `extern crate` and `use` re-exports in the same section.
291 } else if myty != curty {
293 w.write_str(ITEM_TABLE_CLOSE);
296 let (short, name) = item_ty_to_strs(myty.unwrap());
299 "<h2 id=\"{id}\" class=\"section-header\">\
300 <a href=\"#{id}\">{name}</a>\
303 id = cx.derive_id(short.to_owned()),
309 clean::ExternCrateItem { ref src } => {
310 use crate::html::format::anchor;
312 w.write_str(ITEM_TABLE_ROW_OPEN);
314 Some(ref src) => write!(
316 "<div class=\"item-left\"><code>{}extern crate {} as {};",
317 myitem.visibility.print_with_space(myitem.def_id, cx),
318 anchor(myitem.def_id.expect_def_id(), &*src.as_str(), cx),
319 myitem.name.as_ref().unwrap(),
323 "<div class=\"item-left\"><code>{}extern crate {};",
324 myitem.visibility.print_with_space(myitem.def_id, cx),
326 myitem.def_id.expect_def_id(),
327 &*myitem.name.as_ref().unwrap().as_str(),
332 w.write_str("</code></div>");
333 w.write_str(ITEM_TABLE_ROW_CLOSE);
336 clean::ImportItem(ref import) => {
337 let (stab, stab_tags) = if let Some(import_def_id) = import.source.did {
338 let ast_attrs = cx.tcx().get_attrs(import_def_id);
339 let import_attrs = Box::new(clean::Attributes::from_ast(ast_attrs, None));
341 // Just need an item with the correct def_id and attrs
342 let import_item = clean::Item {
343 def_id: import_def_id.into(),
345 cfg: ast_attrs.cfg(cx.tcx(), &cx.cache().hidden_cfg),
349 let stab = import_item.stability_class(cx.tcx());
350 let stab_tags = Some(extra_info_tags(&import_item, item, cx.tcx()));
356 let add = if stab.is_some() { " " } else { "" };
358 w.write_str(ITEM_TABLE_ROW_OPEN);
361 "<div class=\"item-left {stab}{add}import-item\">\
362 <code>{vis}{imp}</code>\
364 <div class=\"item-right docblock-short\">{stab_tags}</div>",
365 stab = stab.unwrap_or_default(),
367 vis = myitem.visibility.print_with_space(myitem.def_id, cx),
368 imp = import.print(cx),
369 stab_tags = stab_tags.unwrap_or_default(),
371 w.write_str(ITEM_TABLE_ROW_CLOSE);
375 if myitem.name.is_none() {
379 let unsafety_flag = match *myitem.kind {
380 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
381 if func.header.unsafety == hir::Unsafety::Unsafe =>
383 "<a title=\"unsafe function\" href=\"#\"><sup>⚠</sup></a>"
388 let stab = myitem.stability_class(cx.tcx());
389 let add = if stab.is_some() { " " } else { "" };
391 let doc_value = myitem.doc_value().unwrap_or_default();
392 w.write_str(ITEM_TABLE_ROW_OPEN);
395 "<div class=\"item-left {stab}{add}module-item\">\
396 <a class=\"{class}\" href=\"{href}\" title=\"{title}\">{name}</a>\
400 <div class=\"item-right docblock-short\">{docs}</div>",
401 name = *myitem.name.as_ref().unwrap(),
402 stab_tags = extra_info_tags(myitem, item, cx.tcx()),
403 docs = MarkdownSummaryLine(&doc_value, &myitem.links(cx)).into_string(),
404 class = myitem.type_(),
406 stab = stab.unwrap_or_default(),
407 unsafety_flag = unsafety_flag,
408 href = item_path(myitem.type_(), &myitem.name.unwrap().as_str()),
409 title = [full_path(cx, myitem), myitem.type_().to_string()]
411 .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
415 w.write_str(ITEM_TABLE_ROW_CLOSE);
421 w.write_str(ITEM_TABLE_CLOSE);
425 /// Render the stability, deprecation and portability tags that are displayed in the item's summary
426 /// at the module level.
427 fn extra_info_tags(item: &clean::Item, parent: &clean::Item, tcx: TyCtxt<'_>) -> String {
428 let mut tags = String::new();
430 fn tag_html(class: &str, title: &str, contents: &str) -> String {
431 format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
434 // The trailing space after each tag is to space it properly against the rest of the docs.
435 if let Some(depr) = &item.deprecation(tcx) {
436 let mut message = "Deprecated";
437 if !stability::deprecation_in_effect(depr) {
438 message = "Deprecation planned";
440 tags += &tag_html("deprecated", "", message);
443 // The "rustc_private" crates are permanently unstable so it makes no sense
444 // to render "unstable" everywhere.
448 .map(|s| s.level.is_unstable() && s.feature != sym::rustc_private)
451 tags += &tag_html("unstable", "", "Experimental");
454 let cfg = match (&item.cfg, parent.cfg.as_ref()) {
455 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
456 (cfg, _) => cfg.as_deref().cloned(),
459 debug!("Portability {:?} - {:?} = {:?}", item.cfg, parent.cfg, cfg);
460 if let Some(ref cfg) = cfg {
461 tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
467 fn item_function(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, f: &clean::Function) {
468 let vis = it.visibility.print_with_space(it.def_id, cx).to_string();
469 let constness = print_constness_with_space(&f.header.constness, it.const_stability(cx.tcx()));
470 let asyncness = f.header.asyncness.print_with_space();
471 let unsafety = f.header.unsafety.print_with_space();
472 let abi = print_abi_with_space(f.header.abi).to_string();
473 let name = it.name.as_ref().unwrap();
475 let generics_len = format!("{:#}", f.generics.print(cx)).len();
476 let header_len = "fn ".len()
482 + name.as_str().len()
485 wrap_into_docblock(w, |w| {
486 wrap_item(w, "fn", |w| {
487 render_attributes_in_pre(w, it, "");
488 w.reserve(header_len);
491 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
492 {name}{generics}{decl}{notable_traits}{where_clause}",
494 constness = constness,
495 asyncness = asyncness,
499 generics = f.generics.print(cx),
500 where_clause = print_where_clause(&f.generics, cx, 0, true),
501 decl = f.decl.full_print(header_len, 0, f.header.asyncness, cx),
502 notable_traits = notable_traits_decl(&f.decl, cx),
506 document(w, cx, it, None, HeadingOffset::H2)
509 fn item_trait(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Trait) {
510 let bounds = bounds(&t.bounds, false, cx);
511 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
512 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
513 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
514 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
515 let count_types = types.len();
516 let count_consts = consts.len();
517 let count_methods = required.len() + provided.len();
519 // Output the trait definition
520 wrap_into_docblock(w, |w| {
521 wrap_item(w, "trait", |w| {
522 render_attributes_in_pre(w, it, "");
525 "{}{}{}trait {}{}{}",
526 it.visibility.print_with_space(it.def_id, cx),
527 t.unsafety.print_with_space(),
528 if t.is_auto { "auto " } else { "" },
529 it.name.as_ref().unwrap(),
530 t.generics.print(cx),
534 if !t.generics.where_predicates.is_empty() {
535 write!(w, "{}", print_where_clause(&t.generics, cx, 0, true));
540 if t.items.is_empty() {
543 // FIXME: we should be using a derived_id for the Anchors here
545 let mut toggle = false;
547 // If there are too many associated types, hide _everything_
548 if should_hide_fields(count_types) {
553 "{} associated items",
554 count_types + count_consts + count_methods
559 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait, cx);
562 // If there are too many associated constants, hide everything after them
563 // We also do this if the types + consts is large because otherwise we could
564 // render a bunch of types and _then_ a bunch of consts just because both were
565 // _just_ under the limit
566 if !toggle && should_hide_fields(count_types + count_consts) {
571 "{} associated constant{} and {} method{}",
573 pluralize(count_consts),
575 pluralize(count_methods),
579 if !types.is_empty() && !consts.is_empty() {
583 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait, cx);
586 if !toggle && should_hide_fields(count_methods) {
588 toggle_open(w, format_args!("{} methods", count_methods));
590 if !consts.is_empty() && !required.is_empty() {
593 for (pos, m) in required.iter().enumerate() {
594 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait, cx);
597 if pos < required.len() - 1 {
598 w.write_str("<div class=\"item-spacer\"></div>");
601 if !required.is_empty() && !provided.is_empty() {
604 for (pos, m) in provided.iter().enumerate() {
605 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait, cx);
607 clean::MethodItem(ref inner, _)
608 if !inner.generics.where_predicates.is_empty() =>
610 w.write_str(",\n { ... }\n");
613 w.write_str(" { ... }\n");
616 if pos < provided.len() - 1 {
617 w.write_str("<div class=\"item-spacer\"></div>");
628 // Trait documentation
629 document(w, cx, it, None, HeadingOffset::H2);
631 fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
634 "<h2 id=\"{0}\" class=\"small-section-header\">\
635 {1}<a href=\"#{0}\" class=\"anchor\"></a>\
637 id, title, extra_content
641 fn trait_item(w: &mut Buffer, cx: &Context<'_>, m: &clean::Item, t: &clean::Item) {
642 let name = m.name.as_ref().unwrap();
643 info!("Documenting {} on {:?}", name, t.name);
644 let item_type = m.type_();
645 let id = cx.derive_id(format!("{}.{}", item_type, name));
646 let mut content = Buffer::empty_from(w);
647 document(&mut content, cx, m, Some(t), HeadingOffset::H5);
648 let toggled = !content.is_empty();
650 write!(w, "<details class=\"rustdoc-toggle\" open><summary>");
652 write!(w, "<div id=\"{}\" class=\"method has-srclink\">", id);
653 write!(w, "<div class=\"rightside\">");
654 render_stability_since(w, m, t, cx.tcx());
655 write_srclink(cx, m, w);
657 write!(w, "<h4 class=\"code-header\">");
658 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl, cx);
659 w.write_str("</h4>");
660 w.write_str("</div>");
662 write!(w, "</summary>");
663 w.push_buffer(content);
664 write!(w, "</details>");
668 if !types.is_empty() {
669 write_small_section_header(
673 "<div class=\"methods\">",
676 trait_item(w, cx, t, it);
678 w.write_str("</div>");
681 if !consts.is_empty() {
682 write_small_section_header(
685 "Associated Constants",
686 "<div class=\"methods\">",
689 trait_item(w, cx, t, it);
691 w.write_str("</div>");
694 // Output the documentation for each function individually
695 if !required.is_empty() {
696 write_small_section_header(
700 "<div class=\"methods\">",
703 trait_item(w, cx, m, it);
705 w.write_str("</div>");
707 if !provided.is_empty() {
708 write_small_section_header(
712 "<div class=\"methods\">",
715 trait_item(w, cx, m, it);
717 w.write_str("</div>");
720 // If there are methods directly on this trait object, render them here.
721 render_assoc_items(w, cx, it, it.def_id.expect_def_id(), AssocItemRender::All);
723 let cache = cx.cache();
724 if let Some(implementors) = cache.implementors.get(&it.def_id.expect_def_id()) {
725 // The DefId is for the first Type found with that name. The bool is
726 // if any Types with the same name but different DefId have been found.
727 let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();
728 for implementor in implementors {
729 match implementor.inner_impl().for_ {
730 clean::Type::Path { ref path }
731 | clean::BorrowedRef { type_: box clean::Type::Path { ref path }, .. }
732 if !path.is_assoc_ty() =>
734 let did = path.def_id();
735 let &mut (prev_did, ref mut has_duplicates) =
736 implementor_dups.entry(path.last()).or_insert((did, false));
738 *has_duplicates = true;
745 let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| {
746 i.inner_impl().for_.def_id(cache).map_or(true, |d| cache.paths.contains_key(&d))
749 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
750 local.iter().partition(|i| i.inner_impl().kind.is_auto());
752 synthetic.sort_by(|a, b| compare_impl(a, b, cx));
753 concrete.sort_by(|a, b| compare_impl(a, b, cx));
755 if !foreign.is_empty() {
756 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
758 for implementor in foreign {
759 let provided_methods = implementor.inner_impl().provided_trait_methods(cx.tcx());
761 AssocItemLink::GotoSource(implementor.impl_item.def_id, &provided_methods);
771 ImplRenderingParameters {
772 show_def_docs: false,
773 is_on_foreign_type: true,
774 show_default_items: false,
775 show_non_assoc_items: true,
776 toggle_open_by_default: false,
782 write_small_section_header(
786 "<div class=\"item-list\" id=\"implementors-list\">",
788 for implementor in concrete {
789 render_implementor(cx, implementor, it, w, &implementor_dups, &[]);
791 w.write_str("</div>");
794 write_small_section_header(
796 "synthetic-implementors",
798 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
800 for implementor in synthetic {
807 &collect_paths_for_type(implementor.inner_impl().for_.clone(), cache),
810 w.write_str("</div>");
813 // even without any implementations to write in, we still want the heading and list, so the
814 // implementors javascript file pulled in below has somewhere to write the impls into
815 write_small_section_header(
819 "<div class=\"item-list\" id=\"implementors-list\"></div>",
823 write_small_section_header(
825 "synthetic-implementors",
827 "<div class=\"item-list\" id=\"synthetic-implementors-list\"></div>",
834 "<script type=\"text/javascript\" \
835 src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\
837 root_path = vec![".."; cx.current.len()].join("/"),
838 path = if it.def_id.is_local() {
841 let (ref path, _) = cache.external_paths[&it.def_id.expect_def_id()];
842 path[..path.len() - 1].join("/")
845 name = *it.name.as_ref().unwrap()
849 fn item_trait_alias(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::TraitAlias) {
850 wrap_into_docblock(w, |w| {
851 wrap_item(w, "trait-alias", |w| {
852 render_attributes_in_pre(w, it, "");
855 "trait {}{}{} = {};",
856 it.name.as_ref().unwrap(),
857 t.generics.print(cx),
858 print_where_clause(&t.generics, cx, 0, true),
859 bounds(&t.bounds, true, cx)
864 document(w, cx, it, None, HeadingOffset::H2);
866 // Render any items associated directly to this alias, as otherwise they
867 // won't be visible anywhere in the docs. It would be nice to also show
868 // associated items from the aliased type (see discussion in #32077), but
869 // we need #14072 to make sense of the generics.
870 render_assoc_items(w, cx, it, it.def_id.expect_def_id(), AssocItemRender::All)
873 fn item_opaque_ty(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::OpaqueTy) {
874 wrap_into_docblock(w, |w| {
875 wrap_item(w, "opaque", |w| {
876 render_attributes_in_pre(w, it, "");
879 "type {}{}{where_clause} = impl {bounds};",
880 it.name.as_ref().unwrap(),
881 t.generics.print(cx),
882 where_clause = print_where_clause(&t.generics, cx, 0, true),
883 bounds = bounds(&t.bounds, false, cx),
888 document(w, cx, it, None, HeadingOffset::H2);
890 // Render any items associated directly to this alias, as otherwise they
891 // won't be visible anywhere in the docs. It would be nice to also show
892 // associated items from the aliased type (see discussion in #32077), but
893 // we need #14072 to make sense of the generics.
894 render_assoc_items(w, cx, it, it.def_id.expect_def_id(), AssocItemRender::All)
911 wrap_item(w, "typedef", |w| {
912 render_attributes_in_pre(w, it, "");
914 write!(w, "{}", it.visibility.print_with_space(it.def_id, cx));
918 "type {}{}{where_clause} = {type_};",
919 it.name.as_ref().unwrap(),
920 t.generics.print(cx),
921 where_clause = print_where_clause(&t.generics, cx, 0, true),
922 type_ = t.type_.print(cx),
927 // If this is an associated typedef, we don't want to wrap it into a docblock.
929 write_content(w, cx, it, t, is_associated);
931 wrap_into_docblock(w, |w| {
932 write_content(w, cx, it, t, is_associated);
936 document(w, cx, it, None, HeadingOffset::H2);
938 let def_id = it.def_id.expect_def_id();
939 // Render any items associated directly to this alias, as otherwise they
940 // won't be visible anywhere in the docs. It would be nice to also show
941 // associated items from the aliased type (see discussion in #32077), but
942 // we need #14072 to make sense of the generics.
943 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
946 fn item_union(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Union) {
947 wrap_into_docblock(w, |w| {
948 wrap_item(w, "union", |w| {
949 render_attributes_in_pre(w, it, "");
950 render_union(w, it, Some(&s.generics), &s.fields, "", cx);
954 document(w, cx, it, None, HeadingOffset::H2);
959 .filter_map(|f| match *f.kind {
960 clean::StructFieldItem(ref ty) => Some((f, ty)),
964 if fields.peek().is_some() {
967 "<h2 id=\"fields\" class=\"fields small-section-header\">\
968 Fields<a href=\"#fields\" class=\"anchor\"></a></h2>"
970 for (field, ty) in fields {
971 let name = field.name.as_ref().expect("union field name");
972 let id = format!("{}.{}", ItemType::StructField, name);
975 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
976 <a href=\"#{id}\" class=\"anchor field\"></a>\
977 <code>{name}: {ty}</code>\
981 shortty = ItemType::StructField,
984 if let Some(stability_class) = field.stability_class(cx.tcx()) {
985 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
987 document(w, cx, field, Some(it), HeadingOffset::H3);
990 let def_id = it.def_id.expect_def_id();
991 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
992 document_type_layout(w, cx, def_id);
995 fn print_tuple_struct_fields(w: &mut Buffer, cx: &Context<'_>, s: &[clean::Item]) {
996 for (i, ty) in s.iter().enumerate() {
998 w.write_str(", ");
1001 clean::StrippedItem(box clean::StructFieldItem(_)) => w.write_str("_"),
1002 clean::StructFieldItem(ref ty) => write!(w, "{}", ty.print(cx)),
1003 _ => unreachable!(),
1008 fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum) {
1009 wrap_into_docblock(w, |w| {
1010 wrap_item(w, "enum", |w| {
1011 render_attributes_in_pre(w, it, "");
1015 it.visibility.print_with_space(it.def_id, cx),
1016 it.name.as_ref().unwrap(),
1017 e.generics.print(cx),
1018 print_where_clause(&e.generics, cx, 0, true),
1020 if e.variants.is_empty() && !e.variants_stripped {
1023 w.write_str(" {\n");
1024 let count_variants = e.variants.len();
1025 let toggle = should_hide_fields(count_variants);
1027 toggle_open(w, format_args!("{} variants", count_variants));
1029 for v in &e.variants {
1031 let name = v.name.as_ref().unwrap();
1033 clean::VariantItem(ref var) => match var {
1034 clean::Variant::CLike => write!(w, "{}", name),
1035 clean::Variant::Tuple(ref s) => {
1036 write!(w, "{}(", name);
1037 print_tuple_struct_fields(w, cx, s);
1040 clean::Variant::Struct(ref s) => {
1053 _ => unreachable!(),
1058 if e.variants_stripped {
1059 w.write_str(" // some variants omitted\n");
1069 document(w, cx, it, None, HeadingOffset::H2);
1071 if !e.variants.is_empty() {
1074 "<h2 id=\"variants\" class=\"variants small-section-header\">\
1075 Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>",
1076 document_non_exhaustive_header(it)
1078 document_non_exhaustive(w, it);
1079 for variant in &e.variants {
1081 cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap()));
1084 "<h3 id=\"{id}\" class=\"variant small-section-header\">\
1085 <a href=\"#{id}\" class=\"anchor field\"></a>\
1088 name = variant.name.as_ref().unwrap()
1090 if let clean::VariantItem(clean::Variant::Tuple(ref s)) = *variant.kind {
1092 print_tuple_struct_fields(w, cx, s);
1095 w.write_str("</code>");
1096 render_stability_since(w, variant, it, cx.tcx());
1097 w.write_str("</h3>");
1099 use crate::clean::Variant;
1100 if let Some((extra, fields)) = match *variant.kind {
1101 clean::VariantItem(Variant::Struct(ref s)) => Some(("", &s.fields)),
1102 clean::VariantItem(Variant::Tuple(ref fields)) => Some(("Tuple ", fields)),
1105 let variant_id = cx.derive_id(format!(
1108 variant.name.as_ref().unwrap()
1110 write!(w, "<div class=\"sub-variant\" id=\"{id}\">", id = variant_id);
1111 write!(w, "<h4>{extra}Fields</h4>", extra = extra,);
1112 document_non_exhaustive(w, variant);
1113 for field in fields {
1115 clean::StrippedItem(box clean::StructFieldItem(_)) => {}
1116 clean::StructFieldItem(ref ty) => {
1117 let id = cx.derive_id(format!(
1118 "variant.{}.field.{}",
1119 variant.name.as_ref().unwrap(),
1120 field.name.as_ref().unwrap()
1124 "<div class=\"sub-variant-field\">\
1125 <span id=\"{id}\" class=\"variant small-section-header\">\
1126 <a href=\"#{id}\" class=\"anchor field\"></a>\
1127 <code>{f}: {t}</code>\
1130 f = field.name.as_ref().unwrap(),
1133 document(w, cx, field, Some(variant), HeadingOffset::H5);
1134 write!(w, "</div>");
1136 _ => unreachable!(),
1139 w.write_str("</div>");
1142 document(w, cx, variant, Some(it), HeadingOffset::H4);
1145 let def_id = it.def_id.expect_def_id();
1146 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1147 document_type_layout(w, cx, def_id);
1150 fn item_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Macro) {
1151 wrap_into_docblock(w, |w| {
1152 highlight::render_with_highlighting(
1158 it.span(cx.tcx()).inner().edition(),
1164 document(w, cx, it, None, HeadingOffset::H2)
1167 fn item_proc_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, m: &clean::ProcMacro) {
1168 wrap_into_docblock(w, |w| {
1169 let name = it.name.as_ref().expect("proc-macros always have names");
1171 MacroKind::Bang => {
1172 wrap_item(w, "macro", |w| {
1173 write!(w, "{}!() {{ /* proc-macro */ }}", name);
1176 MacroKind::Attr => {
1177 wrap_item(w, "attr", |w| {
1178 write!(w, "#[{}]", name);
1181 MacroKind::Derive => {
1182 wrap_item(w, "derive", |w| {
1183 write!(w, "#[derive({})]", name);
1184 if !m.helpers.is_empty() {
1185 w.push_str("\n{\n");
1186 w.push_str(" // Attributes available to this derive:\n");
1187 for attr in &m.helpers {
1188 writeln!(w, " #[{}]", attr);
1196 document(w, cx, it, None, HeadingOffset::H2)
1199 fn item_primitive(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
1200 document(w, cx, it, None, HeadingOffset::H2);
1201 render_assoc_items(w, cx, it, it.def_id.expect_def_id(), AssocItemRender::All)
1204 fn item_constant(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, c: &clean::Constant) {
1205 wrap_into_docblock(w, |w| {
1206 wrap_item(w, "const", |w| {
1207 render_attributes_in_code(w, it);
1211 "{vis}const {name}: {typ}",
1212 vis = it.visibility.print_with_space(it.def_id, cx),
1213 name = it.name.as_ref().unwrap(),
1214 typ = c.type_.print(cx),
1217 let value = c.value(cx.tcx());
1218 let is_literal = c.is_literal(cx.tcx());
1219 let expr = c.expr(cx.tcx());
1220 if value.is_some() || is_literal {
1221 write!(w, " = {expr};", expr = Escape(&expr));
1227 if let Some(value) = &value {
1228 let value_lowercase = value.to_lowercase();
1229 let expr_lowercase = expr.to_lowercase();
1231 if value_lowercase != expr_lowercase
1232 && value_lowercase.trim_end_matches("i32") != expr_lowercase
1234 write!(w, " // {value}", value = Escape(value));
1241 document(w, cx, it, None, HeadingOffset::H2)
1244 fn item_struct(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Struct) {
1245 wrap_into_docblock(w, |w| {
1246 wrap_item(w, "struct", |w| {
1247 render_attributes_in_code(w, it);
1248 render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true, cx);
1252 document(w, cx, it, None, HeadingOffset::H2);
1257 .filter_map(|f| match *f.kind {
1258 clean::StructFieldItem(ref ty) => Some((f, ty)),
1262 if let CtorKind::Fictive | CtorKind::Fn = s.struct_type {
1263 if fields.peek().is_some() {
1266 "<h2 id=\"fields\" class=\"fields small-section-header\">\
1267 {}{}<a href=\"#fields\" class=\"anchor\"></a>\
1269 if let CtorKind::Fictive = s.struct_type { "Fields" } else { "Tuple Fields" },
1270 document_non_exhaustive_header(it)
1272 document_non_exhaustive(w, it);
1273 for (index, (field, ty)) in fields.enumerate() {
1275 field.name.map_or_else(|| index.to_string(), |sym| (*sym.as_str()).to_string());
1276 let id = cx.derive_id(format!("{}.{}", ItemType::StructField, field_name));
1279 "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
1280 <a href=\"#{id}\" class=\"anchor field\"></a>\
1281 <code>{name}: {ty}</code>\
1283 item_type = ItemType::StructField,
1288 document(w, cx, field, Some(it), HeadingOffset::H3);
1292 let def_id = it.def_id.expect_def_id();
1293 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1294 document_type_layout(w, cx, def_id);
1297 fn item_static(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Static) {
1298 wrap_into_docblock(w, |w| {
1299 wrap_item(w, "static", |w| {
1300 render_attributes_in_code(w, it);
1303 "{vis}static {mutability}{name}: {typ}",
1304 vis = it.visibility.print_with_space(it.def_id, cx),
1305 mutability = s.mutability.print_with_space(),
1306 name = it.name.as_ref().unwrap(),
1307 typ = s.type_.print(cx)
1311 document(w, cx, it, None, HeadingOffset::H2)
1314 fn item_foreign_type(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
1315 wrap_into_docblock(w, |w| {
1316 wrap_item(w, "foreigntype", |w| {
1317 w.write_str("extern {\n");
1318 render_attributes_in_code(w, it);
1322 it.visibility.print_with_space(it.def_id, cx),
1323 it.name.as_ref().unwrap(),
1328 document(w, cx, it, None, HeadingOffset::H2);
1330 render_assoc_items(w, cx, it, it.def_id.expect_def_id(), AssocItemRender::All)
1333 fn item_keyword(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
1334 document(w, cx, it, None, HeadingOffset::H2)
1337 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
1338 crate fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
1339 /// Takes a non-numeric and a numeric part from the given &str.
1340 fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
1341 let i = s.find(|c: char| c.is_ascii_digit());
1342 let (a, b) = s.split_at(i.unwrap_or(s.len()));
1343 let i = b.find(|c: char| !c.is_ascii_digit());
1344 let (b, c) = b.split_at(i.unwrap_or(b.len()));
1349 while !lhs.is_empty() || !rhs.is_empty() {
1350 let (la, lb) = take_parts(&mut lhs);
1351 let (ra, rb) = take_parts(&mut rhs);
1352 // First process the non-numeric part.
1354 Ordering::Equal => (),
1357 // Then process the numeric part, if both sides have one (and they fit in a u64).
1358 if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
1360 Ordering::Equal => (),
1364 // Then process the numeric part again, but this time as strings.
1366 Ordering::Equal => (),
1374 pub(super) fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
1375 let mut s = cx.current.join("::");
1377 s.push_str(&item.name.unwrap().as_str());
1381 pub(super) fn item_path(ty: ItemType, name: &str) -> String {
1383 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1384 _ => format!("{}.{}.html", ty, name),
1388 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool, cx: &Context<'_>) -> String {
1389 let mut bounds = String::new();
1390 if !t_bounds.is_empty() {
1392 bounds.push_str(": ");
1394 for (i, p) in t_bounds.iter().enumerate() {
1396 bounds.push_str(" + ");
1398 bounds.push_str(&p.print(cx).to_string());
1404 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1406 F: FnOnce(&mut Buffer),
1408 w.write_str("<div class=\"docblock item-decl\">");
1410 w.write_str("</div>")
1413 fn wrap_item<F>(w: &mut Buffer, item_name: &str, f: F)
1415 F: FnOnce(&mut Buffer),
1417 w.write_fmt(format_args!("<pre class=\"rust {}\"><code>", item_name));
1419 w.write_str("</code></pre>");
1422 fn render_stability_since(
1425 containing_item: &clean::Item,
1428 render_stability_since_raw(
1430 item.stable_since(tcx).as_deref(),
1431 item.const_stability(tcx),
1432 containing_item.stable_since(tcx).as_deref(),
1433 containing_item.const_stable_since(tcx).as_deref(),
1437 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl, cx: &Context<'_>) -> Ordering {
1438 let lhss = format!("{}", lhs.inner_impl().print(false, cx));
1439 let rhss = format!("{}", rhs.inner_impl().print(false, cx));
1441 // lhs and rhs are formatted as HTML, which may be unnecessary
1442 compare_names(&lhss, &rhss)
1445 fn render_implementor(
1448 trait_: &clean::Item,
1450 implementor_dups: &FxHashMap<Symbol, (DefId, bool)>,
1453 // If there's already another implementor that has the same abridged name, use the
1454 // full path, for example in `std::iter::ExactSizeIterator`
1455 let use_absolute = match implementor.inner_impl().for_ {
1456 clean::Type::Path { ref path, .. }
1457 | clean::BorrowedRef { type_: box clean::Type::Path { ref path, .. }, .. }
1458 if !path.is_assoc_ty() =>
1460 implementor_dups[&path.last()].1
1469 AssocItemLink::Anchor(None),
1473 ImplRenderingParameters {
1474 show_def_docs: false,
1475 is_on_foreign_type: false,
1476 show_default_items: false,
1477 show_non_assoc_items: false,
1478 toggle_open_by_default: false,
1486 g: Option<&clean::Generics>,
1487 fields: &[clean::Item],
1494 it.visibility.print_with_space(it.def_id, cx),
1495 it.name.as_ref().unwrap()
1497 if let Some(g) = g {
1498 write!(w, "{}", g.print(cx));
1499 write!(w, "{}", print_where_clause(g, cx, 0, true));
1502 write!(w, " {{\n{}", tab);
1504 fields.iter().filter(|f| matches!(*f.kind, clean::StructFieldItem(..))).count();
1505 let toggle = should_hide_fields(count_fields);
1507 toggle_open(w, format_args!("{} fields", count_fields));
1510 for field in fields {
1511 if let clean::StructFieldItem(ref ty) = *field.kind {
1515 field.visibility.print_with_space(field.def_id, cx),
1516 field.name.as_ref().unwrap(),
1523 if it.has_stripped_fields().unwrap() {
1524 write!(w, " // some fields omitted\n{}", tab);
1535 g: Option<&clean::Generics>,
1537 fields: &[clean::Item],
1545 it.visibility.print_with_space(it.def_id, cx),
1546 if structhead { "struct " } else { "" },
1547 it.name.as_ref().unwrap()
1549 if let Some(g) = g {
1550 write!(w, "{}", g.print(cx))
1553 CtorKind::Fictive => {
1554 if let Some(g) = g {
1555 write!(w, "{}", print_where_clause(g, cx, 0, true),)
1559 fields.iter().filter(|f| matches!(*f.kind, clean::StructFieldItem(..))).count();
1560 let has_visible_fields = count_fields > 0;
1561 let toggle = should_hide_fields(count_fields);
1563 toggle_open(w, format_args!("{} fields", count_fields));
1565 for field in fields {
1566 if let clean::StructFieldItem(ref ty) = *field.kind {
1571 field.visibility.print_with_space(field.def_id, cx),
1572 field.name.as_ref().unwrap(),
1578 if has_visible_fields {
1579 if it.has_stripped_fields().unwrap() {
1580 write!(w, "\n{} // some fields omitted", tab);
1582 write!(w, "\n{}", tab);
1583 } else if it.has_stripped_fields().unwrap() {
1584 // If there are no visible fields we can just display
1585 // `{ /* fields omitted */ }` to save space.
1586 write!(w, " /* fields omitted */ ");
1595 for (i, field) in fields.iter().enumerate() {
1600 clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
1601 clean::StructFieldItem(ref ty) => {
1605 field.visibility.print_with_space(field.def_id, cx),
1609 _ => unreachable!(),
1613 if let Some(g) = g {
1614 write!(w, "{}", print_where_clause(g, cx, 0, false),)
1616 // We only want a ";" when we are displaying a tuple struct, not a variant tuple struct.
1621 CtorKind::Const => {
1622 // Needed for PhantomData.
1623 if let Some(g) = g {
1624 write!(w, "{}", print_where_clause(g, cx, 0, false),)
1631 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1632 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1635 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1636 if item.is_non_exhaustive() {
1639 "<details class=\"rustdoc-toggle non-exhaustive\">\
1640 <summary class=\"hideme\"><span>{}</span></summary>\
1641 <div class=\"docblock\">",
1643 if item.is_struct() {
1644 "This struct is marked as non-exhaustive"
1645 } else if item.is_enum() {
1646 "This enum is marked as non-exhaustive"
1647 } else if item.is_variant() {
1648 "This variant is marked as non-exhaustive"
1650 "This type is marked as non-exhaustive"
1655 if item.is_struct() {
1657 "Non-exhaustive structs could have additional fields added in future. \
1658 Therefore, non-exhaustive structs cannot be constructed in external crates \
1659 using the traditional <code>Struct { .. }</code> syntax; cannot be \
1660 matched against without a wildcard <code>..</code>; and \
1661 struct update syntax will not work.",
1663 } else if item.is_enum() {
1665 "Non-exhaustive enums could have additional variants added in future. \
1666 Therefore, when matching against variants of non-exhaustive enums, an \
1667 extra wildcard arm must be added to account for any future variants.",
1669 } else if item.is_variant() {
1671 "Non-exhaustive enum variants could have additional fields added in future. \
1672 Therefore, non-exhaustive enum variants cannot be constructed in external \
1673 crates and cannot be matched against.",
1677 "This type will require a wildcard arm in any match statements or constructors.",
1681 w.write_str("</div></details>");
1685 fn document_type_layout(w: &mut Buffer, cx: &Context<'_>, ty_def_id: DefId) {
1686 fn write_size_of_layout(w: &mut Buffer, layout: &Layout, tag_size: u64) {
1687 if layout.abi.is_unsized() {
1688 write!(w, "(unsized)");
1690 let bytes = layout.size.bytes() - tag_size;
1691 write!(w, "{size} byte{pl}", size = bytes, pl = if bytes == 1 { "" } else { "s" },);
1695 if !cx.shared.show_type_layout {
1699 writeln!(w, "<h2 class=\"small-section-header\">Layout</h2>");
1700 writeln!(w, "<div class=\"docblock\">");
1703 let param_env = tcx.param_env(ty_def_id);
1704 let ty = tcx.type_of(ty_def_id);
1705 match tcx.layout_of(param_env.and(ty)) {
1709 "<div class=\"warning\"><p><strong>Note:</strong> Most layout information is \
1710 <strong>completely unstable</strong> and may even differ between compilations. \
1711 The only exception is types with certain <code>repr(...)</code> attributes. \
1712 Please see the Rust Reference’s \
1713 <a href=\"https://doc.rust-lang.org/reference/type-layout.html\">“Type Layout”</a> \
1714 chapter for details on type layout guarantees.</p></div>"
1716 w.write_str("<p><strong>Size:</strong> ");
1717 write_size_of_layout(w, ty_layout.layout, 0);
1718 writeln!(w, "</p>");
1719 if let Variants::Multiple { variants, tag, tag_encoding, .. } =
1720 &ty_layout.layout.variants
1722 if !variants.is_empty() {
1724 "<p><strong>Size for each variant:</strong></p>\
1728 let adt = if let Adt(adt, _) = ty_layout.ty.kind() {
1731 span_bug!(tcx.def_span(ty_def_id), "not an adt")
1734 let tag_size = if let TagEncoding::Niche { .. } = tag_encoding {
1736 } else if let Primitive::Int(i, _) = tag.value {
1739 span_bug!(tcx.def_span(ty_def_id), "tag is neither niche nor int")
1742 for (index, layout) in variants.iter_enumerated() {
1743 let ident = adt.variants[index].ident;
1744 write!(w, "<li><code>{name}</code>: ", name = ident);
1745 write_size_of_layout(w, layout, tag_size);
1746 writeln!(w, "</li>");
1748 w.write_str("</ul>");
1752 // This kind of layout error can occur with valid code, e.g. if you try to
1753 // get the layout of a generic type such as `Vec<T>`.
1754 Err(LayoutError::Unknown(_)) => {
1757 "<p><strong>Note:</strong> Unable to compute type layout, \
1758 possibly due to this type having generic parameters. \
1759 Layout can only be computed for concrete, fully-instantiated types.</p>"
1762 // This kind of error probably can't happen with valid code, but we don't
1763 // want to panic and prevent the docs from building, so we just let the
1764 // user know that we couldn't compute the layout.
1765 Err(LayoutError::SizeOverflow(_)) => {
1768 "<p><strong>Note:</strong> Encountered an error during type layout; \
1769 the type was too big.</p>"
1772 Err(LayoutError::NormalizationFailure(_, _)) => {
1775 "<p><strong>Note:</strong> Encountered an error during type layout; \
1776 the type failed to be normalized.</p>"
1781 writeln!(w, "</div>");
1784 fn pluralize(count: usize) -> &'static str {
1785 if count > 1 { "s" } else { "" }