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::config::ModuleSorting;
27 use crate::formats::item_type::ItemType;
28 use crate::formats::{AssocItemRender, Impl, RenderMode};
29 use crate::html::escape::Escape;
30 use crate::html::format::{
31 join_with_double_colon, print_abi_with_space, print_constness_with_space, print_where_clause,
32 Buffer, PrintWithSpace,
34 use crate::html::highlight;
35 use crate::html::layout::Page;
36 use crate::html::markdown::{HeadingOffset, MarkdownSummaryLine};
37 use crate::html::url_parts_builder::UrlPartsBuilder;
41 const ITEM_TABLE_OPEN: &str = "<div class=\"item-table\">";
42 const ITEM_TABLE_CLOSE: &str = "</div>";
43 const ITEM_TABLE_ROW_OPEN: &str = "<div class=\"item-row\">";
44 const ITEM_TABLE_ROW_CLOSE: &str = "</div>";
46 // A component in a `use` path, like `string` in std::string::ToString
47 struct PathComponent {
53 #[template(path = "print_item.html")]
56 static_root_path: &'a str,
60 path_components: Vec<PathComponent>,
61 stability_since_raw: &'a str,
62 src_href: Option<&'a str>,
65 pub(super) fn print_item(
71 debug_assert!(!item.is_stripped());
72 let typ = match *item.kind {
73 clean::ModuleItem(_) => {
80 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
81 clean::TraitItem(..) => "Trait ",
82 clean::StructItem(..) => "Struct ",
83 clean::UnionItem(..) => "Union ",
84 clean::EnumItem(..) => "Enum ",
85 clean::TypedefItem(..) => "Type Definition ",
86 clean::MacroItem(..) => "Macro ",
87 clean::ProcMacroItem(ref mac) => match mac.kind {
88 MacroKind::Bang => "Macro ",
89 MacroKind::Attr => "Attribute Macro ",
90 MacroKind::Derive => "Derive Macro ",
92 clean::PrimitiveItem(..) => "Primitive Type ",
93 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
94 clean::ConstantItem(..) => "Constant ",
95 clean::ForeignTypeItem => "Foreign Type ",
96 clean::KeywordItem(..) => "Keyword ",
97 clean::OpaqueTyItem(..) => "Opaque Type ",
98 clean::TraitAliasItem(..) => "Trait Alias ",
100 // We don't generate pages for any other type.
104 let mut stability_since_raw = Buffer::new();
105 render_stability_since_raw(
106 &mut stability_since_raw,
107 item.stable_since(cx.tcx()),
108 item.const_stability(cx.tcx()),
112 let stability_since_raw: String = stability_since_raw.into_inner();
116 // When this item is part of a `crate use` in a downstream crate, the
117 // source link in the downstream documentation will actually come back to
118 // this page, and this link will be auto-clicked. The `id` attribute is
119 // used to find the link to auto-click.
121 if cx.include_sources && !item.is_primitive() { cx.src_href(item) } else { None };
123 let path_components = if item.is_primitive() || item.is_keyword() {
126 let cur = &cx.current;
127 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
131 .map(|(i, component)| PathComponent {
132 path: "../".repeat(cur.len() - i - 1),
138 let item_vars = ItemVars {
140 static_root_path: page.get_static_root_path(),
142 name: item.name.as_ref().unwrap().as_str(),
143 item_type: &item.type_().to_string(),
145 stability_since_raw: &stability_since_raw,
146 src_href: src_href.as_deref(),
149 item_vars.render_into(buf).unwrap();
152 clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
153 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
154 item_function(buf, cx, item, f)
156 clean::TraitItem(ref t) => item_trait(buf, cx, item, t),
157 clean::StructItem(ref s) => item_struct(buf, cx, item, s),
158 clean::UnionItem(ref s) => item_union(buf, cx, item, s),
159 clean::EnumItem(ref e) => item_enum(buf, cx, item, e),
160 clean::TypedefItem(ref t) => item_typedef(buf, cx, item, t),
161 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
162 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
163 clean::PrimitiveItem(_) => item_primitive(buf, cx, item),
164 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
165 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
166 clean::ForeignTypeItem => item_foreign_type(buf, cx, item),
167 clean::KeywordItem(_) => item_keyword(buf, cx, item),
168 clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e),
169 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta),
171 // We don't generate pages for any other type.
177 /// For large structs, enums, unions, etc, determine whether to hide their fields
178 fn should_hide_fields(n_fields: usize) -> bool {
182 fn toggle_open(w: &mut Buffer, text: impl fmt::Display) {
185 "<details class=\"rustdoc-toggle type-contents-toggle\">\
186 <summary class=\"hideme\">\
187 <span>Show {}</span>\
193 fn toggle_close(w: &mut Buffer) {
194 w.write_str("</details>");
197 fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items: &[clean::Item]) {
198 document(w, cx, item, None, HeadingOffset::H2);
200 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
202 // the order of item types in the listing
203 fn reorder(ty: ItemType) -> u8 {
205 ItemType::ExternCrate => 0,
206 ItemType::Import => 1,
207 ItemType::Primitive => 2,
208 ItemType::Module => 3,
209 ItemType::Macro => 4,
210 ItemType::Struct => 5,
212 ItemType::Constant => 7,
213 ItemType::Static => 8,
214 ItemType::Trait => 9,
215 ItemType::Function => 10,
216 ItemType::Typedef => 12,
217 ItemType::Union => 13,
229 let ty1 = i1.type_();
230 let ty2 = i2.type_();
231 if item_ty_to_section(ty1) != item_ty_to_section(ty2)
232 || (ty1 != ty2 && (ty1 == ItemType::ExternCrate || ty2 == ItemType::ExternCrate))
234 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
236 let s1 = i1.stability(tcx).as_ref().map(|s| s.level);
237 let s2 = i2.stability(tcx).as_ref().map(|s| s.level);
238 if let (Some(a), Some(b)) = (s1, s2) {
239 match (a.is_stable(), b.is_stable()) {
240 (true, true) | (false, false) => {}
241 (false, true) => return Ordering::Less,
242 (true, false) => return Ordering::Greater,
245 let lhs = i1.name.unwrap_or(kw::Empty);
246 let rhs = i2.name.unwrap_or(kw::Empty);
247 compare_names(lhs.as_str(), rhs.as_str())
250 match cx.shared.module_sorting {
251 ModuleSorting::Alphabetical => {
252 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2, cx.tcx()));
254 ModuleSorting::DeclarationOrder => {}
256 // This call is to remove re-export duplicates in cases such as:
259 // pub(crate) mod foo {
260 // pub(crate) mod bar {
261 // pub(crate) trait Double { fn foo(); }
265 // pub(crate) use foo::bar::*;
266 // pub(crate) use foo::*;
269 // `Double` will appear twice in the generated docs.
271 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
272 // can be identical even if the elements are different (mostly in imports).
273 // So in case this is an import, we keep everything by adding a "unique id"
274 // (which is the position in the vector).
275 indices.dedup_by_key(|i| {
278 if items[*i].name.is_some() { Some(full_path(cx, &items[*i])) } else { None },
280 if items[*i].is_import() { *i } else { 0 },
284 debug!("{:?}", indices);
285 let mut last_section = None;
287 for &idx in &indices {
288 let myitem = &items[idx];
289 if myitem.is_stripped() {
293 let my_section = item_ty_to_section(myitem.type_());
294 if Some(my_section) != last_section {
295 if last_section.is_some() {
296 w.write_str(ITEM_TABLE_CLOSE);
298 last_section = Some(my_section);
301 "<h2 id=\"{id}\" class=\"small-section-header\">\
302 <a href=\"#{id}\">{name}</a>\
305 id = cx.derive_id(my_section.id().to_owned()),
306 name = my_section.name(),
311 clean::ExternCrateItem { ref src } => {
312 use crate::html::format::anchor;
314 w.write_str(ITEM_TABLE_ROW_OPEN);
318 "<div class=\"item-left\"><code>{}extern crate {} as {};",
319 myitem.visibility.print_with_space(myitem.item_id, cx),
320 anchor(myitem.item_id.expect_def_id(), src, cx),
321 myitem.name.unwrap(),
325 "<div class=\"item-left\"><code>{}extern crate {};",
326 myitem.visibility.print_with_space(myitem.item_id, cx),
327 anchor(myitem.item_id.expect_def_id(), myitem.name.unwrap(), cx),
330 w.write_str("</code></div>");
331 w.write_str(ITEM_TABLE_ROW_CLOSE);
334 clean::ImportItem(ref import) => {
335 let (stab, stab_tags) = if let Some(import_def_id) = import.source.did {
336 let ast_attrs = cx.tcx().get_attrs_unchecked(import_def_id);
337 let import_attrs = Box::new(clean::Attributes::from_ast(ast_attrs, None));
339 // Just need an item with the correct def_id and attrs
340 let import_item = clean::Item {
341 item_id: import_def_id.into(),
343 cfg: ast_attrs.cfg(cx.tcx(), &cx.cache().hidden_cfg),
347 let stab = import_item.stability_class(cx.tcx());
348 let stab_tags = Some(extra_info_tags(&import_item, item, cx.tcx()));
354 let add = if stab.is_some() { " " } else { "" };
356 w.write_str(ITEM_TABLE_ROW_OPEN);
357 let id = match import.kind {
358 clean::ImportKind::Simple(s) => {
359 format!(" id=\"{}\"", cx.derive_id(format!("reexport.{}", s)))
361 clean::ImportKind::Glob => String::new(),
365 "<div class=\"item-left {stab}{add}import-item\"{id}>\
366 <code>{vis}{imp}</code>\
368 <div class=\"item-right docblock-short\">{stab_tags}</div>",
369 stab = stab.unwrap_or_default(),
370 vis = myitem.visibility.print_with_space(myitem.item_id, cx),
371 imp = import.print(cx),
372 stab_tags = stab_tags.unwrap_or_default(),
374 w.write_str(ITEM_TABLE_ROW_CLOSE);
378 if myitem.name.is_none() {
382 let unsafety_flag = match *myitem.kind {
383 clean::FunctionItem(_) | clean::ForeignFunctionItem(_)
384 if myitem.fn_header(cx.tcx()).unwrap().unsafety
385 == hir::Unsafety::Unsafe =>
387 "<a title=\"unsafe function\" href=\"#\"><sup>⚠</sup></a>"
392 let stab = myitem.stability_class(cx.tcx());
393 let add = if stab.is_some() { " " } else { "" };
395 let visibility_emoji = match myitem.visibility {
396 clean::Visibility::Restricted(_) => {
397 "<span title=\"Restricted Visibility\"> 🔒</span> "
402 let doc_value = myitem.doc_value().unwrap_or_default();
403 w.write_str(ITEM_TABLE_ROW_OPEN);
406 "<div class=\"item-left {stab}{add}module-item\">\
407 <a class=\"{class}\" href=\"{href}\" title=\"{title}\">{name}</a>\
412 <div class=\"item-right docblock-short\">{docs}</div>",
413 name = myitem.name.unwrap(),
414 visibility_emoji = visibility_emoji,
415 stab_tags = extra_info_tags(myitem, item, cx.tcx()),
416 docs = MarkdownSummaryLine(&doc_value, &myitem.links(cx)).into_string(),
417 class = myitem.type_(),
419 stab = stab.unwrap_or_default(),
420 unsafety_flag = unsafety_flag,
421 href = item_path(myitem.type_(), myitem.name.unwrap().as_str()),
422 title = [full_path(cx, myitem), myitem.type_().to_string()]
424 .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
428 w.write_str(ITEM_TABLE_ROW_CLOSE);
433 if last_section.is_some() {
434 w.write_str(ITEM_TABLE_CLOSE);
438 /// Render the stability, deprecation and portability tags that are displayed in the item's summary
439 /// at the module level.
440 fn extra_info_tags(item: &clean::Item, parent: &clean::Item, tcx: TyCtxt<'_>) -> String {
441 let mut tags = String::new();
443 fn tag_html(class: &str, title: &str, contents: &str) -> String {
444 format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
447 // The trailing space after each tag is to space it properly against the rest of the docs.
448 if let Some(depr) = &item.deprecation(tcx) {
449 let mut message = "Deprecated";
450 if !stability::deprecation_in_effect(depr) {
451 message = "Deprecation planned";
453 tags += &tag_html("deprecated", "", message);
456 // The "rustc_private" crates are permanently unstable so it makes no sense
457 // to render "unstable" everywhere.
458 if item.stability(tcx).as_ref().map(|s| s.is_unstable() && s.feature != sym::rustc_private)
461 tags += &tag_html("unstable", "", "Experimental");
464 let cfg = match (&item.cfg, parent.cfg.as_ref()) {
465 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
466 (cfg, _) => cfg.as_deref().cloned(),
469 debug!("Portability {:?} - {:?} = {:?}", item.cfg, parent.cfg, cfg);
470 if let Some(ref cfg) = cfg {
471 tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
477 fn item_function(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, f: &clean::Function) {
478 let header = it.fn_header(cx.tcx()).expect("printing a function which isn't a function");
479 let constness = print_constness_with_space(&header.constness, it.const_stability(cx.tcx()));
480 let unsafety = header.unsafety.print_with_space();
481 let abi = print_abi_with_space(header.abi).to_string();
482 let asyncness = header.asyncness.print_with_space();
483 let visibility = it.visibility.print_with_space(it.item_id, cx).to_string();
484 let name = it.name.unwrap();
486 let generics_len = format!("{:#}", f.generics.print(cx)).len();
487 let header_len = "fn ".len()
493 + name.as_str().len()
496 wrap_into_docblock(w, |w| {
497 wrap_item(w, "fn", |w| {
498 render_attributes_in_pre(w, it, "");
499 w.reserve(header_len);
502 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
503 {name}{generics}{decl}{notable_traits}{where_clause}",
505 constness = constness,
506 asyncness = asyncness,
510 generics = f.generics.print(cx),
511 where_clause = print_where_clause(&f.generics, cx, 0, true),
512 decl = f.decl.full_print(header_len, 0, header.asyncness, cx),
513 notable_traits = notable_traits_decl(&f.decl, cx),
517 document(w, cx, it, None, HeadingOffset::H2)
520 fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::Trait) {
521 let bounds = bounds(&t.bounds, false, cx);
522 let required_types = t.items.iter().filter(|m| m.is_ty_associated_type()).collect::<Vec<_>>();
523 let provided_types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
524 let required_consts = t.items.iter().filter(|m| m.is_ty_associated_const()).collect::<Vec<_>>();
525 let provided_consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
526 let required_methods = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
527 let provided_methods = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
528 let count_types = required_types.len() + provided_types.len();
529 let count_consts = required_consts.len() + provided_consts.len();
530 let count_methods = required_methods.len() + provided_methods.len();
532 // Output the trait definition
533 wrap_into_docblock(w, |w| {
534 wrap_item(w, "trait", |w| {
535 render_attributes_in_pre(w, it, "");
538 "{}{}{}trait {}{}{}",
539 it.visibility.print_with_space(it.item_id, cx),
540 t.unsafety.print_with_space(),
541 if t.is_auto { "auto " } else { "" },
543 t.generics.print(cx),
547 if !t.generics.where_predicates.is_empty() {
548 write!(w, "{}", print_where_clause(&t.generics, cx, 0, true));
553 if t.items.is_empty() {
556 // FIXME: we should be using a derived_id for the Anchors here
558 let mut toggle = false;
560 // If there are too many associated types, hide _everything_
561 if should_hide_fields(count_types) {
566 "{} associated items",
567 count_types + count_consts + count_methods
571 for types in [&required_types, &provided_types] {
576 AssocItemLink::Anchor(None),
584 // If there are too many associated constants, hide everything after them
585 // We also do this if the types + consts is large because otherwise we could
586 // render a bunch of types and _then_ a bunch of consts just because both were
587 // _just_ under the limit
588 if !toggle && should_hide_fields(count_types + count_consts) {
593 "{} associated constant{} and {} method{}",
595 pluralize(count_consts),
597 pluralize(count_methods),
601 if count_types != 0 && (count_consts != 0 || count_methods != 0) {
604 for consts in [&required_consts, &provided_consts] {
609 AssocItemLink::Anchor(None),
617 if !toggle && should_hide_fields(count_methods) {
619 toggle_open(w, format_args!("{} methods", count_methods));
621 if count_consts != 0 && count_methods != 0 {
624 for (pos, m) in required_methods.iter().enumerate() {
628 AssocItemLink::Anchor(None),
635 if pos < required_methods.len() - 1 {
636 w.write_str("<span class=\"item-spacer\"></span>");
639 if !required_methods.is_empty() && !provided_methods.is_empty() {
642 for (pos, m) in provided_methods.iter().enumerate() {
646 AssocItemLink::Anchor(None),
652 clean::MethodItem(ref inner, _)
653 if !inner.generics.where_predicates.is_empty() =>
655 w.write_str(",\n { ... }\n");
658 w.write_str(" { ... }\n");
662 if pos < provided_methods.len() - 1 {
663 w.write_str("<span class=\"item-spacer\"></span>");
674 // Trait documentation
675 document(w, cx, it, None, HeadingOffset::H2);
677 fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
680 "<h2 id=\"{0}\" class=\"small-section-header\">\
681 {1}<a href=\"#{0}\" class=\"anchor\"></a>\
683 id, title, extra_content
687 fn trait_item(w: &mut Buffer, cx: &mut Context<'_>, m: &clean::Item, t: &clean::Item) {
688 let name = m.name.unwrap();
689 info!("Documenting {} on {:?}", name, t.name);
690 let item_type = m.type_();
691 let id = cx.derive_id(format!("{}.{}", item_type, name));
692 let mut content = Buffer::empty_from(w);
693 document(&mut content, cx, m, Some(t), HeadingOffset::H5);
694 let toggled = !content.is_empty();
696 write!(w, "<details class=\"rustdoc-toggle\" open><summary>");
698 write!(w, "<div id=\"{}\" class=\"method has-srclink\">", id);
699 write!(w, "<div class=\"rightside\">");
701 let has_stability = render_stability_since(w, m, t, cx.tcx());
705 write_srclink(cx, m, w);
707 write!(w, "<h4 class=\"code-header\">");
711 AssocItemLink::Anchor(Some(&id)),
716 w.write_str("</h4>");
717 w.write_str("</div>");
719 write!(w, "</summary>");
720 w.push_buffer(content);
721 write!(w, "</details>");
725 if !required_types.is_empty() {
726 write_small_section_header(
728 "required-associated-types",
729 "Required Associated Types",
730 "<div class=\"methods\">",
732 for t in required_types {
733 trait_item(w, cx, t, it);
735 w.write_str("</div>");
737 if !provided_types.is_empty() {
738 write_small_section_header(
740 "provided-associated-types",
741 "Provided Associated Types",
742 "<div class=\"methods\">",
744 for t in provided_types {
745 trait_item(w, cx, t, it);
747 w.write_str("</div>");
750 if !required_consts.is_empty() {
751 write_small_section_header(
753 "required-associated-consts",
754 "Required Associated Constants",
755 "<div class=\"methods\">",
757 for t in required_consts {
758 trait_item(w, cx, t, it);
760 w.write_str("</div>");
762 if !provided_consts.is_empty() {
763 write_small_section_header(
765 "provided-associated-consts",
766 "Provided Associated Constants",
767 "<div class=\"methods\">",
769 for t in provided_consts {
770 trait_item(w, cx, t, it);
772 w.write_str("</div>");
775 // Output the documentation for each function individually
776 if !required_methods.is_empty() {
777 write_small_section_header(
781 "<div class=\"methods\">",
783 for m in required_methods {
784 trait_item(w, cx, m, it);
786 w.write_str("</div>");
788 if !provided_methods.is_empty() {
789 write_small_section_header(
793 "<div class=\"methods\">",
795 for m in provided_methods {
796 trait_item(w, cx, m, it);
798 w.write_str("</div>");
801 // If there are methods directly on this trait object, render them here.
802 render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All);
804 let cloned_shared = Rc::clone(&cx.shared);
805 let cache = &cloned_shared.cache;
806 let mut extern_crates = FxHashSet::default();
807 if let Some(implementors) = cache.implementors.get(&it.item_id.expect_def_id()) {
808 // The DefId is for the first Type found with that name. The bool is
809 // if any Types with the same name but different DefId have been found.
810 let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();
811 for implementor in implementors {
812 if let Some(did) = implementor.inner_impl().for_.without_borrowed_ref().def_id(cache) &&
814 extern_crates.insert(did.krate);
816 match implementor.inner_impl().for_.without_borrowed_ref() {
817 clean::Type::Path { ref path } if !path.is_assoc_ty() => {
818 let did = path.def_id();
819 let &mut (prev_did, ref mut has_duplicates) =
820 implementor_dups.entry(path.last()).or_insert((did, false));
822 *has_duplicates = true;
829 let (local, foreign) =
830 implementors.iter().partition::<Vec<_>, _>(|i| i.is_on_local_type(cx));
832 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
833 local.iter().partition(|i| i.inner_impl().kind.is_auto());
835 synthetic.sort_by(|a, b| compare_impl(a, b, cx));
836 concrete.sort_by(|a, b| compare_impl(a, b, cx));
838 if !foreign.is_empty() {
839 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
841 for implementor in foreign {
842 let provided_methods = implementor.inner_impl().provided_trait_methods(cx.tcx());
844 AssocItemLink::GotoSource(implementor.impl_item.item_id, &provided_methods);
854 ImplRenderingParameters {
855 show_def_docs: false,
856 show_default_items: false,
857 show_non_assoc_items: true,
858 toggle_open_by_default: false,
864 write_small_section_header(
868 "<div class=\"item-list\" id=\"implementors-list\">",
870 for implementor in concrete {
871 render_implementor(cx, implementor, it, w, &implementor_dups, &[]);
873 w.write_str("</div>");
876 write_small_section_header(
878 "synthetic-implementors",
880 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
882 for implementor in synthetic {
889 &collect_paths_for_type(implementor.inner_impl().for_.clone(), cache),
892 w.write_str("</div>");
895 // even without any implementations to write in, we still want the heading and list, so the
896 // implementors javascript file pulled in below has somewhere to write the impls into
897 write_small_section_header(
901 "<div class=\"item-list\" id=\"implementors-list\"></div>",
905 write_small_section_header(
907 "synthetic-implementors",
909 "<div class=\"item-list\" id=\"synthetic-implementors-list\"></div>",
914 // Include implementors in crates that depend on the current crate.
916 // This is complicated by the way rustdoc is invoked, which is basically
917 // the same way rustc is invoked: it gets called, one at a time, for each
918 // crate. When building the rustdocs for the current crate, rustdoc can
919 // see crate metadata for its dependencies, but cannot see metadata for its
922 // To make this work, we generate a "hook" at this stage, and our
923 // dependents can "plug in" to it when they build. For simplicity's sake,
924 // it's [JSONP]: a JavaScript file with the data we need (and can parse),
925 // surrounded by a tiny wrapper that the Rust side ignores, but allows the
926 // JavaScript side to include without having to worry about Same Origin
927 // Policy. The code for *that* is in `write_shared.rs`.
929 // This is further complicated by `#[doc(inline)]`. We want all copies
930 // of an inlined trait to reference the same JS file, to address complex
931 // dependency graphs like this one (lower crates depend on higher crates):
934 // --------------------------------------------
935 // | crate A: trait Foo |
936 // --------------------------------------------
938 // -------------------------------- |
939 // | crate B: impl A::Foo for Bar | |
940 // -------------------------------- |
942 // ---------------------------------------------
943 // | crate C: #[doc(inline)] use A::Foo as Baz |
944 // | impl Baz for Quux |
945 // ---------------------------------------------
948 // Basically, we want `C::Baz` and `A::Foo` to show the same set of
949 // impls, which is easier if they both treat `/implementors/A/trait.Foo.js`
950 // as the Single Source of Truth.
952 // We also want the `impl Baz for Quux` to be written to
953 // `trait.Foo.js`. However, when we generate plain HTML for `C::Baz`,
954 // we're going to want to generate plain HTML for `impl Baz for Quux` too,
955 // because that'll load faster, and it's better for SEO. And we don't want
956 // the same impl to show up twice on the same page.
958 // To make this work, the implementors JS file has a structure kinda
963 // "B": {"impl A::Foo for Bar"},
964 // "C": {"impl Baz for Quux"},
968 // First of all, this means we can rebuild a crate, and it'll replace its own
969 // data if something changes. That is, `rustdoc` is idempotent. The other
970 // advantage is that we can list the crates that get included in the HTML,
971 // and ignore them when doing the JavaScript-based part of rendering.
972 // So C's HTML will have something like this:
975 // <script type="text/javascript" src="/implementors/A/trait.Foo.js"
976 // data-ignore-extern-crates="A,B" async></script>
979 // And, when the JS runs, anything in data-ignore-extern-crates is known
980 // to already be in the HTML, and will be ignored.
982 // [JSONP]: https://en.wikipedia.org/wiki/JSONP
983 let mut js_src_path: UrlPartsBuilder = std::iter::repeat("..")
984 .take(cx.current.len())
985 .chain(std::iter::once("implementors"))
987 if let Some(did) = it.item_id.as_def_id() &&
988 let get_extern = { || cache.external_paths.get(&did).map(|s| s.0.clone()) } &&
989 let Some(fqp) = cache.exact_paths.get(&did).cloned().or_else(get_extern) {
990 js_src_path.extend(fqp[..fqp.len() - 1].iter().copied());
991 js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), fqp.last().unwrap()));
993 js_src_path.extend(cx.current.iter().copied());
994 js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), it.name.unwrap()));
996 let extern_crates = extern_crates
998 .map(|cnum| cx.shared.tcx.crate_name(cnum).to_string())
1003 "<script type=\"text/javascript\" src=\"{src}\" data-ignore-extern-crates=\"{extern_crates}\" async></script>",
1004 src = js_src_path.finish(),
1008 fn item_trait_alias(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::TraitAlias) {
1009 wrap_into_docblock(w, |w| {
1010 wrap_item(w, "trait-alias", |w| {
1011 render_attributes_in_pre(w, it, "");
1014 "trait {}{}{} = {};",
1016 t.generics.print(cx),
1017 print_where_clause(&t.generics, cx, 0, true),
1018 bounds(&t.bounds, true, cx)
1023 document(w, cx, it, None, HeadingOffset::H2);
1025 // Render any items associated directly to this alias, as otherwise they
1026 // won't be visible anywhere in the docs. It would be nice to also show
1027 // associated items from the aliased type (see discussion in #32077), but
1028 // we need #14072 to make sense of the generics.
1029 render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1032 fn item_opaque_ty(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::OpaqueTy) {
1033 wrap_into_docblock(w, |w| {
1034 wrap_item(w, "opaque", |w| {
1035 render_attributes_in_pre(w, it, "");
1038 "type {}{}{where_clause} = impl {bounds};",
1040 t.generics.print(cx),
1041 where_clause = print_where_clause(&t.generics, cx, 0, true),
1042 bounds = bounds(&t.bounds, false, cx),
1047 document(w, cx, it, None, HeadingOffset::H2);
1049 // Render any items associated directly to this alias, as otherwise they
1050 // won't be visible anywhere in the docs. It would be nice to also show
1051 // associated items from the aliased type (see discussion in #32077), but
1052 // we need #14072 to make sense of the generics.
1053 render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1056 fn item_typedef(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::Typedef) {
1057 fn write_content(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Typedef) {
1058 wrap_item(w, "typedef", |w| {
1059 render_attributes_in_pre(w, it, "");
1060 write!(w, "{}", it.visibility.print_with_space(it.item_id, cx));
1063 "type {}{}{where_clause} = {type_};",
1065 t.generics.print(cx),
1066 where_clause = print_where_clause(&t.generics, cx, 0, true),
1067 type_ = t.type_.print(cx),
1072 wrap_into_docblock(w, |w| write_content(w, cx, it, t));
1074 document(w, cx, it, None, HeadingOffset::H2);
1076 let def_id = it.item_id.expect_def_id();
1077 // Render any items associated directly to this alias, as otherwise they
1078 // won't be visible anywhere in the docs. It would be nice to also show
1079 // associated items from the aliased type (see discussion in #32077), but
1080 // we need #14072 to make sense of the generics.
1081 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1082 document_type_layout(w, cx, def_id);
1085 fn item_union(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Union) {
1086 wrap_into_docblock(w, |w| {
1087 wrap_item(w, "union", |w| {
1088 render_attributes_in_pre(w, it, "");
1089 render_union(w, it, Some(&s.generics), &s.fields, "", cx);
1093 document(w, cx, it, None, HeadingOffset::H2);
1098 .filter_map(|f| match *f.kind {
1099 clean::StructFieldItem(ref ty) => Some((f, ty)),
1103 if fields.peek().is_some() {
1106 "<h2 id=\"fields\" class=\"fields small-section-header\">\
1107 Fields<a href=\"#fields\" class=\"anchor\"></a></h2>"
1109 for (field, ty) in fields {
1110 let name = field.name.expect("union field name");
1111 let id = format!("{}.{}", ItemType::StructField, name);
1114 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
1115 <a href=\"#{id}\" class=\"anchor field\"></a>\
1116 <code>{name}: {ty}</code>\
1120 shortty = ItemType::StructField,
1123 if let Some(stability_class) = field.stability_class(cx.tcx()) {
1124 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
1126 document(w, cx, field, Some(it), HeadingOffset::H3);
1129 let def_id = it.item_id.expect_def_id();
1130 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1131 document_type_layout(w, cx, def_id);
1134 fn print_tuple_struct_fields(w: &mut Buffer, cx: &Context<'_>, s: &[clean::Item]) {
1135 for (i, ty) in s.iter().enumerate() {
1137 w.write_str(", ");
1140 clean::StrippedItem(box clean::StructFieldItem(_)) => w.write_str("_"),
1141 clean::StructFieldItem(ref ty) => write!(w, "{}", ty.print(cx)),
1142 _ => unreachable!(),
1147 fn item_enum(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, e: &clean::Enum) {
1148 let count_variants = e.variants().count();
1149 wrap_into_docblock(w, |w| {
1150 wrap_item(w, "enum", |w| {
1151 render_attributes_in_pre(w, it, "");
1155 it.visibility.print_with_space(it.item_id, cx),
1157 e.generics.print(cx),
1158 print_where_clause(&e.generics, cx, 0, true),
1160 let variants_stripped = e.has_stripped_entries();
1161 if count_variants == 0 && !variants_stripped {
1164 w.write_str(" {\n");
1165 let toggle = should_hide_fields(count_variants);
1167 toggle_open(w, format_args!("{} variants", count_variants));
1169 for v in e.variants() {
1171 let name = v.name.unwrap();
1173 clean::VariantItem(ref var) => match var {
1174 clean::Variant::CLike => write!(w, "{}", name),
1175 clean::Variant::Tuple(ref s) => {
1176 write!(w, "{}(", name);
1177 print_tuple_struct_fields(w, cx, s);
1180 clean::Variant::Struct(ref s) => {
1193 _ => unreachable!(),
1198 if variants_stripped {
1199 w.write_str(" // some variants omitted\n");
1209 document(w, cx, it, None, HeadingOffset::H2);
1211 if count_variants != 0 {
1214 "<h2 id=\"variants\" class=\"variants small-section-header\">\
1215 Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>",
1216 document_non_exhaustive_header(it)
1218 document_non_exhaustive(w, it);
1219 for variant in e.variants() {
1220 let id = cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.unwrap()));
1223 "<h3 id=\"{id}\" class=\"variant small-section-header\">\
1224 <a href=\"#{id}\" class=\"anchor field\"></a>\
1227 name = variant.name.unwrap()
1229 if let clean::VariantItem(clean::Variant::Tuple(ref s)) = *variant.kind {
1231 print_tuple_struct_fields(w, cx, s);
1234 w.write_str("</code>");
1235 render_stability_since(w, variant, it, cx.tcx());
1236 w.write_str("</h3>");
1238 use crate::clean::Variant;
1240 let heading_and_fields = match &*variant.kind {
1241 clean::VariantItem(Variant::Struct(s)) => Some(("Fields", &s.fields)),
1242 // Documentation on tuple variant fields is rare, so to reduce noise we only emit
1243 // the section if at least one field is documented.
1244 clean::VariantItem(Variant::Tuple(fields))
1245 if fields.iter().any(|f| f.doc_value().is_some()) =>
1247 Some(("Tuple Fields", fields))
1252 if let Some((heading, fields)) = heading_and_fields {
1254 cx.derive_id(format!("{}.{}.fields", ItemType::Variant, variant.name.unwrap()));
1255 write!(w, "<div class=\"sub-variant\" id=\"{id}\">", id = variant_id);
1256 write!(w, "<h4>{heading}</h4>", heading = heading);
1257 document_non_exhaustive(w, variant);
1258 for field in fields {
1260 clean::StrippedItem(box clean::StructFieldItem(_)) => {}
1261 clean::StructFieldItem(ref ty) => {
1262 let id = cx.derive_id(format!(
1263 "variant.{}.field.{}",
1264 variant.name.unwrap(),
1269 "<div class=\"sub-variant-field\">\
1270 <span id=\"{id}\" class=\"variant small-section-header\">\
1271 <a href=\"#{id}\" class=\"anchor field\"></a>\
1272 <code>{f}: {t}</code>\
1275 f = field.name.unwrap(),
1278 document(w, cx, field, Some(variant), HeadingOffset::H5);
1279 write!(w, "</div>");
1281 _ => unreachable!(),
1284 w.write_str("</div>");
1287 document(w, cx, variant, Some(it), HeadingOffset::H4);
1290 let def_id = it.item_id.expect_def_id();
1291 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1292 document_type_layout(w, cx, def_id);
1295 fn item_macro(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::Macro) {
1296 wrap_into_docblock(w, |w| {
1297 highlight::render_with_highlighting(
1303 it.span(cx.tcx()).inner().edition(),
1309 document(w, cx, it, None, HeadingOffset::H2)
1312 fn item_proc_macro(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, m: &clean::ProcMacro) {
1313 wrap_into_docblock(w, |w| {
1314 let name = it.name.expect("proc-macros always have names");
1316 MacroKind::Bang => {
1317 wrap_item(w, "macro", |w| {
1318 write!(w, "{}!() {{ /* proc-macro */ }}", name);
1321 MacroKind::Attr => {
1322 wrap_item(w, "attr", |w| {
1323 write!(w, "#[{}]", name);
1326 MacroKind::Derive => {
1327 wrap_item(w, "derive", |w| {
1328 write!(w, "#[derive({})]", name);
1329 if !m.helpers.is_empty() {
1330 w.push_str("\n{\n");
1331 w.push_str(" // Attributes available to this derive:\n");
1332 for attr in &m.helpers {
1333 writeln!(w, " #[{}]", attr);
1341 document(w, cx, it, None, HeadingOffset::H2)
1344 fn item_primitive(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item) {
1345 document(w, cx, it, None, HeadingOffset::H2);
1346 render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1349 fn item_constant(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, c: &clean::Constant) {
1350 wrap_into_docblock(w, |w| {
1351 wrap_item(w, "const", |w| {
1352 render_attributes_in_code(w, it);
1356 "{vis}const {name}: {typ}",
1357 vis = it.visibility.print_with_space(it.item_id, cx),
1358 name = it.name.unwrap(),
1359 typ = c.type_.print(cx),
1362 // FIXME: The code below now prints
1363 // ` = _; // 100i32`
1364 // if the expression is
1366 // which looks just wrong.
1371 let value = c.value(cx.tcx());
1372 let is_literal = c.is_literal(cx.tcx());
1373 let expr = c.expr(cx.tcx());
1374 if value.is_some() || is_literal {
1375 write!(w, " = {expr};", expr = Escape(&expr));
1381 if let Some(value) = &value {
1382 let value_lowercase = value.to_lowercase();
1383 let expr_lowercase = expr.to_lowercase();
1385 if value_lowercase != expr_lowercase
1386 && value_lowercase.trim_end_matches("i32") != expr_lowercase
1388 write!(w, " // {value}", value = Escape(value));
1395 document(w, cx, it, None, HeadingOffset::H2)
1398 fn item_struct(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Struct) {
1399 wrap_into_docblock(w, |w| {
1400 wrap_item(w, "struct", |w| {
1401 render_attributes_in_code(w, it);
1402 render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true, cx);
1406 document(w, cx, it, None, HeadingOffset::H2);
1411 .filter_map(|f| match *f.kind {
1412 clean::StructFieldItem(ref ty) => Some((f, ty)),
1416 if let CtorKind::Fictive | CtorKind::Fn = s.struct_type {
1417 if fields.peek().is_some() {
1420 "<h2 id=\"fields\" class=\"fields small-section-header\">\
1421 {}{}<a href=\"#fields\" class=\"anchor\"></a>\
1423 if let CtorKind::Fictive = s.struct_type { "Fields" } else { "Tuple Fields" },
1424 document_non_exhaustive_header(it)
1426 document_non_exhaustive(w, it);
1427 for (index, (field, ty)) in fields.enumerate() {
1429 field.name.map_or_else(|| index.to_string(), |sym| sym.as_str().to_string());
1430 let id = cx.derive_id(format!("{}.{}", ItemType::StructField, field_name));
1433 "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
1434 <a href=\"#{id}\" class=\"anchor field\"></a>\
1435 <code>{name}: {ty}</code>\
1437 item_type = ItemType::StructField,
1442 document(w, cx, field, Some(it), HeadingOffset::H3);
1446 let def_id = it.item_id.expect_def_id();
1447 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1448 document_type_layout(w, cx, def_id);
1451 fn item_static(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Static) {
1452 wrap_into_docblock(w, |w| {
1453 wrap_item(w, "static", |w| {
1454 render_attributes_in_code(w, it);
1457 "{vis}static {mutability}{name}: {typ}",
1458 vis = it.visibility.print_with_space(it.item_id, cx),
1459 mutability = s.mutability.print_with_space(),
1460 name = it.name.unwrap(),
1461 typ = s.type_.print(cx)
1465 document(w, cx, it, None, HeadingOffset::H2)
1468 fn item_foreign_type(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item) {
1469 wrap_into_docblock(w, |w| {
1470 wrap_item(w, "foreigntype", |w| {
1471 w.write_str("extern {\n");
1472 render_attributes_in_code(w, it);
1476 it.visibility.print_with_space(it.item_id, cx),
1482 document(w, cx, it, None, HeadingOffset::H2);
1484 render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1487 fn item_keyword(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item) {
1488 document(w, cx, it, None, HeadingOffset::H2)
1491 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
1492 pub(crate) fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
1493 /// Takes a non-numeric and a numeric part from the given &str.
1494 fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
1495 let i = s.find(|c: char| c.is_ascii_digit());
1496 let (a, b) = s.split_at(i.unwrap_or(s.len()));
1497 let i = b.find(|c: char| !c.is_ascii_digit());
1498 let (b, c) = b.split_at(i.unwrap_or(b.len()));
1503 while !lhs.is_empty() || !rhs.is_empty() {
1504 let (la, lb) = take_parts(&mut lhs);
1505 let (ra, rb) = take_parts(&mut rhs);
1506 // First process the non-numeric part.
1508 Ordering::Equal => (),
1511 // Then process the numeric part, if both sides have one (and they fit in a u64).
1512 if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
1514 Ordering::Equal => (),
1518 // Then process the numeric part again, but this time as strings.
1520 Ordering::Equal => (),
1528 pub(super) fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
1529 let mut s = join_with_double_colon(&cx.current);
1531 s.push_str(item.name.unwrap().as_str());
1535 pub(super) fn item_path(ty: ItemType, name: &str) -> String {
1537 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1538 _ => format!("{}.{}.html", ty, name),
1542 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool, cx: &Context<'_>) -> String {
1543 let mut bounds = String::new();
1544 if !t_bounds.is_empty() {
1546 bounds.push_str(": ");
1548 for (i, p) in t_bounds.iter().enumerate() {
1550 bounds.push_str(" + ");
1552 bounds.push_str(&p.print(cx).to_string());
1558 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1560 F: FnOnce(&mut Buffer),
1562 w.write_str("<div class=\"docblock item-decl\">");
1564 w.write_str("</div>")
1567 fn wrap_item<F>(w: &mut Buffer, item_name: &str, f: F)
1569 F: FnOnce(&mut Buffer),
1571 w.write_fmt(format_args!("<pre class=\"rust {}\"><code>", item_name));
1573 w.write_str("</code></pre>");
1576 fn render_stability_since(
1579 containing_item: &clean::Item,
1582 render_stability_since_raw(
1584 item.stable_since(tcx),
1585 item.const_stability(tcx),
1586 containing_item.stable_since(tcx),
1587 containing_item.const_stable_since(tcx),
1591 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl, cx: &Context<'_>) -> Ordering {
1592 let lhss = format!("{}", lhs.inner_impl().print(false, cx));
1593 let rhss = format!("{}", rhs.inner_impl().print(false, cx));
1595 // lhs and rhs are formatted as HTML, which may be unnecessary
1596 compare_names(&lhss, &rhss)
1599 fn render_implementor(
1600 cx: &mut Context<'_>,
1602 trait_: &clean::Item,
1604 implementor_dups: &FxHashMap<Symbol, (DefId, bool)>,
1607 // If there's already another implementor that has the same abridged name, use the
1608 // full path, for example in `std::iter::ExactSizeIterator`
1609 let use_absolute = match implementor.inner_impl().for_ {
1610 clean::Type::Path { ref path, .. }
1611 | clean::BorrowedRef { type_: box clean::Type::Path { ref path, .. }, .. }
1612 if !path.is_assoc_ty() =>
1614 implementor_dups[&path.last()].1
1623 AssocItemLink::Anchor(None),
1627 ImplRenderingParameters {
1628 show_def_docs: false,
1629 show_default_items: false,
1630 show_non_assoc_items: false,
1631 toggle_open_by_default: false,
1639 g: Option<&clean::Generics>,
1640 fields: &[clean::Item],
1644 write!(w, "{}union {}", it.visibility.print_with_space(it.item_id, cx), it.name.unwrap());
1645 if let Some(g) = g {
1646 write!(w, "{}", g.print(cx));
1647 write!(w, "{}", print_where_clause(g, cx, 0, true));
1650 write!(w, " {{\n{}", tab);
1652 fields.iter().filter(|f| matches!(*f.kind, clean::StructFieldItem(..))).count();
1653 let toggle = should_hide_fields(count_fields);
1655 toggle_open(w, format_args!("{} fields", count_fields));
1658 for field in fields {
1659 if let clean::StructFieldItem(ref ty) = *field.kind {
1663 field.visibility.print_with_space(field.item_id, cx),
1664 field.name.unwrap(),
1671 if it.has_stripped_entries().unwrap() {
1672 write!(w, " /* private fields */\n{}", tab);
1683 g: Option<&clean::Generics>,
1685 fields: &[clean::Item],
1693 it.visibility.print_with_space(it.item_id, cx),
1694 if structhead { "struct " } else { "" },
1697 if let Some(g) = g {
1698 write!(w, "{}", g.print(cx))
1701 CtorKind::Fictive => {
1702 if let Some(g) = g {
1703 write!(w, "{}", print_where_clause(g, cx, 0, true),)
1707 fields.iter().filter(|f| matches!(*f.kind, clean::StructFieldItem(..))).count();
1708 let has_visible_fields = count_fields > 0;
1709 let toggle = should_hide_fields(count_fields);
1711 toggle_open(w, format_args!("{} fields", count_fields));
1713 for field in fields {
1714 if let clean::StructFieldItem(ref ty) = *field.kind {
1719 field.visibility.print_with_space(field.item_id, cx),
1720 field.name.unwrap(),
1726 if has_visible_fields {
1727 if it.has_stripped_entries().unwrap() {
1728 write!(w, "\n{} /* private fields */", tab);
1730 write!(w, "\n{}", tab);
1731 } else if it.has_stripped_entries().unwrap() {
1732 write!(w, " /* private fields */ ");
1741 for (i, field) in fields.iter().enumerate() {
1746 clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
1747 clean::StructFieldItem(ref ty) => {
1751 field.visibility.print_with_space(field.item_id, cx),
1755 _ => unreachable!(),
1759 if let Some(g) = g {
1760 write!(w, "{}", print_where_clause(g, cx, 0, false),)
1762 // We only want a ";" when we are displaying a tuple struct, not a variant tuple struct.
1767 CtorKind::Const => {
1768 // Needed for PhantomData.
1769 if let Some(g) = g {
1770 write!(w, "{}", print_where_clause(g, cx, 0, false),)
1777 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1778 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1781 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1782 if item.is_non_exhaustive() {
1785 "<details class=\"rustdoc-toggle non-exhaustive\">\
1786 <summary class=\"hideme\"><span>{}</span></summary>\
1787 <div class=\"docblock\">",
1789 if item.is_struct() {
1790 "This struct is marked as non-exhaustive"
1791 } else if item.is_enum() {
1792 "This enum is marked as non-exhaustive"
1793 } else if item.is_variant() {
1794 "This variant is marked as non-exhaustive"
1796 "This type is marked as non-exhaustive"
1801 if item.is_struct() {
1803 "Non-exhaustive structs could have additional fields added in future. \
1804 Therefore, non-exhaustive structs cannot be constructed in external crates \
1805 using the traditional <code>Struct { .. }</code> syntax; cannot be \
1806 matched against without a wildcard <code>..</code>; and \
1807 struct update syntax will not work.",
1809 } else if item.is_enum() {
1811 "Non-exhaustive enums could have additional variants added in future. \
1812 Therefore, when matching against variants of non-exhaustive enums, an \
1813 extra wildcard arm must be added to account for any future variants.",
1815 } else if item.is_variant() {
1817 "Non-exhaustive enum variants could have additional fields added in future. \
1818 Therefore, non-exhaustive enum variants cannot be constructed in external \
1819 crates and cannot be matched against.",
1823 "This type will require a wildcard arm in any match statements or constructors.",
1827 w.write_str("</div></details>");
1831 fn document_type_layout(w: &mut Buffer, cx: &Context<'_>, ty_def_id: DefId) {
1832 fn write_size_of_layout(w: &mut Buffer, layout: Layout<'_>, tag_size: u64) {
1833 if layout.abi().is_unsized() {
1834 write!(w, "(unsized)");
1836 let bytes = layout.size().bytes() - tag_size;
1837 write!(w, "{size} byte{pl}", size = bytes, pl = if bytes == 1 { "" } else { "s" },);
1841 if !cx.shared.show_type_layout {
1845 writeln!(w, "<h2 class=\"small-section-header\">Layout</h2>");
1846 writeln!(w, "<div class=\"docblock\">");
1849 let param_env = tcx.param_env(ty_def_id);
1850 let ty = tcx.type_of(ty_def_id);
1851 match tcx.layout_of(param_env.and(ty)) {
1855 "<div class=\"warning\"><p><strong>Note:</strong> Most layout information is \
1856 <strong>completely unstable</strong> and may even differ between compilations. \
1857 The only exception is types with certain <code>repr(...)</code> attributes. \
1858 Please see the Rust Reference’s \
1859 <a href=\"https://doc.rust-lang.org/reference/type-layout.html\">“Type Layout”</a> \
1860 chapter for details on type layout guarantees.</p></div>"
1862 w.write_str("<p><strong>Size:</strong> ");
1863 write_size_of_layout(w, ty_layout.layout, 0);
1864 writeln!(w, "</p>");
1865 if let Variants::Multiple { variants, tag, tag_encoding, .. } =
1866 &ty_layout.layout.variants()
1868 if !variants.is_empty() {
1870 "<p><strong>Size for each variant:</strong></p>\
1874 let Adt(adt, _) = ty_layout.ty.kind() else {
1875 span_bug!(tcx.def_span(ty_def_id), "not an adt")
1878 let tag_size = if let TagEncoding::Niche { .. } = tag_encoding {
1880 } else if let Primitive::Int(i, _) = tag.primitive() {
1883 span_bug!(tcx.def_span(ty_def_id), "tag is neither niche nor int")
1886 for (index, layout) in variants.iter_enumerated() {
1887 let name = adt.variant(index).name;
1888 write!(w, "<li><code>{name}</code>: ", name = name);
1889 write_size_of_layout(w, *layout, tag_size);
1890 writeln!(w, "</li>");
1892 w.write_str("</ul>");
1896 // This kind of layout error can occur with valid code, e.g. if you try to
1897 // get the layout of a generic type such as `Vec<T>`.
1898 Err(LayoutError::Unknown(_)) => {
1901 "<p><strong>Note:</strong> Unable to compute type layout, \
1902 possibly due to this type having generic parameters. \
1903 Layout can only be computed for concrete, fully-instantiated types.</p>"
1906 // This kind of error probably can't happen with valid code, but we don't
1907 // want to panic and prevent the docs from building, so we just let the
1908 // user know that we couldn't compute the layout.
1909 Err(LayoutError::SizeOverflow(_)) => {
1912 "<p><strong>Note:</strong> Encountered an error during type layout; \
1913 the type was too big.</p>"
1916 Err(LayoutError::NormalizationFailure(_, _)) => {
1919 "<p><strong>Note:</strong> Encountered an error during type layout; \
1920 the type failed to be normalized.</p>"
1925 writeln!(w, "</div>");
1928 fn pluralize(count: usize) -> &'static str {
1929 if count > 1 { "s" } else { "" }