1 //! Rustdoc's HTML rendering module.
3 //! This modules contains the bulk of the logic necessary for rendering a
4 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
5 //! rendering process is largely driven by the `format!` syntax extension to
6 //! perform all I/O into files and streams.
8 //! The rendering process is largely driven by the `Context` and `Cache`
9 //! structures. The cache is pre-populated by crawling the crate in question,
10 //! and then it is shared among the various rendering threads. The cache is meant
11 //! to be a fairly large structure not implementing `Clone` (because it's shared
12 //! among threads). The context, however, should be a lightweight structure. This
13 //! is cloned per-thread and contains information about what is currently being
16 //! In order to speed up rendering (mostly because of markdown rendering), the
17 //! rendering process has been parallelized. This parallelization is only
18 //! exposed through the `crate` method on the context, and then also from the
19 //! fact that the shared cache is stored in TLS (and must be accessed as such).
21 //! In addition to rendering the crate itself, this module is also responsible
22 //! for creating the corresponding search index and source file renderings.
23 //! These threads are not parallelized (they haven't been a bottleneck yet), and
24 //! both occur before the crate is rendered.
37 use std::collections::VecDeque;
38 use std::default::Default;
40 use std::path::PathBuf;
42 use std::string::ToString;
44 use rustc_ast_pretty::pprust;
45 use rustc_attr::{ConstStability, Deprecation, StabilityLevel};
46 use rustc_data_structures::fx::FxHashSet;
48 use rustc_hir::def::CtorKind;
49 use rustc_hir::def_id::DefId;
50 use rustc_hir::Mutability;
51 use rustc_middle::middle::stability;
52 use rustc_span::symbol::{kw, sym, Symbol};
53 use serde::ser::SerializeSeq;
54 use serde::{Serialize, Serializer};
56 use crate::clean::{self, FakeDefId, GetDefId, RenderedLink, SelfTy};
57 use crate::docfs::PathError;
58 use crate::error::Error;
59 use crate::formats::cache::Cache;
60 use crate::formats::item_type::ItemType;
61 use crate::formats::{AssocItemRender, Impl, RenderMode};
62 use crate::html::escape::Escape;
63 use crate::html::format::{
64 href, print_abi_with_space, print_constness_with_space, print_default_space,
65 print_generic_bounds, print_where_clause, Buffer, PrintWithSpace,
67 use crate::html::markdown::{Markdown, MarkdownHtml, MarkdownSummaryLine};
69 /// A pair of name and its optional document.
70 crate type NameDoc = (String, Option<String>);
72 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
73 crate::html::format::display_fn(move |f| {
74 if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { f.write_str(v) }
78 // Helper structs for rendering items/sidebars and carrying along contextual
81 /// Struct representing one entry in the JS search index. These are all emitted
82 /// by hand to a large JS file at the end of cache-creation.
84 crate struct IndexItem {
89 crate parent: Option<DefId>,
90 crate parent_idx: Option<usize>,
91 crate search_type: Option<IndexItemFunctionType>,
92 crate aliases: Box<[String]>,
95 /// A type used for the search index.
97 crate struct RenderType {
99 generics: Option<Vec<String>>,
102 /// Full type of functions/methods in the search index.
104 crate struct IndexItemFunctionType {
105 inputs: Vec<TypeWithKind>,
106 output: Option<Vec<TypeWithKind>>,
109 impl Serialize for IndexItemFunctionType {
110 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
114 // If we couldn't figure out a type, just write `null`.
115 let mut iter = self.inputs.iter();
116 if match self.output {
117 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
118 None => iter.any(|ref i| i.ty.name.is_none()),
120 serializer.serialize_none()
122 let mut seq = serializer.serialize_seq(None)?;
123 seq.serialize_element(&self.inputs)?;
124 if let Some(output) = &self.output {
125 if output.len() > 1 {
126 seq.serialize_element(&output)?;
128 seq.serialize_element(&output[0])?;
137 crate struct TypeWithKind {
142 impl From<(RenderType, ItemType)> for TypeWithKind {
143 fn from(x: (RenderType, ItemType)) -> TypeWithKind {
144 TypeWithKind { ty: x.0, kind: x.1 }
148 impl Serialize for TypeWithKind {
149 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
153 let mut seq = serializer.serialize_seq(None)?;
154 seq.serialize_element(&self.ty.name)?;
155 seq.serialize_element(&self.kind)?;
156 if let Some(generics) = &self.ty.generics {
157 seq.serialize_element(generics)?;
163 #[derive(Debug, Clone)]
164 crate struct StylePath {
165 /// The path to the theme
167 /// What the `disabled` attribute should be set to in the HTML tag
168 crate disabled: bool,
171 fn write_srclink(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) {
172 if let Some(l) = cx.src_href(item) {
173 write!(buf, "<a class=\"srclink\" href=\"{}\" title=\"goto source code\">[src]</a>", l)
177 #[derive(Debug, Eq, PartialEq, Hash)]
184 fn new(mut url: String, name: String) -> ItemEntry {
185 while url.starts_with('/') {
188 ItemEntry { url, name }
193 crate fn print(&self) -> impl fmt::Display + '_ {
194 crate::html::format::display_fn(move |f| {
195 write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name))
200 impl PartialOrd for ItemEntry {
201 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
202 Some(self.cmp(other))
206 impl Ord for ItemEntry {
207 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
208 self.name.cmp(&other.name)
214 structs: FxHashSet<ItemEntry>,
215 enums: FxHashSet<ItemEntry>,
216 unions: FxHashSet<ItemEntry>,
217 primitives: FxHashSet<ItemEntry>,
218 traits: FxHashSet<ItemEntry>,
219 macros: FxHashSet<ItemEntry>,
220 functions: FxHashSet<ItemEntry>,
221 typedefs: FxHashSet<ItemEntry>,
222 opaque_tys: FxHashSet<ItemEntry>,
223 statics: FxHashSet<ItemEntry>,
224 constants: FxHashSet<ItemEntry>,
225 keywords: FxHashSet<ItemEntry>,
226 attributes: FxHashSet<ItemEntry>,
227 derives: FxHashSet<ItemEntry>,
228 trait_aliases: FxHashSet<ItemEntry>,
232 fn new() -> AllTypes {
233 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
235 structs: new_set(100),
237 unions: new_set(100),
238 primitives: new_set(26),
239 traits: new_set(100),
240 macros: new_set(100),
241 functions: new_set(100),
242 typedefs: new_set(100),
243 opaque_tys: new_set(100),
244 statics: new_set(100),
245 constants: new_set(100),
246 keywords: new_set(100),
247 attributes: new_set(100),
248 derives: new_set(100),
249 trait_aliases: new_set(100),
253 fn append(&mut self, item_name: String, item_type: &ItemType) {
254 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
255 if let Some(name) = url.pop() {
256 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
258 let name = url.join("::");
260 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
261 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
262 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
263 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
264 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
265 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
266 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
267 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
268 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
269 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
270 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
271 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
272 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
273 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
281 fn print(self, f: &mut Buffer) {
282 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
284 let mut e: Vec<&ItemEntry> = e.iter().collect();
288 "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">",
289 title.replace(' ', "-"), // IDs cannot contain whitespaces.
295 write!(f, "<li>{}</li>", s.print());
298 f.write_str("</ul>");
304 <span class=\"in-band\">List of all items</span>\
305 <span class=\"out-of-band\">\
306 <span id=\"render-detail\">\
307 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
308 title=\"collapse all docs\">\
309 [<span class=\"inner\">−</span>]\
315 // Note: print_entries does not escape the title, because we know the current set of titles
316 // doesn't require escaping.
317 print_entries(f, &self.structs, "Structs", "structs");
318 print_entries(f, &self.enums, "Enums", "enums");
319 print_entries(f, &self.unions, "Unions", "unions");
320 print_entries(f, &self.primitives, "Primitives", "primitives");
321 print_entries(f, &self.traits, "Traits", "traits");
322 print_entries(f, &self.macros, "Macros", "macros");
323 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
324 print_entries(f, &self.derives, "Derive Macros", "derives");
325 print_entries(f, &self.functions, "Functions", "functions");
326 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
327 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
328 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
329 print_entries(f, &self.statics, "Statics", "statics");
330 print_entries(f, &self.constants, "Constants", "constants")
337 description: &'static str,
338 sub_settings: Vec<Setting>,
341 js_data_name: &'static str,
342 description: &'static str,
346 js_data_name: &'static str,
347 description: &'static str,
348 default_value: &'static str,
349 options: Vec<(String, String)>,
354 fn display(&self, root_path: &str, suffix: &str) -> String {
356 Setting::Section { description, ref sub_settings } => format!(
357 "<div class=\"setting-line\">\
358 <div class=\"title\">{}</div>\
359 <div class=\"sub-settings\">{}</div>
362 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
364 Setting::Toggle { js_data_name, description, default_value } => format!(
365 "<div class=\"setting-line\">\
366 <label class=\"toggle\">\
367 <input type=\"checkbox\" id=\"{}\" {}>\
368 <span class=\"slider\"></span>\
373 if default_value { " checked" } else { "" },
376 Setting::Select { js_data_name, description, default_value, ref options } => format!(
377 "<div class=\"setting-line\">\
379 <label class=\"select-wrapper\">\
380 <select id=\"{}\" autocomplete=\"off\">{}</select>\
381 <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
389 "<option value=\"{}\" {}>{}</option>",
391 if opt.0 == default_value { "selected" } else { "" },
394 .collect::<String>(),
402 impl From<(&'static str, &'static str, bool)> for Setting {
403 fn from(values: (&'static str, &'static str, bool)) -> Setting {
404 Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
408 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
409 fn from(values: (&'static str, Vec<T>)) -> Setting {
411 description: values.0,
412 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
417 fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
418 let theme_names: Vec<(String, String)> = themes
422 try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
425 Ok((theme.clone(), theme))
427 .collect::<Result<_, Error>>()?;
429 // (id, explanation, default value)
430 let settings: &[Setting] = &[
434 Setting::from(("use-system-theme", "Use system theme", true)),
436 js_data_name: "preferred-dark-theme",
437 description: "Preferred dark theme",
438 default_value: "dark",
439 options: theme_names.clone(),
442 js_data_name: "preferred-light-theme",
443 description: "Preferred light theme",
444 default_value: "light",
445 options: theme_names,
450 ("auto-hide-large-items", "Auto-hide item contents for large items.", true).into(),
451 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
452 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", false)
454 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
456 ("line-numbers", "Show line numbers on code examples", false).into(),
457 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
462 <span class=\"in-band\">Rustdoc settings</span>\
464 <div class=\"settings\">{}</div>\
465 <script src=\"{}settings{}.js\"></script>",
466 settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
472 fn document(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, parent: Option<&clean::Item>) {
473 if let Some(ref name) = item.name {
474 info!("Documenting {}", name);
476 document_item_info(w, cx, item, parent);
477 if parent.is_none() {
478 document_full_collapsible(w, item, cx);
480 document_full(w, item, cx);
484 /// Render md_text as markdown.
485 fn render_markdown(w: &mut Buffer, cx: &Context<'_>, md_text: &str, links: Vec<RenderedLink>) {
486 let mut ids = cx.id_map.borrow_mut();
489 "<div class=\"docblock\">{}</div>",
496 &cx.shared.playground
502 /// Writes a documentation block containing only the first paragraph of the documentation. If the
503 /// docs are longer, a "Read more" link is appended to the end.
508 link: AssocItemLink<'_>,
509 parent: &clean::Item,
512 document_item_info(w, cx, item, Some(parent));
516 if let Some(s) = item.doc_value() {
517 let mut summary_html = MarkdownSummaryLine(&s, &item.links(cx)).into_string();
519 if s.contains('\n') {
520 let link = format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link, cx));
522 if let Some(idx) = summary_html.rfind("</p>") {
523 summary_html.insert_str(idx, &link);
525 summary_html.push_str(&link);
529 write!(w, "<div class='docblock'>{}</div>", summary_html,);
533 fn document_full_collapsible(w: &mut Buffer, item: &clean::Item, cx: &Context<'_>) {
534 document_full_inner(w, item, cx, true);
537 fn document_full(w: &mut Buffer, item: &clean::Item, cx: &Context<'_>) {
538 document_full_inner(w, item, cx, false);
541 fn document_full_inner(w: &mut Buffer, item: &clean::Item, cx: &Context<'_>, is_collapsible: bool) {
542 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
543 debug!("Doc block: =====\n{}\n=====", s);
546 "<details class=\"rustdoc-toggle top-doc\" open>\
547 <summary class=\"hideme\">\
548 <span>Expand description</span>\
551 render_markdown(w, cx, &s, item.links(cx));
552 w.write_str("</details>");
554 render_markdown(w, cx, &s, item.links(cx));
559 /// Add extra information about an item such as:
563 /// * Required features (through the `doc_cfg` feature)
564 fn document_item_info(
568 parent: Option<&clean::Item>,
570 let item_infos = short_item_info(item, cx, parent);
571 if !item_infos.is_empty() {
572 w.write_str("<div class=\"item-info\">");
573 for info in item_infos {
576 w.write_str("</div>");
580 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
581 let cfg = match (&item.cfg, parent.and_then(|p| p.cfg.as_ref())) {
582 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
583 (cfg, _) => cfg.as_deref().cloned(),
586 debug!("Portability {:?} - {:?} = {:?}", item.cfg, parent.and_then(|p| p.cfg.as_ref()), cfg);
588 Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
591 /// Render the stability, deprecation and portability information that is displayed at the top of
592 /// the item's documentation.
596 parent: Option<&clean::Item>,
598 let mut extra_info = vec![];
599 let error_codes = cx.shared.codes;
601 if let Some(Deprecation { note, since, is_since_rustc_version, suggestion: _ }) =
602 item.deprecation(cx.tcx())
604 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
605 // but only display the future-deprecation messages for #[rustc_deprecated].
606 let mut message = if let Some(since) = since {
607 let since = &since.as_str();
608 if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
610 String::from("Deprecating in a future Rust version")
612 format!("Deprecating in {}", Escape(since))
615 format!("Deprecated since {}", Escape(since))
618 String::from("Deprecated")
621 if let Some(note) = note {
622 let note = note.as_str();
623 let mut ids = cx.id_map.borrow_mut();
624 let html = MarkdownHtml(
629 &cx.shared.playground,
631 message.push_str(&format!(": {}", html.into_string()));
633 extra_info.push(format!(
634 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
639 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
640 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
641 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
644 .filter(|stab| stab.feature != sym::rustc_private)
645 .map(|stab| (stab.level, stab.feature))
648 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
650 let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
651 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
652 feature.push_str(&format!(
653 " <a href=\"{url}{issue}\">#{issue}</a>",
659 message.push_str(&format!(" ({})", feature));
661 if let Some(unstable_reason) = reason {
662 let mut ids = cx.id_map.borrow_mut();
664 "<details><summary>{}</summary>{}</details>",
667 &unstable_reason.as_str(),
671 &cx.shared.playground,
677 extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
680 if let Some(portability) = portability(item, parent) {
681 extra_info.push(portability);
687 // Render the list of items inside one of the sections "Trait Implementations",
688 // "Auto Trait Implementations," "Blanket Trait Implementations" (on struct/enum pages).
693 containing_item: &clean::Item,
695 let cache = cx.cache();
697 let mut impls = traits
700 let did = i.trait_did_full(cache).unwrap();
701 let provided_trait_methods = i.inner_impl().provided_trait_methods(tcx);
702 let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_trait_methods);
703 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
719 .collect::<Vec<_>>();
721 w.write_str(&impls.join(""));
724 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>, cx: &Context<'_>) -> String {
725 use crate::formats::item_type::ItemType::*;
727 let name = it.name.as_ref().unwrap();
728 let ty = match it.type_() {
729 Typedef | AssocType => AssocType,
733 let anchor = format!("#{}.{}", ty, name);
735 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
736 AssocItemLink::Anchor(None) => anchor,
737 AssocItemLink::GotoSource(did, _) => {
738 href(did.expect_real(), cx).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
747 _default: Option<&String>,
748 link: AssocItemLink<'_>,
754 "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
756 it.visibility.print_with_space(it.def_id, cx),
757 naive_assoc_href(it, link, cx),
758 it.name.as_ref().unwrap(),
766 bounds: &[clean::GenericBound],
767 default: Option<&clean::Type>,
768 link: AssocItemLink<'_>,
774 "{}type <a href=\"{}\" class=\"type\">{}</a>",
776 naive_assoc_href(it, link, cx),
777 it.name.as_ref().unwrap()
779 if !bounds.is_empty() {
780 write!(w, ": {}", print_generic_bounds(bounds, cx))
782 if let Some(default) = default {
783 write!(w, " = {}", default.print(cx))
787 fn render_stability_since_raw(
790 const_stability: Option<&ConstStability>,
791 containing_ver: Option<&str>,
792 containing_const_ver: Option<&str>,
794 let ver = ver.filter(|inner| !inner.is_empty());
796 match (ver, const_stability) {
797 // stable and const stable
798 (Some(v), Some(ConstStability { level: StabilityLevel::Stable { since }, .. }))
799 if Some(since.as_str()).as_deref() != containing_const_ver =>
803 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
807 // stable and const unstable
810 Some(ConstStability { level: StabilityLevel::Unstable { issue, .. }, feature, .. }),
814 "<span class=\"since\" title=\"Stable since Rust version {0}, const unstable\">{0} (const: ",
817 if let Some(n) = issue {
820 "<a href=\"https://github.com/rust-lang/rust/issues/{}\" title=\"Tracking issue for {}\">unstable</a>",
824 write!(w, "unstable");
826 write!(w, ")</span>");
829 (Some(v), _) if ver != containing_ver => {
832 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
840 fn render_assoc_item(
843 link: AssocItemLink<'_>,
850 header: hir::FnHeader,
853 link: AssocItemLink<'_>,
857 let name = meth.name.as_ref().unwrap();
858 let href = match link {
859 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
860 AssocItemLink::Anchor(None) => format!("#{}.{}", meth.type_(), name),
861 AssocItemLink::GotoSource(did, provided_methods) => {
862 // We're creating a link from an impl-item to the corresponding
863 // trait-item and need to map the anchored type accordingly.
864 let ty = if provided_methods.contains(&name) {
870 href(did.expect_real(), cx)
871 .map(|p| format!("{}#{}.{}", p.0, ty, name))
872 .unwrap_or_else(|| format!("#{}.{}", ty, name))
875 let vis = meth.visibility.print_with_space(meth.def_id, cx).to_string();
877 print_constness_with_space(&header.constness, meth.const_stability(cx.tcx()));
878 let asyncness = header.asyncness.print_with_space();
879 let unsafety = header.unsafety.print_with_space();
880 let defaultness = print_default_space(meth.is_default());
881 let abi = print_abi_with_space(header.abi).to_string();
883 // NOTE: `{:#}` does not print HTML formatting, `{}` does. So `g.print` can't be reused between the length calculation and `write!`.
884 let generics_len = format!("{:#}", g.print(cx)).len();
885 let mut header_len = "fn ".len()
892 + name.as_str().len()
895 let (indent, indent_str, end_newline) = if parent == ItemType::Trait {
897 let indent_str = " ";
898 render_attributes_in_pre(w, meth, indent_str);
899 (4, indent_str, false)
901 render_attributes_in_code(w, meth);
904 w.reserve(header_len + "<a href=\"\" class=\"fnname\">{".len() + "</a>".len());
907 "{indent}{vis}{constness}{asyncness}{unsafety}{defaultness}{abi}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
908 {generics}{decl}{notable_traits}{where_clause}",
911 constness = constness,
912 asyncness = asyncness,
914 defaultness = defaultness,
918 generics = g.print(cx),
919 decl = d.full_print(header_len, indent, header.asyncness, cx),
920 notable_traits = notable_traits_decl(&d, cx),
921 where_clause = print_where_clause(g, cx, indent, end_newline),
925 clean::StrippedItem(..) => {}
926 clean::TyMethodItem(ref m) => {
927 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
929 clean::MethodItem(ref m, _) => {
930 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
932 clean::AssocConstItem(ref ty, ref default) => assoc_const(
938 if parent == ItemType::Trait { " " } else { "" },
941 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
947 if parent == ItemType::Trait { " " } else { "" },
950 _ => panic!("render_assoc_item called on non-associated-item"),
954 const ALLOWED_ATTRIBUTES: &[Symbol] =
955 &[sym::export_name, sym::link_section, sym::no_mangle, sym::repr, sym::non_exhaustive];
957 fn attributes(it: &clean::Item) -> Vec<String> {
962 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
963 Some(pprust::attribute_to_string(&attr).replace("\n", "").replace(" ", " "))
971 // When an attribute is rendered inside a `<pre>` tag, it is formatted using
972 // a whitespace prefix and newline.
973 fn render_attributes_in_pre(w: &mut Buffer, it: &clean::Item, prefix: &str) {
974 for a in attributes(it) {
975 writeln!(w, "{}{}", prefix, a);
979 // When an attribute is rendered inside a <code> tag, it is formatted using
980 // a div to produce a newline after it.
981 fn render_attributes_in_code(w: &mut Buffer, it: &clean::Item) {
982 for a in attributes(it) {
983 write!(w, "<div class=\"code-attribute\">{}</div>", a);
987 #[derive(Copy, Clone)]
988 enum AssocItemLink<'a> {
989 Anchor(Option<&'a str>),
990 GotoSource(FakeDefId, &'a FxHashSet<Symbol>),
993 impl<'a> AssocItemLink<'a> {
994 fn anchor(&self, id: &'a str) -> Self {
996 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
1002 fn render_assoc_items(
1005 containing_item: &clean::Item,
1007 what: AssocItemRender<'_>,
1009 info!("Documenting associated items of {:?}", containing_item.name);
1010 let v = match cx.cache.impls.get(&it) {
1014 let cache = cx.cache();
1015 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
1016 if !non_trait.is_empty() {
1017 let render_mode = match what {
1018 AssocItemRender::All => {
1020 "<h2 id=\"implementations\" class=\"small-section-header\">\
1021 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
1026 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
1029 "<h2 id=\"deref-methods\" class=\"small-section-header\">\
1030 Methods from {trait_}<Target = {type_}>\
1031 <a href=\"#deref-methods\" class=\"anchor\"></a>\
1033 trait_ = trait_.print(cx),
1034 type_ = type_.print(cx),
1036 RenderMode::ForDeref { mut_: deref_mut_ }
1039 for i in &non_trait {
1045 AssocItemLink::Anchor(None),
1055 if let AssocItemRender::DerefFor { .. } = what {
1058 if !traits.is_empty() {
1059 let deref_impl = traits
1061 .find(|t| t.inner_impl().trait_.def_id_full(cache) == cx.cache.deref_trait_did);
1062 if let Some(impl_) = deref_impl {
1063 let has_deref_mut = traits
1065 .any(|t| t.inner_impl().trait_.def_id_full(cache) == cx.cache.deref_mut_trait_did);
1066 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut);
1068 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
1069 traits.iter().partition(|t| t.inner_impl().synthetic);
1070 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
1071 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
1073 let mut impls = Buffer::empty_from(&w);
1074 render_impls(cx, &mut impls, &concrete, containing_item);
1075 let impls = impls.into_inner();
1076 if !impls.is_empty() {
1079 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
1080 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
1082 <div id=\"trait-implementations-list\">{}</div>",
1087 if !synthetic.is_empty() {
1089 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
1090 Auto Trait Implementations\
1091 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
1093 <div id=\"synthetic-implementations-list\">",
1095 render_impls(cx, w, &synthetic, containing_item);
1096 w.write_str("</div>");
1099 if !blanket_impl.is_empty() {
1101 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
1102 Blanket Implementations\
1103 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
1105 <div id=\"blanket-implementations-list\">",
1107 render_impls(cx, w, &blanket_impl, containing_item);
1108 w.write_str("</div>");
1113 fn render_deref_methods(
1117 container_item: &clean::Item,
1120 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
1121 let (target, real_target) = impl_
1125 .find_map(|item| match *item.kind {
1126 clean::TypedefItem(ref t, true) => Some(match *t {
1127 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
1128 _ => (&t.type_, &t.type_),
1132 .expect("Expected associated type binding");
1133 debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target);
1135 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
1136 if let Some(did) = target.def_id_full(cx.cache()) {
1137 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) {
1138 // `impl Deref<Target = S> for S`
1139 if did == type_did {
1140 // Avoid infinite cycles
1144 render_assoc_items(w, cx, container_item, did, what);
1146 if let Some(prim) = target.primitive_type() {
1147 if let Some(&did) = cx.cache.primitive_locations.get(&prim) {
1148 render_assoc_items(w, cx, container_item, did, what);
1154 fn should_render_item(item: &clean::Item, deref_mut_: bool, cache: &Cache) -> bool {
1155 let self_type_opt = match *item.kind {
1156 clean::MethodItem(ref method, _) => method.decl.self_type(),
1157 clean::TyMethodItem(ref method) => method.decl.self_type(),
1161 if let Some(self_ty) = self_type_opt {
1162 let (by_mut_ref, by_box, by_value) = match self_ty {
1163 SelfTy::SelfBorrowed(_, mutability)
1164 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
1165 (mutability == Mutability::Mut, false, false)
1167 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
1168 (false, Some(did) == cache.owned_box_did, false)
1170 SelfTy::SelfValue => (false, false, true),
1171 _ => (false, false, false),
1174 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
1180 fn notable_traits_decl(decl: &clean::FnDecl, cx: &Context<'_>) -> String {
1181 let mut out = Buffer::html();
1182 let mut trait_ = String::new();
1184 if let Some(did) = decl.output.def_id_full(cx.cache()) {
1185 if let Some(impls) = cx.cache().impls.get(&did) {
1187 let impl_ = i.inner_impl();
1188 if impl_.trait_.def_id().map_or(false, |d| {
1189 cx.cache().traits.get(&d).map(|t| t.is_notable).unwrap_or(false)
1194 "<h3 class=\"notable\">Notable traits for {}</h3>\
1195 <code class=\"content\">",
1196 impl_.for_.print(cx)
1198 trait_.push_str(&impl_.for_.print(cx).to_string());
1201 //use the "where" class here to make it small
1204 "<span class=\"where fmt-newline\">{}</span>",
1205 impl_.print(false, cx)
1207 let t_did = impl_.trait_.def_id_full(cx.cache()).unwrap();
1208 for it in &impl_.items {
1209 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1210 out.push_str("<span class=\"where fmt-newline\"> ");
1216 AssocItemLink::GotoSource(t_did.into(), &FxHashSet::default()),
1220 out.push_str(";</span>");
1228 if !out.is_empty() {
1231 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
1232 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
1234 out.push_str("</code></span></div></span></span>");
1244 parent: &clean::Item,
1245 link: AssocItemLink<'_>,
1246 render_mode: RenderMode,
1247 show_def_docs: bool,
1248 use_absolute: Option<bool>,
1249 is_on_foreign_type: bool,
1250 show_default_items: bool,
1251 // This argument is used to reference same type with different paths to avoid duplication
1252 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
1255 let cache = cx.cache();
1256 let traits = &cache.traits;
1257 let trait_ = i.trait_did_full(cache).map(|did| &traits[&did]);
1258 let mut close_tags = String::new();
1260 // For trait implementations, the `interesting` output contains all methods that have doc
1261 // comments, and the `boring` output contains all methods that do not. The distinction is
1262 // used to allow hiding the boring methods.
1263 // `containing_item` is used for rendering stability info. If the parent is a trait impl,
1264 // `containing_item` will the grandparent, since trait impls can't have stability attached.
1266 boring: &mut Buffer,
1267 interesting: &mut Buffer,
1270 parent: &clean::Item,
1271 containing_item: &clean::Item,
1272 link: AssocItemLink<'_>,
1273 render_mode: RenderMode,
1274 is_default_item: bool,
1275 trait_: Option<&clean::Trait>,
1276 show_def_docs: bool,
1278 let item_type = item.type_();
1279 let name = item.name.as_ref().unwrap();
1281 let render_method_item = match render_mode {
1282 RenderMode::Normal => true,
1283 RenderMode::ForDeref { mut_: deref_mut_ } => {
1284 should_render_item(&item, deref_mut_, &cx.cache)
1288 let in_trait_class = if trait_.is_some() { " trait-impl" } else { "" };
1290 let mut doc_buffer = Buffer::empty_from(boring);
1291 let mut info_buffer = Buffer::empty_from(boring);
1292 let mut short_documented = true;
1294 if render_method_item {
1295 if !is_default_item {
1296 if let Some(t) = trait_ {
1297 // The trait item may have been stripped so we might not
1298 // find any documentation or stability for it.
1299 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
1300 // We need the stability of the item from the trait
1301 // because impls can't have a stability.
1302 if item.doc_value().is_some() {
1303 document_item_info(&mut info_buffer, cx, it, Some(parent));
1304 document_full(&mut doc_buffer, item, cx);
1305 short_documented = false;
1307 // In case the item isn't documented,
1308 // provide short documentation from the trait.
1309 document_short(&mut doc_buffer, it, cx, link, parent, show_def_docs);
1313 document_item_info(&mut info_buffer, cx, item, Some(parent));
1315 document_full(&mut doc_buffer, item, cx);
1316 short_documented = false;
1320 document_short(&mut doc_buffer, item, cx, link, parent, show_def_docs);
1323 let w = if short_documented && trait_.is_some() { interesting } else { boring };
1325 let toggled = !doc_buffer.is_empty();
1327 let method_toggle_class =
1328 if item_type == ItemType::Method { " method-toggle" } else { "" };
1329 write!(w, "<details class=\"rustdoc-toggle{}\" open><summary>", method_toggle_class);
1332 clean::MethodItem(..) | clean::TyMethodItem(_) => {
1333 // Only render when the method is not static or we allow static methods
1334 if render_method_item {
1335 let id = cx.derive_id(format!("{}.{}", item_type, name));
1336 let source_id = trait_
1337 .and_then(|trait_| {
1338 trait_.items.iter().find(|item| {
1339 item.name.map(|n| n.as_str().eq(&name.as_str())).unwrap_or(false)
1342 .map(|item| format!("{}.{}", item.type_(), name));
1345 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1346 id, item_type, in_trait_class,
1348 render_rightside(w, cx, item, containing_item);
1349 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1350 w.write_str("<code>");
1354 link.anchor(source_id.as_ref().unwrap_or(&id)),
1358 w.write_str("</code>");
1359 w.write_str("</div>");
1362 clean::TypedefItem(ref tydef, _) => {
1363 let source_id = format!("{}.{}", ItemType::AssocType, name);
1364 let id = cx.derive_id(source_id.clone());
1367 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1368 id, item_type, in_trait_class
1370 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1371 w.write_str("<code>");
1377 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1381 w.write_str("</code>");
1382 w.write_str("</div>");
1384 clean::AssocConstItem(ref ty, ref default) => {
1385 let source_id = format!("{}.{}", item_type, name);
1386 let id = cx.derive_id(source_id.clone());
1389 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1390 id, item_type, in_trait_class
1392 render_rightside(w, cx, item, containing_item);
1393 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1394 w.write_str("<code>");
1400 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1404 w.write_str("</code>");
1405 w.write_str("</div>");
1407 clean::AssocTypeItem(ref bounds, ref default) => {
1408 let source_id = format!("{}.{}", item_type, name);
1409 let id = cx.derive_id(source_id.clone());
1410 write!(w, "<div id=\"{}\" class=\"{}{}\">", id, item_type, in_trait_class,);
1411 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1412 w.write_str("<code>");
1418 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1422 w.write_str("</code>");
1423 w.write_str("</div>");
1425 clean::StrippedItem(..) => return,
1426 _ => panic!("can't make docs for trait item with name {:?}", item.name),
1429 w.push_buffer(info_buffer);
1431 w.write_str("</summary>");
1432 w.push_buffer(doc_buffer);
1433 w.push_str("</details>");
1437 let mut impl_items = Buffer::empty_from(w);
1438 let mut default_impl_items = Buffer::empty_from(w);
1440 for trait_item in &i.inner_impl().items {
1442 &mut default_impl_items,
1446 if trait_.is_some() { &i.impl_item } else { parent },
1451 trait_.map(|t| &t.trait_),
1456 fn render_default_items(
1457 boring: &mut Buffer,
1458 interesting: &mut Buffer,
1462 parent: &clean::Item,
1463 containing_item: &clean::Item,
1464 render_mode: RenderMode,
1465 show_def_docs: bool,
1467 for trait_item in &t.items {
1468 let n = trait_item.name;
1469 if i.items.iter().any(|m| m.name == n) {
1472 let did = i.trait_.as_ref().unwrap().def_id_full(cx.cache()).unwrap();
1473 let provided_methods = i.provided_trait_methods(cx.tcx());
1474 let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_methods);
1492 // If we've implemented a trait, then also emit documentation for all
1493 // default items which weren't overridden in the implementation block.
1494 // We don't emit documentation for default items if they appear in the
1495 // Implementations on Foreign Types or Implementors sections.
1496 if show_default_items {
1497 if let Some(t) = trait_ {
1498 render_default_items(
1499 &mut default_impl_items,
1511 if render_mode == RenderMode::Normal {
1512 let toggled = !(impl_items.is_empty() && default_impl_items.is_empty());
1514 close_tags.insert_str(0, "</details>");
1515 write!(w, "<details class=\"rustdoc-toggle implementors-toggle\" open>");
1516 write!(w, "<summary>")
1518 render_impl_summary(
1530 write!(w, "</summary>")
1533 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
1534 let mut ids = cx.id_map.borrow_mut();
1537 "<div class=\"docblock\">{}</div>",
1540 &i.impl_item.links(cx),
1543 cx.shared.edition(),
1544 &cx.shared.playground
1550 if !default_impl_items.is_empty() || !impl_items.is_empty() {
1551 w.write_str("<div class=\"impl-items\">");
1552 w.push_buffer(default_impl_items);
1553 w.push_buffer(impl_items);
1554 close_tags.insert_str(0, "</div>");
1556 w.write_str(&close_tags);
1559 // Render the items that appear on the right side of methods, impls, and
1560 // associated types. For example "1.0.0 (const: 1.39.0) [src]".
1561 fn render_rightside(
1565 containing_item: &clean::Item,
1569 write!(w, "<div class=\"rightside\">");
1570 render_stability_since_raw(
1572 item.stable_since(tcx).as_deref(),
1573 item.const_stability(tcx),
1574 containing_item.stable_since(tcx).as_deref(),
1575 containing_item.const_stable_since(tcx).as_deref(),
1578 write_srclink(cx, item, w);
1579 w.write_str("</div>");
1582 pub(crate) fn render_impl_summary(
1586 parent: &clean::Item,
1587 containing_item: &clean::Item,
1588 show_def_docs: bool,
1589 use_absolute: Option<bool>,
1590 is_on_foreign_type: bool,
1591 // This argument is used to reference same type with different paths to avoid duplication
1592 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
1595 let id = cx.derive_id(match i.inner_impl().trait_ {
1597 if is_on_foreign_type {
1598 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t, cx)
1600 format!("impl-{}", small_url_encode(format!("{:#}", t.print(cx))))
1603 None => "impl".to_string(),
1605 let aliases = if aliases.is_empty() {
1608 format!(" data-aliases=\"{}\"", aliases.join(","))
1610 write!(w, "<div id=\"{}\" class=\"impl has-srclink\"{}>", id, aliases);
1611 render_rightside(w, cx, &i.impl_item, containing_item);
1612 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1613 write!(w, "<code class=\"in-band\">");
1615 if let Some(use_absolute) = use_absolute {
1616 write!(w, "{}", i.inner_impl().print(use_absolute, cx));
1618 for it in &i.inner_impl().items {
1619 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1620 w.write_str("<span class=\"where fmt-newline\"> ");
1621 assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "", cx);
1622 w.write_str(";</span>");
1627 write!(w, "{}", i.inner_impl().print(false, cx));
1629 write!(w, "</code>");
1631 let is_trait = i.inner_impl().trait_.is_some();
1633 if let Some(portability) = portability(&i.impl_item, Some(parent)) {
1634 write!(w, "<div class=\"item-info\">{}</div>", portability);
1638 w.write_str("</div>");
1641 fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) {
1642 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
1646 || it.is_primitive()
1654 "<p class=\"location\">{}{}</p>",
1656 clean::StructItem(..) => "Struct ",
1657 clean::TraitItem(..) => "Trait ",
1658 clean::PrimitiveItem(..) => "Primitive Type ",
1659 clean::UnionItem(..) => "Union ",
1660 clean::EnumItem(..) => "Enum ",
1661 clean::TypedefItem(..) => "Type Definition ",
1662 clean::ForeignTypeItem => "Foreign Type ",
1663 clean::ModuleItem(..) =>
1671 it.name.as_ref().unwrap()
1676 if let Some(ref version) = cx.cache.crate_version {
1679 "<div class=\"block version\">\
1680 <div class=\"narrow-helper\"></div>\
1688 buffer.write_str("<div class=\"sidebar-elems\">");
1692 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
1693 it.name.as_ref().expect("crates always have a name"),
1698 clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s),
1699 clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t),
1700 clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it),
1701 clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u),
1702 clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e),
1703 clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it),
1704 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
1705 clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, it),
1709 // The sidebar is designed to display sibling functions, modules and
1710 // other miscellaneous information. since there are lots of sibling
1711 // items (and that causes quadratic growth in large modules),
1712 // we refactor common parts into a shared JavaScript file per module.
1713 // still, we don't move everything into JS because we want to preserve
1714 // as much HTML as possible in order to allow non-JS-enabled browsers
1715 // to navigate the documentation (though slightly inefficiently).
1718 buffer.write_str("<p class=\"location\">Other items in<br>");
1719 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
1721 buffer.write_str("::<wbr>");
1725 "<a href=\"{}index.html\">{}</a>",
1726 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
1730 buffer.write_str("</p>");
1733 // Sidebar refers to the enclosing module, not this module.
1734 let relpath = if it.is_mod() && parentlen != 0 { "./" } else { "" };
1737 "<div id=\"sidebar-vars\" data-name=\"{name}\" data-ty=\"{ty}\" data-relpath=\"{path}\">\
1739 name = it.name.unwrap_or(kw::Empty),
1743 write!(buffer, "<script defer src=\"{}sidebar-items.js\"></script>", relpath);
1744 // Closes sidebar-elems div.
1745 buffer.write_str("</div>");
1748 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
1749 if used_links.insert(url.clone()) {
1753 while !used_links.insert(format!("{}-{}", url, add)) {
1756 format!("{}-{}", url, add)
1762 used_links: &mut FxHashSet<String>,
1768 .filter_map(|item| match item.name {
1769 Some(ref name) if !name.is_empty() && item.is_method() => {
1770 if !for_deref || should_render_item(item, deref_mut, cache) {
1772 "<a href=\"#{}\">{}</a>",
1773 get_next_url(used_links, format!("method.{}", name)),
1782 .collect::<Vec<_>>()
1785 // The point is to url encode any potential character from a type with genericity.
1786 fn small_url_encode(s: String) -> String {
1787 let mut st = String::new();
1788 let mut last_match = 0;
1789 for (idx, c) in s.char_indices() {
1790 let escaped = match c {
1806 st += &s[last_match..idx];
1808 // NOTE: we only expect single byte characters here - which is fine as long as we
1809 // only match single byte characters
1810 last_match = idx + 1;
1813 if last_match != 0 {
1814 st += &s[last_match..];
1821 fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) {
1822 let did = it.def_id.expect_real();
1823 if let Some(v) = cx.cache.impls.get(&did) {
1824 let mut used_links = FxHashSet::default();
1825 let cache = cx.cache();
1828 let used_links_bor = &mut used_links;
1831 .filter(|i| i.inner_impl().trait_.is_none())
1832 .flat_map(move |i| {
1833 get_methods(i.inner_impl(), false, used_links_bor, false, &cx.cache)
1835 .collect::<Vec<_>>();
1836 if !ret.is_empty() {
1837 // We want links' order to be reproducible so we don't use unstable sort.
1841 "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
1842 <div class=\"sidebar-links\">",
1845 out.push_str(&line);
1847 out.push_str("</div>");
1851 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
1852 if let Some(impl_) = v
1854 .filter(|i| i.inner_impl().trait_.is_some())
1855 .find(|i| i.inner_impl().trait_.def_id_full(cache) == cx.cache.deref_trait_did)
1857 sidebar_deref_methods(cx, out, impl_, v);
1860 let format_impls = |impls: Vec<&Impl>| {
1861 let mut links = FxHashSet::default();
1866 if let Some(ref i) = it.inner_impl().trait_ {
1867 let i_display = format!("{:#}", i.print(cx));
1868 let out = Escape(&i_display);
1869 let encoded = small_url_encode(format!("{:#}", i.print(cx)));
1870 let generated = format!(
1871 "<a href=\"#impl-{}\">{}{}</a>",
1873 if it.inner_impl().negative_polarity { "!" } else { "" },
1876 if links.insert(generated.clone()) { Some(generated) } else { None }
1881 .collect::<Vec<String>>();
1886 let write_sidebar_links = |out: &mut Buffer, links: Vec<String>| {
1887 out.push_str("<div class=\"sidebar-links\">");
1889 out.push_str(&link);
1891 out.push_str("</div>");
1894 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
1895 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
1896 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
1898 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
1900 let concrete_format = format_impls(concrete);
1901 let synthetic_format = format_impls(synthetic);
1902 let blanket_format = format_impls(blanket_impl);
1904 if !concrete_format.is_empty() {
1906 "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
1907 Trait Implementations</a>",
1909 write_sidebar_links(out, concrete_format);
1912 if !synthetic_format.is_empty() {
1914 "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
1915 Auto Trait Implementations</a>",
1917 write_sidebar_links(out, synthetic_format);
1920 if !blanket_format.is_empty() {
1922 "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
1923 Blanket Implementations</a>",
1925 write_sidebar_links(out, blanket_format);
1931 fn sidebar_deref_methods(cx: &Context<'_>, out: &mut Buffer, impl_: &Impl, v: &Vec<Impl>) {
1934 debug!("found Deref: {:?}", impl_);
1935 if let Some((target, real_target)) =
1936 impl_.inner_impl().items.iter().find_map(|item| match *item.kind {
1937 clean::TypedefItem(ref t, true) => Some(match *t {
1938 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
1939 _ => (&t.type_, &t.type_),
1944 debug!("found target, real_target: {:?} {:?}", target, real_target);
1945 if let Some(did) = target.def_id_full(c) {
1946 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(c) {
1947 // `impl Deref<Target = S> for S`
1948 if did == type_did {
1949 // Avoid infinite cycles
1956 .filter(|i| i.inner_impl().trait_.is_some())
1957 .any(|i| i.inner_impl().trait_.def_id_full(c) == c.deref_mut_trait_did);
1958 let inner_impl = target
1961 target.primitive_type().and_then(|prim| c.primitive_locations.get(&prim).cloned())
1963 .and_then(|did| c.impls.get(&did));
1964 if let Some(impls) = inner_impl {
1965 debug!("found inner_impl: {:?}", impls);
1966 let mut used_links = FxHashSet::default();
1969 .filter(|i| i.inner_impl().trait_.is_none())
1970 .flat_map(|i| get_methods(i.inner_impl(), true, &mut used_links, deref_mut, c))
1971 .collect::<Vec<_>>();
1972 if !ret.is_empty() {
1975 "<a class=\"sidebar-title\" href=\"#deref-methods\">Methods from {}<Target={}></a>",
1976 Escape(&format!("{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print(cx))),
1977 Escape(&format!("{:#}", real_target.print(cx))),
1979 // We want links' order to be reproducible so we don't use unstable sort.
1981 out.push_str("<div class=\"sidebar-links\">");
1983 out.push_str(&link);
1985 out.push_str("</div>");
1991 fn sidebar_struct(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
1992 let mut sidebar = Buffer::new();
1993 let fields = get_struct_fields_name(&s.fields);
1995 if !fields.is_empty() {
1996 if let CtorKind::Fictive = s.struct_type {
1998 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
1999 <div class=\"sidebar-links\">",
2002 for field in fields {
2003 sidebar.push_str(&field);
2006 sidebar.push_str("</div>");
2010 sidebar_assoc_items(cx, &mut sidebar, it);
2012 if !sidebar.is_empty() {
2013 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2017 fn get_id_for_impl_on_foreign_type(
2019 trait_: &clean::Type,
2022 small_url_encode(format!("impl-{:#}-for-{:#}", trait_.print(cx), for_.print(cx),))
2025 fn extract_for_impl_name(item: &clean::Item, cx: &Context<'_>) -> Option<(String, String)> {
2027 clean::ItemKind::ImplItem(ref i) => {
2028 if let Some(ref trait_) = i.trait_ {
2029 // Alternative format produces no URLs,
2030 // so this parameter does nothing.
2032 format!("{:#}", i.for_.print(cx)),
2033 get_id_for_impl_on_foreign_type(&i.for_, trait_, cx),
2043 fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
2044 buf.write_str("<div class=\"block items\">");
2046 fn print_sidebar_section(
2048 items: &[clean::Item],
2050 filter: impl Fn(&clean::Item) -> bool,
2051 write: impl Fn(&mut Buffer, &str),
2054 let mut items = items
2056 .filter_map(|m| match m.name {
2057 Some(ref name) if filter(m) => Some(name.as_str()),
2060 .collect::<Vec<_>>();
2062 if !items.is_empty() {
2063 items.sort_unstable();
2064 out.push_str(before);
2065 for item in items.into_iter() {
2068 out.push_str(after);
2072 print_sidebar_section(
2075 "<a class=\"sidebar-title\" href=\"#associated-types\">\
2076 Associated Types</a><div class=\"sidebar-links\">",
2077 |m| m.is_associated_type(),
2078 |out, sym| write!(out, "<a href=\"#associatedtype.{0}\">{0}</a>", sym),
2082 print_sidebar_section(
2085 "<a class=\"sidebar-title\" href=\"#associated-const\">\
2086 Associated Constants</a><div class=\"sidebar-links\">",
2087 |m| m.is_associated_const(),
2088 |out, sym| write!(out, "<a href=\"#associatedconstant.{0}\">{0}</a>", sym),
2092 print_sidebar_section(
2095 "<a class=\"sidebar-title\" href=\"#required-methods\">\
2096 Required Methods</a><div class=\"sidebar-links\">",
2097 |m| m.is_ty_method(),
2098 |out, sym| write!(out, "<a href=\"#tymethod.{0}\">{0}</a>", sym),
2102 print_sidebar_section(
2105 "<a class=\"sidebar-title\" href=\"#provided-methods\">\
2106 Provided Methods</a><div class=\"sidebar-links\">",
2108 |out, sym| write!(out, "<a href=\"#method.{0}\">{0}</a>", sym),
2112 if let Some(implementors) = cx.cache.implementors.get(&it.def_id.expect_real()) {
2113 let cache = cx.cache();
2114 let mut res = implementors
2120 .map_or(false, |d| !cx.cache.paths.contains_key(&d))
2122 .filter_map(|i| extract_for_impl_name(&i.impl_item, cx))
2123 .collect::<Vec<_>>();
2125 if !res.is_empty() {
2128 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
2129 Implementations on Foreign Types</a>\
2130 <div class=\"sidebar-links\">",
2132 for (name, id) in res.into_iter() {
2133 write!(buf, "<a href=\"#{}\">{}</a>", id, Escape(&name));
2135 buf.push_str("</div>");
2139 sidebar_assoc_items(cx, buf, it);
2141 buf.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
2144 "<a class=\"sidebar-title\" \
2145 href=\"#synthetic-implementors\">Auto Implementors</a>",
2149 buf.push_str("</div>")
2152 fn sidebar_primitive(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2153 let mut sidebar = Buffer::new();
2154 sidebar_assoc_items(cx, &mut sidebar, it);
2156 if !sidebar.is_empty() {
2157 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2161 fn sidebar_typedef(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2162 let mut sidebar = Buffer::new();
2163 sidebar_assoc_items(cx, &mut sidebar, it);
2165 if !sidebar.is_empty() {
2166 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2170 fn get_struct_fields_name(fields: &[clean::Item]) -> Vec<String> {
2171 let mut fields = fields
2173 .filter(|f| matches!(*f.kind, clean::StructFieldItem(..)))
2175 f.name.map(|name| format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
2177 .collect::<Vec<_>>();
2182 fn sidebar_union(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
2183 let mut sidebar = Buffer::new();
2184 let fields = get_struct_fields_name(&u.fields);
2186 if !fields.is_empty() {
2188 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
2189 <div class=\"sidebar-links\">",
2192 for field in fields {
2193 sidebar.push_str(&field);
2196 sidebar.push_str("</div>");
2199 sidebar_assoc_items(cx, &mut sidebar, it);
2201 if !sidebar.is_empty() {
2202 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2206 fn sidebar_enum(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
2207 let mut sidebar = Buffer::new();
2209 let mut variants = e
2212 .filter_map(|v| match v.name {
2213 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
2216 .collect::<Vec<_>>();
2217 if !variants.is_empty() {
2218 variants.sort_unstable();
2219 sidebar.push_str(&format!(
2220 "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
2221 <div class=\"sidebar-links\">{}</div>",
2226 sidebar_assoc_items(cx, &mut sidebar, it);
2228 if !sidebar.is_empty() {
2229 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2233 fn item_ty_to_strs(ty: ItemType) -> (&'static str, &'static str) {
2235 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
2236 ItemType::Module => ("modules", "Modules"),
2237 ItemType::Struct => ("structs", "Structs"),
2238 ItemType::Union => ("unions", "Unions"),
2239 ItemType::Enum => ("enums", "Enums"),
2240 ItemType::Function => ("functions", "Functions"),
2241 ItemType::Typedef => ("types", "Type Definitions"),
2242 ItemType::Static => ("statics", "Statics"),
2243 ItemType::Constant => ("constants", "Constants"),
2244 ItemType::Trait => ("traits", "Traits"),
2245 ItemType::Impl => ("impls", "Implementations"),
2246 ItemType::TyMethod => ("tymethods", "Type Methods"),
2247 ItemType::Method => ("methods", "Methods"),
2248 ItemType::StructField => ("fields", "Struct Fields"),
2249 ItemType::Variant => ("variants", "Variants"),
2250 ItemType::Macro => ("macros", "Macros"),
2251 ItemType::Primitive => ("primitives", "Primitive Types"),
2252 ItemType::AssocType => ("associated-types", "Associated Types"),
2253 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
2254 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
2255 ItemType::Keyword => ("keywords", "Keywords"),
2256 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
2257 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
2258 ItemType::ProcDerive => ("derives", "Derive Macros"),
2259 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
2263 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
2264 let mut sidebar = String::new();
2266 // Re-exports are handled a bit differently because they can be extern crates or imports.
2267 if items.iter().any(|it| {
2269 && (it.type_() == ItemType::ExternCrate
2270 || (it.type_() == ItemType::Import && !it.is_stripped()))
2272 let (id, name) = item_ty_to_strs(ItemType::Import);
2273 sidebar.push_str(&format!("<li><a href=\"#{}\">{}</a></li>", id, name));
2276 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
2277 // to print its headings
2279 ItemType::Primitive,
2293 ItemType::StructField,
2295 ItemType::AssocType,
2296 ItemType::AssocConst,
2297 ItemType::ForeignType,
2300 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty && it.name.is_some()) {
2301 let (id, name) = item_ty_to_strs(myty);
2302 sidebar.push_str(&format!("<li><a href=\"#{}\">{}</a></li>", id, name));
2306 if !sidebar.is_empty() {
2307 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
2311 fn sidebar_foreign_type(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2312 let mut sidebar = Buffer::new();
2313 sidebar_assoc_items(cx, &mut sidebar, it);
2315 if !sidebar.is_empty() {
2316 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2320 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
2322 /// Returns a list of all paths used in the type.
2323 /// This is used to help deduplicate imported impls
2324 /// for reexported types. If any of the contained
2325 /// types are re-exported, we don't use the corresponding
2326 /// entry from the js file, as inlining will have already
2327 /// picked up the impl
2328 fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> {
2329 let mut out = Vec::new();
2330 let mut visited = FxHashSet::default();
2331 let mut work = VecDeque::new();
2333 work.push_back(first_ty);
2335 while let Some(ty) = work.pop_front() {
2336 if !visited.insert(ty.clone()) {
2341 clean::Type::ResolvedPath { did, .. } => {
2342 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
2343 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
2345 if let Some(path) = fqp {
2346 out.push(path.join("::"));
2349 clean::Type::Tuple(tys) => {
2350 work.extend(tys.into_iter());
2352 clean::Type::Slice(ty) => {
2353 work.push_back(*ty);
2355 clean::Type::Array(ty, _) => {
2356 work.push_back(*ty);
2358 clean::Type::RawPointer(_, ty) => {
2359 work.push_back(*ty);
2361 clean::Type::BorrowedRef { type_, .. } => {
2362 work.push_back(*type_);
2364 clean::Type::QPath { self_type, trait_, .. } => {
2365 work.push_back(*self_type);
2366 work.push_back(*trait_);