1 use clean::AttributesExt;
3 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
5 use rustc_hir::def::CtorKind;
6 use rustc_hir::def_id::DefId;
7 use rustc_middle::middle::stability;
8 use rustc_middle::span_bug;
9 use rustc_middle::ty::layout::LayoutError;
10 use rustc_middle::ty::{self, Adt, TyCtxt};
11 use rustc_span::hygiene::MacroKind;
12 use rustc_span::symbol::{kw, sym, Symbol};
13 use rustc_target::abi::{LayoutS, Primitive, TagEncoding, VariantIdx, Variants};
14 use std::cmp::Ordering;
19 collect_paths_for_type, document, ensure_trailing_slash, get_filtered_impls_for_reference,
20 item_ty_to_section, notable_traits_button, notable_traits_json, render_all_impls,
21 render_assoc_item, render_assoc_items, render_attributes_in_code, render_attributes_in_pre,
22 render_impl, render_rightside, render_stability_since_raw,
23 render_stability_since_raw_with_extra, 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 visibility_print_with_space, Buffer, Ending, PrintWithSpace,
34 use crate::html::layout::Page;
35 use crate::html::markdown::{HeadingOffset, MarkdownSummaryLine};
36 use crate::html::url_parts_builder::UrlPartsBuilder;
37 use crate::html::{highlight, static_files};
40 use itertools::Itertools;
42 const ITEM_TABLE_OPEN: &str = "<div class=\"item-table\">";
43 const ITEM_TABLE_CLOSE: &str = "</div>";
44 const ITEM_TABLE_ROW_OPEN: &str = "<div class=\"item-row\">";
45 const ITEM_TABLE_ROW_CLOSE: &str = "</div>";
47 // A component in a `use` path, like `string` in std::string::ToString
48 struct PathComponent {
54 #[template(path = "print_item.html")]
56 static_root_path: &'a str,
57 clipboard_svg: &'static static_files::StaticFile,
61 path_components: Vec<PathComponent>,
62 stability_since_raw: &'a str,
63 src_href: Option<&'a str>,
66 /// Calls `print_where_clause` and returns `true` if a `where` clause was generated.
67 fn print_where_clause_and_check<'a, 'tcx: 'a>(
69 gens: &'a clean::Generics,
70 cx: &'a Context<'tcx>,
72 let len_before = buffer.len();
73 write!(buffer, "{}", print_where_clause(gens, cx, 0, Ending::Newline));
74 len_before != buffer.len()
77 pub(super) fn print_item(
83 debug_assert!(!item.is_stripped());
84 let typ = match *item.kind {
85 clean::ModuleItem(_) => {
92 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
93 clean::TraitItem(..) => "Trait ",
94 clean::StructItem(..) => "Struct ",
95 clean::UnionItem(..) => "Union ",
96 clean::EnumItem(..) => "Enum ",
97 clean::TypedefItem(..) => "Type Definition ",
98 clean::MacroItem(..) => "Macro ",
99 clean::ProcMacroItem(ref mac) => match mac.kind {
100 MacroKind::Bang => "Macro ",
101 MacroKind::Attr => "Attribute Macro ",
102 MacroKind::Derive => "Derive Macro ",
104 clean::PrimitiveItem(..) => "Primitive Type ",
105 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
106 clean::ConstantItem(..) => "Constant ",
107 clean::ForeignTypeItem => "Foreign Type ",
108 clean::KeywordItem => "Keyword ",
109 clean::OpaqueTyItem(..) => "Opaque Type ",
110 clean::TraitAliasItem(..) => "Trait Alias ",
112 // We don't generate pages for any other type.
116 let mut stability_since_raw = Buffer::new();
117 render_stability_since_raw(
118 &mut stability_since_raw,
119 item.stable_since(cx.tcx()),
120 item.const_stability(cx.tcx()),
124 let stability_since_raw: String = stability_since_raw.into_inner();
128 // When this item is part of a `crate use` in a downstream crate, the
129 // source link in the downstream documentation will actually come back to
130 // this page, and this link will be auto-clicked. The `id` attribute is
131 // used to find the link to auto-click.
133 if cx.include_sources && !item.is_primitive() { cx.src_href(item) } else { None };
135 let path_components = if item.is_primitive() || item.is_keyword() {
138 let cur = &cx.current;
139 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
143 .map(|(i, component)| PathComponent {
144 path: "../".repeat(cur.len() - i - 1),
150 let item_vars = ItemVars {
151 static_root_path: &page.get_static_root_path(),
152 clipboard_svg: &static_files::STATIC_FILES.clipboard_svg,
154 name: item.name.as_ref().unwrap().as_str(),
155 item_type: &item.type_().to_string(),
157 stability_since_raw: &stability_since_raw,
158 src_href: src_href.as_deref(),
161 item_vars.render_into(buf).unwrap();
164 clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
165 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
166 item_function(buf, cx, item, f)
168 clean::TraitItem(ref t) => item_trait(buf, cx, item, t),
169 clean::StructItem(ref s) => item_struct(buf, cx, item, s),
170 clean::UnionItem(ref s) => item_union(buf, cx, item, s),
171 clean::EnumItem(ref e) => item_enum(buf, cx, item, e),
172 clean::TypedefItem(ref t) => item_typedef(buf, cx, item, t),
173 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
174 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
175 clean::PrimitiveItem(_) => item_primitive(buf, cx, item),
176 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
177 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
178 clean::ForeignTypeItem => item_foreign_type(buf, cx, item),
179 clean::KeywordItem => item_keyword(buf, cx, item),
180 clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e),
181 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta),
183 // We don't generate pages for any other type.
188 // Render notable-traits.js used for all methods in this module.
189 if !cx.types_with_notable_traits.is_empty() {
192 r#"<script type="text/json" id="notable-traits-data">{}</script>"#,
193 notable_traits_json(cx.types_with_notable_traits.iter(), cx)
195 cx.types_with_notable_traits.clear();
199 /// For large structs, enums, unions, etc, determine whether to hide their fields
200 fn should_hide_fields(n_fields: usize) -> bool {
204 fn toggle_open(w: &mut Buffer, text: impl fmt::Display) {
207 "<details class=\"toggle type-contents-toggle\">\
208 <summary class=\"hideme\">\
209 <span>Show {}</span>\
215 fn toggle_close(w: &mut Buffer) {
216 w.write_str("</details>");
219 fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items: &[clean::Item]) {
220 document(w, cx, item, None, HeadingOffset::H2);
222 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
224 // the order of item types in the listing
225 fn reorder(ty: ItemType) -> u8 {
227 ItemType::ExternCrate => 0,
228 ItemType::Import => 1,
229 ItemType::Primitive => 2,
230 ItemType::Module => 3,
231 ItemType::Macro => 4,
232 ItemType::Struct => 5,
234 ItemType::Constant => 7,
235 ItemType::Static => 8,
236 ItemType::Trait => 9,
237 ItemType::Function => 10,
238 ItemType::Typedef => 12,
239 ItemType::Union => 13,
251 let ty1 = i1.type_();
252 let ty2 = i2.type_();
253 if item_ty_to_section(ty1) != item_ty_to_section(ty2)
254 || (ty1 != ty2 && (ty1 == ItemType::ExternCrate || ty2 == ItemType::ExternCrate))
256 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
258 let s1 = i1.stability(tcx).as_ref().map(|s| s.level);
259 let s2 = i2.stability(tcx).as_ref().map(|s| s.level);
260 if let (Some(a), Some(b)) = (s1, s2) {
261 match (a.is_stable(), b.is_stable()) {
262 (true, true) | (false, false) => {}
263 (false, true) => return Ordering::Less,
264 (true, false) => return Ordering::Greater,
267 let lhs = i1.name.unwrap_or(kw::Empty);
268 let rhs = i2.name.unwrap_or(kw::Empty);
269 compare_names(lhs.as_str(), rhs.as_str())
272 match cx.shared.module_sorting {
273 ModuleSorting::Alphabetical => {
274 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2, cx.tcx()));
276 ModuleSorting::DeclarationOrder => {}
278 // This call is to remove re-export duplicates in cases such as:
281 // pub(crate) mod foo {
282 // pub(crate) mod bar {
283 // pub(crate) trait Double { fn foo(); }
287 // pub(crate) use foo::bar::*;
288 // pub(crate) use foo::*;
291 // `Double` will appear twice in the generated docs.
293 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
294 // can be identical even if the elements are different (mostly in imports).
295 // So in case this is an import, we keep everything by adding a "unique id"
296 // (which is the position in the vector).
297 indices.dedup_by_key(|i| {
300 if items[*i].name.is_some() { Some(full_path(cx, &items[*i])) } else { None },
302 if items[*i].is_import() { *i } else { 0 },
306 debug!("{:?}", indices);
307 let mut last_section = None;
309 for &idx in &indices {
310 let myitem = &items[idx];
311 if myitem.is_stripped() {
315 let my_section = item_ty_to_section(myitem.type_());
316 if Some(my_section) != last_section {
317 if last_section.is_some() {
318 w.write_str(ITEM_TABLE_CLOSE);
320 last_section = Some(my_section);
323 "<h2 id=\"{id}\" class=\"small-section-header\">\
324 <a href=\"#{id}\">{name}</a>\
327 id = cx.derive_id(my_section.id().to_owned()),
328 name = my_section.name(),
334 clean::ExternCrateItem { ref src } => {
335 use crate::html::format::anchor;
337 w.write_str(ITEM_TABLE_ROW_OPEN);
341 "<div class=\"item-left\"><code>{}extern crate {} as {};",
342 visibility_print_with_space(myitem.visibility(tcx), myitem.item_id, cx),
343 anchor(myitem.item_id.expect_def_id(), src, cx),
344 myitem.name.unwrap(),
348 "<div class=\"item-left\"><code>{}extern crate {};",
349 visibility_print_with_space(myitem.visibility(tcx), myitem.item_id, cx),
350 anchor(myitem.item_id.expect_def_id(), myitem.name.unwrap(), cx),
353 w.write_str("</code></div>");
354 w.write_str(ITEM_TABLE_ROW_CLOSE);
357 clean::ImportItem(ref import) => {
358 let stab_tags = if let Some(import_def_id) = import.source.did {
359 let ast_attrs = cx.tcx().get_attrs_unchecked(import_def_id);
360 let import_attrs = Box::new(clean::Attributes::from_ast(ast_attrs));
362 // Just need an item with the correct def_id and attrs
363 let import_item = clean::Item {
364 item_id: import_def_id.into(),
366 cfg: ast_attrs.cfg(cx.tcx(), &cx.cache().hidden_cfg),
370 let stab_tags = Some(extra_info_tags(&import_item, item, cx.tcx()));
376 w.write_str(ITEM_TABLE_ROW_OPEN);
377 let id = match import.kind {
378 clean::ImportKind::Simple(s) => {
379 format!(" id=\"{}\"", cx.derive_id(format!("reexport.{}", s)))
381 clean::ImportKind::Glob => String::new(),
383 let stab_tags = stab_tags.unwrap_or_default();
384 let (stab_tags_before, stab_tags_after) = if stab_tags.is_empty() {
387 ("<div class=\"item-right docblock-short\">", "</div>")
391 "<div class=\"item-left\"{id}>\
392 <code>{vis}{imp}</code>\
394 {stab_tags_before}{stab_tags}{stab_tags_after}",
395 vis = visibility_print_with_space(myitem.visibility(tcx), myitem.item_id, cx),
396 imp = import.print(cx),
398 w.write_str(ITEM_TABLE_ROW_CLOSE);
402 if myitem.name.is_none() {
406 let unsafety_flag = match *myitem.kind {
407 clean::FunctionItem(_) | clean::ForeignFunctionItem(_)
408 if myitem.fn_header(cx.tcx()).unwrap().unsafety
409 == hir::Unsafety::Unsafe =>
411 "<sup title=\"unsafe function\">⚠</sup>"
416 let visibility_emoji = match myitem.visibility(tcx) {
417 Some(ty::Visibility::Restricted(_)) => {
418 "<span title=\"Restricted Visibility\"> 🔒</span> "
423 let doc_value = myitem.doc_value().unwrap_or_default();
424 w.write_str(ITEM_TABLE_ROW_OPEN);
425 let docs = MarkdownSummaryLine(&doc_value, &myitem.links(cx)).into_string();
426 let (docs_before, docs_after) = if docs.is_empty() {
429 ("<div class=\"item-right docblock-short\">", "</div>")
433 "<div class=\"item-left\">\
434 <a class=\"{class}\" href=\"{href}\" title=\"{title}\">{name}</a>\
439 {docs_before}{docs}{docs_after}",
440 name = myitem.name.unwrap(),
441 visibility_emoji = visibility_emoji,
442 stab_tags = extra_info_tags(myitem, item, cx.tcx()),
443 class = myitem.type_(),
444 unsafety_flag = unsafety_flag,
445 href = item_path(myitem.type_(), myitem.name.unwrap().as_str()),
446 title = [myitem.type_().to_string(), full_path(cx, myitem)]
448 .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
452 w.write_str(ITEM_TABLE_ROW_CLOSE);
457 if last_section.is_some() {
458 w.write_str(ITEM_TABLE_CLOSE);
462 /// Render the stability, deprecation and portability tags that are displayed in the item's summary
463 /// at the module level.
464 fn extra_info_tags(item: &clean::Item, parent: &clean::Item, tcx: TyCtxt<'_>) -> String {
465 let mut tags = String::new();
467 fn tag_html(class: &str, title: &str, contents: &str) -> String {
468 format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
471 // The trailing space after each tag is to space it properly against the rest of the docs.
472 if let Some(depr) = &item.deprecation(tcx) {
473 let mut message = "Deprecated";
474 if !stability::deprecation_in_effect(depr) {
475 message = "Deprecation planned";
477 tags += &tag_html("deprecated", "", message);
480 // The "rustc_private" crates are permanently unstable so it makes no sense
481 // to render "unstable" everywhere.
482 if item.stability(tcx).as_ref().map(|s| s.is_unstable() && s.feature != sym::rustc_private)
485 tags += &tag_html("unstable", "", "Experimental");
488 let cfg = match (&item.cfg, parent.cfg.as_ref()) {
489 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
490 (cfg, _) => cfg.as_deref().cloned(),
493 debug!("Portability name={:?} {:?} - {:?} = {:?}", item.name, item.cfg, parent.cfg, cfg);
494 if let Some(ref cfg) = cfg {
495 tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
501 fn item_function(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, f: &clean::Function) {
503 let header = it.fn_header(tcx).expect("printing a function which isn't a function");
504 let constness = print_constness_with_space(&header.constness, it.const_stability(tcx));
505 let unsafety = header.unsafety.print_with_space();
506 let abi = print_abi_with_space(header.abi).to_string();
507 let asyncness = header.asyncness.print_with_space();
508 let visibility = visibility_print_with_space(it.visibility(tcx), it.item_id, cx).to_string();
509 let name = it.name.unwrap();
511 let generics_len = format!("{:#}", f.generics.print(cx)).len();
512 let header_len = "fn ".len()
518 + name.as_str().len()
522 f.decl.output.as_return().and_then(|output| notable_traits_button(output, cx));
525 render_attributes_in_pre(w, it, "");
526 w.reserve(header_len);
529 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
530 {name}{generics}{decl}{notable_traits}{where_clause}",
532 constness = constness,
533 asyncness = asyncness,
537 generics = f.generics.print(cx),
538 where_clause = print_where_clause(&f.generics, cx, 0, Ending::Newline),
539 decl = f.decl.full_print(header_len, 0, cx),
540 notable_traits = notable_traits.unwrap_or_default(),
543 document(w, cx, it, None, HeadingOffset::H2);
546 fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::Trait) {
548 let bounds = bounds(&t.bounds, false, cx);
549 let required_types = t.items.iter().filter(|m| m.is_ty_associated_type()).collect::<Vec<_>>();
550 let provided_types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
551 let required_consts = t.items.iter().filter(|m| m.is_ty_associated_const()).collect::<Vec<_>>();
552 let provided_consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
553 let required_methods = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
554 let provided_methods = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
555 let count_types = required_types.len() + provided_types.len();
556 let count_consts = required_consts.len() + provided_consts.len();
557 let count_methods = required_methods.len() + provided_methods.len();
558 let must_implement_one_of_functions = tcx.trait_def(t.def_id).must_implement_one_of.clone();
560 // Output the trait definition
562 render_attributes_in_pre(w, it, "");
565 "{}{}{}trait {}{}{}",
566 visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
567 t.unsafety(tcx).print_with_space(),
568 if t.is_auto(tcx) { "auto " } else { "" },
570 t.generics.print(cx),
574 if !t.generics.where_predicates.is_empty() {
575 write!(w, "{}", print_where_clause(&t.generics, cx, 0, Ending::Newline));
580 if t.items.is_empty() {
583 // FIXME: we should be using a derived_id for the Anchors here
585 let mut toggle = false;
587 // If there are too many associated types, hide _everything_
588 if should_hide_fields(count_types) {
592 format_args!("{} associated items", count_types + count_consts + count_methods),
595 for types in [&required_types, &provided_types] {
600 AssocItemLink::Anchor(None),
608 // If there are too many associated constants, hide everything after them
609 // We also do this if the types + consts is large because otherwise we could
610 // render a bunch of types and _then_ a bunch of consts just because both were
611 // _just_ under the limit
612 if !toggle && should_hide_fields(count_types + count_consts) {
617 "{} associated constant{} and {} method{}",
619 pluralize(count_consts),
621 pluralize(count_methods),
625 if count_types != 0 && (count_consts != 0 || count_methods != 0) {
628 for consts in [&required_consts, &provided_consts] {
633 AssocItemLink::Anchor(None),
641 if !toggle && should_hide_fields(count_methods) {
643 toggle_open(w, format_args!("{} methods", count_methods));
645 if count_consts != 0 && count_methods != 0 {
648 for (pos, m) in required_methods.iter().enumerate() {
652 AssocItemLink::Anchor(None),
659 if pos < required_methods.len() - 1 {
660 w.write_str("<span class=\"item-spacer\"></span>");
663 if !required_methods.is_empty() && !provided_methods.is_empty() {
666 for (pos, m) in provided_methods.iter().enumerate() {
670 AssocItemLink::Anchor(None),
676 clean::MethodItem(ref inner, _)
677 if !inner.generics.where_predicates.is_empty() =>
679 w.write_str(",\n { ... }\n");
682 w.write_str(" { ... }\n");
686 if pos < provided_methods.len() - 1 {
687 w.write_str("<span class=\"item-spacer\"></span>");
697 // Trait documentation
698 document(w, cx, it, None, HeadingOffset::H2);
700 fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
703 "<h2 id=\"{0}\" class=\"small-section-header\">\
704 {1}<a href=\"#{0}\" class=\"anchor\">§</a>\
706 id, title, extra_content
710 fn trait_item(w: &mut Buffer, cx: &mut Context<'_>, m: &clean::Item, t: &clean::Item) {
711 let name = m.name.unwrap();
712 info!("Documenting {} on {:?}", name, t.name);
713 let item_type = m.type_();
714 let id = cx.derive_id(format!("{}.{}", item_type, name));
715 let mut content = Buffer::empty_from(w);
716 document(&mut content, cx, m, Some(t), HeadingOffset::H5);
717 let toggled = !content.is_empty();
719 let method_toggle_class = if item_type.is_method() { " method-toggle" } else { "" };
720 write!(w, "<details class=\"toggle{method_toggle_class}\" open><summary>");
722 write!(w, "<section id=\"{}\" class=\"method\">", id);
723 render_rightside(w, cx, m, t, RenderMode::Normal);
724 write!(w, "<h4 class=\"code-header\">");
728 AssocItemLink::Anchor(Some(&id)),
733 w.write_str("</h4>");
734 w.write_str("</section>");
736 write!(w, "</summary>");
737 w.push_buffer(content);
738 write!(w, "</details>");
742 if !required_types.is_empty() {
743 write_small_section_header(
745 "required-associated-types",
746 "Required Associated Types",
747 "<div class=\"methods\">",
749 for t in required_types {
750 trait_item(w, cx, t, it);
752 w.write_str("</div>");
754 if !provided_types.is_empty() {
755 write_small_section_header(
757 "provided-associated-types",
758 "Provided Associated Types",
759 "<div class=\"methods\">",
761 for t in provided_types {
762 trait_item(w, cx, t, it);
764 w.write_str("</div>");
767 if !required_consts.is_empty() {
768 write_small_section_header(
770 "required-associated-consts",
771 "Required Associated Constants",
772 "<div class=\"methods\">",
774 for t in required_consts {
775 trait_item(w, cx, t, it);
777 w.write_str("</div>");
779 if !provided_consts.is_empty() {
780 write_small_section_header(
782 "provided-associated-consts",
783 "Provided Associated Constants",
784 "<div class=\"methods\">",
786 for t in provided_consts {
787 trait_item(w, cx, t, it);
789 w.write_str("</div>");
792 // Output the documentation for each function individually
793 if !required_methods.is_empty() || must_implement_one_of_functions.is_some() {
794 write_small_section_header(
798 "<div class=\"methods\">",
801 if let Some(list) = must_implement_one_of_functions.as_deref() {
804 "<div class=\"stab must_implement\">At least one of the `{}` methods is required.</div>",
805 list.iter().join("`, `")
809 for m in required_methods {
810 trait_item(w, cx, m, it);
812 w.write_str("</div>");
814 if !provided_methods.is_empty() {
815 write_small_section_header(
819 "<div class=\"methods\">",
821 for m in provided_methods {
822 trait_item(w, cx, m, it);
824 w.write_str("</div>");
827 // If there are methods directly on this trait object, render them here.
828 render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All);
830 let cloned_shared = Rc::clone(&cx.shared);
831 let cache = &cloned_shared.cache;
832 let mut extern_crates = FxHashSet::default();
833 if let Some(implementors) = cache.implementors.get(&it.item_id.expect_def_id()) {
834 // The DefId is for the first Type found with that name. The bool is
835 // if any Types with the same name but different DefId have been found.
836 let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();
837 for implementor in implementors {
838 if let Some(did) = implementor.inner_impl().for_.without_borrowed_ref().def_id(cache) &&
840 extern_crates.insert(did.krate);
842 match implementor.inner_impl().for_.without_borrowed_ref() {
843 clean::Type::Path { ref path } if !path.is_assoc_ty() => {
844 let did = path.def_id();
845 let &mut (prev_did, ref mut has_duplicates) =
846 implementor_dups.entry(path.last()).or_insert((did, false));
848 *has_duplicates = true;
855 let (local, foreign) =
856 implementors.iter().partition::<Vec<_>, _>(|i| i.is_on_local_type(cx));
858 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
859 local.iter().partition(|i| i.inner_impl().kind.is_auto());
861 synthetic.sort_by(|a, b| compare_impl(a, b, cx));
862 concrete.sort_by(|a, b| compare_impl(a, b, cx));
864 if !foreign.is_empty() {
865 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
867 for implementor in foreign {
868 let provided_methods = implementor.inner_impl().provided_trait_methods(cx.tcx());
870 AssocItemLink::GotoSource(implementor.impl_item.item_id, &provided_methods);
880 ImplRenderingParameters {
881 show_def_docs: false,
882 show_default_items: false,
883 show_non_assoc_items: true,
884 toggle_open_by_default: false,
890 write_small_section_header(
894 "<div id=\"implementors-list\">",
896 for implementor in concrete {
897 render_implementor(cx, implementor, it, w, &implementor_dups, &[]);
899 w.write_str("</div>");
901 if t.is_auto(cx.tcx()) {
902 write_small_section_header(
904 "synthetic-implementors",
906 "<div id=\"synthetic-implementors-list\">",
908 for implementor in synthetic {
915 &collect_paths_for_type(implementor.inner_impl().for_.clone(), cache),
918 w.write_str("</div>");
921 // even without any implementations to write in, we still want the heading and list, so the
922 // implementors javascript file pulled in below has somewhere to write the impls into
923 write_small_section_header(
927 "<div id=\"implementors-list\"></div>",
930 if t.is_auto(cx.tcx()) {
931 write_small_section_header(
933 "synthetic-implementors",
935 "<div id=\"synthetic-implementors-list\"></div>",
940 // Include implementors in crates that depend on the current crate.
942 // This is complicated by the way rustdoc is invoked, which is basically
943 // the same way rustc is invoked: it gets called, one at a time, for each
944 // crate. When building the rustdocs for the current crate, rustdoc can
945 // see crate metadata for its dependencies, but cannot see metadata for its
948 // To make this work, we generate a "hook" at this stage, and our
949 // dependents can "plug in" to it when they build. For simplicity's sake,
950 // it's [JSONP]: a JavaScript file with the data we need (and can parse),
951 // surrounded by a tiny wrapper that the Rust side ignores, but allows the
952 // JavaScript side to include without having to worry about Same Origin
953 // Policy. The code for *that* is in `write_shared.rs`.
955 // This is further complicated by `#[doc(inline)]`. We want all copies
956 // of an inlined trait to reference the same JS file, to address complex
957 // dependency graphs like this one (lower crates depend on higher crates):
960 // --------------------------------------------
961 // | crate A: trait Foo |
962 // --------------------------------------------
964 // -------------------------------- |
965 // | crate B: impl A::Foo for Bar | |
966 // -------------------------------- |
968 // ---------------------------------------------
969 // | crate C: #[doc(inline)] use A::Foo as Baz |
970 // | impl Baz for Quux |
971 // ---------------------------------------------
974 // Basically, we want `C::Baz` and `A::Foo` to show the same set of
975 // impls, which is easier if they both treat `/implementors/A/trait.Foo.js`
976 // as the Single Source of Truth.
978 // We also want the `impl Baz for Quux` to be written to
979 // `trait.Foo.js`. However, when we generate plain HTML for `C::Baz`,
980 // we're going to want to generate plain HTML for `impl Baz for Quux` too,
981 // because that'll load faster, and it's better for SEO. And we don't want
982 // the same impl to show up twice on the same page.
984 // To make this work, the implementors JS file has a structure kinda
989 // "B": {"impl A::Foo for Bar"},
990 // "C": {"impl Baz for Quux"},
994 // First of all, this means we can rebuild a crate, and it'll replace its own
995 // data if something changes. That is, `rustdoc` is idempotent. The other
996 // advantage is that we can list the crates that get included in the HTML,
997 // and ignore them when doing the JavaScript-based part of rendering.
998 // So C's HTML will have something like this:
1001 // <script src="/implementors/A/trait.Foo.js"
1002 // data-ignore-extern-crates="A,B" async></script>
1005 // And, when the JS runs, anything in data-ignore-extern-crates is known
1006 // to already be in the HTML, and will be ignored.
1008 // [JSONP]: https://en.wikipedia.org/wiki/JSONP
1009 let mut js_src_path: UrlPartsBuilder = std::iter::repeat("..")
1010 .take(cx.current.len())
1011 .chain(std::iter::once("implementors"))
1013 if let Some(did) = it.item_id.as_def_id() &&
1014 let get_extern = { || cache.external_paths.get(&did).map(|s| &s.0) } &&
1015 let Some(fqp) = cache.exact_paths.get(&did).or_else(get_extern) {
1016 js_src_path.extend(fqp[..fqp.len() - 1].iter().copied());
1017 js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), fqp.last().unwrap()));
1019 js_src_path.extend(cx.current.iter().copied());
1020 js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), it.name.unwrap()));
1022 let extern_crates = extern_crates
1024 .map(|cnum| tcx.crate_name(cnum).to_string())
1025 .collect::<Vec<_>>()
1027 let (extern_before, extern_after) =
1028 if extern_crates.is_empty() { ("", "") } else { (" data-ignore-extern-crates=\"", "\"") };
1031 "<script src=\"{src}\"{extern_before}{extern_crates}{extern_after} async></script>",
1032 src = js_src_path.finish(),
1036 fn item_trait_alias(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::TraitAlias) {
1038 render_attributes_in_pre(w, it, "");
1041 "trait {}{}{} = {};",
1043 t.generics.print(cx),
1044 print_where_clause(&t.generics, cx, 0, Ending::Newline),
1045 bounds(&t.bounds, true, cx)
1049 document(w, cx, it, None, HeadingOffset::H2);
1051 // Render any items associated directly to this alias, as otherwise they
1052 // won't be visible anywhere in the docs. It would be nice to also show
1053 // associated items from the aliased type (see discussion in #32077), but
1054 // we need #14072 to make sense of the generics.
1055 render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1058 fn item_opaque_ty(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::OpaqueTy) {
1060 render_attributes_in_pre(w, it, "");
1063 "type {}{}{where_clause} = impl {bounds};",
1065 t.generics.print(cx),
1066 where_clause = print_where_clause(&t.generics, cx, 0, Ending::Newline),
1067 bounds = bounds(&t.bounds, false, cx),
1071 document(w, cx, it, None, HeadingOffset::H2);
1073 // Render any items associated directly to this alias, as otherwise they
1074 // won't be visible anywhere in the docs. It would be nice to also show
1075 // associated items from the aliased type (see discussion in #32077), but
1076 // we need #14072 to make sense of the generics.
1077 render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1080 fn item_typedef(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::Typedef) {
1081 fn write_content(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Typedef) {
1083 render_attributes_in_pre(w, it, "");
1084 write!(w, "{}", visibility_print_with_space(it.visibility(cx.tcx()), it.item_id, cx));
1087 "type {}{}{where_clause} = {type_};",
1089 t.generics.print(cx),
1090 where_clause = print_where_clause(&t.generics, cx, 0, Ending::Newline),
1091 type_ = t.type_.print(cx),
1096 write_content(w, cx, it, t);
1098 document(w, cx, it, None, HeadingOffset::H2);
1100 let def_id = it.item_id.expect_def_id();
1101 // Render any items associated directly to this alias, as otherwise they
1102 // won't be visible anywhere in the docs. It would be nice to also show
1103 // associated items from the aliased type (see discussion in #32077), but
1104 // we need #14072 to make sense of the generics.
1105 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1106 document_type_layout(w, cx, def_id);
1109 fn item_union(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Union) {
1111 render_attributes_in_pre(w, it, "");
1112 render_union(w, it, Some(&s.generics), &s.fields, "", cx);
1115 document(w, cx, it, None, HeadingOffset::H2);
1120 .filter_map(|f| match *f.kind {
1121 clean::StructFieldItem(ref ty) => Some((f, ty)),
1125 if fields.peek().is_some() {
1128 "<h2 id=\"fields\" class=\"fields small-section-header\">\
1129 Fields<a href=\"#fields\" class=\"anchor\">§</a>\
1132 for (field, ty) in fields {
1133 let name = field.name.expect("union field name");
1134 let id = format!("{}.{}", ItemType::StructField, name);
1137 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
1138 <a href=\"#{id}\" class=\"anchor field\">§</a>\
1139 <code>{name}: {ty}</code>\
1143 shortty = ItemType::StructField,
1146 if let Some(stability_class) = field.stability_class(cx.tcx()) {
1147 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
1149 document(w, cx, field, Some(it), HeadingOffset::H3);
1152 let def_id = it.item_id.expect_def_id();
1153 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1154 document_type_layout(w, cx, def_id);
1157 fn print_tuple_struct_fields(w: &mut Buffer, cx: &Context<'_>, s: &[clean::Item]) {
1158 for (i, ty) in s.iter().enumerate() {
1160 w.write_str(", ");
1163 clean::StrippedItem(box clean::StructFieldItem(_)) => w.write_str("_"),
1164 clean::StructFieldItem(ref ty) => write!(w, "{}", ty.print(cx)),
1165 _ => unreachable!(),
1170 fn item_enum(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, e: &clean::Enum) {
1172 let count_variants = e.variants().count();
1174 render_attributes_in_pre(w, it, "");
1178 visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
1180 e.generics.print(cx),
1182 if !print_where_clause_and_check(w, &e.generics, cx) {
1183 // If there wasn't a `where` clause, we add a whitespace.
1187 let variants_stripped = e.has_stripped_entries();
1188 if count_variants == 0 && !variants_stripped {
1192 let toggle = should_hide_fields(count_variants);
1194 toggle_open(w, format_args!("{} variants", count_variants));
1196 for v in e.variants() {
1198 let name = v.name.unwrap();
1200 // FIXME(#101337): Show discriminant
1201 clean::VariantItem(ref var) => match var.kind {
1202 clean::VariantKind::CLike => write!(w, "{}", name),
1203 clean::VariantKind::Tuple(ref s) => {
1204 write!(w, "{}(", name);
1205 print_tuple_struct_fields(w, cx, s);
1208 clean::VariantKind::Struct(ref s) => {
1209 render_struct(w, v, None, None, &s.fields, " ", false, cx);
1212 _ => unreachable!(),
1217 if variants_stripped {
1218 w.write_str(" // some variants omitted\n");
1227 document(w, cx, it, None, HeadingOffset::H2);
1229 if count_variants != 0 {
1232 "<h2 id=\"variants\" class=\"variants small-section-header\">\
1233 Variants{}<a href=\"#variants\" class=\"anchor\">§</a>\
1235 document_non_exhaustive_header(it)
1237 document_non_exhaustive(w, it);
1238 write!(w, "<div class=\"variants\">");
1239 for variant in e.variants() {
1240 let id = cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.unwrap()));
1243 "<section id=\"{id}\" class=\"variant\">\
1244 <a href=\"#{id}\" class=\"anchor\">§</a>",
1247 render_stability_since_raw_with_extra(
1249 variant.stable_since(tcx),
1250 variant.const_stability(tcx),
1251 it.stable_since(tcx),
1252 it.const_stable_since(tcx),
1255 write!(w, "<h3 class=\"code-header\">{name}", name = variant.name.unwrap());
1257 let clean::VariantItem(variant_data) = &*variant.kind else { unreachable!() };
1259 if let clean::VariantKind::Tuple(ref s) = variant_data.kind {
1261 print_tuple_struct_fields(w, cx, s);
1264 w.write_str("</h3></section>");
1266 let heading_and_fields = match &variant_data.kind {
1267 clean::VariantKind::Struct(s) => Some(("Fields", &s.fields)),
1268 clean::VariantKind::Tuple(fields) => {
1269 // Documentation on tuple variant fields is rare, so to reduce noise we only emit
1270 // the section if at least one field is documented.
1271 if fields.iter().any(|f| f.doc_value().is_some()) {
1272 Some(("Tuple Fields", fields))
1277 clean::VariantKind::CLike => None,
1280 if let Some((heading, fields)) = heading_and_fields {
1282 cx.derive_id(format!("{}.{}.fields", ItemType::Variant, variant.name.unwrap()));
1283 write!(w, "<div class=\"sub-variant\" id=\"{id}\">", id = variant_id);
1284 write!(w, "<h4>{heading}</h4>", heading = heading);
1285 document_non_exhaustive(w, variant);
1286 for field in fields {
1288 clean::StrippedItem(box clean::StructFieldItem(_)) => {}
1289 clean::StructFieldItem(ref ty) => {
1290 let id = cx.derive_id(format!(
1291 "variant.{}.field.{}",
1292 variant.name.unwrap(),
1297 "<div class=\"sub-variant-field\">\
1298 <span id=\"{id}\" class=\"small-section-header\">\
1299 <a href=\"#{id}\" class=\"anchor field\">§</a>\
1300 <code>{f}: {t}</code>\
1303 f = field.name.unwrap(),
1306 document(w, cx, field, Some(variant), HeadingOffset::H5);
1307 write!(w, "</div>");
1309 _ => unreachable!(),
1312 w.write_str("</div>");
1315 document(w, cx, variant, Some(it), HeadingOffset::H4);
1317 write!(w, "</div>");
1319 let def_id = it.item_id.expect_def_id();
1320 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1321 document_type_layout(w, cx, def_id);
1324 fn item_macro(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::Macro) {
1325 highlight::render_item_decl_with_highlighting(&t.source, w);
1326 document(w, cx, it, None, HeadingOffset::H2)
1329 fn item_proc_macro(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, m: &clean::ProcMacro) {
1331 let name = it.name.expect("proc-macros always have names");
1333 MacroKind::Bang => {
1334 write!(w, "{}!() {{ /* proc-macro */ }}", name);
1336 MacroKind::Attr => {
1337 write!(w, "#[{}]", name);
1339 MacroKind::Derive => {
1340 write!(w, "#[derive({})]", name);
1341 if !m.helpers.is_empty() {
1342 w.push_str("\n{\n");
1343 w.push_str(" // Attributes available to this derive:\n");
1344 for attr in &m.helpers {
1345 writeln!(w, " #[{}]", attr);
1352 document(w, cx, it, None, HeadingOffset::H2)
1355 fn item_primitive(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item) {
1356 let def_id = it.item_id.expect_def_id();
1357 document(w, cx, it, None, HeadingOffset::H2);
1358 if it.name.map(|n| n.as_str() != "reference").unwrap_or(false) {
1359 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1361 // We handle the "reference" primitive type on its own because we only want to list
1362 // implementations on generic types.
1363 let shared = Rc::clone(&cx.shared);
1364 let (concrete, synthetic, blanket_impl) = get_filtered_impls_for_reference(&shared, it);
1366 render_all_impls(w, cx, it, &concrete, &synthetic, &blanket_impl);
1370 fn item_constant(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, c: &clean::Constant) {
1373 render_attributes_in_code(w, it);
1377 "{vis}const {name}: {typ}",
1378 vis = visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
1379 name = it.name.unwrap(),
1380 typ = c.type_.print(cx),
1383 // FIXME: The code below now prints
1384 // ` = _; // 100i32`
1385 // if the expression is
1387 // which looks just wrong.
1392 let value = c.value(tcx);
1393 let is_literal = c.is_literal(tcx);
1394 let expr = c.expr(tcx);
1395 if value.is_some() || is_literal {
1396 write!(w, " = {expr};", expr = Escape(&expr));
1402 if let Some(value) = &value {
1403 let value_lowercase = value.to_lowercase();
1404 let expr_lowercase = expr.to_lowercase();
1406 if value_lowercase != expr_lowercase
1407 && value_lowercase.trim_end_matches("i32") != expr_lowercase
1409 write!(w, " // {value}", value = Escape(value));
1415 document(w, cx, it, None, HeadingOffset::H2)
1418 fn item_struct(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Struct) {
1420 render_attributes_in_code(w, it);
1421 render_struct(w, it, Some(&s.generics), s.ctor_kind, &s.fields, "", true, cx);
1424 document(w, cx, it, None, HeadingOffset::H2);
1429 .filter_map(|f| match *f.kind {
1430 clean::StructFieldItem(ref ty) => Some((f, ty)),
1434 if let None | Some(CtorKind::Fn) = s.ctor_kind {
1435 if fields.peek().is_some() {
1438 "<h2 id=\"fields\" class=\"fields small-section-header\">\
1439 {}{}<a href=\"#fields\" class=\"anchor\">§</a>\
1441 if s.ctor_kind.is_none() { "Fields" } else { "Tuple Fields" },
1442 document_non_exhaustive_header(it)
1444 document_non_exhaustive(w, it);
1445 for (index, (field, ty)) in fields.enumerate() {
1447 field.name.map_or_else(|| index.to_string(), |sym| sym.as_str().to_string());
1448 let id = cx.derive_id(format!("{}.{}", ItemType::StructField, field_name));
1451 "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
1452 <a href=\"#{id}\" class=\"anchor field\">§</a>\
1453 <code>{name}: {ty}</code>\
1455 item_type = ItemType::StructField,
1460 document(w, cx, field, Some(it), HeadingOffset::H3);
1464 let def_id = it.item_id.expect_def_id();
1465 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1466 document_type_layout(w, cx, def_id);
1469 fn item_static(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Static) {
1471 render_attributes_in_code(w, it);
1474 "{vis}static {mutability}{name}: {typ}",
1475 vis = visibility_print_with_space(it.visibility(cx.tcx()), it.item_id, cx),
1476 mutability = s.mutability.print_with_space(),
1477 name = it.name.unwrap(),
1478 typ = s.type_.print(cx)
1481 document(w, cx, it, None, HeadingOffset::H2)
1484 fn item_foreign_type(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item) {
1486 w.write_str("extern {\n");
1487 render_attributes_in_code(w, it);
1491 visibility_print_with_space(it.visibility(cx.tcx()), it.item_id, cx),
1496 document(w, cx, it, None, HeadingOffset::H2);
1498 render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1501 fn item_keyword(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item) {
1502 document(w, cx, it, None, HeadingOffset::H2)
1505 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
1506 pub(crate) fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
1507 /// Takes a non-numeric and a numeric part from the given &str.
1508 fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
1509 let i = s.find(|c: char| c.is_ascii_digit());
1510 let (a, b) = s.split_at(i.unwrap_or(s.len()));
1511 let i = b.find(|c: char| !c.is_ascii_digit());
1512 let (b, c) = b.split_at(i.unwrap_or(b.len()));
1517 while !lhs.is_empty() || !rhs.is_empty() {
1518 let (la, lb) = take_parts(&mut lhs);
1519 let (ra, rb) = take_parts(&mut rhs);
1520 // First process the non-numeric part.
1522 Ordering::Equal => (),
1525 // Then process the numeric part, if both sides have one (and they fit in a u64).
1526 if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
1528 Ordering::Equal => (),
1532 // Then process the numeric part again, but this time as strings.
1534 Ordering::Equal => (),
1542 pub(super) fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
1543 let mut s = join_with_double_colon(&cx.current);
1545 s.push_str(item.name.unwrap().as_str());
1549 pub(super) fn item_path(ty: ItemType, name: &str) -> String {
1551 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1552 _ => format!("{}.{}.html", ty, name),
1556 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool, cx: &Context<'_>) -> String {
1557 let mut bounds = String::new();
1558 if !t_bounds.is_empty() {
1560 bounds.push_str(": ");
1562 for (i, p) in t_bounds.iter().enumerate() {
1564 bounds.push_str(" + ");
1566 bounds.push_str(&p.print(cx).to_string());
1572 fn wrap_item<F>(w: &mut Buffer, f: F)
1574 F: FnOnce(&mut Buffer),
1576 w.write_str(r#"<pre class="rust item-decl"><code>"#);
1578 w.write_str("</code></pre>");
1581 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl, cx: &Context<'_>) -> Ordering {
1582 let lhss = format!("{}", lhs.inner_impl().print(false, cx));
1583 let rhss = format!("{}", rhs.inner_impl().print(false, cx));
1585 // lhs and rhs are formatted as HTML, which may be unnecessary
1586 compare_names(&lhss, &rhss)
1589 fn render_implementor(
1590 cx: &mut Context<'_>,
1592 trait_: &clean::Item,
1594 implementor_dups: &FxHashMap<Symbol, (DefId, bool)>,
1597 // If there's already another implementor that has the same abridged name, use the
1598 // full path, for example in `std::iter::ExactSizeIterator`
1599 let use_absolute = match implementor.inner_impl().for_ {
1600 clean::Type::Path { ref path, .. }
1601 | clean::BorrowedRef { type_: box clean::Type::Path { ref path, .. }, .. }
1602 if !path.is_assoc_ty() =>
1604 implementor_dups[&path.last()].1
1613 AssocItemLink::Anchor(None),
1617 ImplRenderingParameters {
1618 show_def_docs: false,
1619 show_default_items: false,
1620 show_non_assoc_items: false,
1621 toggle_open_by_default: false,
1629 g: Option<&clean::Generics>,
1630 fields: &[clean::Item],
1638 visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
1642 let where_displayed = g
1644 write!(w, "{}", g.print(cx));
1645 print_where_clause_and_check(w, g, cx)
1649 // If there wasn't a `where` clause, we add a whitespace.
1650 if !where_displayed {
1654 write!(w, "{{\n{}", tab);
1656 fields.iter().filter(|f| matches!(*f.kind, clean::StructFieldItem(..))).count();
1657 let toggle = should_hide_fields(count_fields);
1659 toggle_open(w, format_args!("{} fields", count_fields));
1662 for field in fields {
1663 if let clean::StructFieldItem(ref ty) = *field.kind {
1667 visibility_print_with_space(field.visibility(tcx), field.item_id, cx),
1668 field.name.unwrap(),
1675 if it.has_stripped_entries().unwrap() {
1676 write!(w, " /* private fields */\n{}", tab);
1687 g: Option<&clean::Generics>,
1688 ty: Option<CtorKind>,
1689 fields: &[clean::Item],
1698 visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
1699 if structhead { "struct " } else { "" },
1702 if let Some(g) = g {
1703 write!(w, "{}", g.print(cx))
1707 let where_diplayed = g.map(|g| print_where_clause_and_check(w, g, cx)).unwrap_or(false);
1709 // If there wasn't a `where` clause, we add a whitespace.
1710 if !where_diplayed {
1716 fields.iter().filter(|f| matches!(*f.kind, clean::StructFieldItem(..))).count();
1717 let has_visible_fields = count_fields > 0;
1718 let toggle = should_hide_fields(count_fields);
1720 toggle_open(w, format_args!("{} fields", count_fields));
1722 for field in fields {
1723 if let clean::StructFieldItem(ref ty) = *field.kind {
1728 visibility_print_with_space(field.visibility(tcx), field.item_id, cx),
1729 field.name.unwrap(),
1735 if has_visible_fields {
1736 if it.has_stripped_entries().unwrap() {
1737 write!(w, "\n{} /* private fields */", tab);
1739 write!(w, "\n{}", tab);
1740 } else if it.has_stripped_entries().unwrap() {
1741 write!(w, " /* private fields */ ");
1748 Some(CtorKind::Fn) => {
1750 for (i, field) in fields.iter().enumerate() {
1755 clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
1756 clean::StructFieldItem(ref ty) => {
1760 visibility_print_with_space(field.visibility(tcx), field.item_id, cx),
1764 _ => unreachable!(),
1768 if let Some(g) = g {
1769 write!(w, "{}", print_where_clause(g, cx, 0, Ending::NoNewline));
1771 // We only want a ";" when we are displaying a tuple struct, not a variant tuple struct.
1776 Some(CtorKind::Const) => {
1777 // Needed for PhantomData.
1778 if let Some(g) = g {
1779 write!(w, "{}", print_where_clause(g, cx, 0, Ending::NoNewline));
1786 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1787 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1790 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1791 if item.is_non_exhaustive() {
1794 "<details class=\"toggle non-exhaustive\">\
1795 <summary class=\"hideme\"><span>{}</span></summary>\
1796 <div class=\"docblock\">",
1798 if item.is_struct() {
1799 "This struct is marked as non-exhaustive"
1800 } else if item.is_enum() {
1801 "This enum is marked as non-exhaustive"
1802 } else if item.is_variant() {
1803 "This variant is marked as non-exhaustive"
1805 "This type is marked as non-exhaustive"
1810 if item.is_struct() {
1812 "Non-exhaustive structs could have additional fields added in future. \
1813 Therefore, non-exhaustive structs cannot be constructed in external crates \
1814 using the traditional <code>Struct { .. }</code> syntax; cannot be \
1815 matched against without a wildcard <code>..</code>; and \
1816 struct update syntax will not work.",
1818 } else if item.is_enum() {
1820 "Non-exhaustive enums could have additional variants added in future. \
1821 Therefore, when matching against variants of non-exhaustive enums, an \
1822 extra wildcard arm must be added to account for any future variants.",
1824 } else if item.is_variant() {
1826 "Non-exhaustive enum variants could have additional fields added in future. \
1827 Therefore, non-exhaustive enum variants cannot be constructed in external \
1828 crates and cannot be matched against.",
1832 "This type will require a wildcard arm in any match statements or constructors.",
1836 w.write_str("</div></details>");
1840 fn document_type_layout(w: &mut Buffer, cx: &Context<'_>, ty_def_id: DefId) {
1841 fn write_size_of_layout(w: &mut Buffer, layout: &LayoutS<VariantIdx>, tag_size: u64) {
1842 if layout.abi.is_unsized() {
1843 write!(w, "(unsized)");
1845 let bytes = layout.size.bytes() - tag_size;
1846 write!(w, "{size} byte{pl}", size = bytes, pl = if bytes == 1 { "" } else { "s" },);
1850 if !cx.shared.show_type_layout {
1856 "<h2 id=\"layout\" class=\"small-section-header\"> \
1857 Layout<a href=\"#layout\" class=\"anchor\">§</a></h2>"
1859 writeln!(w, "<div class=\"docblock\">");
1862 let param_env = tcx.param_env(ty_def_id);
1863 let ty = tcx.type_of(ty_def_id);
1864 match tcx.layout_of(param_env.and(ty)) {
1868 "<div class=\"warning\"><p><strong>Note:</strong> Most layout information is \
1869 <strong>completely unstable</strong> and may even differ between compilations. \
1870 The only exception is types with certain <code>repr(...)</code> attributes. \
1871 Please see the Rust Reference’s \
1872 <a href=\"https://doc.rust-lang.org/reference/type-layout.html\">“Type Layout”</a> \
1873 chapter for details on type layout guarantees.</p></div>"
1875 w.write_str("<p><strong>Size:</strong> ");
1876 write_size_of_layout(w, &ty_layout.layout.0, 0);
1877 writeln!(w, "</p>");
1878 if let Variants::Multiple { variants, tag, tag_encoding, .. } =
1879 &ty_layout.layout.variants()
1881 if !variants.is_empty() {
1883 "<p><strong>Size for each variant:</strong></p>\
1887 let Adt(adt, _) = ty_layout.ty.kind() else {
1888 span_bug!(tcx.def_span(ty_def_id), "not an adt")
1891 let tag_size = if let TagEncoding::Niche { .. } = tag_encoding {
1893 } else if let Primitive::Int(i, _) = tag.primitive() {
1896 span_bug!(tcx.def_span(ty_def_id), "tag is neither niche nor int")
1899 for (index, layout) in variants.iter_enumerated() {
1900 let name = adt.variant(index).name;
1901 write!(w, "<li><code>{name}</code>: ", name = name);
1902 write_size_of_layout(w, layout, tag_size);
1903 writeln!(w, "</li>");
1905 w.write_str("</ul>");
1909 // This kind of layout error can occur with valid code, e.g. if you try to
1910 // get the layout of a generic type such as `Vec<T>`.
1911 Err(LayoutError::Unknown(_)) => {
1914 "<p><strong>Note:</strong> Unable to compute type layout, \
1915 possibly due to this type having generic parameters. \
1916 Layout can only be computed for concrete, fully-instantiated types.</p>"
1919 // This kind of error probably can't happen with valid code, but we don't
1920 // want to panic and prevent the docs from building, so we just let the
1921 // user know that we couldn't compute the layout.
1922 Err(LayoutError::SizeOverflow(_)) => {
1925 "<p><strong>Note:</strong> Encountered an error during type layout; \
1926 the type was too big.</p>"
1929 Err(LayoutError::NormalizationFailure(_, _)) => {
1932 "<p><strong>Note:</strong> Encountered an error during type layout; \
1933 the type failed to be normalized.</p>"
1938 writeln!(w, "</div>");
1941 fn pluralize(count: usize) -> &'static str {
1942 if count > 1 { "s" } else { "" }