1 use std::cmp::Ordering;
3 use rustc_data_structures::fx::FxHashMap;
5 use rustc_hir::def::CtorKind;
6 use rustc_hir::def_id::DefId;
7 use rustc_middle::middle::stability;
8 use rustc_middle::ty::TyCtxt;
9 use rustc_span::hygiene::MacroKind;
10 use rustc_span::symbol::{kw, sym, Symbol};
13 collect_paths_for_type, document, ensure_trailing_slash, item_ty_to_strs, notable_traits_decl,
14 render_assoc_item, render_assoc_items, render_attributes, render_impl,
15 render_stability_since_raw, write_srclink, AssocItemLink, Context,
17 use crate::clean::{self, GetDefId};
18 use crate::formats::cache::Cache;
19 use crate::formats::item_type::ItemType;
20 use crate::formats::{AssocItemRender, FormatRenderer, Impl, RenderMode};
21 use crate::html::escape::Escape;
22 use crate::html::format::{print_abi_with_space, print_where_clause, Buffer, PrintWithSpace};
23 use crate::html::highlight;
24 use crate::html::markdown::MarkdownSummaryLine;
26 pub(super) fn print_item(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) {
27 debug_assert!(!item.is_stripped());
28 // Write the breadcrumb trail header for the top
29 buf.write_str("<h1 class=\"fqn\"><span class=\"in-band\">");
30 let name = match *item.kind {
31 clean::ModuleItem(ref m) => {
38 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
39 clean::TraitItem(..) => "Trait ",
40 clean::StructItem(..) => "Struct ",
41 clean::UnionItem(..) => "Union ",
42 clean::EnumItem(..) => "Enum ",
43 clean::TypedefItem(..) => "Type Definition ",
44 clean::MacroItem(..) => "Macro ",
45 clean::ProcMacroItem(ref mac) => match mac.kind {
46 MacroKind::Bang => "Macro ",
47 MacroKind::Attr => "Attribute Macro ",
48 MacroKind::Derive => "Derive Macro ",
50 clean::PrimitiveItem(..) => "Primitive Type ",
51 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
52 clean::ConstantItem(..) => "Constant ",
53 clean::ForeignTypeItem => "Foreign Type ",
54 clean::KeywordItem(..) => "Keyword ",
55 clean::OpaqueTyItem(..) => "Opaque Type ",
56 clean::TraitAliasItem(..) => "Trait Alias ",
58 // We don't generate pages for any other type.
63 if !item.is_primitive() && !item.is_keyword() {
64 let cur = &cx.current;
65 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
66 for (i, component) in cur.iter().enumerate().take(amt) {
69 "<a href=\"{}index.html\">{}</a>::<wbr>",
70 "../".repeat(cur.len() - i - 1),
75 write!(buf, "<a class=\"{}\" href=\"\">{}</a>", item.type_(), item.name.as_ref().unwrap());
76 write!(buf, "<button id=\"copy-path\" onclick=\"copy_path(this)\">⎘</button>");
78 buf.write_str("</span>"); // in-band
79 buf.write_str("<span class=\"out-of-band\">");
80 render_stability_since_raw(
82 item.stable_since(cx.tcx()).as_deref(),
83 item.const_stable_since(cx.tcx()).as_deref(),
88 "<span id=\"render-detail\">\
89 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
90 title=\"collapse all docs\">\
91 [<span class=\"inner\">−</span>]\
98 // When this item is part of a `crate use` in a downstream crate, the
99 // [src] link in the downstream documentation will actually come back to
100 // this page, and this link will be auto-clicked. The `id` attribute is
101 // used to find the link to auto-click.
102 if cx.shared.include_sources && !item.is_primitive() {
103 write_srclink(cx, item, buf);
106 buf.write_str("</span></h1>"); // out-of-band
109 clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
110 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
111 item_function(buf, cx, item, f)
113 clean::TraitItem(ref t) => item_trait(buf, cx, item, t),
114 clean::StructItem(ref s) => item_struct(buf, cx, item, s),
115 clean::UnionItem(ref s) => item_union(buf, cx, item, s),
116 clean::EnumItem(ref e) => item_enum(buf, cx, item, e),
117 clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t),
118 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
119 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
120 clean::PrimitiveItem(_) => item_primitive(buf, cx, item),
121 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
122 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
123 clean::ForeignTypeItem => item_foreign_type(buf, cx, item),
124 clean::KeywordItem(_) => item_keyword(buf, cx, item),
125 clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e),
126 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta),
128 // We don't generate pages for any other type.
134 fn item_module(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, items: &[clean::Item]) {
135 document(w, cx, item, None);
137 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
139 // the order of item types in the listing
140 fn reorder(ty: ItemType) -> u8 {
142 ItemType::ExternCrate => 0,
143 ItemType::Import => 1,
144 ItemType::Primitive => 2,
145 ItemType::Module => 3,
146 ItemType::Macro => 4,
147 ItemType::Struct => 5,
149 ItemType::Constant => 7,
150 ItemType::Static => 8,
151 ItemType::Trait => 9,
152 ItemType::Function => 10,
153 ItemType::Typedef => 12,
154 ItemType::Union => 13,
166 let ty1 = i1.type_();
167 let ty2 = i2.type_();
169 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
171 let s1 = i1.stability(tcx).as_ref().map(|s| s.level);
172 let s2 = i2.stability(tcx).as_ref().map(|s| s.level);
173 if let (Some(a), Some(b)) = (s1, s2) {
174 match (a.is_stable(), b.is_stable()) {
175 (true, true) | (false, false) => {}
176 (false, true) => return Ordering::Less,
177 (true, false) => return Ordering::Greater,
180 let lhs = i1.name.unwrap_or(kw::Empty).as_str();
181 let rhs = i2.name.unwrap_or(kw::Empty).as_str();
182 compare_names(&lhs, &rhs)
185 if cx.shared.sort_modules_alphabetically {
186 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2, cx.tcx()));
188 // This call is to remove re-export duplicates in cases such as:
193 // crate trait Double { fn foo(); }
197 // crate use foo::bar::*;
201 // `Double` will appear twice in the generated docs.
203 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
204 // can be identical even if the elements are different (mostly in imports).
205 // So in case this is an import, we keep everything by adding a "unique id"
206 // (which is the position in the vector).
207 indices.dedup_by_key(|i| {
210 if items[*i].name.as_ref().is_some() { Some(full_path(cx, &items[*i])) } else { None },
212 if items[*i].is_import() { *i } else { 0 },
216 debug!("{:?}", indices);
217 let mut curty = None;
218 for &idx in &indices {
219 let myitem = &items[idx];
220 if myitem.is_stripped() {
224 let myty = Some(myitem.type_());
225 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
226 // Put `extern crate` and `use` re-exports in the same section.
228 } else if myty != curty {
230 w.write_str("</table>");
233 let (short, name) = item_ty_to_strs(&myty.unwrap());
236 "<h2 id=\"{id}\" class=\"section-header\">\
237 <a href=\"#{id}\">{name}</a></h2>\n<table>",
238 id = cx.derive_id(short.to_owned()),
244 clean::ExternCrateItem { ref src } => {
245 use crate::html::format::anchor;
248 Some(ref src) => write!(
250 "<tr><td><code>{}extern crate {} as {};",
251 myitem.visibility.print_with_space(cx.tcx(), myitem.def_id, cx.cache()),
252 anchor(myitem.def_id, &*src.as_str(), cx.cache()),
253 myitem.name.as_ref().unwrap(),
257 "<tr><td><code>{}extern crate {};",
258 myitem.visibility.print_with_space(cx.tcx(), myitem.def_id, cx.cache()),
259 anchor(myitem.def_id, &*myitem.name.as_ref().unwrap().as_str(), cx.cache()),
262 w.write_str("</code></td></tr>");
265 clean::ImportItem(ref import) => {
268 "<tr><td><code>{}{}</code></td></tr>",
269 myitem.visibility.print_with_space(cx.tcx(), myitem.def_id, cx.cache()),
270 import.print(cx.cache(), cx.tcx()),
275 if myitem.name.is_none() {
279 let unsafety_flag = match *myitem.kind {
280 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
281 if func.header.unsafety == hir::Unsafety::Unsafe =>
283 "<a title=\"unsafe function\" href=\"#\"><sup>⚠</sup></a>"
288 let stab = myitem.stability_class(cx.tcx());
289 let add = if stab.is_some() { " " } else { "" };
291 let doc_value = myitem.doc_value().unwrap_or_default();
294 "<tr class=\"{stab}{add}module-item\">\
295 <td><a class=\"{class}\" href=\"{href}\" \
296 title=\"{title}\">{name}</a>{unsafety_flag}</td>\
297 <td class=\"docblock-short\">{stab_tags}{docs}</td>\
299 name = *myitem.name.as_ref().unwrap(),
300 stab_tags = extra_info_tags(myitem, item, cx.tcx()),
301 docs = MarkdownSummaryLine(&doc_value, &myitem.links(&cx.cache)).into_string(),
302 class = myitem.type_(),
304 stab = stab.unwrap_or_else(String::new),
305 unsafety_flag = unsafety_flag,
306 href = item_path(myitem.type_(), &myitem.name.unwrap().as_str()),
307 title = [full_path(cx, myitem), myitem.type_().to_string()]
309 .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
318 w.write_str("</table>");
322 /// Render the stability, deprecation and portability tags that are displayed in the item's summary
323 /// at the module level.
324 fn extra_info_tags(item: &clean::Item, parent: &clean::Item, tcx: TyCtxt<'_>) -> String {
325 let mut tags = String::new();
327 fn tag_html(class: &str, title: &str, contents: &str) -> String {
328 format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
331 // The trailing space after each tag is to space it properly against the rest of the docs.
332 if let Some(depr) = &item.deprecation(tcx) {
333 let mut message = "Deprecated";
334 if !stability::deprecation_in_effect(
335 depr.is_since_rustc_version,
336 depr.since.map(|s| s.as_str()).as_deref(),
338 message = "Deprecation planned";
340 tags += &tag_html("deprecated", "", message);
343 // The "rustc_private" crates are permanently unstable so it makes no sense
344 // to render "unstable" everywhere.
348 .map(|s| s.level.is_unstable() && s.feature != sym::rustc_private)
351 tags += &tag_html("unstable", "", "Experimental");
354 let cfg = match (&item.attrs.cfg, parent.attrs.cfg.as_ref()) {
355 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
356 (cfg, _) => cfg.as_deref().cloned(),
359 debug!("Portability {:?} - {:?} = {:?}", item.attrs.cfg, parent.attrs.cfg, cfg);
360 if let Some(ref cfg) = cfg {
361 tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
367 fn item_function(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, f: &clean::Function) {
368 let header_len = format!(
369 "{}{}{}{}{:#}fn {}{:#}",
370 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
371 f.header.constness.print_with_space(),
372 f.header.asyncness.print_with_space(),
373 f.header.unsafety.print_with_space(),
374 print_abi_with_space(f.header.abi),
375 it.name.as_ref().unwrap(),
376 f.generics.print(cx.cache(), cx.tcx())
379 w.write_str("<pre class=\"rust fn\">");
380 render_attributes(w, it, false);
383 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
384 {name}{generics}{decl}{notable_traits}{where_clause}</pre>",
385 vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
386 constness = f.header.constness.print_with_space(),
387 asyncness = f.header.asyncness.print_with_space(),
388 unsafety = f.header.unsafety.print_with_space(),
389 abi = print_abi_with_space(f.header.abi),
390 name = it.name.as_ref().unwrap(),
391 generics = f.generics.print(cx.cache(), cx.tcx()),
392 where_clause = print_where_clause(&f.generics, cx.cache(), cx.tcx(), 0, true),
393 decl = f.decl.full_print(cx.cache(), cx.tcx(), header_len, 0, f.header.asyncness),
394 notable_traits = notable_traits_decl(&f.decl, cx.cache(), cx.tcx()),
396 document(w, cx, it, None)
399 fn item_trait(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Trait) {
400 let bounds = bounds(&t.bounds, false, cx.cache(), cx.tcx());
401 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
402 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
403 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
404 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
406 // Output the trait definition
407 wrap_into_docblock(w, |w| {
408 w.write_str("<pre class=\"rust trait\">");
409 render_attributes(w, it, true);
412 "{}{}{}trait {}{}{}",
413 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
414 t.unsafety.print_with_space(),
415 if t.is_auto { "auto " } else { "" },
416 it.name.as_ref().unwrap(),
417 t.generics.print(cx.cache(), cx.tcx()),
421 if !t.generics.where_predicates.is_empty() {
422 write!(w, "{}", print_where_clause(&t.generics, cx.cache(), cx.tcx(), 0, true));
427 if t.items.is_empty() {
430 // FIXME: we should be using a derived_id for the Anchors here
433 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait, cx);
436 if !types.is_empty() && !consts.is_empty() {
440 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait, cx);
443 if !consts.is_empty() && !required.is_empty() {
446 for (pos, m) in required.iter().enumerate() {
447 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait, cx);
450 if pos < required.len() - 1 {
451 w.write_str("<div class=\"item-spacer\"></div>");
454 if !required.is_empty() && !provided.is_empty() {
457 for (pos, m) in provided.iter().enumerate() {
458 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait, cx);
460 clean::MethodItem(ref inner, _)
461 if !inner.generics.where_predicates.is_empty() =>
463 w.write_str(",\n { ... }\n");
466 w.write_str(" { ... }\n");
469 if pos < provided.len() - 1 {
470 w.write_str("<div class=\"item-spacer\"></div>");
475 w.write_str("</pre>")
478 // Trait documentation
479 document(w, cx, it, None);
481 fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
484 "<h2 id=\"{0}\" class=\"small-section-header\">\
485 {1}<a href=\"#{0}\" class=\"anchor\"></a>\
487 id, title, extra_content
491 fn write_loading_content(w: &mut Buffer, extra_content: &str) {
492 write!(w, "{}<span class=\"loading-content\">Loading content...</span>", extra_content)
495 fn trait_item(w: &mut Buffer, cx: &Context<'_>, m: &clean::Item, t: &clean::Item) {
496 let name = m.name.as_ref().unwrap();
497 info!("Documenting {} on {:?}", name, t.name);
498 let item_type = m.type_();
499 let id = cx.derive_id(format!("{}.{}", item_type, name));
500 write!(w, "<h3 id=\"{id}\" class=\"method\"><code>", id = id,);
501 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl, cx);
502 w.write_str("</code>");
503 render_stability_since(w, m, t, cx.tcx());
504 write_srclink(cx, m, w);
505 w.write_str("</h3>");
506 document(w, cx, m, Some(t));
509 if !types.is_empty() {
510 write_small_section_header(
514 "<div class=\"methods\">",
517 trait_item(w, cx, t, it);
519 write_loading_content(w, "</div>");
522 if !consts.is_empty() {
523 write_small_section_header(
526 "Associated Constants",
527 "<div class=\"methods\">",
530 trait_item(w, cx, t, it);
532 write_loading_content(w, "</div>");
535 // Output the documentation for each function individually
536 if !required.is_empty() {
537 write_small_section_header(
541 "<div class=\"methods\">",
544 trait_item(w, cx, m, it);
546 write_loading_content(w, "</div>");
548 if !provided.is_empty() {
549 write_small_section_header(
553 "<div class=\"methods\">",
556 trait_item(w, cx, m, it);
558 write_loading_content(w, "</div>");
561 // If there are methods directly on this trait object, render them here.
562 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All);
564 if let Some(implementors) = cx.cache.implementors.get(&it.def_id) {
565 // The DefId is for the first Type found with that name. The bool is
566 // if any Types with the same name but different DefId have been found.
567 let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();
568 for implementor in implementors {
569 match implementor.inner_impl().for_ {
570 clean::ResolvedPath { ref path, did, is_generic: false, .. }
571 | clean::BorrowedRef {
572 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
575 let &mut (prev_did, ref mut has_duplicates) =
576 implementor_dups.entry(path.last()).or_insert((did, false));
578 *has_duplicates = true;
585 let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| {
588 .def_id_full(cx.cache())
589 .map_or(true, |d| cx.cache.paths.contains_key(&d))
592 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
593 local.iter().partition(|i| i.inner_impl().synthetic);
595 synthetic.sort_by(|a, b| compare_impl(a, b, cx.cache(), cx.tcx()));
596 concrete.sort_by(|a, b| compare_impl(a, b, cx.cache(), cx.tcx()));
598 if !foreign.is_empty() {
599 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
601 for implementor in foreign {
602 let assoc_link = AssocItemLink::GotoSource(
603 implementor.impl_item.def_id,
604 &implementor.inner_impl().provided_trait_methods,
613 implementor.impl_item.stable_since(cx.tcx()).as_deref(),
614 implementor.impl_item.const_stable_since(cx.tcx()).as_deref(),
622 write_loading_content(w, "");
625 write_small_section_header(
629 "<div class=\"item-list\" id=\"implementors-list\">",
631 for implementor in concrete {
632 render_implementor(cx, implementor, it, w, &implementor_dups, &[]);
634 write_loading_content(w, "</div>");
637 write_small_section_header(
639 "synthetic-implementors",
641 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
643 for implementor in synthetic {
650 &collect_paths_for_type(implementor.inner_impl().for_.clone(), &cx.cache),
653 write_loading_content(w, "</div>");
656 // even without any implementations to write in, we still want the heading and list, so the
657 // implementors javascript file pulled in below has somewhere to write the impls into
658 write_small_section_header(
662 "<div class=\"item-list\" id=\"implementors-list\">",
664 write_loading_content(w, "</div>");
667 write_small_section_header(
669 "synthetic-implementors",
671 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
673 write_loading_content(w, "</div>");
679 "<script type=\"text/javascript\" \
680 src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\
682 root_path = vec![".."; cx.current.len()].join("/"),
683 path = if it.def_id.is_local() {
686 let (ref path, _) = cx.cache.external_paths[&it.def_id];
687 path[..path.len() - 1].join("/")
690 name = *it.name.as_ref().unwrap()
694 fn item_trait_alias(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::TraitAlias) {
695 w.write_str("<pre class=\"rust trait-alias\">");
696 render_attributes(w, it, false);
699 "trait {}{}{} = {};</pre>",
700 it.name.as_ref().unwrap(),
701 t.generics.print(cx.cache(), cx.tcx()),
702 print_where_clause(&t.generics, cx.cache(), cx.tcx(), 0, true),
703 bounds(&t.bounds, true, cx.cache(), cx.tcx())
706 document(w, cx, it, None);
708 // Render any items associated directly to this alias, as otherwise they
709 // won't be visible anywhere in the docs. It would be nice to also show
710 // associated items from the aliased type (see discussion in #32077), but
711 // we need #14072 to make sense of the generics.
712 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
715 fn item_opaque_ty(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::OpaqueTy) {
716 w.write_str("<pre class=\"rust opaque\">");
717 render_attributes(w, it, false);
720 "type {}{}{where_clause} = impl {bounds};</pre>",
721 it.name.as_ref().unwrap(),
722 t.generics.print(cx.cache(), cx.tcx()),
723 where_clause = print_where_clause(&t.generics, cx.cache(), cx.tcx(), 0, true),
724 bounds = bounds(&t.bounds, false, cx.cache(), cx.tcx()),
727 document(w, cx, it, None);
729 // Render any items associated directly to this alias, as otherwise they
730 // won't be visible anywhere in the docs. It would be nice to also show
731 // associated items from the aliased type (see discussion in #32077), but
732 // we need #14072 to make sense of the generics.
733 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
736 fn item_typedef(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Typedef) {
737 w.write_str("<pre class=\"rust typedef\">");
738 render_attributes(w, it, false);
741 "type {}{}{where_clause} = {type_};</pre>",
742 it.name.as_ref().unwrap(),
743 t.generics.print(cx.cache(), cx.tcx()),
744 where_clause = print_where_clause(&t.generics, cx.cache(), cx.tcx(), 0, true),
745 type_ = t.type_.print(cx.cache(), cx.tcx()),
748 document(w, cx, it, None);
750 // Render any items associated directly to this alias, as otherwise they
751 // won't be visible anywhere in the docs. It would be nice to also show
752 // associated items from the aliased type (see discussion in #32077), but
753 // we need #14072 to make sense of the generics.
754 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
757 fn item_union(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Union) {
758 wrap_into_docblock(w, |w| {
759 w.write_str("<pre class=\"rust union\">");
760 render_attributes(w, it, true);
761 render_union(w, it, Some(&s.generics), &s.fields, "", true, cx);
762 w.write_str("</pre>")
765 document(w, cx, it, None);
769 .filter_map(|f| match *f.kind {
770 clean::StructFieldItem(ref ty) => Some((f, ty)),
774 if fields.peek().is_some() {
777 "<h2 id=\"fields\" class=\"fields small-section-header\">
778 Fields<a href=\"#fields\" class=\"anchor\"></a></h2>"
780 for (field, ty) in fields {
781 let name = field.name.as_ref().expect("union field name");
782 let id = format!("{}.{}", ItemType::StructField, name);
785 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
786 <a href=\"#{id}\" class=\"anchor field\"></a>\
787 <code>{name}: {ty}</code>\
791 shortty = ItemType::StructField,
792 ty = ty.print(cx.cache(), cx.tcx()),
794 if let Some(stability_class) = field.stability_class(cx.tcx()) {
795 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
797 document(w, cx, field, Some(it));
800 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
803 fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum) {
804 wrap_into_docblock(w, |w| {
805 w.write_str("<pre class=\"rust enum\">");
806 render_attributes(w, it, true);
810 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
811 it.name.as_ref().unwrap(),
812 e.generics.print(cx.cache(), cx.tcx()),
813 print_where_clause(&e.generics, cx.cache(), cx.tcx(), 0, true),
815 if e.variants.is_empty() && !e.variants_stripped {
819 for v in &e.variants {
821 let name = v.name.as_ref().unwrap();
823 clean::VariantItem(ref var) => match var {
824 clean::Variant::CLike => write!(w, "{}", name),
825 clean::Variant::Tuple(ref tys) => {
826 write!(w, "{}(", name);
827 for (i, ty) in tys.iter().enumerate() {
829 w.write_str(", ")
831 write!(w, "{}", ty.print(cx.cache(), cx.tcx()));
835 clean::Variant::Struct(ref s) => {
836 render_struct(w, v, None, s.struct_type, &s.fields, " ", false, cx);
844 if e.variants_stripped {
845 w.write_str(" // some variants omitted\n");
849 w.write_str("</pre>")
852 document(w, cx, it, None);
853 if !e.variants.is_empty() {
856 "<h2 id=\"variants\" class=\"variants small-section-header\">
857 Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>\n",
858 document_non_exhaustive_header(it)
860 document_non_exhaustive(w, it);
861 for variant in &e.variants {
863 cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap()));
866 "<div id=\"{id}\" class=\"variant small-section-header\">\
867 <a href=\"#{id}\" class=\"anchor field\"></a>\
870 name = variant.name.as_ref().unwrap()
872 if let clean::VariantItem(clean::Variant::Tuple(ref tys)) = *variant.kind {
874 for (i, ty) in tys.iter().enumerate() {
876 w.write_str(", ");
878 write!(w, "{}", ty.print(cx.cache(), cx.tcx()));
882 w.write_str("</code></div>");
883 document(w, cx, variant, Some(it));
884 document_non_exhaustive(w, variant);
886 use crate::clean::Variant;
887 if let clean::VariantItem(Variant::Struct(ref s)) = *variant.kind {
888 let variant_id = cx.derive_id(format!(
891 variant.name.as_ref().unwrap()
893 write!(w, "<div class=\"autohide sub-variant\" id=\"{id}\">", id = variant_id);
896 "<h3>Fields of <b>{name}</b></h3><div>",
897 name = variant.name.as_ref().unwrap()
899 for field in &s.fields {
900 use crate::clean::StructFieldItem;
901 if let StructFieldItem(ref ty) = *field.kind {
902 let id = cx.derive_id(format!(
903 "variant.{}.field.{}",
904 variant.name.as_ref().unwrap(),
905 field.name.as_ref().unwrap()
909 "<span id=\"{id}\" class=\"variant small-section-header\">\
910 <a href=\"#{id}\" class=\"anchor field\"></a>\
911 <code>{f}: {t}</code>\
914 f = field.name.as_ref().unwrap(),
915 t = ty.print(cx.cache(), cx.tcx())
917 document(w, cx, field, Some(variant));
920 w.write_str("</div></div>");
922 render_stability_since(w, variant, it, cx.tcx());
925 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
928 fn item_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Macro) {
929 wrap_into_docblock(w, |w| {
930 highlight::render_with_highlighting(
936 it.span.inner().edition(),
939 document(w, cx, it, None)
942 fn item_proc_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, m: &clean::ProcMacro) {
943 let name = it.name.as_ref().expect("proc-macros always have names");
946 w.push_str("<pre class=\"rust macro\">");
947 write!(w, "{}!() {{ /* proc-macro */ }}", name);
948 w.push_str("</pre>");
951 w.push_str("<pre class=\"rust attr\">");
952 write!(w, "#[{}]", name);
953 w.push_str("</pre>");
955 MacroKind::Derive => {
956 w.push_str("<pre class=\"rust derive\">");
957 write!(w, "#[derive({})]", name);
958 if !m.helpers.is_empty() {
960 w.push_str(" // Attributes available to this derive:\n");
961 for attr in &m.helpers {
962 writeln!(w, " #[{}]", attr);
966 w.push_str("</pre>");
969 document(w, cx, it, None)
972 fn item_primitive(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
973 document(w, cx, it, None);
974 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
977 fn item_constant(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, c: &clean::Constant) {
978 w.write_str("<pre class=\"rust const\">");
979 render_attributes(w, it, false);
983 "{vis}const {name}: {typ}",
984 vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
985 name = it.name.as_ref().unwrap(),
986 typ = c.type_.print(cx.cache(), cx.tcx()),
989 let value = c.value(cx.tcx());
990 let is_literal = c.is_literal(cx.tcx());
991 let expr = c.expr(cx.tcx());
992 if value.is_some() || is_literal {
993 write!(w, " = {expr};", expr = Escape(&expr));
999 if let Some(value) = &value {
1000 let value_lowercase = value.to_lowercase();
1001 let expr_lowercase = expr.to_lowercase();
1003 if value_lowercase != expr_lowercase
1004 && value_lowercase.trim_end_matches("i32") != expr_lowercase
1006 write!(w, " // {value}", value = Escape(value));
1011 w.write_str("</pre>");
1012 document(w, cx, it, None)
1015 fn item_struct(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Struct) {
1016 wrap_into_docblock(w, |w| {
1017 w.write_str("<pre class=\"rust struct\">");
1018 render_attributes(w, it, true);
1019 render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true, cx);
1020 w.write_str("</pre>")
1023 document(w, cx, it, None);
1027 .filter_map(|f| match *f.kind {
1028 clean::StructFieldItem(ref ty) => Some((f, ty)),
1032 if let CtorKind::Fictive = s.struct_type {
1033 if fields.peek().is_some() {
1036 "<h2 id=\"fields\" class=\"fields small-section-header\">
1037 Fields{}<a href=\"#fields\" class=\"anchor\"></a></h2>",
1038 document_non_exhaustive_header(it)
1040 document_non_exhaustive(w, it);
1041 for (field, ty) in fields {
1042 let id = cx.derive_id(format!(
1044 ItemType::StructField,
1045 field.name.as_ref().unwrap()
1049 "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
1050 <a href=\"#{id}\" class=\"anchor field\"></a>\
1051 <code>{name}: {ty}</code>\
1053 item_type = ItemType::StructField,
1055 name = field.name.as_ref().unwrap(),
1056 ty = ty.print(cx.cache(), cx.tcx())
1058 document(w, cx, field, Some(it));
1062 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
1065 fn item_static(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Static) {
1066 w.write_str("<pre class=\"rust static\">");
1067 render_attributes(w, it, false);
1070 "{vis}static {mutability}{name}: {typ}</pre>",
1071 vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
1072 mutability = s.mutability.print_with_space(),
1073 name = it.name.as_ref().unwrap(),
1074 typ = s.type_.print(cx.cache(), cx.tcx())
1076 document(w, cx, it, None)
1079 fn item_foreign_type(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
1080 w.write_str("<pre class=\"rust foreigntype\">extern {\n");
1081 render_attributes(w, it, false);
1084 " {}type {};\n}}</pre>",
1085 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
1086 it.name.as_ref().unwrap(),
1089 document(w, cx, it, None);
1091 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
1094 fn item_keyword(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
1095 document(w, cx, it, None)
1098 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
1099 crate fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
1100 /// Takes a non-numeric and a numeric part from the given &str.
1101 fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
1102 let i = s.find(|c: char| c.is_ascii_digit());
1103 let (a, b) = s.split_at(i.unwrap_or(s.len()));
1104 let i = b.find(|c: char| !c.is_ascii_digit());
1105 let (b, c) = b.split_at(i.unwrap_or(b.len()));
1110 while !lhs.is_empty() || !rhs.is_empty() {
1111 let (la, lb) = take_parts(&mut lhs);
1112 let (ra, rb) = take_parts(&mut rhs);
1113 // First process the non-numeric part.
1115 Ordering::Equal => (),
1118 // Then process the numeric part, if both sides have one (and they fit in a u64).
1119 if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
1121 Ordering::Equal => (),
1125 // Then process the numeric part again, but this time as strings.
1127 Ordering::Equal => (),
1135 pub(super) fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
1136 let mut s = cx.current.join("::");
1138 s.push_str(&item.name.unwrap().as_str());
1142 pub(super) fn item_path(ty: ItemType, name: &str) -> String {
1144 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1145 _ => format!("{}.{}.html", ty, name),
1150 t_bounds: &[clean::GenericBound],
1155 let mut bounds = String::new();
1156 if !t_bounds.is_empty() {
1158 bounds.push_str(": ");
1160 for (i, p) in t_bounds.iter().enumerate() {
1162 bounds.push_str(" + ");
1164 bounds.push_str(&p.print(cache, tcx).to_string());
1170 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1172 F: FnOnce(&mut Buffer),
1174 w.write_str("<div class=\"docblock type-decl hidden-by-usual-hider\">");
1176 w.write_str("</div>")
1179 fn render_stability_since(
1182 containing_item: &clean::Item,
1185 render_stability_since_raw(
1187 item.stable_since(tcx).as_deref(),
1188 item.const_stable_since(tcx).as_deref(),
1189 containing_item.stable_since(tcx).as_deref(),
1190 containing_item.const_stable_since(tcx).as_deref(),
1194 fn compare_impl<'a, 'b>(
1200 let lhs = format!("{}", lhs.inner_impl().print(cache, false, tcx));
1201 let rhs = format!("{}", rhs.inner_impl().print(cache, false, tcx));
1203 // lhs and rhs are formatted as HTML, which may be unnecessary
1204 compare_names(&lhs, &rhs)
1207 fn render_implementor(
1210 trait_: &clean::Item,
1212 implementor_dups: &FxHashMap<Symbol, (DefId, bool)>,
1215 // If there's already another implementor that has the same abbridged name, use the
1216 // full path, for example in `std::iter::ExactSizeIterator`
1217 let use_absolute = match implementor.inner_impl().for_ {
1218 clean::ResolvedPath { ref path, is_generic: false, .. }
1219 | clean::BorrowedRef {
1220 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
1222 } => implementor_dups[&path.last()].1,
1230 AssocItemLink::Anchor(None),
1232 trait_.stable_since(cx.tcx()).as_deref(),
1233 trait_.const_stable_since(cx.tcx()).as_deref(),
1245 g: Option<&clean::Generics>,
1246 fields: &[clean::Item],
1254 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
1255 if structhead { "union " } else { "" },
1256 it.name.as_ref().unwrap()
1258 if let Some(g) = g {
1259 write!(w, "{}", g.print(cx.cache(), cx.tcx()));
1260 write!(w, "{}", print_where_clause(&g, cx.cache(), cx.tcx(), 0, true));
1263 write!(w, " {{\n{}", tab);
1264 for field in fields {
1265 if let clean::StructFieldItem(ref ty) = *field.kind {
1269 field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()),
1270 field.name.as_ref().unwrap(),
1271 ty.print(cx.cache(), cx.tcx()),
1277 if it.has_stripped_fields().unwrap() {
1278 write!(w, " // some fields omitted\n{}", tab);
1286 g: Option<&clean::Generics>,
1288 fields: &[clean::Item],
1296 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
1297 if structhead { "struct " } else { "" },
1298 it.name.as_ref().unwrap()
1300 if let Some(g) = g {
1301 write!(w, "{}", g.print(cx.cache(), cx.tcx()))
1304 CtorKind::Fictive => {
1305 if let Some(g) = g {
1306 write!(w, "{}", print_where_clause(g, cx.cache(), cx.tcx(), 0, true),)
1308 let mut has_visible_fields = false;
1310 for field in fields {
1311 if let clean::StructFieldItem(ref ty) = *field.kind {
1316 field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()),
1317 field.name.as_ref().unwrap(),
1318 ty.print(cx.cache(), cx.tcx()),
1320 has_visible_fields = true;
1324 if has_visible_fields {
1325 if it.has_stripped_fields().unwrap() {
1326 write!(w, "\n{} // some fields omitted", tab);
1328 write!(w, "\n{}", tab);
1329 } else if it.has_stripped_fields().unwrap() {
1330 // If there are no visible fields we can just display
1331 // `{ /* fields omitted */ }` to save space.
1332 write!(w, " /* fields omitted */ ");
1338 for (i, field) in fields.iter().enumerate() {
1343 clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
1344 clean::StructFieldItem(ref ty) => {
1348 field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()),
1349 ty.print(cx.cache(), cx.tcx()),
1352 _ => unreachable!(),
1356 if let Some(g) = g {
1357 write!(w, "{}", print_where_clause(g, cx.cache(), cx.tcx(), 0, false),)
1361 CtorKind::Const => {
1362 // Needed for PhantomData.
1363 if let Some(g) = g {
1364 write!(w, "{}", print_where_clause(g, cx.cache(), cx.tcx(), 0, false),)
1371 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1372 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1375 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1376 if item.is_non_exhaustive() {
1377 write!(w, "<div class=\"docblock non-exhaustive non-exhaustive-{}\">", {
1378 if item.is_struct() {
1380 } else if item.is_enum() {
1382 } else if item.is_variant() {
1389 if item.is_struct() {
1391 "Non-exhaustive structs could have additional fields added in future. \
1392 Therefore, non-exhaustive structs cannot be constructed in external crates \
1393 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
1394 matched against without a wildcard <code>..</code>; and \
1395 struct update syntax will not work.",
1397 } else if item.is_enum() {
1399 "Non-exhaustive enums could have additional variants added in future. \
1400 Therefore, when matching against variants of non-exhaustive enums, an \
1401 extra wildcard arm must be added to account for any future variants.",
1403 } else if item.is_variant() {
1405 "Non-exhaustive enum variants could have additional fields added in future. \
1406 Therefore, non-exhaustive enum variants cannot be constructed in external \
1407 crates and cannot be matched against.",
1411 "This type will require a wildcard arm in any match statements or constructors.",
1415 w.write_str("</div>");