1 use clean::AttributesExt;
3 use std::cmp::Ordering;
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
9 use rustc_hir::def::CtorKind;
10 use rustc_hir::def_id::DefId;
11 use rustc_middle::middle::stability;
12 use rustc_middle::span_bug;
13 use rustc_middle::ty::layout::LayoutError;
14 use rustc_middle::ty::{Adt, TyCtxt};
15 use rustc_span::hygiene::MacroKind;
16 use rustc_span::symbol::{kw, sym, Symbol};
17 use rustc_target::abi::{Layout, Primitive, TagEncoding, Variants};
20 collect_paths_for_type, document, ensure_trailing_slash, item_ty_to_section,
21 notable_traits_decl, render_assoc_item, render_assoc_items, render_attributes_in_code,
22 render_attributes_in_pre, render_impl, render_stability_since_raw, write_srclink,
23 AssocItemLink, Context, ImplRenderingParameters,
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, PrintWithSpace,
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;
40 const ITEM_TABLE_OPEN: &str = "<div class=\"item-table\">";
41 const ITEM_TABLE_CLOSE: &str = "</div>";
42 const ITEM_TABLE_ROW_OPEN: &str = "<div class=\"item-row\">";
43 const ITEM_TABLE_ROW_CLOSE: &str = "</div>";
45 // A component in a `use` path, like `string` in std::string::ToString
46 struct PathComponent {
52 #[template(path = "print_item.html")]
55 static_root_path: &'a str,
59 path_components: Vec<PathComponent>,
60 stability_since_raw: &'a str,
61 src_href: Option<&'a str>,
64 pub(super) fn print_item(
70 debug_assert!(!item.is_stripped());
71 let typ = match *item.kind {
72 clean::ModuleItem(_) => {
79 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
80 clean::TraitItem(..) => "Trait ",
81 clean::StructItem(..) => "Struct ",
82 clean::UnionItem(..) => "Union ",
83 clean::EnumItem(..) => "Enum ",
84 clean::TypedefItem(..) => "Type Definition ",
85 clean::MacroItem(..) => "Macro ",
86 clean::ProcMacroItem(ref mac) => match mac.kind {
87 MacroKind::Bang => "Macro ",
88 MacroKind::Attr => "Attribute Macro ",
89 MacroKind::Derive => "Derive Macro ",
91 clean::PrimitiveItem(..) => "Primitive Type ",
92 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
93 clean::ConstantItem(..) => "Constant ",
94 clean::ForeignTypeItem => "Foreign Type ",
95 clean::KeywordItem(..) => "Keyword ",
96 clean::OpaqueTyItem(..) => "Opaque Type ",
97 clean::TraitAliasItem(..) => "Trait Alias ",
99 // We don't generate pages for any other type.
103 let mut stability_since_raw = Buffer::new();
104 render_stability_since_raw(
105 &mut stability_since_raw,
106 item.stable_since(cx.tcx()),
107 item.const_stability(cx.tcx()),
111 let stability_since_raw: String = stability_since_raw.into_inner();
115 // When this item is part of a `crate use` in a downstream crate, the
116 // source link in the downstream documentation will actually come back to
117 // this page, and this link will be auto-clicked. The `id` attribute is
118 // used to find the link to auto-click.
120 if cx.include_sources && !item.is_primitive() { cx.src_href(item) } else { None };
122 let path_components = if item.is_primitive() || item.is_keyword() {
125 let cur = &cx.current;
126 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
130 .map(|(i, component)| PathComponent {
131 path: "../".repeat(cur.len() - i - 1),
137 let item_vars = ItemVars {
139 static_root_path: page.get_static_root_path(),
141 name: item.name.as_ref().unwrap().as_str(),
142 item_type: &item.type_().to_string(),
144 stability_since_raw: &stability_since_raw,
145 src_href: src_href.as_deref(),
148 item_vars.render_into(buf).unwrap();
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) => item_typedef(buf, cx, item, t),
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: &mut 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_();
230 if item_ty_to_section(ty1) != item_ty_to_section(ty2)
231 || (ty1 != ty2 && (ty1 == ItemType::ExternCrate || ty2 == ItemType::ExternCrate))
233 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
235 let s1 = i1.stability(tcx).as_ref().map(|s| s.level);
236 let s2 = i2.stability(tcx).as_ref().map(|s| s.level);
237 if let (Some(a), Some(b)) = (s1, s2) {
238 match (a.is_stable(), b.is_stable()) {
239 (true, true) | (false, false) => {}
240 (false, true) => return Ordering::Less,
241 (true, false) => return Ordering::Greater,
244 let lhs = i1.name.unwrap_or(kw::Empty);
245 let rhs = i2.name.unwrap_or(kw::Empty);
246 compare_names(lhs.as_str(), rhs.as_str())
249 if cx.shared.sort_modules_alphabetically {
250 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2, cx.tcx()));
252 // This call is to remove re-export duplicates in cases such as:
255 // pub(crate) mod foo {
256 // pub(crate) mod bar {
257 // pub(crate) trait Double { fn foo(); }
261 // pub(crate) use foo::bar::*;
262 // pub(crate) use foo::*;
265 // `Double` will appear twice in the generated docs.
267 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
268 // can be identical even if the elements are different (mostly in imports).
269 // So in case this is an import, we keep everything by adding a "unique id"
270 // (which is the position in the vector).
271 indices.dedup_by_key(|i| {
274 if items[*i].name.is_some() { Some(full_path(cx, &items[*i])) } else { None },
276 if items[*i].is_import() { *i } else { 0 },
280 debug!("{:?}", indices);
281 let mut last_section = None;
283 for &idx in &indices {
284 let myitem = &items[idx];
285 if myitem.is_stripped() {
289 let my_section = item_ty_to_section(myitem.type_());
290 if Some(my_section) != last_section {
291 if last_section.is_some() {
292 w.write_str(ITEM_TABLE_CLOSE);
294 last_section = Some(my_section);
297 "<h2 id=\"{id}\" class=\"small-section-header\">\
298 <a href=\"#{id}\">{name}</a>\
301 id = cx.derive_id(my_section.id().to_owned()),
302 name = my_section.name(),
307 clean::ExternCrateItem { ref src } => {
308 use crate::html::format::anchor;
310 w.write_str(ITEM_TABLE_ROW_OPEN);
314 "<div class=\"item-left\"><code>{}extern crate {} as {};",
315 myitem.visibility.print_with_space(myitem.item_id, cx),
316 anchor(myitem.item_id.expect_def_id(), src, cx),
317 myitem.name.unwrap(),
321 "<div class=\"item-left\"><code>{}extern crate {};",
322 myitem.visibility.print_with_space(myitem.item_id, cx),
323 anchor(myitem.item_id.expect_def_id(), myitem.name.unwrap(), cx),
326 w.write_str("</code></div>");
327 w.write_str(ITEM_TABLE_ROW_CLOSE);
330 clean::ImportItem(ref import) => {
331 let (stab, stab_tags) = if let Some(import_def_id) = import.source.did {
332 let ast_attrs = cx.tcx().get_attrs_unchecked(import_def_id);
333 let import_attrs = Box::new(clean::Attributes::from_ast(ast_attrs, None));
335 // Just need an item with the correct def_id and attrs
336 let import_item = clean::Item {
337 item_id: import_def_id.into(),
339 cfg: ast_attrs.cfg(cx.tcx(), &cx.cache().hidden_cfg),
343 let stab = import_item.stability_class(cx.tcx());
344 let stab_tags = Some(extra_info_tags(&import_item, item, cx.tcx()));
350 let add = if stab.is_some() { " " } else { "" };
352 w.write_str(ITEM_TABLE_ROW_OPEN);
353 let id = match import.kind {
354 clean::ImportKind::Simple(s) => {
355 format!(" id=\"{}\"", cx.derive_id(format!("reexport.{}", s)))
357 clean::ImportKind::Glob => String::new(),
361 "<div class=\"item-left {stab}{add}import-item\"{id}>\
362 <code>{vis}{imp}</code>\
364 <div class=\"item-right docblock-short\">{stab_tags}</div>",
365 stab = stab.unwrap_or_default(),
366 vis = myitem.visibility.print_with_space(myitem.item_id, cx),
367 imp = import.print(cx),
368 stab_tags = stab_tags.unwrap_or_default(),
370 w.write_str(ITEM_TABLE_ROW_CLOSE);
374 if myitem.name.is_none() {
378 let unsafety_flag = match *myitem.kind {
379 clean::FunctionItem(_) | clean::ForeignFunctionItem(_)
380 if myitem.fn_header(cx.tcx()).unwrap().unsafety
381 == 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 visibility_emoji = match myitem.visibility {
392 clean::Visibility::Restricted(_) => {
393 "<span title=\"Restricted Visibility\"> 🔒</span> "
398 let doc_value = myitem.doc_value().unwrap_or_default();
399 w.write_str(ITEM_TABLE_ROW_OPEN);
402 "<div class=\"item-left {stab}{add}module-item\">\
403 <a class=\"{class}\" href=\"{href}\" title=\"{title}\">{name}</a>\
408 <div class=\"item-right docblock-short\">{docs}</div>",
409 name = myitem.name.unwrap(),
410 visibility_emoji = visibility_emoji,
411 stab_tags = extra_info_tags(myitem, item, cx.tcx()),
412 docs = MarkdownSummaryLine(&doc_value, &myitem.links(cx)).into_string(),
413 class = myitem.type_(),
415 stab = stab.unwrap_or_default(),
416 unsafety_flag = unsafety_flag,
417 href = item_path(myitem.type_(), myitem.name.unwrap().as_str()),
418 title = [full_path(cx, myitem), myitem.type_().to_string()]
420 .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
424 w.write_str(ITEM_TABLE_ROW_CLOSE);
429 if last_section.is_some() {
430 w.write_str(ITEM_TABLE_CLOSE);
434 /// Render the stability, deprecation and portability tags that are displayed in the item's summary
435 /// at the module level.
436 fn extra_info_tags(item: &clean::Item, parent: &clean::Item, tcx: TyCtxt<'_>) -> String {
437 let mut tags = String::new();
439 fn tag_html(class: &str, title: &str, contents: &str) -> String {
440 format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
443 // The trailing space after each tag is to space it properly against the rest of the docs.
444 if let Some(depr) = &item.deprecation(tcx) {
445 let mut message = "Deprecated";
446 if !stability::deprecation_in_effect(depr) {
447 message = "Deprecation planned";
449 tags += &tag_html("deprecated", "", message);
452 // The "rustc_private" crates are permanently unstable so it makes no sense
453 // to render "unstable" everywhere.
454 if item.stability(tcx).as_ref().map(|s| s.is_unstable() && s.feature != sym::rustc_private)
457 tags += &tag_html("unstable", "", "Experimental");
460 let cfg = match (&item.cfg, parent.cfg.as_ref()) {
461 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
462 (cfg, _) => cfg.as_deref().cloned(),
465 debug!("Portability {:?} - {:?} = {:?}", item.cfg, parent.cfg, cfg);
466 if let Some(ref cfg) = cfg {
467 tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
473 fn item_function(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, f: &clean::Function) {
474 let header = it.fn_header(cx.tcx()).expect("printing a function which isn't a function");
475 let constness = print_constness_with_space(&header.constness, it.const_stability(cx.tcx()));
476 let unsafety = header.unsafety.print_with_space();
477 let abi = print_abi_with_space(header.abi).to_string();
478 let asyncness = header.asyncness.print_with_space();
479 let visibility = it.visibility.print_with_space(it.item_id, cx).to_string();
480 let name = it.name.unwrap();
482 let generics_len = format!("{:#}", f.generics.print(cx)).len();
483 let header_len = "fn ".len()
489 + name.as_str().len()
492 wrap_into_docblock(w, |w| {
493 wrap_item(w, "fn", |w| {
494 render_attributes_in_pre(w, it, "");
495 w.reserve(header_len);
498 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
499 {name}{generics}{decl}{notable_traits}{where_clause}",
501 constness = constness,
502 asyncness = asyncness,
506 generics = f.generics.print(cx),
507 where_clause = print_where_clause(&f.generics, cx, 0, true),
508 decl = f.decl.full_print(header_len, 0, header.asyncness, cx),
509 notable_traits = notable_traits_decl(&f.decl, cx),
513 document(w, cx, it, None, HeadingOffset::H2)
516 fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::Trait) {
517 let bounds = bounds(&t.bounds, false, cx);
518 let required_types = t.items.iter().filter(|m| m.is_ty_associated_type()).collect::<Vec<_>>();
519 let provided_types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
520 let required_consts = t.items.iter().filter(|m| m.is_ty_associated_const()).collect::<Vec<_>>();
521 let provided_consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
522 let required_methods = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
523 let provided_methods = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
524 let count_types = required_types.len() + provided_types.len();
525 let count_consts = required_consts.len() + provided_consts.len();
526 let count_methods = required_methods.len() + provided_methods.len();
528 // Output the trait definition
529 wrap_into_docblock(w, |w| {
530 wrap_item(w, "trait", |w| {
531 render_attributes_in_pre(w, it, "");
534 "{}{}{}trait {}{}{}",
535 it.visibility.print_with_space(it.item_id, cx),
536 t.unsafety.print_with_space(),
537 if t.is_auto { "auto " } else { "" },
539 t.generics.print(cx),
543 if !t.generics.where_predicates.is_empty() {
544 write!(w, "{}", print_where_clause(&t.generics, cx, 0, true));
549 if t.items.is_empty() {
552 // FIXME: we should be using a derived_id for the Anchors here
554 let mut toggle = false;
556 // If there are too many associated types, hide _everything_
557 if should_hide_fields(count_types) {
562 "{} associated items",
563 count_types + count_consts + count_methods
567 for types in [&required_types, &provided_types] {
572 AssocItemLink::Anchor(None),
580 // If there are too many associated constants, hide everything after them
581 // We also do this if the types + consts is large because otherwise we could
582 // render a bunch of types and _then_ a bunch of consts just because both were
583 // _just_ under the limit
584 if !toggle && should_hide_fields(count_types + count_consts) {
589 "{} associated constant{} and {} method{}",
591 pluralize(count_consts),
593 pluralize(count_methods),
597 if count_types != 0 && (count_consts != 0 || count_methods != 0) {
600 for consts in [&required_consts, &provided_consts] {
605 AssocItemLink::Anchor(None),
613 if !toggle && should_hide_fields(count_methods) {
615 toggle_open(w, format_args!("{} methods", count_methods));
617 if count_consts != 0 && count_methods != 0 {
620 for (pos, m) in required_methods.iter().enumerate() {
624 AssocItemLink::Anchor(None),
631 if pos < required_methods.len() - 1 {
632 w.write_str("<span class=\"item-spacer\"></span>");
635 if !required_methods.is_empty() && !provided_methods.is_empty() {
638 for (pos, m) in provided_methods.iter().enumerate() {
642 AssocItemLink::Anchor(None),
648 clean::MethodItem(ref inner, _)
649 if !inner.generics.where_predicates.is_empty() =>
651 w.write_str(",\n { ... }\n");
654 w.write_str(" { ... }\n");
658 if pos < provided_methods.len() - 1 {
659 w.write_str("<span class=\"item-spacer\"></span>");
670 // Trait documentation
671 document(w, cx, it, None, HeadingOffset::H2);
673 fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
676 "<h2 id=\"{0}\" class=\"small-section-header\">\
677 {1}<a href=\"#{0}\" class=\"anchor\"></a>\
679 id, title, extra_content
683 fn trait_item(w: &mut Buffer, cx: &mut Context<'_>, m: &clean::Item, t: &clean::Item) {
684 let name = m.name.unwrap();
685 info!("Documenting {} on {:?}", name, t.name);
686 let item_type = m.type_();
687 let id = cx.derive_id(format!("{}.{}", item_type, name));
688 let mut content = Buffer::empty_from(w);
689 document(&mut content, cx, m, Some(t), HeadingOffset::H5);
690 let toggled = !content.is_empty();
692 write!(w, "<details class=\"rustdoc-toggle\" open><summary>");
694 write!(w, "<div id=\"{}\" class=\"method has-srclink\">", id);
695 write!(w, "<div class=\"rightside\">");
697 let has_stability = render_stability_since(w, m, t, cx.tcx());
701 write_srclink(cx, m, w);
703 write!(w, "<h4 class=\"code-header\">");
707 AssocItemLink::Anchor(Some(&id)),
712 w.write_str("</h4>");
713 w.write_str("</div>");
715 write!(w, "</summary>");
716 w.push_buffer(content);
717 write!(w, "</details>");
721 if !required_types.is_empty() {
722 write_small_section_header(
724 "required-associated-types",
725 "Required Associated Types",
726 "<div class=\"methods\">",
728 for t in required_types {
729 trait_item(w, cx, t, it);
731 w.write_str("</div>");
733 if !provided_types.is_empty() {
734 write_small_section_header(
736 "provided-associated-types",
737 "Provided Associated Types",
738 "<div class=\"methods\">",
740 for t in provided_types {
741 trait_item(w, cx, t, it);
743 w.write_str("</div>");
746 if !required_consts.is_empty() {
747 write_small_section_header(
749 "required-associated-consts",
750 "Required Associated Constants",
751 "<div class=\"methods\">",
753 for t in required_consts {
754 trait_item(w, cx, t, it);
756 w.write_str("</div>");
758 if !provided_consts.is_empty() {
759 write_small_section_header(
761 "provided-associated-consts",
762 "Provided Associated Constants",
763 "<div class=\"methods\">",
765 for t in provided_consts {
766 trait_item(w, cx, t, it);
768 w.write_str("</div>");
771 // Output the documentation for each function individually
772 if !required_methods.is_empty() {
773 write_small_section_header(
777 "<div class=\"methods\">",
779 for m in required_methods {
780 trait_item(w, cx, m, it);
782 w.write_str("</div>");
784 if !provided_methods.is_empty() {
785 write_small_section_header(
789 "<div class=\"methods\">",
791 for m in provided_methods {
792 trait_item(w, cx, m, it);
794 w.write_str("</div>");
797 // If there are methods directly on this trait object, render them here.
798 render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All);
800 let cloned_shared = Rc::clone(&cx.shared);
801 let cache = &cloned_shared.cache;
802 let mut extern_crates = FxHashSet::default();
803 if let Some(implementors) = cache.implementors.get(&it.item_id.expect_def_id()) {
804 // The DefId is for the first Type found with that name. The bool is
805 // if any Types with the same name but different DefId have been found.
806 let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();
807 for implementor in implementors {
808 if let Some(did) = implementor.inner_impl().for_.without_borrowed_ref().def_id(cache) &&
810 extern_crates.insert(did.krate);
812 match implementor.inner_impl().for_.without_borrowed_ref() {
813 clean::Type::Path { ref path } if !path.is_assoc_ty() => {
814 let did = path.def_id();
815 let &mut (prev_did, ref mut has_duplicates) =
816 implementor_dups.entry(path.last()).or_insert((did, false));
818 *has_duplicates = true;
825 let (local, foreign) =
826 implementors.iter().partition::<Vec<_>, _>(|i| i.is_on_local_type(cx));
828 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
829 local.iter().partition(|i| i.inner_impl().kind.is_auto());
831 synthetic.sort_by(|a, b| compare_impl(a, b, cx));
832 concrete.sort_by(|a, b| compare_impl(a, b, cx));
834 if !foreign.is_empty() {
835 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
837 for implementor in foreign {
838 let provided_methods = implementor.inner_impl().provided_trait_methods(cx.tcx());
840 AssocItemLink::GotoSource(implementor.impl_item.item_id, &provided_methods);
850 ImplRenderingParameters {
851 show_def_docs: false,
852 is_on_foreign_type: true,
853 show_default_items: false,
854 show_non_assoc_items: true,
855 toggle_open_by_default: false,
861 write_small_section_header(
865 "<div class=\"item-list\" id=\"implementors-list\">",
867 for implementor in concrete {
868 render_implementor(cx, implementor, it, w, &implementor_dups, &[]);
870 w.write_str("</div>");
873 write_small_section_header(
875 "synthetic-implementors",
877 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
879 for implementor in synthetic {
886 &collect_paths_for_type(implementor.inner_impl().for_.clone(), cache),
889 w.write_str("</div>");
892 // even without any implementations to write in, we still want the heading and list, so the
893 // implementors javascript file pulled in below has somewhere to write the impls into
894 write_small_section_header(
898 "<div class=\"item-list\" id=\"implementors-list\"></div>",
902 write_small_section_header(
904 "synthetic-implementors",
906 "<div class=\"item-list\" id=\"synthetic-implementors-list\"></div>",
911 // Include implementors in crates that depend on the current crate.
913 // This is complicated by the way rustdoc is invoked, which is basically
914 // the same way rustc is invoked: it gets called, one at a time, for each
915 // crate. When building the rustdocs for the current crate, rustdoc can
916 // see crate metadata for its dependencies, but cannot see metadata for its
919 // To make this work, we generate a "hook" at this stage, and our
920 // dependents can "plug in" to it when they build. For simplicity's sake,
921 // it's [JSONP]: a JavaScript file with the data we need (and can parse),
922 // surrounded by a tiny wrapper that the Rust side ignores, but allows the
923 // JavaScript side to include without having to worry about Same Origin
924 // Policy. The code for *that* is in `write_shared.rs`.
926 // This is further complicated by `#[doc(inline)]`. We want all copies
927 // of an inlined trait to reference the same JS file, to address complex
928 // dependency graphs like this one (lower crates depend on higher crates):
931 // --------------------------------------------
932 // | crate A: trait Foo |
933 // --------------------------------------------
935 // -------------------------------- |
936 // | crate B: impl A::Foo for Bar | |
937 // -------------------------------- |
939 // ---------------------------------------------
940 // | crate C: #[doc(inline)] use A::Foo as Baz |
941 // | impl Baz for Quux |
942 // ---------------------------------------------
945 // Basically, we want `C::Baz` and `A::Foo` to show the same set of
946 // impls, which is easier if they both treat `/implementors/A/trait.Foo.js`
947 // as the Single Source of Truth.
949 // We also want the `impl Baz for Quux` to be written to
950 // `trait.Foo.js`. However, when we generate plain HTML for `C::Baz`,
951 // we're going to want to generate plain HTML for `impl Baz for Quux` too,
952 // because that'll load faster, and it's better for SEO. And we don't want
953 // the same impl to show up twice on the same page.
955 // To make this work, the implementors JS file has a structure kinda
960 // "B": {"impl A::Foo for Bar"},
961 // "C": {"impl Baz for Quux"},
965 // First of all, this means we can rebuild a crate, and it'll replace its own
966 // data if something changes. That is, `rustdoc` is idempotent. The other
967 // advantage is that we can list the crates that get included in the HTML,
968 // and ignore them when doing the JavaScript-based part of rendering.
969 // So C's HTML will have something like this:
972 // <script type="text/javascript" src="/implementors/A/trait.Foo.js"
973 // data-ignore-extern-crates="A,B" async></script>
976 // And, when the JS runs, anything in data-ignore-extern-crates is known
977 // to already be in the HTML, and will be ignored.
979 // [JSONP]: https://en.wikipedia.org/wiki/JSONP
980 let mut js_src_path: UrlPartsBuilder = std::iter::repeat("..")
981 .take(cx.current.len())
982 .chain(std::iter::once("implementors"))
984 if let Some(did) = it.item_id.as_def_id() &&
985 let get_extern = { || cache.external_paths.get(&did).map(|s| s.0.clone()) } &&
986 let Some(fqp) = cache.exact_paths.get(&did).cloned().or_else(get_extern) {
987 js_src_path.extend(fqp[..fqp.len() - 1].iter().copied());
988 js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), fqp.last().unwrap()));
990 js_src_path.extend(cx.current.iter().copied());
991 js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), it.name.unwrap()));
993 let extern_crates = extern_crates
995 .map(|cnum| cx.shared.tcx.crate_name(cnum).to_string())
1000 "<script type=\"text/javascript\" src=\"{src}\" data-ignore-extern-crates=\"{extern_crates}\" async></script>",
1001 src = js_src_path.finish(),
1005 fn item_trait_alias(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::TraitAlias) {
1006 wrap_into_docblock(w, |w| {
1007 wrap_item(w, "trait-alias", |w| {
1008 render_attributes_in_pre(w, it, "");
1011 "trait {}{}{} = {};",
1013 t.generics.print(cx),
1014 print_where_clause(&t.generics, cx, 0, true),
1015 bounds(&t.bounds, true, cx)
1020 document(w, cx, it, None, HeadingOffset::H2);
1022 // Render any items associated directly to this alias, as otherwise they
1023 // won't be visible anywhere in the docs. It would be nice to also show
1024 // associated items from the aliased type (see discussion in #32077), but
1025 // we need #14072 to make sense of the generics.
1026 render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1029 fn item_opaque_ty(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::OpaqueTy) {
1030 wrap_into_docblock(w, |w| {
1031 wrap_item(w, "opaque", |w| {
1032 render_attributes_in_pre(w, it, "");
1035 "type {}{}{where_clause} = impl {bounds};",
1037 t.generics.print(cx),
1038 where_clause = print_where_clause(&t.generics, cx, 0, true),
1039 bounds = bounds(&t.bounds, false, cx),
1044 document(w, cx, it, None, HeadingOffset::H2);
1046 // Render any items associated directly to this alias, as otherwise they
1047 // won't be visible anywhere in the docs. It would be nice to also show
1048 // associated items from the aliased type (see discussion in #32077), but
1049 // we need #14072 to make sense of the generics.
1050 render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1053 fn item_typedef(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::Typedef) {
1054 fn write_content(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Typedef) {
1055 wrap_item(w, "typedef", |w| {
1056 render_attributes_in_pre(w, it, "");
1057 write!(w, "{}", it.visibility.print_with_space(it.item_id, cx));
1060 "type {}{}{where_clause} = {type_};",
1062 t.generics.print(cx),
1063 where_clause = print_where_clause(&t.generics, cx, 0, true),
1064 type_ = t.type_.print(cx),
1069 wrap_into_docblock(w, |w| write_content(w, cx, it, t));
1071 document(w, cx, it, None, HeadingOffset::H2);
1073 let def_id = it.item_id.expect_def_id();
1074 // Render any items associated directly to this alias, as otherwise they
1075 // won't be visible anywhere in the docs. It would be nice to also show
1076 // associated items from the aliased type (see discussion in #32077), but
1077 // we need #14072 to make sense of the generics.
1078 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1079 document_type_layout(w, cx, def_id);
1082 fn item_union(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Union) {
1083 wrap_into_docblock(w, |w| {
1084 wrap_item(w, "union", |w| {
1085 render_attributes_in_pre(w, it, "");
1086 render_union(w, it, Some(&s.generics), &s.fields, "", cx);
1090 document(w, cx, it, None, HeadingOffset::H2);
1095 .filter_map(|f| match *f.kind {
1096 clean::StructFieldItem(ref ty) => Some((f, ty)),
1100 if fields.peek().is_some() {
1103 "<h2 id=\"fields\" class=\"fields small-section-header\">\
1104 Fields<a href=\"#fields\" class=\"anchor\"></a></h2>"
1106 for (field, ty) in fields {
1107 let name = field.name.expect("union field name");
1108 let id = format!("{}.{}", ItemType::StructField, name);
1111 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
1112 <a href=\"#{id}\" class=\"anchor field\"></a>\
1113 <code>{name}: {ty}</code>\
1117 shortty = ItemType::StructField,
1120 if let Some(stability_class) = field.stability_class(cx.tcx()) {
1121 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
1123 document(w, cx, field, Some(it), HeadingOffset::H3);
1126 let def_id = it.item_id.expect_def_id();
1127 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1128 document_type_layout(w, cx, def_id);
1131 fn print_tuple_struct_fields(w: &mut Buffer, cx: &Context<'_>, s: &[clean::Item]) {
1132 for (i, ty) in s.iter().enumerate() {
1134 w.write_str(", ");
1137 clean::StrippedItem(box clean::StructFieldItem(_)) => w.write_str("_"),
1138 clean::StructFieldItem(ref ty) => write!(w, "{}", ty.print(cx)),
1139 _ => unreachable!(),
1144 fn item_enum(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, e: &clean::Enum) {
1145 let count_variants = e.variants().count();
1146 wrap_into_docblock(w, |w| {
1147 wrap_item(w, "enum", |w| {
1148 render_attributes_in_pre(w, it, "");
1152 it.visibility.print_with_space(it.item_id, cx),
1154 e.generics.print(cx),
1155 print_where_clause(&e.generics, cx, 0, true),
1157 let variants_stripped = e.has_stripped_entries();
1158 if count_variants == 0 && !variants_stripped {
1161 w.write_str(" {\n");
1162 let toggle = should_hide_fields(count_variants);
1164 toggle_open(w, format_args!("{} variants", count_variants));
1166 for v in e.variants() {
1168 let name = v.name.unwrap();
1170 clean::VariantItem(ref var) => match var {
1171 clean::Variant::CLike => write!(w, "{}", name),
1172 clean::Variant::Tuple(ref s) => {
1173 write!(w, "{}(", name);
1174 print_tuple_struct_fields(w, cx, s);
1177 clean::Variant::Struct(ref s) => {
1190 _ => unreachable!(),
1195 if variants_stripped {
1196 w.write_str(" // some variants omitted\n");
1206 document(w, cx, it, None, HeadingOffset::H2);
1208 if count_variants != 0 {
1211 "<h2 id=\"variants\" class=\"variants small-section-header\">\
1212 Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>",
1213 document_non_exhaustive_header(it)
1215 document_non_exhaustive(w, it);
1216 for variant in e.variants() {
1217 let id = cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.unwrap()));
1220 "<h3 id=\"{id}\" class=\"variant small-section-header\">\
1221 <a href=\"#{id}\" class=\"anchor field\"></a>\
1224 name = variant.name.unwrap()
1226 if let clean::VariantItem(clean::Variant::Tuple(ref s)) = *variant.kind {
1228 print_tuple_struct_fields(w, cx, s);
1231 w.write_str("</code>");
1232 render_stability_since(w, variant, it, cx.tcx());
1233 w.write_str("</h3>");
1235 use crate::clean::Variant;
1237 let heading_and_fields = match &*variant.kind {
1238 clean::VariantItem(Variant::Struct(s)) => Some(("Fields", &s.fields)),
1239 // Documentation on tuple variant fields is rare, so to reduce noise we only emit
1240 // the section if at least one field is documented.
1241 clean::VariantItem(Variant::Tuple(fields))
1242 if fields.iter().any(|f| f.doc_value().is_some()) =>
1244 Some(("Tuple Fields", fields))
1249 if let Some((heading, fields)) = heading_and_fields {
1251 cx.derive_id(format!("{}.{}.fields", ItemType::Variant, variant.name.unwrap()));
1252 write!(w, "<div class=\"sub-variant\" id=\"{id}\">", id = variant_id);
1253 write!(w, "<h4>{heading}</h4>", heading = heading);
1254 document_non_exhaustive(w, variant);
1255 for field in fields {
1257 clean::StrippedItem(box clean::StructFieldItem(_)) => {}
1258 clean::StructFieldItem(ref ty) => {
1259 let id = cx.derive_id(format!(
1260 "variant.{}.field.{}",
1261 variant.name.unwrap(),
1266 "<div class=\"sub-variant-field\">\
1267 <span id=\"{id}\" class=\"variant small-section-header\">\
1268 <a href=\"#{id}\" class=\"anchor field\"></a>\
1269 <code>{f}: {t}</code>\
1272 f = field.name.unwrap(),
1275 document(w, cx, field, Some(variant), HeadingOffset::H5);
1276 write!(w, "</div>");
1278 _ => unreachable!(),
1281 w.write_str("</div>");
1284 document(w, cx, variant, Some(it), HeadingOffset::H4);
1287 let def_id = it.item_id.expect_def_id();
1288 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1289 document_type_layout(w, cx, def_id);
1292 fn item_macro(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::Macro) {
1293 wrap_into_docblock(w, |w| {
1294 highlight::render_with_highlighting(
1300 it.span(cx.tcx()).inner().edition(),
1306 document(w, cx, it, None, HeadingOffset::H2)
1309 fn item_proc_macro(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, m: &clean::ProcMacro) {
1310 wrap_into_docblock(w, |w| {
1311 let name = it.name.expect("proc-macros always have names");
1313 MacroKind::Bang => {
1314 wrap_item(w, "macro", |w| {
1315 write!(w, "{}!() {{ /* proc-macro */ }}", name);
1318 MacroKind::Attr => {
1319 wrap_item(w, "attr", |w| {
1320 write!(w, "#[{}]", name);
1323 MacroKind::Derive => {
1324 wrap_item(w, "derive", |w| {
1325 write!(w, "#[derive({})]", name);
1326 if !m.helpers.is_empty() {
1327 w.push_str("\n{\n");
1328 w.push_str(" // Attributes available to this derive:\n");
1329 for attr in &m.helpers {
1330 writeln!(w, " #[{}]", attr);
1338 document(w, cx, it, None, HeadingOffset::H2)
1341 fn item_primitive(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item) {
1342 document(w, cx, it, None, HeadingOffset::H2);
1343 render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1346 fn item_constant(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, c: &clean::Constant) {
1347 wrap_into_docblock(w, |w| {
1348 wrap_item(w, "const", |w| {
1349 render_attributes_in_code(w, it);
1353 "{vis}const {name}: {typ}",
1354 vis = it.visibility.print_with_space(it.item_id, cx),
1355 name = it.name.unwrap(),
1356 typ = c.type_.print(cx),
1359 let value = c.value(cx.tcx());
1360 let is_literal = c.is_literal(cx.tcx());
1361 let expr = c.expr(cx.tcx());
1362 if value.is_some() || is_literal {
1363 write!(w, " = {expr};", expr = Escape(&expr));
1369 if let Some(value) = &value {
1370 let value_lowercase = value.to_lowercase();
1371 let expr_lowercase = expr.to_lowercase();
1373 if value_lowercase != expr_lowercase
1374 && value_lowercase.trim_end_matches("i32") != expr_lowercase
1376 write!(w, " // {value}", value = Escape(value));
1383 document(w, cx, it, None, HeadingOffset::H2)
1386 fn item_struct(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Struct) {
1387 wrap_into_docblock(w, |w| {
1388 wrap_item(w, "struct", |w| {
1389 render_attributes_in_code(w, it);
1390 render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true, cx);
1394 document(w, cx, it, None, HeadingOffset::H2);
1399 .filter_map(|f| match *f.kind {
1400 clean::StructFieldItem(ref ty) => Some((f, ty)),
1404 if let CtorKind::Fictive | CtorKind::Fn = s.struct_type {
1405 if fields.peek().is_some() {
1408 "<h2 id=\"fields\" class=\"fields small-section-header\">\
1409 {}{}<a href=\"#fields\" class=\"anchor\"></a>\
1411 if let CtorKind::Fictive = s.struct_type { "Fields" } else { "Tuple Fields" },
1412 document_non_exhaustive_header(it)
1414 document_non_exhaustive(w, it);
1415 for (index, (field, ty)) in fields.enumerate() {
1417 field.name.map_or_else(|| index.to_string(), |sym| sym.as_str().to_string());
1418 let id = cx.derive_id(format!("{}.{}", ItemType::StructField, field_name));
1421 "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
1422 <a href=\"#{id}\" class=\"anchor field\"></a>\
1423 <code>{name}: {ty}</code>\
1425 item_type = ItemType::StructField,
1430 document(w, cx, field, Some(it), HeadingOffset::H3);
1434 let def_id = it.item_id.expect_def_id();
1435 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1436 document_type_layout(w, cx, def_id);
1439 fn item_static(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Static) {
1440 wrap_into_docblock(w, |w| {
1441 wrap_item(w, "static", |w| {
1442 render_attributes_in_code(w, it);
1445 "{vis}static {mutability}{name}: {typ}",
1446 vis = it.visibility.print_with_space(it.item_id, cx),
1447 mutability = s.mutability.print_with_space(),
1448 name = it.name.unwrap(),
1449 typ = s.type_.print(cx)
1453 document(w, cx, it, None, HeadingOffset::H2)
1456 fn item_foreign_type(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item) {
1457 wrap_into_docblock(w, |w| {
1458 wrap_item(w, "foreigntype", |w| {
1459 w.write_str("extern {\n");
1460 render_attributes_in_code(w, it);
1464 it.visibility.print_with_space(it.item_id, cx),
1470 document(w, cx, it, None, HeadingOffset::H2);
1472 render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1475 fn item_keyword(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item) {
1476 document(w, cx, it, None, HeadingOffset::H2)
1479 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
1480 pub(crate) fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
1481 /// Takes a non-numeric and a numeric part from the given &str.
1482 fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
1483 let i = s.find(|c: char| c.is_ascii_digit());
1484 let (a, b) = s.split_at(i.unwrap_or(s.len()));
1485 let i = b.find(|c: char| !c.is_ascii_digit());
1486 let (b, c) = b.split_at(i.unwrap_or(b.len()));
1491 while !lhs.is_empty() || !rhs.is_empty() {
1492 let (la, lb) = take_parts(&mut lhs);
1493 let (ra, rb) = take_parts(&mut rhs);
1494 // First process the non-numeric part.
1496 Ordering::Equal => (),
1499 // Then process the numeric part, if both sides have one (and they fit in a u64).
1500 if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
1502 Ordering::Equal => (),
1506 // Then process the numeric part again, but this time as strings.
1508 Ordering::Equal => (),
1516 pub(super) fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
1517 let mut s = join_with_double_colon(&cx.current);
1519 s.push_str(item.name.unwrap().as_str());
1523 pub(super) fn item_path(ty: ItemType, name: &str) -> String {
1525 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1526 _ => format!("{}.{}.html", ty, name),
1530 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool, cx: &Context<'_>) -> String {
1531 let mut bounds = String::new();
1532 if !t_bounds.is_empty() {
1534 bounds.push_str(": ");
1536 for (i, p) in t_bounds.iter().enumerate() {
1538 bounds.push_str(" + ");
1540 bounds.push_str(&p.print(cx).to_string());
1546 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1548 F: FnOnce(&mut Buffer),
1550 w.write_str("<div class=\"docblock item-decl\">");
1552 w.write_str("</div>")
1555 fn wrap_item<F>(w: &mut Buffer, item_name: &str, f: F)
1557 F: FnOnce(&mut Buffer),
1559 w.write_fmt(format_args!("<pre class=\"rust {}\"><code>", item_name));
1561 w.write_str("</code></pre>");
1564 fn render_stability_since(
1567 containing_item: &clean::Item,
1570 render_stability_since_raw(
1572 item.stable_since(tcx),
1573 item.const_stability(tcx),
1574 containing_item.stable_since(tcx),
1575 containing_item.const_stable_since(tcx),
1579 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl, cx: &Context<'_>) -> Ordering {
1580 let lhss = format!("{}", lhs.inner_impl().print(false, cx));
1581 let rhss = format!("{}", rhs.inner_impl().print(false, cx));
1583 // lhs and rhs are formatted as HTML, which may be unnecessary
1584 compare_names(&lhss, &rhss)
1587 fn render_implementor(
1588 cx: &mut Context<'_>,
1590 trait_: &clean::Item,
1592 implementor_dups: &FxHashMap<Symbol, (DefId, bool)>,
1595 // If there's already another implementor that has the same abridged name, use the
1596 // full path, for example in `std::iter::ExactSizeIterator`
1597 let use_absolute = match implementor.inner_impl().for_ {
1598 clean::Type::Path { ref path, .. }
1599 | clean::BorrowedRef { type_: box clean::Type::Path { ref path, .. }, .. }
1600 if !path.is_assoc_ty() =>
1602 implementor_dups[&path.last()].1
1611 AssocItemLink::Anchor(None),
1615 ImplRenderingParameters {
1616 show_def_docs: false,
1617 is_on_foreign_type: false,
1618 show_default_items: false,
1619 show_non_assoc_items: false,
1620 toggle_open_by_default: false,
1628 g: Option<&clean::Generics>,
1629 fields: &[clean::Item],
1633 write!(w, "{}union {}", it.visibility.print_with_space(it.item_id, cx), it.name.unwrap());
1634 if let Some(g) = g {
1635 write!(w, "{}", g.print(cx));
1636 write!(w, "{}", print_where_clause(g, cx, 0, true));
1639 write!(w, " {{\n{}", tab);
1641 fields.iter().filter(|f| matches!(*f.kind, clean::StructFieldItem(..))).count();
1642 let toggle = should_hide_fields(count_fields);
1644 toggle_open(w, format_args!("{} fields", count_fields));
1647 for field in fields {
1648 if let clean::StructFieldItem(ref ty) = *field.kind {
1652 field.visibility.print_with_space(field.item_id, cx),
1653 field.name.unwrap(),
1660 if it.has_stripped_entries().unwrap() {
1661 write!(w, " /* private fields */\n{}", tab);
1672 g: Option<&clean::Generics>,
1674 fields: &[clean::Item],
1682 it.visibility.print_with_space(it.item_id, cx),
1683 if structhead { "struct " } else { "" },
1686 if let Some(g) = g {
1687 write!(w, "{}", g.print(cx))
1690 CtorKind::Fictive => {
1691 if let Some(g) = g {
1692 write!(w, "{}", print_where_clause(g, cx, 0, true),)
1696 fields.iter().filter(|f| matches!(*f.kind, clean::StructFieldItem(..))).count();
1697 let has_visible_fields = count_fields > 0;
1698 let toggle = should_hide_fields(count_fields);
1700 toggle_open(w, format_args!("{} fields", count_fields));
1702 for field in fields {
1703 if let clean::StructFieldItem(ref ty) = *field.kind {
1708 field.visibility.print_with_space(field.item_id, cx),
1709 field.name.unwrap(),
1715 if has_visible_fields {
1716 if it.has_stripped_entries().unwrap() {
1717 write!(w, "\n{} /* private fields */", tab);
1719 write!(w, "\n{}", tab);
1720 } else if it.has_stripped_entries().unwrap() {
1721 write!(w, " /* private fields */ ");
1730 for (i, field) in fields.iter().enumerate() {
1735 clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
1736 clean::StructFieldItem(ref ty) => {
1740 field.visibility.print_with_space(field.item_id, cx),
1744 _ => unreachable!(),
1748 if let Some(g) = g {
1749 write!(w, "{}", print_where_clause(g, cx, 0, false),)
1751 // We only want a ";" when we are displaying a tuple struct, not a variant tuple struct.
1756 CtorKind::Const => {
1757 // Needed for PhantomData.
1758 if let Some(g) = g {
1759 write!(w, "{}", print_where_clause(g, cx, 0, false),)
1766 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1767 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1770 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1771 if item.is_non_exhaustive() {
1774 "<details class=\"rustdoc-toggle non-exhaustive\">\
1775 <summary class=\"hideme\"><span>{}</span></summary>\
1776 <div class=\"docblock\">",
1778 if item.is_struct() {
1779 "This struct is marked as non-exhaustive"
1780 } else if item.is_enum() {
1781 "This enum is marked as non-exhaustive"
1782 } else if item.is_variant() {
1783 "This variant is marked as non-exhaustive"
1785 "This type is marked as non-exhaustive"
1790 if item.is_struct() {
1792 "Non-exhaustive structs could have additional fields added in future. \
1793 Therefore, non-exhaustive structs cannot be constructed in external crates \
1794 using the traditional <code>Struct { .. }</code> syntax; cannot be \
1795 matched against without a wildcard <code>..</code>; and \
1796 struct update syntax will not work.",
1798 } else if item.is_enum() {
1800 "Non-exhaustive enums could have additional variants added in future. \
1801 Therefore, when matching against variants of non-exhaustive enums, an \
1802 extra wildcard arm must be added to account for any future variants.",
1804 } else if item.is_variant() {
1806 "Non-exhaustive enum variants could have additional fields added in future. \
1807 Therefore, non-exhaustive enum variants cannot be constructed in external \
1808 crates and cannot be matched against.",
1812 "This type will require a wildcard arm in any match statements or constructors.",
1816 w.write_str("</div></details>");
1820 fn document_type_layout(w: &mut Buffer, cx: &Context<'_>, ty_def_id: DefId) {
1821 fn write_size_of_layout(w: &mut Buffer, layout: Layout<'_>, tag_size: u64) {
1822 if layout.abi().is_unsized() {
1823 write!(w, "(unsized)");
1825 let bytes = layout.size().bytes() - tag_size;
1826 write!(w, "{size} byte{pl}", size = bytes, pl = if bytes == 1 { "" } else { "s" },);
1830 if !cx.shared.show_type_layout {
1834 writeln!(w, "<h2 class=\"small-section-header\">Layout</h2>");
1835 writeln!(w, "<div class=\"docblock\">");
1838 let param_env = tcx.param_env(ty_def_id);
1839 let ty = tcx.type_of(ty_def_id);
1840 match tcx.layout_of(param_env.and(ty)) {
1844 "<div class=\"warning\"><p><strong>Note:</strong> Most layout information is \
1845 <strong>completely unstable</strong> and may even differ between compilations. \
1846 The only exception is types with certain <code>repr(...)</code> attributes. \
1847 Please see the Rust Reference’s \
1848 <a href=\"https://doc.rust-lang.org/reference/type-layout.html\">“Type Layout”</a> \
1849 chapter for details on type layout guarantees.</p></div>"
1851 w.write_str("<p><strong>Size:</strong> ");
1852 write_size_of_layout(w, ty_layout.layout, 0);
1853 writeln!(w, "</p>");
1854 if let Variants::Multiple { variants, tag, tag_encoding, .. } =
1855 &ty_layout.layout.variants()
1857 if !variants.is_empty() {
1859 "<p><strong>Size for each variant:</strong></p>\
1863 let Adt(adt, _) = ty_layout.ty.kind() else {
1864 span_bug!(tcx.def_span(ty_def_id), "not an adt")
1867 let tag_size = if let TagEncoding::Niche { .. } = tag_encoding {
1869 } else if let Primitive::Int(i, _) = tag.primitive() {
1872 span_bug!(tcx.def_span(ty_def_id), "tag is neither niche nor int")
1875 for (index, layout) in variants.iter_enumerated() {
1876 let name = adt.variant(index).name;
1877 write!(w, "<li><code>{name}</code>: ", name = name);
1878 write_size_of_layout(w, *layout, tag_size);
1879 writeln!(w, "</li>");
1881 w.write_str("</ul>");
1885 // This kind of layout error can occur with valid code, e.g. if you try to
1886 // get the layout of a generic type such as `Vec<T>`.
1887 Err(LayoutError::Unknown(_)) => {
1890 "<p><strong>Note:</strong> Unable to compute type layout, \
1891 possibly due to this type having generic parameters. \
1892 Layout can only be computed for concrete, fully-instantiated types.</p>"
1895 // This kind of error probably can't happen with valid code, but we don't
1896 // want to panic and prevent the docs from building, so we just let the
1897 // user know that we couldn't compute the layout.
1898 Err(LayoutError::SizeOverflow(_)) => {
1901 "<p><strong>Note:</strong> Encountered an error during type layout; \
1902 the type was too big.</p>"
1905 Err(LayoutError::NormalizationFailure(_, _)) => {
1908 "<p><strong>Note:</strong> Encountered an error during type layout; \
1909 the type failed to be normalized.</p>"
1914 writeln!(w, "</div>");
1917 fn pluralize(count: usize) -> &'static str {
1918 if count > 1 { "s" } else { "" }