1 use clean::AttributesExt;
3 use std::cmp::Ordering;
5 use rustc_data_structures::fx::FxHashMap;
7 use rustc_hir::def::CtorKind;
8 use rustc_hir::def_id::DefId;
9 use rustc_middle::middle::stability;
10 use rustc_middle::ty::layout::LayoutError;
11 use rustc_middle::ty::TyCtxt;
12 use rustc_span::hygiene::MacroKind;
13 use rustc_span::symbol::{kw, sym, Symbol};
16 collect_paths_for_type, document, ensure_trailing_slash, item_ty_to_strs, notable_traits_decl,
17 render_assoc_item, render_assoc_items, render_attributes_in_code, render_attributes_in_pre,
18 render_impl, render_stability_since_raw, write_srclink, AssocItemLink, Context,
20 use crate::clean::{self, GetDefId};
21 use crate::formats::item_type::ItemType;
22 use crate::formats::{AssocItemRender, Impl, RenderMode};
23 use crate::html::escape::Escape;
24 use crate::html::format::{print_abi_with_space, print_where_clause, Buffer, PrintWithSpace};
25 use crate::html::highlight;
26 use crate::html::layout::Page;
27 use crate::html::markdown::MarkdownSummaryLine;
29 pub(super) fn print_item(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer, page: &Page<'_>) {
30 debug_assert!(!item.is_stripped());
31 // Write the breadcrumb trail header for the top
32 buf.write_str("<h1 class=\"fqn\"><span class=\"in-band\">");
33 let name = match *item.kind {
34 clean::ModuleItem(_) => {
41 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
42 clean::TraitItem(..) => "Trait ",
43 clean::StructItem(..) => "Struct ",
44 clean::UnionItem(..) => "Union ",
45 clean::EnumItem(..) => "Enum ",
46 clean::TypedefItem(..) => "Type Definition ",
47 clean::MacroItem(..) => "Macro ",
48 clean::ProcMacroItem(ref mac) => match mac.kind {
49 MacroKind::Bang => "Macro ",
50 MacroKind::Attr => "Attribute Macro ",
51 MacroKind::Derive => "Derive Macro ",
53 clean::PrimitiveItem(..) => "Primitive Type ",
54 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
55 clean::ConstantItem(..) => "Constant ",
56 clean::ForeignTypeItem => "Foreign Type ",
57 clean::KeywordItem(..) => "Keyword ",
58 clean::OpaqueTyItem(..) => "Opaque Type ",
59 clean::TraitAliasItem(..) => "Trait Alias ",
61 // We don't generate pages for any other type.
66 if !item.is_primitive() && !item.is_keyword() {
67 let cur = &cx.current;
68 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
69 for (i, component) in cur.iter().enumerate().take(amt) {
72 "<a href=\"{}index.html\">{}</a>::<wbr>",
73 "../".repeat(cur.len() - i - 1),
78 write!(buf, "<a class=\"{}\" href=\"\">{}</a>", item.type_(), item.name.as_ref().unwrap());
81 "<button id=\"copy-path\" onclick=\"copy_path(this)\" title=\"copy path\">\
82 <img src=\"{static_root_path}clipboard{suffix}.svg\" \
83 width=\"19\" height=\"18\" \
84 alt=\"Copy item import\">\
86 static_root_path = page.get_static_root_path(),
87 suffix = page.resource_suffix,
90 buf.write_str("</span>"); // in-band
91 buf.write_str("<span class=\"out-of-band\">");
92 render_stability_since_raw(
94 item.stable_since(cx.tcx()).as_deref(),
95 item.const_stable_since(cx.tcx()).as_deref(),
100 "<span id=\"render-detail\">\
101 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
102 title=\"collapse all docs\">\
103 [<span class=\"inner\">−</span>]\
110 // When this item is part of a `crate use` in a downstream crate, the
111 // [src] link in the downstream documentation will actually come back to
112 // this page, and this link will be auto-clicked. The `id` attribute is
113 // used to find the link to auto-click.
114 if cx.shared.include_sources && !item.is_primitive() {
115 write_srclink(cx, item, buf);
118 buf.write_str("</span></h1>"); // out-of-band
121 clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
122 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
123 item_function(buf, cx, item, f)
125 clean::TraitItem(ref t) => item_trait(buf, cx, item, t),
126 clean::StructItem(ref s) => item_struct(buf, cx, item, s),
127 clean::UnionItem(ref s) => item_union(buf, cx, item, s),
128 clean::EnumItem(ref e) => item_enum(buf, cx, item, e),
129 clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t),
130 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
131 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
132 clean::PrimitiveItem(_) => item_primitive(buf, cx, item),
133 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
134 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
135 clean::ForeignTypeItem => item_foreign_type(buf, cx, item),
136 clean::KeywordItem(_) => item_keyword(buf, cx, item),
137 clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e),
138 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta),
140 // We don't generate pages for any other type.
146 /// For large structs, enums, unions, etc, determine whether to hide their fields
147 fn should_hide_fields(n_fields: usize) -> bool {
151 fn toggle_open(w: &mut Buffer, text: &str) {
154 "<details class=\"rustdoc-toggle type-contents-toggle\">\
155 <summary class=\"hideme\">\
156 <span>Show {}</span>\
162 fn toggle_close(w: &mut Buffer) {
163 w.write_str("</details>");
166 fn item_module(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, items: &[clean::Item]) {
167 document(w, cx, item, None);
169 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
171 // the order of item types in the listing
172 fn reorder(ty: ItemType) -> u8 {
174 ItemType::ExternCrate => 0,
175 ItemType::Import => 1,
176 ItemType::Primitive => 2,
177 ItemType::Module => 3,
178 ItemType::Macro => 4,
179 ItemType::Struct => 5,
181 ItemType::Constant => 7,
182 ItemType::Static => 8,
183 ItemType::Trait => 9,
184 ItemType::Function => 10,
185 ItemType::Typedef => 12,
186 ItemType::Union => 13,
198 let ty1 = i1.type_();
199 let ty2 = i2.type_();
201 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
203 let s1 = i1.stability(tcx).as_ref().map(|s| s.level);
204 let s2 = i2.stability(tcx).as_ref().map(|s| s.level);
205 if let (Some(a), Some(b)) = (s1, s2) {
206 match (a.is_stable(), b.is_stable()) {
207 (true, true) | (false, false) => {}
208 (false, true) => return Ordering::Less,
209 (true, false) => return Ordering::Greater,
212 let lhs = i1.name.unwrap_or(kw::Empty).as_str();
213 let rhs = i2.name.unwrap_or(kw::Empty).as_str();
214 compare_names(&lhs, &rhs)
217 if cx.shared.sort_modules_alphabetically {
218 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2, cx.tcx()));
220 // This call is to remove re-export duplicates in cases such as:
225 // crate trait Double { fn foo(); }
229 // crate use foo::bar::*;
233 // `Double` will appear twice in the generated docs.
235 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
236 // can be identical even if the elements are different (mostly in imports).
237 // So in case this is an import, we keep everything by adding a "unique id"
238 // (which is the position in the vector).
239 indices.dedup_by_key(|i| {
242 if items[*i].name.as_ref().is_some() { Some(full_path(cx, &items[*i])) } else { None },
244 if items[*i].is_import() { *i } else { 0 },
248 debug!("{:?}", indices);
249 let mut curty = None;
250 for &idx in &indices {
251 let myitem = &items[idx];
252 if myitem.is_stripped() {
256 let myty = Some(myitem.type_());
257 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
258 // Put `extern crate` and `use` re-exports in the same section.
260 } else if myty != curty {
262 w.write_str("</table>");
265 let (short, name) = item_ty_to_strs(&myty.unwrap());
268 "<h2 id=\"{id}\" class=\"section-header\">\
269 <a href=\"#{id}\">{name}</a></h2>\n<table>",
270 id = cx.derive_id(short.to_owned()),
276 clean::ExternCrateItem { ref src } => {
277 use crate::html::format::anchor;
280 Some(ref src) => write!(
282 "<tr><td><code>{}extern crate {} as {};",
283 myitem.visibility.print_with_space(myitem.def_id, cx),
284 anchor(myitem.def_id.expect_real(), &*src.as_str(), cx),
285 myitem.name.as_ref().unwrap(),
289 "<tr><td><code>{}extern crate {};",
290 myitem.visibility.print_with_space(myitem.def_id, cx),
292 myitem.def_id.expect_real(),
293 &*myitem.name.as_ref().unwrap().as_str(),
298 w.write_str("</code></td></tr>");
301 clean::ImportItem(ref import) => {
302 let (stab, stab_tags) = if let Some(import_def_id) = import.source.did {
303 let ast_attrs = cx.tcx().get_attrs(import_def_id);
304 let import_attrs = Box::new(clean::Attributes::from_ast(ast_attrs, None));
306 // Just need an item with the correct def_id and attrs
307 let import_item = clean::Item {
308 def_id: import_def_id.into(),
310 cfg: ast_attrs.cfg(cx.sess()),
314 let stab = import_item.stability_class(cx.tcx());
315 let stab_tags = Some(extra_info_tags(&import_item, item, cx.tcx()));
321 let add = if stab.is_some() { " " } else { "" };
325 "<tr class=\"{stab}{add}import-item\">\
326 <td><code>{vis}{imp}</code></td>\
327 <td class=\"docblock-short\">{stab_tags}</td>\
329 stab = stab.unwrap_or_default(),
331 vis = myitem.visibility.print_with_space(myitem.def_id, cx),
332 imp = import.print(cx),
333 stab_tags = stab_tags.unwrap_or_default(),
338 if myitem.name.is_none() {
342 let unsafety_flag = match *myitem.kind {
343 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
344 if func.header.unsafety == hir::Unsafety::Unsafe =>
346 "<a title=\"unsafe function\" href=\"#\"><sup>⚠</sup></a>"
351 let stab = myitem.stability_class(cx.tcx());
352 let add = if stab.is_some() { " " } else { "" };
354 let doc_value = myitem.doc_value().unwrap_or_default();
357 "<tr class=\"{stab}{add}module-item\">\
358 <td><a class=\"{class}\" href=\"{href}\" \
359 title=\"{title}\">{name}</a>{unsafety_flag}</td>\
360 <td class=\"docblock-short\">{stab_tags}{docs}</td>\
362 name = *myitem.name.as_ref().unwrap(),
363 stab_tags = extra_info_tags(myitem, item, cx.tcx()),
364 docs = MarkdownSummaryLine(&doc_value, &myitem.links(cx)).into_string(),
365 class = myitem.type_(),
367 stab = stab.unwrap_or_default(),
368 unsafety_flag = unsafety_flag,
369 href = item_path(myitem.type_(), &myitem.name.unwrap().as_str()),
370 title = [full_path(cx, myitem), myitem.type_().to_string()]
372 .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
381 w.write_str("</table>");
385 /// Render the stability, deprecation and portability tags that are displayed in the item's summary
386 /// at the module level.
387 fn extra_info_tags(item: &clean::Item, parent: &clean::Item, tcx: TyCtxt<'_>) -> String {
388 let mut tags = String::new();
390 fn tag_html(class: &str, title: &str, contents: &str) -> String {
391 format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
394 // The trailing space after each tag is to space it properly against the rest of the docs.
395 if let Some(depr) = &item.deprecation(tcx) {
396 let mut message = "Deprecated";
397 if !stability::deprecation_in_effect(
398 depr.is_since_rustc_version,
399 depr.since.map(|s| s.as_str()).as_deref(),
401 message = "Deprecation planned";
403 tags += &tag_html("deprecated", "", message);
406 // The "rustc_private" crates are permanently unstable so it makes no sense
407 // to render "unstable" everywhere.
411 .map(|s| s.level.is_unstable() && s.feature != sym::rustc_private)
414 tags += &tag_html("unstable", "", "Experimental");
417 let cfg = match (&item.cfg, parent.cfg.as_ref()) {
418 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
419 (cfg, _) => cfg.as_deref().cloned(),
422 debug!("Portability {:?} - {:?} = {:?}", item.cfg, parent.cfg, cfg);
423 if let Some(ref cfg) = cfg {
424 tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
430 fn item_function(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, f: &clean::Function) {
431 let header_len = format!(
432 "{}{}{}{}{:#}fn {}{:#}",
433 it.visibility.print_with_space(it.def_id, cx),
434 f.header.constness.print_with_space(),
435 f.header.asyncness.print_with_space(),
436 f.header.unsafety.print_with_space(),
437 print_abi_with_space(f.header.abi),
438 it.name.as_ref().unwrap(),
439 f.generics.print(cx),
442 w.write_str("<pre class=\"rust fn\">");
443 render_attributes_in_pre(w, it, "");
446 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
447 {name}{generics}{decl}{notable_traits}{where_clause}</pre>",
448 vis = it.visibility.print_with_space(it.def_id, cx),
449 constness = f.header.constness.print_with_space(),
450 asyncness = f.header.asyncness.print_with_space(),
451 unsafety = f.header.unsafety.print_with_space(),
452 abi = print_abi_with_space(f.header.abi),
453 name = it.name.as_ref().unwrap(),
454 generics = f.generics.print(cx),
455 where_clause = print_where_clause(&f.generics, cx, 0, true),
456 decl = f.decl.full_print(header_len, 0, f.header.asyncness, cx),
457 notable_traits = notable_traits_decl(&f.decl, cx),
459 document(w, cx, it, None)
462 fn item_trait(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Trait) {
463 let bounds = bounds(&t.bounds, false, cx);
464 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
465 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
466 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
467 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
469 // Output the trait definition
470 wrap_into_docblock(w, |w| {
471 w.write_str("<pre class=\"rust trait\">");
472 render_attributes_in_pre(w, it, "");
475 "{}{}{}trait {}{}{}",
476 it.visibility.print_with_space(it.def_id, cx),
477 t.unsafety.print_with_space(),
478 if t.is_auto { "auto " } else { "" },
479 it.name.as_ref().unwrap(),
480 t.generics.print(cx),
484 if !t.generics.where_predicates.is_empty() {
485 write!(w, "{}", print_where_clause(&t.generics, cx, 0, true));
490 if t.items.is_empty() {
493 // FIXME: we should be using a derived_id for the Anchors here
495 let mut toggle = false;
497 // If there are too many associated types, hide _everything_
498 if should_hide_fields(types.len()) {
500 toggle_open(w, "associated items");
503 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait, cx);
506 // If there are too many associated constants, hide everything after them
507 // We also do this if the types + consts is large because otherwise we could
508 // render a bunch of types and _then_ a bunch of consts just because both were
509 // _just_ under the limit
510 if !toggle && should_hide_fields(types.len() + consts.len()) {
512 toggle_open(w, "associated constants and methods");
514 if !types.is_empty() && !consts.is_empty() {
518 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait, cx);
521 if !toggle && should_hide_fields(required.len() + provided.len()) {
523 toggle_open(w, "methods");
525 if !consts.is_empty() && !required.is_empty() {
528 for (pos, m) in required.iter().enumerate() {
529 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait, cx);
532 if pos < required.len() - 1 {
533 w.write_str("<div class=\"item-spacer\"></div>");
536 if !required.is_empty() && !provided.is_empty() {
539 for (pos, m) in provided.iter().enumerate() {
540 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait, cx);
542 clean::MethodItem(ref inner, _)
543 if !inner.generics.where_predicates.is_empty() =>
545 w.write_str(",\n { ... }\n");
548 w.write_str(" { ... }\n");
551 if pos < provided.len() - 1 {
552 w.write_str("<div class=\"item-spacer\"></div>");
560 w.write_str("</pre>")
563 // Trait documentation
564 document(w, cx, it, None);
566 fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
569 "<h2 id=\"{0}\" class=\"small-section-header\">\
570 {1}<a href=\"#{0}\" class=\"anchor\"></a>\
572 id, title, extra_content
576 fn trait_item(w: &mut Buffer, cx: &Context<'_>, m: &clean::Item, t: &clean::Item) {
577 let name = m.name.as_ref().unwrap();
578 info!("Documenting {} on {:?}", name, t.name);
579 let item_type = m.type_();
580 let id = cx.derive_id(format!("{}.{}", item_type, name));
581 write!(w, "<details class=\"rustdoc-toggle\" open><summary>");
582 write!(w, "<h3 id=\"{id}\" class=\"method\"><code>", id = id,);
583 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl, cx);
584 w.write_str("</code>");
585 render_stability_since(w, m, t, cx.tcx());
586 write_srclink(cx, m, w);
587 w.write_str("</h3></summary>");
588 document(w, cx, m, Some(t));
591 if !types.is_empty() {
592 write_small_section_header(
596 "<div class=\"methods\">",
599 trait_item(w, cx, t, it);
601 w.write_str("</div>");
604 if !consts.is_empty() {
605 write_small_section_header(
608 "Associated Constants",
609 "<div class=\"methods\">",
612 trait_item(w, cx, t, it);
614 w.write_str("</div>");
617 // Output the documentation for each function individually
618 if !required.is_empty() {
619 write_small_section_header(
623 "<div class=\"methods\">",
626 trait_item(w, cx, m, it);
628 w.write_str("</div>");
630 if !provided.is_empty() {
631 write_small_section_header(
635 "<div class=\"methods\">",
638 trait_item(w, cx, m, it);
640 w.write_str("</div>");
643 // If there are methods directly on this trait object, render them here.
644 render_assoc_items(w, cx, it, it.def_id.expect_real(), AssocItemRender::All);
646 if let Some(implementors) = cx.cache.implementors.get(&it.def_id.expect_real()) {
647 // The DefId is for the first Type found with that name. The bool is
648 // if any Types with the same name but different DefId have been found.
649 let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();
650 for implementor in implementors {
651 match implementor.inner_impl().for_ {
652 clean::ResolvedPath { ref path, did, is_generic: false, .. }
653 | clean::BorrowedRef {
654 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
657 let &mut (prev_did, ref mut has_duplicates) =
658 implementor_dups.entry(path.last()).or_insert((did, false));
660 *has_duplicates = true;
667 let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| {
670 .def_id_full(cx.cache())
671 .map_or(true, |d| cx.cache.paths.contains_key(&d))
674 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
675 local.iter().partition(|i| i.inner_impl().synthetic);
677 synthetic.sort_by(|a, b| compare_impl(a, b, cx));
678 concrete.sort_by(|a, b| compare_impl(a, b, cx));
680 if !foreign.is_empty() {
681 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
683 for implementor in foreign {
684 let provided_methods = implementor.inner_impl().provided_trait_methods(cx.tcx());
686 AssocItemLink::GotoSource(implementor.impl_item.def_id, &provided_methods);
694 implementor.impl_item.stable_since(cx.tcx()).as_deref(),
695 implementor.impl_item.const_stable_since(cx.tcx()).as_deref(),
705 write_small_section_header(
709 "<div class=\"item-list\" id=\"implementors-list\">",
711 for implementor in concrete {
712 render_implementor(cx, implementor, it, w, &implementor_dups, &[]);
714 w.write_str("</div>");
717 write_small_section_header(
719 "synthetic-implementors",
721 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
723 for implementor in synthetic {
730 &collect_paths_for_type(implementor.inner_impl().for_.clone(), &cx.cache),
733 w.write_str("</div>");
736 // even without any implementations to write in, we still want the heading and list, so the
737 // implementors javascript file pulled in below has somewhere to write the impls into
738 write_small_section_header(
742 "<div class=\"item-list\" id=\"implementors-list\"></div>",
746 write_small_section_header(
748 "synthetic-implementors",
750 "<div class=\"item-list\" id=\"synthetic-implementors-list\"></div>",
757 "<script type=\"text/javascript\" \
758 src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\
760 root_path = vec![".."; cx.current.len()].join("/"),
761 path = if it.def_id.is_local() {
764 let (ref path, _) = cx.cache.external_paths[&it.def_id.expect_real()];
765 path[..path.len() - 1].join("/")
768 name = *it.name.as_ref().unwrap()
772 fn item_trait_alias(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::TraitAlias) {
773 w.write_str("<pre class=\"rust trait-alias\">");
774 render_attributes_in_pre(w, it, "");
777 "trait {}{}{} = {};</pre>",
778 it.name.as_ref().unwrap(),
779 t.generics.print(cx),
780 print_where_clause(&t.generics, cx, 0, true),
781 bounds(&t.bounds, true, cx)
784 document(w, cx, it, None);
786 // Render any items associated directly to this alias, as otherwise they
787 // won't be visible anywhere in the docs. It would be nice to also show
788 // associated items from the aliased type (see discussion in #32077), but
789 // we need #14072 to make sense of the generics.
790 render_assoc_items(w, cx, it, it.def_id.expect_real(), AssocItemRender::All)
793 fn item_opaque_ty(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::OpaqueTy) {
794 w.write_str("<pre class=\"rust opaque\">");
795 render_attributes_in_pre(w, it, "");
798 "type {}{}{where_clause} = impl {bounds};</pre>",
799 it.name.as_ref().unwrap(),
800 t.generics.print(cx),
801 where_clause = print_where_clause(&t.generics, cx, 0, true),
802 bounds = bounds(&t.bounds, false, cx),
805 document(w, cx, it, None);
807 // Render any items associated directly to this alias, as otherwise they
808 // won't be visible anywhere in the docs. It would be nice to also show
809 // associated items from the aliased type (see discussion in #32077), but
810 // we need #14072 to make sense of the generics.
811 render_assoc_items(w, cx, it, it.def_id.expect_real(), AssocItemRender::All)
814 fn item_typedef(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Typedef) {
815 w.write_str("<pre class=\"rust typedef\">");
816 render_attributes_in_pre(w, it, "");
819 "type {}{}{where_clause} = {type_};</pre>",
820 it.name.as_ref().unwrap(),
821 t.generics.print(cx),
822 where_clause = print_where_clause(&t.generics, cx, 0, true),
823 type_ = t.type_.print(cx),
826 document(w, cx, it, None);
828 let def_id = it.def_id.expect_real();
829 // Render any items associated directly to this alias, as otherwise they
830 // won't be visible anywhere in the docs. It would be nice to also show
831 // associated items from the aliased type (see discussion in #32077), but
832 // we need #14072 to make sense of the generics.
833 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
836 fn item_union(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Union) {
837 wrap_into_docblock(w, |w| {
838 w.write_str("<pre class=\"rust union\">");
839 render_attributes_in_pre(w, it, "");
840 render_union(w, it, Some(&s.generics), &s.fields, "", true, cx);
841 w.write_str("</pre>")
844 document(w, cx, it, None);
849 .filter_map(|f| match *f.kind {
850 clean::StructFieldItem(ref ty) => Some((f, ty)),
854 if fields.peek().is_some() {
857 "<h2 id=\"fields\" class=\"fields small-section-header\">
858 Fields<a href=\"#fields\" class=\"anchor\"></a></h2>"
860 for (field, ty) in fields {
861 let name = field.name.as_ref().expect("union field name");
862 let id = format!("{}.{}", ItemType::StructField, name);
865 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
866 <a href=\"#{id}\" class=\"anchor field\"></a>\
867 <code>{name}: {ty}</code>\
871 shortty = ItemType::StructField,
874 if let Some(stability_class) = field.stability_class(cx.tcx()) {
875 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
877 document(w, cx, field, Some(it));
880 let def_id = it.def_id.expect_real();
881 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
882 document_type_layout(w, cx, def_id);
885 fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum) {
886 wrap_into_docblock(w, |w| {
887 w.write_str("<pre class=\"rust enum\">");
888 render_attributes_in_pre(w, it, "");
892 it.visibility.print_with_space(it.def_id, cx),
893 it.name.as_ref().unwrap(),
894 e.generics.print(cx),
895 print_where_clause(&e.generics, cx, 0, true),
897 if e.variants.is_empty() && !e.variants_stripped {
901 let toggle = should_hide_fields(e.variants.len());
903 toggle_open(w, "variants");
905 for v in &e.variants {
907 let name = v.name.as_ref().unwrap();
909 clean::VariantItem(ref var) => match var {
910 clean::Variant::CLike => write!(w, "{}", name),
911 clean::Variant::Tuple(ref tys) => {
912 write!(w, "{}(", name);
913 for (i, ty) in tys.iter().enumerate() {
915 w.write_str(", ")
917 write!(w, "{}", ty.print(cx));
921 clean::Variant::Struct(ref s) => {
922 render_struct(w, v, None, s.struct_type, &s.fields, " ", false, cx);
930 if e.variants_stripped {
931 w.write_str(" // some variants omitted\n");
938 w.write_str("</pre>")
941 document(w, cx, it, None);
943 if !e.variants.is_empty() {
946 "<h2 id=\"variants\" class=\"variants small-section-header\">
947 Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>\n",
948 document_non_exhaustive_header(it)
950 document_non_exhaustive(w, it);
951 for variant in &e.variants {
953 cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap()));
956 "<div id=\"{id}\" class=\"variant small-section-header\">\
957 <a href=\"#{id}\" class=\"anchor field\"></a>\
960 name = variant.name.as_ref().unwrap()
962 if let clean::VariantItem(clean::Variant::Tuple(ref tys)) = *variant.kind {
964 for (i, ty) in tys.iter().enumerate() {
966 w.write_str(", ");
968 write!(w, "{}", ty.print(cx));
972 w.write_str("</code></div>");
973 document(w, cx, variant, Some(it));
974 document_non_exhaustive(w, variant);
976 use crate::clean::Variant;
977 if let clean::VariantItem(Variant::Struct(ref s)) = *variant.kind {
978 toggle_open(w, "fields");
979 let variant_id = cx.derive_id(format!(
982 variant.name.as_ref().unwrap()
984 write!(w, "<div class=\"autohide sub-variant\" id=\"{id}\">", id = variant_id);
987 "<h3>Fields of <b>{name}</b></h3><div>",
988 name = variant.name.as_ref().unwrap()
990 for field in &s.fields {
991 use crate::clean::StructFieldItem;
992 if let StructFieldItem(ref ty) = *field.kind {
993 let id = cx.derive_id(format!(
994 "variant.{}.field.{}",
995 variant.name.as_ref().unwrap(),
996 field.name.as_ref().unwrap()
1000 "<span id=\"{id}\" class=\"variant small-section-header\">\
1001 <a href=\"#{id}\" class=\"anchor field\"></a>\
1002 <code>{f}: {t}</code>\
1005 f = field.name.as_ref().unwrap(),
1008 document(w, cx, field, Some(variant));
1011 w.write_str("</div></div>");
1014 render_stability_since(w, variant, it, cx.tcx());
1017 let def_id = it.def_id.expect_real();
1018 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1019 document_type_layout(w, cx, def_id);
1022 fn item_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Macro) {
1023 wrap_into_docblock(w, |w| {
1024 highlight::render_with_highlighting(
1030 it.span(cx.tcx()).inner().edition(),
1034 document(w, cx, it, None)
1037 fn item_proc_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, m: &clean::ProcMacro) {
1038 let name = it.name.as_ref().expect("proc-macros always have names");
1040 MacroKind::Bang => {
1041 w.push_str("<pre class=\"rust macro\">");
1042 write!(w, "{}!() {{ /* proc-macro */ }}", name);
1043 w.push_str("</pre>");
1045 MacroKind::Attr => {
1046 w.push_str("<pre class=\"rust attr\">");
1047 write!(w, "#[{}]", name);
1048 w.push_str("</pre>");
1050 MacroKind::Derive => {
1051 w.push_str("<pre class=\"rust derive\">");
1052 write!(w, "#[derive({})]", name);
1053 if !m.helpers.is_empty() {
1054 w.push_str("\n{\n");
1055 w.push_str(" // Attributes available to this derive:\n");
1056 for attr in &m.helpers {
1057 writeln!(w, " #[{}]", attr);
1061 w.push_str("</pre>");
1064 document(w, cx, it, None)
1067 fn item_primitive(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
1068 document(w, cx, it, None);
1069 render_assoc_items(w, cx, it, it.def_id.expect_real(), AssocItemRender::All)
1072 fn item_constant(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, c: &clean::Constant) {
1073 w.write_str("<pre class=\"rust const\">");
1074 render_attributes_in_code(w, it);
1078 "{vis}const {name}: {typ}",
1079 vis = it.visibility.print_with_space(it.def_id, cx),
1080 name = it.name.as_ref().unwrap(),
1081 typ = c.type_.print(cx),
1084 let value = c.value(cx.tcx());
1085 let is_literal = c.is_literal(cx.tcx());
1086 let expr = c.expr(cx.tcx());
1087 if value.is_some() || is_literal {
1088 write!(w, " = {expr};", expr = Escape(&expr));
1094 if let Some(value) = &value {
1095 let value_lowercase = value.to_lowercase();
1096 let expr_lowercase = expr.to_lowercase();
1098 if value_lowercase != expr_lowercase
1099 && value_lowercase.trim_end_matches("i32") != expr_lowercase
1101 write!(w, " // {value}", value = Escape(value));
1106 w.write_str("</pre>");
1107 document(w, cx, it, None)
1110 fn item_struct(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Struct) {
1111 wrap_into_docblock(w, |w| {
1112 w.write_str("<pre class=\"rust struct\">");
1113 render_attributes_in_code(w, it);
1114 render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true, cx);
1115 w.write_str("</pre>")
1118 document(w, cx, it, None);
1123 .filter_map(|f| match *f.kind {
1124 clean::StructFieldItem(ref ty) => Some((f, ty)),
1128 if let CtorKind::Fictive = s.struct_type {
1129 if fields.peek().is_some() {
1132 "<h2 id=\"fields\" class=\"fields small-section-header\">
1133 Fields{}<a href=\"#fields\" class=\"anchor\"></a></h2>",
1134 document_non_exhaustive_header(it)
1136 document_non_exhaustive(w, it);
1137 for (field, ty) in fields {
1138 let id = cx.derive_id(format!(
1140 ItemType::StructField,
1141 field.name.as_ref().unwrap()
1145 "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
1146 <a href=\"#{id}\" class=\"anchor field\"></a>\
1147 <code>{name}: {ty}</code>\
1149 item_type = ItemType::StructField,
1151 name = field.name.as_ref().unwrap(),
1154 document(w, cx, field, Some(it));
1158 let def_id = it.def_id.expect_real();
1159 render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1160 document_type_layout(w, cx, def_id);
1163 fn item_static(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Static) {
1164 w.write_str("<pre class=\"rust static\">");
1165 render_attributes_in_code(w, it);
1168 "{vis}static {mutability}{name}: {typ}</pre>",
1169 vis = it.visibility.print_with_space(it.def_id, cx),
1170 mutability = s.mutability.print_with_space(),
1171 name = it.name.as_ref().unwrap(),
1172 typ = s.type_.print(cx)
1174 document(w, cx, it, None)
1177 fn item_foreign_type(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
1178 w.write_str("<pre class=\"rust foreigntype\">extern {\n");
1179 render_attributes_in_code(w, it);
1182 " {}type {};\n}}</pre>",
1183 it.visibility.print_with_space(it.def_id, cx),
1184 it.name.as_ref().unwrap(),
1187 document(w, cx, it, None);
1189 render_assoc_items(w, cx, it, it.def_id.expect_real(), AssocItemRender::All)
1192 fn item_keyword(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
1193 document(w, cx, it, None)
1196 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
1197 crate fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
1198 /// Takes a non-numeric and a numeric part from the given &str.
1199 fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
1200 let i = s.find(|c: char| c.is_ascii_digit());
1201 let (a, b) = s.split_at(i.unwrap_or(s.len()));
1202 let i = b.find(|c: char| !c.is_ascii_digit());
1203 let (b, c) = b.split_at(i.unwrap_or(b.len()));
1208 while !lhs.is_empty() || !rhs.is_empty() {
1209 let (la, lb) = take_parts(&mut lhs);
1210 let (ra, rb) = take_parts(&mut rhs);
1211 // First process the non-numeric part.
1213 Ordering::Equal => (),
1216 // Then process the numeric part, if both sides have one (and they fit in a u64).
1217 if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
1219 Ordering::Equal => (),
1223 // Then process the numeric part again, but this time as strings.
1225 Ordering::Equal => (),
1233 pub(super) fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
1234 let mut s = cx.current.join("::");
1236 s.push_str(&item.name.unwrap().as_str());
1240 pub(super) fn item_path(ty: ItemType, name: &str) -> String {
1242 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1243 _ => format!("{}.{}.html", ty, name),
1247 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool, cx: &Context<'_>) -> String {
1248 let mut bounds = String::new();
1249 if !t_bounds.is_empty() {
1251 bounds.push_str(": ");
1253 for (i, p) in t_bounds.iter().enumerate() {
1255 bounds.push_str(" + ");
1257 bounds.push_str(&p.print(cx).to_string());
1263 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1265 F: FnOnce(&mut Buffer),
1267 w.write_str("<div class=\"docblock type-decl\">");
1269 w.write_str("</div>")
1272 fn render_stability_since(
1275 containing_item: &clean::Item,
1278 render_stability_since_raw(
1280 item.stable_since(tcx).as_deref(),
1281 item.const_stable_since(tcx).as_deref(),
1282 containing_item.stable_since(tcx).as_deref(),
1283 containing_item.const_stable_since(tcx).as_deref(),
1287 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl, cx: &Context<'_>) -> Ordering {
1288 let lhss = format!("{}", lhs.inner_impl().print(false, cx));
1289 let rhss = format!("{}", rhs.inner_impl().print(false, cx));
1291 // lhs and rhs are formatted as HTML, which may be unnecessary
1292 compare_names(&lhss, &rhss)
1295 fn render_implementor(
1298 trait_: &clean::Item,
1300 implementor_dups: &FxHashMap<Symbol, (DefId, bool)>,
1303 // If there's already another implementor that has the same abbridged name, use the
1304 // full path, for example in `std::iter::ExactSizeIterator`
1305 let use_absolute = match implementor.inner_impl().for_ {
1306 clean::ResolvedPath { ref path, is_generic: false, .. }
1307 | clean::BorrowedRef {
1308 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
1310 } => implementor_dups[&path.last()].1,
1318 AssocItemLink::Anchor(None),
1320 trait_.stable_since(cx.tcx()).as_deref(),
1321 trait_.const_stable_since(cx.tcx()).as_deref(),
1333 g: Option<&clean::Generics>,
1334 fields: &[clean::Item],
1342 it.visibility.print_with_space(it.def_id, cx),
1343 if structhead { "union " } else { "" },
1344 it.name.as_ref().unwrap()
1346 if let Some(g) = g {
1347 write!(w, "{}", g.print(cx));
1348 write!(w, "{}", print_where_clause(&g, cx, 0, true));
1351 write!(w, " {{\n{}", tab);
1353 fields.iter().filter(|f| matches!(*f.kind, clean::StructFieldItem(..))).count();
1354 let toggle = should_hide_fields(count_fields);
1356 toggle_open(w, "fields");
1359 for field in fields {
1360 if let clean::StructFieldItem(ref ty) = *field.kind {
1364 field.visibility.print_with_space(field.def_id, cx),
1365 field.name.as_ref().unwrap(),
1372 if it.has_stripped_fields().unwrap() {
1373 write!(w, " // some fields omitted\n{}", tab);
1384 g: Option<&clean::Generics>,
1386 fields: &[clean::Item],
1394 it.visibility.print_with_space(it.def_id, cx),
1395 if structhead { "struct " } else { "" },
1396 it.name.as_ref().unwrap()
1398 if let Some(g) = g {
1399 write!(w, "{}", g.print(cx))
1402 CtorKind::Fictive => {
1403 if let Some(g) = g {
1404 write!(w, "{}", print_where_clause(g, cx, 0, true),)
1408 fields.iter().filter(|f| matches!(*f.kind, clean::StructFieldItem(..))).count();
1409 let has_visible_fields = count_fields > 0;
1410 let toggle = should_hide_fields(count_fields);
1412 toggle_open(w, "fields");
1414 for field in fields {
1415 if let clean::StructFieldItem(ref ty) = *field.kind {
1420 field.visibility.print_with_space(field.def_id, cx),
1421 field.name.as_ref().unwrap(),
1427 if has_visible_fields {
1428 if it.has_stripped_fields().unwrap() {
1429 write!(w, "\n{} // some fields omitted", tab);
1431 write!(w, "\n{}", tab);
1432 } else if it.has_stripped_fields().unwrap() {
1433 // If there are no visible fields we can just display
1434 // `{ /* fields omitted */ }` to save space.
1435 write!(w, " /* fields omitted */ ");
1444 for (i, field) in fields.iter().enumerate() {
1449 clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
1450 clean::StructFieldItem(ref ty) => {
1454 field.visibility.print_with_space(field.def_id, cx),
1458 _ => unreachable!(),
1462 if let Some(g) = g {
1463 write!(w, "{}", print_where_clause(g, cx, 0, false),)
1467 CtorKind::Const => {
1468 // Needed for PhantomData.
1469 if let Some(g) = g {
1470 write!(w, "{}", print_where_clause(g, cx, 0, false),)
1477 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1478 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1481 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1482 if item.is_non_exhaustive() {
1485 "<details class=\"rustdoc-toggle non-exhaustive\">\
1486 <summary class=\"hideme\"><span>{}</span></summary>\
1487 <div class=\"docblock\">",
1489 if item.is_struct() {
1490 "This struct is marked as non-exhaustive"
1491 } else if item.is_enum() {
1492 "This enum is marked as non-exhaustive"
1493 } else if item.is_variant() {
1494 "This variant is marked as non-exhaustive"
1496 "This type is marked as non-exhaustive"
1501 if item.is_struct() {
1503 "Non-exhaustive structs could have additional fields added in future. \
1504 Therefore, non-exhaustive structs cannot be constructed in external crates \
1505 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
1506 matched against without a wildcard <code>..</code>; and \
1507 struct update syntax will not work.",
1509 } else if item.is_enum() {
1511 "Non-exhaustive enums could have additional variants added in future. \
1512 Therefore, when matching against variants of non-exhaustive enums, an \
1513 extra wildcard arm must be added to account for any future variants.",
1515 } else if item.is_variant() {
1517 "Non-exhaustive enum variants could have additional fields added in future. \
1518 Therefore, non-exhaustive enum variants cannot be constructed in external \
1519 crates and cannot be matched against.",
1523 "This type will require a wildcard arm in any match statements or constructors.",
1527 w.write_str("</div></details>");
1531 fn document_type_layout(w: &mut Buffer, cx: &Context<'_>, ty_def_id: DefId) {
1532 if !cx.shared.show_type_layout {
1536 writeln!(w, "<h2 class=\"small-section-header\">Layout</h2>");
1537 writeln!(w, "<div class=\"docblock\">");
1540 let param_env = tcx.param_env(ty_def_id);
1541 let ty = tcx.type_of(ty_def_id);
1542 match tcx.layout_of(param_env.and(ty)) {
1546 "<div class=\"warning\"><p><strong>Note:</strong> Most layout information is \
1547 completely unstable and may be different between compiler versions and platforms. \
1548 The only exception is types with certain <code>repr(...)</code> attributes. \
1549 Please see the Rust Reference’s \
1550 <a href=\"https://doc.rust-lang.org/reference/type-layout.html\">“Type Layout”</a> \
1551 chapter for details on type layout guarantees.</p></div>"
1553 if ty_layout.layout.abi.is_unsized() {
1554 writeln!(w, "<p><strong>Size:</strong> (unsized)</p>");
1556 let bytes = ty_layout.layout.size.bytes();
1559 "<p><strong>Size:</strong> {size} byte{pl}</p>",
1561 pl = if bytes == 1 { "" } else { "s" },
1565 // This kind of layout error can occur with valid code, e.g. if you try to
1566 // get the layout of a generic type such as `Vec<T>`.
1567 Err(LayoutError::Unknown(_)) => {
1570 "<p><strong>Note:</strong> Unable to compute type layout, \
1571 possibly due to this type having generic parameters. \
1572 Layout can only be computed for concrete, fully-instantiated types.</p>"
1575 // This kind of error probably can't happen with valid code, but we don't
1576 // want to panic and prevent the docs from building, so we just let the
1577 // user know that we couldn't compute the layout.
1578 Err(LayoutError::SizeOverflow(_)) => {
1581 "<p><strong>Note:</strong> Encountered an error during type layout; \
1582 the type was too big.</p>"
1587 writeln!(w, "</div>");