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.
38 crate use span_map::{collect_spans_and_sources, LinkFromSrc};
40 use std::collections::VecDeque;
41 use std::default::Default;
43 use std::path::PathBuf;
45 use std::string::ToString;
47 use rustc_ast_pretty::pprust;
48 use rustc_attr::{ConstStability, Deprecation, StabilityLevel};
49 use rustc_data_structures::fx::FxHashSet;
51 use rustc_hir::def::CtorKind;
52 use rustc_hir::def_id::DefId;
53 use rustc_hir::Mutability;
54 use rustc_middle::middle::stability;
55 use rustc_middle::ty::TyCtxt;
56 use rustc_span::symbol::{kw, sym, Symbol};
57 use serde::ser::SerializeSeq;
58 use serde::{Serialize, Serializer};
60 use crate::clean::{self, GetDefId, ItemId, RenderedLink, SelfTy};
61 use crate::docfs::PathError;
62 use crate::error::Error;
63 use crate::formats::cache::Cache;
64 use crate::formats::item_type::ItemType;
65 use crate::formats::{AssocItemRender, Impl, RenderMode};
66 use crate::html::escape::Escape;
67 use crate::html::format::{
68 href, print_abi_with_space, print_constness_with_space, print_default_space,
69 print_generic_bounds, print_where_clause, Buffer, HrefError, PrintWithSpace,
71 use crate::html::markdown::{HeadingOffset, Markdown, MarkdownHtml, MarkdownSummaryLine};
73 /// A pair of name and its optional document.
74 crate type NameDoc = (String, Option<String>);
76 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
77 crate::html::format::display_fn(move |f| {
78 if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { f.write_str(v) }
82 // Helper structs for rendering items/sidebars and carrying along contextual
85 /// Struct representing one entry in the JS search index. These are all emitted
86 /// by hand to a large JS file at the end of cache-creation.
88 crate struct IndexItem {
93 crate parent: Option<DefId>,
94 crate parent_idx: Option<usize>,
95 crate search_type: Option<IndexItemFunctionType>,
96 crate aliases: Box<[String]>,
99 /// A type used for the search index.
101 crate struct RenderType {
102 name: Option<String>,
103 generics: Option<Vec<String>>,
106 /// Full type of functions/methods in the search index.
108 crate struct IndexItemFunctionType {
109 inputs: Vec<TypeWithKind>,
110 output: Option<Vec<TypeWithKind>>,
113 impl Serialize for IndexItemFunctionType {
114 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
118 // If we couldn't figure out a type, just write `null`.
119 let mut iter = self.inputs.iter();
120 if match self.output {
121 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
122 None => iter.any(|ref i| i.ty.name.is_none()),
124 serializer.serialize_none()
126 let mut seq = serializer.serialize_seq(None)?;
127 seq.serialize_element(&self.inputs)?;
128 if let Some(output) = &self.output {
129 if output.len() > 1 {
130 seq.serialize_element(&output)?;
132 seq.serialize_element(&output[0])?;
141 crate struct TypeWithKind {
146 impl From<(RenderType, ItemType)> for TypeWithKind {
147 fn from(x: (RenderType, ItemType)) -> TypeWithKind {
148 TypeWithKind { ty: x.0, kind: x.1 }
152 impl Serialize for TypeWithKind {
153 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
157 let mut seq = serializer.serialize_seq(None)?;
158 seq.serialize_element(&self.ty.name)?;
159 seq.serialize_element(&self.kind)?;
160 if let Some(generics) = &self.ty.generics {
161 seq.serialize_element(generics)?;
167 #[derive(Debug, Clone)]
168 crate struct StylePath {
169 /// The path to the theme
171 /// What the `disabled` attribute should be set to in the HTML tag
172 crate disabled: bool,
175 fn write_srclink(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) {
176 if let Some(l) = cx.src_href(item) {
177 write!(buf, "<a class=\"srclink\" href=\"{}\" title=\"goto source code\">[src]</a>", l)
181 #[derive(Debug, Eq, PartialEq, Hash)]
188 fn new(mut url: String, name: String) -> ItemEntry {
189 while url.starts_with('/') {
192 ItemEntry { url, name }
197 crate fn print(&self) -> impl fmt::Display + '_ {
198 crate::html::format::display_fn(move |f| {
199 write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name))
204 impl PartialOrd for ItemEntry {
205 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
206 Some(self.cmp(other))
210 impl Ord for ItemEntry {
211 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
212 self.name.cmp(&other.name)
218 structs: FxHashSet<ItemEntry>,
219 enums: FxHashSet<ItemEntry>,
220 unions: FxHashSet<ItemEntry>,
221 primitives: FxHashSet<ItemEntry>,
222 traits: FxHashSet<ItemEntry>,
223 macros: FxHashSet<ItemEntry>,
224 functions: FxHashSet<ItemEntry>,
225 typedefs: FxHashSet<ItemEntry>,
226 opaque_tys: FxHashSet<ItemEntry>,
227 statics: FxHashSet<ItemEntry>,
228 constants: FxHashSet<ItemEntry>,
229 attributes: FxHashSet<ItemEntry>,
230 derives: FxHashSet<ItemEntry>,
231 trait_aliases: FxHashSet<ItemEntry>,
235 fn new() -> AllTypes {
236 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
238 structs: new_set(100),
240 unions: new_set(100),
241 primitives: new_set(26),
242 traits: new_set(100),
243 macros: new_set(100),
244 functions: new_set(100),
245 typedefs: new_set(100),
246 opaque_tys: new_set(100),
247 statics: new_set(100),
248 constants: new_set(100),
249 attributes: new_set(100),
250 derives: new_set(100),
251 trait_aliases: new_set(100),
255 fn append(&mut self, item_name: String, item_type: &ItemType) {
256 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
257 if let Some(name) = url.pop() {
258 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
260 let name = url.join("::");
262 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
263 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
264 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
265 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
266 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
267 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
268 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
269 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
270 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
271 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
272 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
273 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
274 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
275 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
283 fn print(self, f: &mut Buffer) {
284 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
286 let mut e: Vec<&ItemEntry> = e.iter().collect();
290 "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">",
291 title.replace(' ', "-"), // IDs cannot contain whitespaces.
297 write!(f, "<li>{}</li>", s.print());
300 f.write_str("</ul>");
306 <span class=\"in-band\">List of all items</span>\
307 <span class=\"out-of-band\">\
308 <span id=\"render-detail\">\
309 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
310 title=\"collapse all docs\">\
311 [<span class=\"inner\">−</span>]\
317 // Note: print_entries does not escape the title, because we know the current set of titles
318 // doesn't require escaping.
319 print_entries(f, &self.structs, "Structs", "structs");
320 print_entries(f, &self.enums, "Enums", "enums");
321 print_entries(f, &self.unions, "Unions", "unions");
322 print_entries(f, &self.primitives, "Primitives", "primitives");
323 print_entries(f, &self.traits, "Traits", "traits");
324 print_entries(f, &self.macros, "Macros", "macros");
325 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
326 print_entries(f, &self.derives, "Derive Macros", "derives");
327 print_entries(f, &self.functions, "Functions", "functions");
328 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
329 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
330 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
331 print_entries(f, &self.statics, "Statics", "statics");
332 print_entries(f, &self.constants, "Constants", "constants")
339 description: &'static str,
340 sub_settings: Vec<Setting>,
343 js_data_name: &'static str,
344 description: &'static str,
348 js_data_name: &'static str,
349 description: &'static str,
350 default_value: &'static str,
351 options: Vec<(String, String)>,
356 fn display(&self, root_path: &str, suffix: &str) -> String {
358 Setting::Section { description, ref sub_settings } => format!(
359 "<div class=\"setting-line\">\
360 <div class=\"title\">{}</div>\
361 <div class=\"sub-settings\">{}</div>
364 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
366 Setting::Toggle { js_data_name, description, default_value } => format!(
367 "<div class=\"setting-line\">\
368 <label class=\"toggle\">\
369 <input type=\"checkbox\" id=\"{}\" {}>\
370 <span class=\"slider\"></span>\
375 if default_value { " checked" } else { "" },
378 Setting::Select { js_data_name, description, default_value, ref options } => format!(
379 "<div class=\"setting-line\">\
381 <label class=\"select-wrapper\">\
382 <select id=\"{}\" autocomplete=\"off\">{}</select>\
383 <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
391 "<option value=\"{}\" {}>{}</option>",
393 if opt.0 == default_value { "selected" } else { "" },
396 .collect::<String>(),
404 impl From<(&'static str, &'static str, bool)> for Setting {
405 fn from(values: (&'static str, &'static str, bool)) -> Setting {
406 Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
410 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
411 fn from(values: (&'static str, Vec<T>)) -> Setting {
413 description: values.0,
414 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
419 fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
420 let theme_names: Vec<(String, String)> = themes
424 try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
427 Ok((theme.clone(), theme))
429 .collect::<Result<_, Error>>()?;
431 // (id, explanation, default value)
432 let settings: &[Setting] = &[
436 Setting::from(("use-system-theme", "Use system theme", true)),
438 js_data_name: "preferred-dark-theme",
439 description: "Preferred dark theme",
440 default_value: "dark",
441 options: theme_names.clone(),
444 js_data_name: "preferred-light-theme",
445 description: "Preferred light theme",
446 default_value: "light",
447 options: theme_names,
452 ("auto-hide-large-items", "Auto-hide item contents for large items.", true).into(),
453 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
454 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", false)
456 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
458 ("line-numbers", "Show line numbers on code examples", false).into(),
459 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
464 <span class=\"in-band\">Rustdoc settings</span>\
466 <div class=\"settings\">{}</div>\
467 <script src=\"{}settings{}.js\"></script>",
468 settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
478 parent: Option<&clean::Item>,
479 heading_offset: HeadingOffset,
481 if let Some(ref name) = item.name {
482 info!("Documenting {}", name);
484 document_item_info(w, cx, item, parent);
485 if parent.is_none() {
486 document_full_collapsible(w, item, cx, heading_offset);
488 document_full(w, item, cx, heading_offset);
492 /// Render md_text as markdown.
497 links: Vec<RenderedLink>,
498 heading_offset: HeadingOffset,
500 let mut ids = cx.id_map.borrow_mut();
503 "<div class=\"docblock\">{}</div>",
508 error_codes: cx.shared.codes,
509 edition: cx.shared.edition(),
510 playground: &cx.shared.playground,
517 /// Writes a documentation block containing only the first paragraph of the documentation. If the
518 /// docs are longer, a "Read more" link is appended to the end.
523 link: AssocItemLink<'_>,
524 parent: &clean::Item,
527 document_item_info(w, cx, item, Some(parent));
531 if let Some(s) = item.doc_value() {
532 let mut summary_html = MarkdownSummaryLine(&s, &item.links(cx)).into_string();
534 if s.contains('\n') {
535 let link = format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link, cx));
537 if let Some(idx) = summary_html.rfind("</p>") {
538 summary_html.insert_str(idx, &link);
540 summary_html.push_str(&link);
544 write!(w, "<div class='docblock'>{}</div>", summary_html,);
548 fn document_full_collapsible(
552 heading_offset: HeadingOffset,
554 document_full_inner(w, item, cx, true, heading_offset);
561 heading_offset: HeadingOffset,
563 document_full_inner(w, item, cx, false, heading_offset);
566 fn document_full_inner(
570 is_collapsible: bool,
571 heading_offset: HeadingOffset,
573 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
574 debug!("Doc block: =====\n{}\n=====", s);
577 "<details class=\"rustdoc-toggle top-doc\" open>\
578 <summary class=\"hideme\">\
579 <span>Expand description</span>\
582 render_markdown(w, cx, &s, item.links(cx), heading_offset);
583 w.write_str("</details>");
585 render_markdown(w, cx, &s, item.links(cx), heading_offset);
590 /// Add extra information about an item such as:
594 /// * Required features (through the `doc_cfg` feature)
595 fn document_item_info(
599 parent: Option<&clean::Item>,
601 let item_infos = short_item_info(item, cx, parent);
602 if !item_infos.is_empty() {
603 w.write_str("<div class=\"item-info\">");
604 for info in item_infos {
607 w.write_str("</div>");
611 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
612 let cfg = match (&item.cfg, parent.and_then(|p| p.cfg.as_ref())) {
613 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
614 (cfg, _) => cfg.as_deref().cloned(),
617 debug!("Portability {:?} - {:?} = {:?}", item.cfg, parent.and_then(|p| p.cfg.as_ref()), cfg);
619 Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
622 /// Render the stability, deprecation and portability information that is displayed at the top of
623 /// the item's documentation.
627 parent: Option<&clean::Item>,
629 let mut extra_info = vec![];
630 let error_codes = cx.shared.codes;
632 if let Some(depr @ Deprecation { note, since, is_since_rustc_version: _, suggestion: _ }) =
633 item.deprecation(cx.tcx())
635 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
636 // but only display the future-deprecation messages for #[rustc_deprecated].
637 let mut message = if let Some(since) = since {
638 let since = &since.as_str();
639 if !stability::deprecation_in_effect(&depr) {
641 String::from("Deprecating in a future Rust version")
643 format!("Deprecating in {}", Escape(since))
646 format!("Deprecated since {}", Escape(since))
649 String::from("Deprecated")
652 if let Some(note) = note {
653 let note = note.as_str();
654 let mut ids = cx.id_map.borrow_mut();
655 let html = MarkdownHtml(
660 &cx.shared.playground,
662 message.push_str(&format!(": {}", html.into_string()));
664 extra_info.push(format!(
665 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
670 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
671 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
672 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
675 .filter(|stab| stab.feature != sym::rustc_private)
676 .map(|stab| (stab.level, stab.feature))
679 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
681 let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
682 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
683 feature.push_str(&format!(
684 " <a href=\"{url}{issue}\">#{issue}</a>",
690 message.push_str(&format!(" ({})", feature));
692 if let Some(unstable_reason) = reason {
693 let mut ids = cx.id_map.borrow_mut();
695 "<details><summary>{}</summary>{}</details>",
698 &unstable_reason.as_str(),
702 &cx.shared.playground,
708 extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
711 if let Some(portability) = portability(item, parent) {
712 extra_info.push(portability);
718 // Render the list of items inside one of the sections "Trait Implementations",
719 // "Auto Trait Implementations," "Blanket Trait Implementations" (on struct/enum pages).
720 fn render_impls(cx: &Context<'_>, w: &mut Buffer, impls: &[&&Impl], containing_item: &clean::Item) {
722 let mut rendered_impls = impls
725 let did = i.trait_did().unwrap();
726 let provided_trait_methods = i.inner_impl().provided_trait_methods(tcx);
727 let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_trait_methods);
728 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
738 ImplRenderingParameters {
740 is_on_foreign_type: false,
741 show_default_items: true,
742 show_non_assoc_items: true,
743 toggle_open_by_default: true,
748 .collect::<Vec<_>>();
749 rendered_impls.sort();
750 w.write_str(&rendered_impls.join(""));
753 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>, cx: &Context<'_>) -> String {
754 use crate::formats::item_type::ItemType::*;
756 let name = it.name.as_ref().unwrap();
757 let ty = match it.type_() {
758 Typedef | AssocType => AssocType,
762 let anchor = format!("#{}.{}", ty, name);
764 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
765 AssocItemLink::Anchor(None) => anchor,
766 AssocItemLink::GotoSource(did, _) => {
767 href(did.expect_def_id(), cx).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
776 _default: Option<&String>,
777 link: AssocItemLink<'_>,
783 "{}{}const <a href=\"{}\" class=\"constant\">{}</a>: {}",
785 it.visibility.print_with_space(it.def_id, cx),
786 naive_assoc_href(it, link, cx),
787 it.name.as_ref().unwrap(),
795 bounds: &[clean::GenericBound],
796 default: Option<&clean::Type>,
797 link: AssocItemLink<'_>,
803 "{}type <a href=\"{}\" class=\"type\">{}</a>",
805 naive_assoc_href(it, link, cx),
806 it.name.as_ref().unwrap()
808 if !bounds.is_empty() {
809 write!(w, ": {}", print_generic_bounds(bounds, cx))
811 if let Some(default) = default {
812 write!(w, " = {}", default.print(cx))
816 fn render_stability_since_raw(
819 const_stability: Option<&ConstStability>,
820 containing_ver: Option<&str>,
821 containing_const_ver: Option<&str>,
823 let ver = ver.filter(|inner| !inner.is_empty());
825 match (ver, const_stability) {
826 // stable and const stable
827 (Some(v), Some(ConstStability { level: StabilityLevel::Stable { since }, .. }))
828 if Some(since.as_str()).as_deref() != containing_const_ver =>
832 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
836 // stable and const unstable
839 Some(ConstStability { level: StabilityLevel::Unstable { issue, .. }, feature, .. }),
843 "<span class=\"since\" title=\"Stable since Rust version {0}, const unstable\">{0} (const: ",
846 if let Some(n) = issue {
849 "<a href=\"https://github.com/rust-lang/rust/issues/{}\" title=\"Tracking issue for {}\">unstable</a>",
853 write!(w, "unstable");
855 write!(w, ")</span>");
858 (Some(v), _) if ver != containing_ver => {
861 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
869 fn render_assoc_item(
872 link: AssocItemLink<'_>,
879 header: hir::FnHeader,
882 link: AssocItemLink<'_>,
886 let name = meth.name.as_ref().unwrap();
887 let href = match link {
888 AssocItemLink::Anchor(Some(ref id)) => Some(format!("#{}", id)),
889 AssocItemLink::Anchor(None) => Some(format!("#{}.{}", meth.type_(), name)),
890 AssocItemLink::GotoSource(did, provided_methods) => {
891 // We're creating a link from an impl-item to the corresponding
892 // trait-item and need to map the anchored type accordingly.
893 let ty = if provided_methods.contains(&name) {
899 match (href(did.expect_def_id(), cx), ty) {
900 (Ok(p), ty) => Some(format!("{}#{}.{}", p.0, ty, name)),
901 (Err(HrefError::DocumentationNotBuilt), ItemType::TyMethod) => None,
902 (Err(_), ty) => Some(format!("#{}.{}", ty, name)),
906 let vis = meth.visibility.print_with_space(meth.def_id, cx).to_string();
908 print_constness_with_space(&header.constness, meth.const_stability(cx.tcx()));
909 let asyncness = header.asyncness.print_with_space();
910 let unsafety = header.unsafety.print_with_space();
911 let defaultness = print_default_space(meth.is_default());
912 let abi = print_abi_with_space(header.abi).to_string();
914 // NOTE: `{:#}` does not print HTML formatting, `{}` does. So `g.print` can't be reused between the length calculation and `write!`.
915 let generics_len = format!("{:#}", g.print(cx)).len();
916 let mut header_len = "fn ".len()
923 + name.as_str().len()
926 let (indent, indent_str, end_newline) = if parent == ItemType::Trait {
928 let indent_str = " ";
929 render_attributes_in_pre(w, meth, indent_str);
930 (4, indent_str, false)
932 render_attributes_in_code(w, meth);
935 w.reserve(header_len + "<a href=\"\" class=\"fnname\">{".len() + "</a>".len());
938 "{indent}{vis}{constness}{asyncness}{unsafety}{defaultness}{abi}fn <a {href} class=\"fnname\">{name}</a>\
939 {generics}{decl}{notable_traits}{where_clause}",
942 constness = constness,
943 asyncness = asyncness,
945 defaultness = defaultness,
947 // links without a href are valid - https://www.w3schools.com/tags/att_a_href.asp
948 href = href.map(|href| format!("href=\"{}\"", href)).unwrap_or_else(|| "".to_string()),
950 generics = g.print(cx),
951 decl = d.full_print(header_len, indent, header.asyncness, cx),
952 notable_traits = notable_traits_decl(&d, cx),
953 where_clause = print_where_clause(g, cx, indent, end_newline),
957 clean::StrippedItem(..) => {}
958 clean::TyMethodItem(ref m) => {
959 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
961 clean::MethodItem(ref m, _) => {
962 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
964 clean::AssocConstItem(ref ty, ref default) => assoc_const(
970 if parent == ItemType::Trait { " " } else { "" },
973 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
979 if parent == ItemType::Trait { " " } else { "" },
982 _ => panic!("render_assoc_item called on non-associated-item"),
986 const ALLOWED_ATTRIBUTES: &[Symbol] =
987 &[sym::export_name, sym::link_section, sym::no_mangle, sym::repr, sym::non_exhaustive];
989 fn attributes(it: &clean::Item) -> Vec<String> {
994 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
995 Some(pprust::attribute_to_string(&attr).replace("\n", "").replace(" ", " "))
1003 // When an attribute is rendered inside a `<pre>` tag, it is formatted using
1004 // a whitespace prefix and newline.
1005 fn render_attributes_in_pre(w: &mut Buffer, it: &clean::Item, prefix: &str) {
1006 for a in attributes(it) {
1007 writeln!(w, "{}{}", prefix, a);
1011 // When an attribute is rendered inside a <code> tag, it is formatted using
1012 // a div to produce a newline after it.
1013 fn render_attributes_in_code(w: &mut Buffer, it: &clean::Item) {
1014 for a in attributes(it) {
1015 write!(w, "<div class=\"code-attribute\">{}</div>", a);
1019 #[derive(Copy, Clone)]
1020 enum AssocItemLink<'a> {
1021 Anchor(Option<&'a str>),
1022 GotoSource(ItemId, &'a FxHashSet<Symbol>),
1025 impl<'a> AssocItemLink<'a> {
1026 fn anchor(&self, id: &'a str) -> Self {
1028 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
1029 ref other => *other,
1034 fn render_assoc_items(
1037 containing_item: &clean::Item,
1039 what: AssocItemRender<'_>,
1041 info!("Documenting associated items of {:?}", containing_item.name);
1042 let cache = cx.cache();
1043 let v = match cache.impls.get(&it) {
1047 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
1048 if !non_trait.is_empty() {
1049 let render_mode = match what {
1050 AssocItemRender::All => {
1052 "<h2 id=\"implementations\" class=\"small-section-header\">\
1053 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
1058 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
1061 "<h2 id=\"deref-methods\" class=\"small-section-header\">\
1062 <span>Methods from {trait_}<Target = {type_}></span>\
1063 <a href=\"#deref-methods\" class=\"anchor\"></a>\
1065 trait_ = trait_.print(cx),
1066 type_ = type_.print(cx),
1068 RenderMode::ForDeref { mut_: deref_mut_ }
1071 for i in &non_trait {
1077 AssocItemLink::Anchor(None),
1081 ImplRenderingParameters {
1082 show_def_docs: true,
1083 is_on_foreign_type: false,
1084 show_default_items: true,
1085 show_non_assoc_items: true,
1086 toggle_open_by_default: true,
1091 if let AssocItemRender::DerefFor { .. } = what {
1094 if !traits.is_empty() {
1096 traits.iter().find(|t| t.trait_did() == cx.tcx().lang_items().deref_trait());
1097 if let Some(impl_) = deref_impl {
1099 traits.iter().any(|t| t.trait_did() == cx.tcx().lang_items().deref_mut_trait());
1100 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut);
1102 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
1103 traits.iter().partition(|t| t.inner_impl().synthetic);
1104 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
1105 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
1107 let mut impls = Buffer::empty_from(&w);
1108 render_impls(cx, &mut impls, &concrete, containing_item);
1109 let impls = impls.into_inner();
1110 if !impls.is_empty() {
1113 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
1114 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
1116 <div id=\"trait-implementations-list\">{}</div>",
1121 if !synthetic.is_empty() {
1123 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
1124 Auto Trait Implementations\
1125 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
1127 <div id=\"synthetic-implementations-list\">",
1129 render_impls(cx, w, &synthetic, containing_item);
1130 w.write_str("</div>");
1133 if !blanket_impl.is_empty() {
1135 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
1136 Blanket Implementations\
1137 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
1139 <div id=\"blanket-implementations-list\">",
1141 render_impls(cx, w, &blanket_impl, containing_item);
1142 w.write_str("</div>");
1147 fn render_deref_methods(
1151 container_item: &clean::Item,
1154 let cache = cx.cache();
1155 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
1156 let (target, real_target) = impl_
1160 .find_map(|item| match *item.kind {
1161 clean::TypedefItem(ref t, true) => Some(match *t {
1162 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
1163 _ => (&t.type_, &t.type_),
1167 .expect("Expected associated type binding");
1168 debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target);
1170 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
1171 if let Some(did) = target.def_id_full(cache) {
1172 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cache) {
1173 // `impl Deref<Target = S> for S`
1174 if did == type_did {
1175 // Avoid infinite cycles
1179 render_assoc_items(w, cx, container_item, did, what);
1181 if let Some(prim) = target.primitive_type() {
1182 if let Some(&did) = cache.primitive_locations.get(&prim) {
1183 render_assoc_items(w, cx, container_item, did, what);
1189 fn should_render_item(item: &clean::Item, deref_mut_: bool, tcx: TyCtxt<'_>) -> bool {
1190 let self_type_opt = match *item.kind {
1191 clean::MethodItem(ref method, _) => method.decl.self_type(),
1192 clean::TyMethodItem(ref method) => method.decl.self_type(),
1196 if let Some(self_ty) = self_type_opt {
1197 let (by_mut_ref, by_box, by_value) = match self_ty {
1198 SelfTy::SelfBorrowed(_, mutability)
1199 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
1200 (mutability == Mutability::Mut, false, false)
1202 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
1203 (false, Some(did) == tcx.lang_items().owned_box(), false)
1205 SelfTy::SelfValue => (false, false, true),
1206 _ => (false, false, false),
1209 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
1215 fn notable_traits_decl(decl: &clean::FnDecl, cx: &Context<'_>) -> String {
1216 let mut out = Buffer::html();
1218 if let Some(did) = decl.output.def_id_full(cx.cache()) {
1219 if let Some(impls) = cx.cache().impls.get(&did) {
1221 let impl_ = i.inner_impl();
1222 if let Some(trait_) = &impl_.trait_ {
1223 let trait_did = trait_.def_id();
1225 if cx.cache().traits.get(&trait_did).map_or(false, |t| t.is_notable) {
1229 "<div class=\"notable\">Notable traits for {}</div>\
1230 <code class=\"content\">",
1231 impl_.for_.print(cx)
1235 //use the "where" class here to make it small
1238 "<span class=\"where fmt-newline\">{}</span>",
1239 impl_.print(false, cx)
1241 for it in &impl_.items {
1242 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1243 out.push_str("<span class=\"where fmt-newline\"> ");
1244 let empty_set = FxHashSet::default();
1246 AssocItemLink::GotoSource(trait_did.into(), &empty_set);
1247 assoc_type(&mut out, it, &[], Some(&tydef.type_), src_link, "", cx);
1248 out.push_str(";</span>");
1257 if !out.is_empty() {
1260 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
1261 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
1263 out.push_str("</code></span></div></span></span>");
1269 #[derive(Clone, Copy, Debug)]
1270 struct ImplRenderingParameters {
1271 show_def_docs: bool,
1272 is_on_foreign_type: bool,
1273 show_default_items: bool,
1274 /// Whether or not to show methods.
1275 show_non_assoc_items: bool,
1276 toggle_open_by_default: bool,
1283 parent: &clean::Item,
1284 link: AssocItemLink<'_>,
1285 render_mode: RenderMode,
1286 use_absolute: Option<bool>,
1288 rendering_params: ImplRenderingParameters,
1290 let cache = cx.cache();
1291 let traits = &cache.traits;
1292 let trait_ = i.trait_did().map(|did| &traits[&did]);
1293 let mut close_tags = String::new();
1295 // For trait implementations, the `interesting` output contains all methods that have doc
1296 // comments, and the `boring` output contains all methods that do not. The distinction is
1297 // used to allow hiding the boring methods.
1298 // `containing_item` is used for rendering stability info. If the parent is a trait impl,
1299 // `containing_item` will the grandparent, since trait impls can't have stability attached.
1301 boring: &mut Buffer,
1302 interesting: &mut Buffer,
1305 parent: &clean::Item,
1306 containing_item: &clean::Item,
1307 link: AssocItemLink<'_>,
1308 render_mode: RenderMode,
1309 is_default_item: bool,
1310 trait_: Option<&clean::Trait>,
1311 rendering_params: ImplRenderingParameters,
1313 let item_type = item.type_();
1314 let name = item.name.as_ref().unwrap();
1316 let render_method_item = rendering_params.show_non_assoc_items
1317 && match render_mode {
1318 RenderMode::Normal => true,
1319 RenderMode::ForDeref { mut_: deref_mut_ } => {
1320 should_render_item(&item, deref_mut_, cx.tcx())
1324 let in_trait_class = if trait_.is_some() { " trait-impl" } else { "" };
1326 let mut doc_buffer = Buffer::empty_from(boring);
1327 let mut info_buffer = Buffer::empty_from(boring);
1328 let mut short_documented = true;
1330 if render_method_item {
1331 if !is_default_item {
1332 if let Some(t) = trait_ {
1333 // The trait item may have been stripped so we might not
1334 // find any documentation or stability for it.
1335 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
1336 // We need the stability of the item from the trait
1337 // because impls can't have a stability.
1338 if item.doc_value().is_some() {
1339 document_item_info(&mut info_buffer, cx, it, Some(parent));
1340 document_full(&mut doc_buffer, item, cx, HeadingOffset::H5);
1341 short_documented = false;
1343 // In case the item isn't documented,
1344 // provide short documentation from the trait.
1351 rendering_params.show_def_docs,
1356 document_item_info(&mut info_buffer, cx, item, Some(parent));
1357 if rendering_params.show_def_docs {
1358 document_full(&mut doc_buffer, item, cx, HeadingOffset::H5);
1359 short_documented = false;
1369 rendering_params.show_def_docs,
1373 let w = if short_documented && trait_.is_some() { interesting } else { boring };
1375 let toggled = !doc_buffer.is_empty();
1377 let method_toggle_class =
1378 if item_type == ItemType::Method { " method-toggle" } else { "" };
1379 write!(w, "<details class=\"rustdoc-toggle{}\" open><summary>", method_toggle_class);
1382 clean::MethodItem(..) | clean::TyMethodItem(_) => {
1383 // Only render when the method is not static or we allow static methods
1384 if render_method_item {
1385 let id = cx.derive_id(format!("{}.{}", item_type, name));
1386 let source_id = trait_
1387 .and_then(|trait_| {
1388 trait_.items.iter().find(|item| {
1389 item.name.map(|n| n.as_str().eq(&name.as_str())).unwrap_or(false)
1392 .map(|item| format!("{}.{}", item.type_(), name));
1395 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1396 id, item_type, in_trait_class,
1398 render_rightside(w, cx, item, containing_item);
1399 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1400 w.write_str("<h4 class=\"code-header\">");
1404 link.anchor(source_id.as_ref().unwrap_or(&id)),
1408 w.write_str("</h4>");
1409 w.write_str("</div>");
1412 clean::TypedefItem(ref tydef, _) => {
1413 let source_id = format!("{}.{}", ItemType::AssocType, name);
1414 let id = cx.derive_id(source_id.clone());
1417 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1418 id, item_type, in_trait_class
1420 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1421 w.write_str("<h4 class=\"code-header\">");
1427 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1431 w.write_str("</h4>");
1432 w.write_str("</div>");
1434 clean::AssocConstItem(ref ty, ref default) => {
1435 let source_id = format!("{}.{}", item_type, name);
1436 let id = cx.derive_id(source_id.clone());
1439 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1440 id, item_type, in_trait_class
1442 render_rightside(w, cx, item, containing_item);
1443 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1444 w.write_str("<h4 class=\"code-header\">");
1450 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1454 w.write_str("</h4>");
1455 w.write_str("</div>");
1457 clean::AssocTypeItem(ref bounds, ref default) => {
1458 let source_id = format!("{}.{}", item_type, name);
1459 let id = cx.derive_id(source_id.clone());
1460 write!(w, "<div id=\"{}\" class=\"{}{}\">", id, item_type, in_trait_class,);
1461 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1462 w.write_str("<h4 class=\"code-header\">");
1468 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1472 w.write_str("</h4>");
1473 w.write_str("</div>");
1475 clean::StrippedItem(..) => return,
1476 _ => panic!("can't make docs for trait item with name {:?}", item.name),
1479 w.push_buffer(info_buffer);
1481 w.write_str("</summary>");
1482 w.push_buffer(doc_buffer);
1483 w.push_str("</details>");
1487 let mut impl_items = Buffer::empty_from(w);
1488 let mut default_impl_items = Buffer::empty_from(w);
1490 for trait_item in &i.inner_impl().items {
1492 &mut default_impl_items,
1496 if trait_.is_some() { &i.impl_item } else { parent },
1501 trait_.map(|t| &t.trait_),
1506 fn render_default_items(
1507 boring: &mut Buffer,
1508 interesting: &mut Buffer,
1512 parent: &clean::Item,
1513 containing_item: &clean::Item,
1514 render_mode: RenderMode,
1515 rendering_params: ImplRenderingParameters,
1517 for trait_item in &t.items {
1518 let n = trait_item.name;
1519 if i.items.iter().any(|m| m.name == n) {
1522 let did = i.trait_.as_ref().unwrap().def_id();
1523 let provided_methods = i.provided_trait_methods(cx.tcx());
1524 let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_methods);
1542 // If we've implemented a trait, then also emit documentation for all
1543 // default items which weren't overridden in the implementation block.
1544 // We don't emit documentation for default items if they appear in the
1545 // Implementations on Foreign Types or Implementors sections.
1546 if rendering_params.show_default_items {
1547 if let Some(t) = trait_ {
1548 render_default_items(
1549 &mut default_impl_items,
1561 if render_mode == RenderMode::Normal {
1562 let toggled = !(impl_items.is_empty() && default_impl_items.is_empty());
1564 close_tags.insert_str(0, "</details>");
1567 "<details class=\"rustdoc-toggle implementors-toggle\"{}>",
1568 if rendering_params.toggle_open_by_default { " open" } else { "" }
1570 write!(w, "<summary>")
1572 render_impl_summary(
1578 rendering_params.show_def_docs,
1580 rendering_params.is_on_foreign_type,
1584 write!(w, "</summary>")
1587 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
1588 let mut ids = cx.id_map.borrow_mut();
1591 "<div class=\"docblock\">{}</div>",
1594 links: &i.impl_item.links(cx),
1596 error_codes: cx.shared.codes,
1597 edition: cx.shared.edition(),
1598 playground: &cx.shared.playground,
1599 heading_offset: HeadingOffset::H2
1605 if !default_impl_items.is_empty() || !impl_items.is_empty() {
1606 w.write_str("<div class=\"impl-items\">");
1607 w.push_buffer(default_impl_items);
1608 w.push_buffer(impl_items);
1609 close_tags.insert_str(0, "</div>");
1611 w.write_str(&close_tags);
1614 // Render the items that appear on the right side of methods, impls, and
1615 // associated types. For example "1.0.0 (const: 1.39.0) [src]".
1616 fn render_rightside(
1620 containing_item: &clean::Item,
1624 write!(w, "<div class=\"rightside\">");
1625 render_stability_since_raw(
1627 item.stable_since(tcx).as_deref(),
1628 item.const_stability(tcx),
1629 containing_item.stable_since(tcx).as_deref(),
1630 containing_item.const_stable_since(tcx).as_deref(),
1633 write_srclink(cx, item, w);
1634 w.write_str("</div>");
1637 pub(crate) fn render_impl_summary(
1641 parent: &clean::Item,
1642 containing_item: &clean::Item,
1643 show_def_docs: bool,
1644 use_absolute: Option<bool>,
1645 is_on_foreign_type: bool,
1646 // This argument is used to reference same type with different paths to avoid duplication
1647 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
1650 let id = cx.derive_id(match i.inner_impl().trait_ {
1652 if is_on_foreign_type {
1653 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t, cx)
1655 format!("impl-{}", small_url_encode(format!("{:#}", t.print(cx))))
1658 None => "impl".to_string(),
1660 let aliases = if aliases.is_empty() {
1663 format!(" data-aliases=\"{}\"", aliases.join(","))
1665 write!(w, "<div id=\"{}\" class=\"impl has-srclink\"{}>", id, aliases);
1666 render_rightside(w, cx, &i.impl_item, containing_item);
1667 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1668 write!(w, "<h3 class=\"code-header in-band\">");
1670 if let Some(use_absolute) = use_absolute {
1671 write!(w, "{}", i.inner_impl().print(use_absolute, cx));
1673 for it in &i.inner_impl().items {
1674 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1675 w.write_str("<span class=\"where fmt-newline\"> ");
1676 assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "", cx);
1677 w.write_str(";</span>");
1682 write!(w, "{}", i.inner_impl().print(false, cx));
1686 let is_trait = i.inner_impl().trait_.is_some();
1688 if let Some(portability) = portability(&i.impl_item, Some(parent)) {
1689 write!(w, "<div class=\"item-info\">{}</div>", portability);
1693 w.write_str("</div>");
1696 fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) {
1697 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
1701 || it.is_primitive()
1709 "<h2 class=\"location\">{}{}</h2>",
1711 clean::StructItem(..) => "Struct ",
1712 clean::TraitItem(..) => "Trait ",
1713 clean::PrimitiveItem(..) => "Primitive Type ",
1714 clean::UnionItem(..) => "Union ",
1715 clean::EnumItem(..) => "Enum ",
1716 clean::TypedefItem(..) => "Type Definition ",
1717 clean::ForeignTypeItem => "Foreign Type ",
1718 clean::ModuleItem(..) =>
1726 it.name.as_ref().unwrap()
1731 if let Some(ref version) = cx.cache().crate_version {
1734 "<div class=\"block version\">\
1735 <div class=\"narrow-helper\"></div>\
1743 buffer.write_str("<div class=\"sidebar-elems\">");
1747 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
1748 it.name.as_ref().expect("crates always have a name"),
1753 clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s),
1754 clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t),
1755 clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it),
1756 clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u),
1757 clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e),
1758 clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it),
1759 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
1760 clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, it),
1764 // The sidebar is designed to display sibling functions, modules and
1765 // other miscellaneous information. since there are lots of sibling
1766 // items (and that causes quadratic growth in large modules),
1767 // we refactor common parts into a shared JavaScript file per module.
1768 // still, we don't move everything into JS because we want to preserve
1769 // as much HTML as possible in order to allow non-JS-enabled browsers
1770 // to navigate the documentation (though slightly inefficiently).
1773 buffer.write_str("<h2 class=\"location\">Other items in<br>");
1774 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
1776 buffer.write_str("::<wbr>");
1780 "<a href=\"{}index.html\">{}</a>",
1781 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
1785 buffer.write_str("</h2>");
1788 // Sidebar refers to the enclosing module, not this module.
1789 let relpath = if it.is_mod() && parentlen != 0 { "./" } else { "" };
1792 "<div id=\"sidebar-vars\" data-name=\"{name}\" data-ty=\"{ty}\" data-relpath=\"{path}\">\
1794 name = it.name.unwrap_or(kw::Empty),
1798 write!(buffer, "<script defer src=\"{}sidebar-items.js\"></script>", relpath);
1799 // Closes sidebar-elems div.
1800 buffer.write_str("</div>");
1803 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
1804 if used_links.insert(url.clone()) {
1808 while !used_links.insert(format!("{}-{}", url, add)) {
1811 format!("{}-{}", url, add)
1814 struct SidebarLink {
1819 impl fmt::Display for SidebarLink {
1820 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1821 write!(f, "<a href=\"#{}\">{}</a>", self.url, self.name)
1825 impl PartialEq for SidebarLink {
1826 fn eq(&self, other: &Self) -> bool {
1827 self.url == other.url
1831 impl Eq for SidebarLink {}
1833 impl PartialOrd for SidebarLink {
1834 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1835 Some(self.cmp(other))
1839 impl Ord for SidebarLink {
1840 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1841 self.url.cmp(&other.url)
1848 used_links: &mut FxHashSet<String>,
1851 ) -> Vec<SidebarLink> {
1854 .filter_map(|item| match item.name {
1855 Some(name) if !name.is_empty() && item.is_method() => {
1856 if !for_deref || should_render_item(item, deref_mut, tcx) {
1859 url: get_next_url(used_links, format!("method.{}", name)),
1867 .collect::<Vec<_>>()
1870 fn get_associated_constants(
1872 used_links: &mut FxHashSet<String>,
1873 ) -> Vec<SidebarLink> {
1876 .filter_map(|item| match item.name {
1877 Some(name) if !name.is_empty() && item.is_associated_const() => Some(SidebarLink {
1879 url: get_next_url(used_links, format!("associatedconstant.{}", name)),
1883 .collect::<Vec<_>>()
1886 // The point is to url encode any potential character from a type with genericity.
1887 fn small_url_encode(s: String) -> String {
1888 let mut st = String::new();
1889 let mut last_match = 0;
1890 for (idx, c) in s.char_indices() {
1891 let escaped = match c {
1907 st += &s[last_match..idx];
1909 // NOTE: we only expect single byte characters here - which is fine as long as we
1910 // only match single byte characters
1911 last_match = idx + 1;
1914 if last_match != 0 {
1915 st += &s[last_match..];
1922 fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) {
1923 let did = it.def_id.expect_def_id();
1924 let cache = cx.cache();
1925 if let Some(v) = cache.impls.get(&did) {
1926 let mut used_links = FxHashSet::default();
1929 let used_links_bor = &mut used_links;
1930 let mut assoc_consts = v
1932 .flat_map(|i| get_associated_constants(i.inner_impl(), used_links_bor))
1933 .collect::<Vec<_>>();
1934 if !assoc_consts.is_empty() {
1935 // We want links' order to be reproducible so we don't use unstable sort.
1936 assoc_consts.sort();
1939 "<h3 class=\"sidebar-title\">\
1940 <a href=\"#implementations\">Associated Constants</a>\
1942 <div class=\"sidebar-links\">",
1944 for line in assoc_consts {
1945 write!(out, "{}", line);
1947 out.push_str("</div>");
1951 .filter(|i| i.inner_impl().trait_.is_none())
1952 .flat_map(|i| get_methods(i.inner_impl(), false, used_links_bor, false, cx.tcx()))
1953 .collect::<Vec<_>>();
1954 if !methods.is_empty() {
1955 // We want links' order to be reproducible so we don't use unstable sort.
1959 "<h3 class=\"sidebar-title\"><a href=\"#implementations\">Methods</a></h3>\
1960 <div class=\"sidebar-links\">",
1962 for line in methods {
1963 write!(out, "{}", line);
1965 out.push_str("</div>");
1969 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
1970 if let Some(impl_) =
1971 v.iter().find(|i| i.trait_did() == cx.tcx().lang_items().deref_trait())
1973 sidebar_deref_methods(cx, out, impl_, v);
1976 let format_impls = |impls: Vec<&Impl>| {
1977 let mut links = FxHashSet::default();
1982 if let Some(ref i) = it.inner_impl().trait_ {
1983 let i_display = format!("{:#}", i.print(cx));
1984 let out = Escape(&i_display);
1985 let encoded = small_url_encode(format!("{:#}", i.print(cx)));
1986 let generated = format!(
1987 "<a href=\"#impl-{}\">{}{}</a>",
1989 if it.inner_impl().negative_polarity { "!" } else { "" },
1992 if links.insert(generated.clone()) { Some(generated) } else { None }
1997 .collect::<Vec<String>>();
2002 let write_sidebar_links = |out: &mut Buffer, links: Vec<String>| {
2003 out.push_str("<div class=\"sidebar-links\">");
2005 out.push_str(&link);
2007 out.push_str("</div>");
2010 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
2011 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
2012 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
2014 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
2016 let concrete_format = format_impls(concrete);
2017 let synthetic_format = format_impls(synthetic);
2018 let blanket_format = format_impls(blanket_impl);
2020 if !concrete_format.is_empty() {
2022 "<h3 class=\"sidebar-title\"><a href=\"#trait-implementations\">\
2023 Trait Implementations</a></h3>",
2025 write_sidebar_links(out, concrete_format);
2028 if !synthetic_format.is_empty() {
2030 "<h3 class=\"sidebar-title\"><a href=\"#synthetic-implementations\">\
2031 Auto Trait Implementations</a></h3>",
2033 write_sidebar_links(out, synthetic_format);
2036 if !blanket_format.is_empty() {
2038 "<h3 class=\"sidebar-title\"><a href=\"#blanket-implementations\">\
2039 Blanket Implementations</a></h3>",
2041 write_sidebar_links(out, blanket_format);
2047 fn sidebar_deref_methods(cx: &Context<'_>, out: &mut Buffer, impl_: &Impl, v: &Vec<Impl>) {
2050 debug!("found Deref: {:?}", impl_);
2051 if let Some((target, real_target)) =
2052 impl_.inner_impl().items.iter().find_map(|item| match *item.kind {
2053 clean::TypedefItem(ref t, true) => Some(match *t {
2054 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
2055 _ => (&t.type_, &t.type_),
2060 debug!("found target, real_target: {:?} {:?}", target, real_target);
2061 if let Some(did) = target.def_id_full(c) {
2062 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(c) {
2063 // `impl Deref<Target = S> for S`
2064 if did == type_did {
2065 // Avoid infinite cycles
2070 let deref_mut = v.iter().any(|i| i.trait_did() == cx.tcx().lang_items().deref_mut_trait());
2071 let inner_impl = target
2074 target.primitive_type().and_then(|prim| c.primitive_locations.get(&prim).cloned())
2076 .and_then(|did| c.impls.get(&did));
2077 if let Some(impls) = inner_impl {
2078 debug!("found inner_impl: {:?}", impls);
2079 let mut used_links = FxHashSet::default();
2082 .filter(|i| i.inner_impl().trait_.is_none())
2084 get_methods(i.inner_impl(), true, &mut used_links, deref_mut, cx.tcx())
2086 .collect::<Vec<_>>();
2087 if !ret.is_empty() {
2090 "<h3 class=\"sidebar-title\"><a href=\"#deref-methods\">Methods from {}<Target={}></a></h3>",
2091 Escape(&format!("{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print(cx))),
2092 Escape(&format!("{:#}", real_target.print(cx))),
2094 // We want links' order to be reproducible so we don't use unstable sort.
2096 out.push_str("<div class=\"sidebar-links\">");
2098 write!(out, "{}", link);
2100 out.push_str("</div>");
2106 fn sidebar_struct(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
2107 let mut sidebar = Buffer::new();
2108 let fields = get_struct_fields_name(&s.fields);
2110 if !fields.is_empty() {
2111 if let CtorKind::Fictive = s.struct_type {
2113 "<h3 class=\"sidebar-title\"><a href=\"#fields\">Fields</a></h3>\
2114 <div class=\"sidebar-links\">",
2117 for field in fields {
2118 sidebar.push_str(&field);
2121 sidebar.push_str("</div>");
2122 } else if let CtorKind::Fn = s.struct_type {
2124 .push_str("<h3 class=\"sidebar-title\"><a href=\"#fields\">Tuple Fields</a></h3>");
2128 sidebar_assoc_items(cx, &mut sidebar, it);
2130 if !sidebar.is_empty() {
2131 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2135 fn get_id_for_impl_on_foreign_type(
2137 trait_: &clean::Path,
2140 small_url_encode(format!("impl-{:#}-for-{:#}", trait_.print(cx), for_.print(cx)))
2143 fn extract_for_impl_name(item: &clean::Item, cx: &Context<'_>) -> Option<(String, String)> {
2145 clean::ItemKind::ImplItem(ref i) => {
2146 if let Some(ref trait_) = i.trait_ {
2147 // Alternative format produces no URLs,
2148 // so this parameter does nothing.
2150 format!("{:#}", i.for_.print(cx)),
2151 get_id_for_impl_on_foreign_type(&i.for_, trait_, cx),
2161 fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
2162 buf.write_str("<div class=\"block items\">");
2164 fn print_sidebar_section(
2166 items: &[clean::Item],
2168 filter: impl Fn(&clean::Item) -> bool,
2169 write: impl Fn(&mut Buffer, &str),
2172 let mut items = items
2174 .filter_map(|m| match m.name {
2175 Some(ref name) if filter(m) => Some(name.as_str()),
2178 .collect::<Vec<_>>();
2180 if !items.is_empty() {
2181 items.sort_unstable();
2182 out.push_str(before);
2183 for item in items.into_iter() {
2186 out.push_str(after);
2190 print_sidebar_section(
2193 "<h3 class=\"sidebar-title\"><a href=\"#associated-types\">\
2194 Associated Types</a></h3><div class=\"sidebar-links\">",
2195 |m| m.is_associated_type(),
2196 |out, sym| write!(out, "<a href=\"#associatedtype.{0}\">{0}</a>", sym),
2200 print_sidebar_section(
2203 "<h3 class=\"sidebar-title\"><a href=\"#associated-const\">\
2204 Associated Constants</a></h3><div class=\"sidebar-links\">",
2205 |m| m.is_associated_const(),
2206 |out, sym| write!(out, "<a href=\"#associatedconstant.{0}\">{0}</a>", sym),
2210 print_sidebar_section(
2213 "<h3 class=\"sidebar-title\"><a href=\"#required-methods\">\
2214 Required Methods</a></h3><div class=\"sidebar-links\">",
2215 |m| m.is_ty_method(),
2216 |out, sym| write!(out, "<a href=\"#tymethod.{0}\">{0}</a>", sym),
2220 print_sidebar_section(
2223 "<h3 class=\"sidebar-title\"><a href=\"#provided-methods\">\
2224 Provided Methods</a></h3><div class=\"sidebar-links\">",
2226 |out, sym| write!(out, "<a href=\"#method.{0}\">{0}</a>", sym),
2230 let cache = cx.cache();
2231 if let Some(implementors) = cache.implementors.get(&it.def_id.expect_def_id()) {
2232 let mut res = implementors
2238 .map_or(false, |d| !cache.paths.contains_key(&d))
2240 .filter_map(|i| extract_for_impl_name(&i.impl_item, cx))
2241 .collect::<Vec<_>>();
2243 if !res.is_empty() {
2246 "<h3 class=\"sidebar-title\"><a href=\"#foreign-impls\">\
2247 Implementations on Foreign Types</a></h3>\
2248 <div class=\"sidebar-links\">",
2250 for (name, id) in res.into_iter() {
2251 write!(buf, "<a href=\"#{}\">{}</a>", id, Escape(&name));
2253 buf.push_str("</div>");
2257 sidebar_assoc_items(cx, buf, it);
2259 buf.push_str("<h3 class=\"sidebar-title\"><a href=\"#implementors\">Implementors</a></h3>");
2262 "<h3 class=\"sidebar-title\"><a \
2263 href=\"#synthetic-implementors\">Auto Implementors</a></h3>",
2267 buf.push_str("</div>")
2270 fn sidebar_primitive(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2271 let mut sidebar = Buffer::new();
2272 sidebar_assoc_items(cx, &mut sidebar, it);
2274 if !sidebar.is_empty() {
2275 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2279 fn sidebar_typedef(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2280 let mut sidebar = Buffer::new();
2281 sidebar_assoc_items(cx, &mut sidebar, it);
2283 if !sidebar.is_empty() {
2284 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2288 fn get_struct_fields_name(fields: &[clean::Item]) -> Vec<String> {
2289 let mut fields = fields
2291 .filter(|f| matches!(*f.kind, clean::StructFieldItem(..)))
2293 f.name.map(|name| format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
2295 .collect::<Vec<_>>();
2300 fn sidebar_union(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
2301 let mut sidebar = Buffer::new();
2302 let fields = get_struct_fields_name(&u.fields);
2304 if !fields.is_empty() {
2306 "<h3 class=\"sidebar-title\"><a href=\"#fields\">Fields</a></h3>\
2307 <div class=\"sidebar-links\">",
2310 for field in fields {
2311 sidebar.push_str(&field);
2314 sidebar.push_str("</div>");
2317 sidebar_assoc_items(cx, &mut sidebar, it);
2319 if !sidebar.is_empty() {
2320 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2324 fn sidebar_enum(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
2325 let mut sidebar = Buffer::new();
2327 let mut variants = e
2330 .filter_map(|v| match v.name {
2331 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
2334 .collect::<Vec<_>>();
2335 if !variants.is_empty() {
2336 variants.sort_unstable();
2337 sidebar.push_str(&format!(
2338 "<h3 class=\"sidebar-title\"><a href=\"#variants\">Variants</a></h3>\
2339 <div class=\"sidebar-links\">{}</div>",
2344 sidebar_assoc_items(cx, &mut sidebar, it);
2346 if !sidebar.is_empty() {
2347 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2351 fn item_ty_to_strs(ty: ItemType) -> (&'static str, &'static str) {
2353 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
2354 ItemType::Module => ("modules", "Modules"),
2355 ItemType::Struct => ("structs", "Structs"),
2356 ItemType::Union => ("unions", "Unions"),
2357 ItemType::Enum => ("enums", "Enums"),
2358 ItemType::Function => ("functions", "Functions"),
2359 ItemType::Typedef => ("types", "Type Definitions"),
2360 ItemType::Static => ("statics", "Statics"),
2361 ItemType::Constant => ("constants", "Constants"),
2362 ItemType::Trait => ("traits", "Traits"),
2363 ItemType::Impl => ("impls", "Implementations"),
2364 ItemType::TyMethod => ("tymethods", "Type Methods"),
2365 ItemType::Method => ("methods", "Methods"),
2366 ItemType::StructField => ("fields", "Struct Fields"),
2367 ItemType::Variant => ("variants", "Variants"),
2368 ItemType::Macro => ("macros", "Macros"),
2369 ItemType::Primitive => ("primitives", "Primitive Types"),
2370 ItemType::AssocType => ("associated-types", "Associated Types"),
2371 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
2372 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
2373 ItemType::Keyword => ("keywords", "Keywords"),
2374 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
2375 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
2376 ItemType::ProcDerive => ("derives", "Derive Macros"),
2377 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
2381 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
2382 let mut sidebar = String::new();
2384 // Re-exports are handled a bit differently because they can be extern crates or imports.
2385 if items.iter().any(|it| {
2387 && (it.type_() == ItemType::ExternCrate
2388 || (it.type_() == ItemType::Import && !it.is_stripped()))
2390 let (id, name) = item_ty_to_strs(ItemType::Import);
2391 sidebar.push_str(&format!("<li><a href=\"#{}\">{}</a></li>", id, name));
2394 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
2395 // to print its headings
2397 ItemType::Primitive,
2411 ItemType::StructField,
2413 ItemType::AssocType,
2414 ItemType::AssocConst,
2415 ItemType::ForeignType,
2418 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty && it.name.is_some()) {
2419 let (id, name) = item_ty_to_strs(myty);
2420 sidebar.push_str(&format!("<li><a href=\"#{}\">{}</a></li>", id, name));
2424 if !sidebar.is_empty() {
2425 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
2429 fn sidebar_foreign_type(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2430 let mut sidebar = Buffer::new();
2431 sidebar_assoc_items(cx, &mut sidebar, it);
2433 if !sidebar.is_empty() {
2434 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2438 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
2440 /// Returns a list of all paths used in the type.
2441 /// This is used to help deduplicate imported impls
2442 /// for reexported types. If any of the contained
2443 /// types are re-exported, we don't use the corresponding
2444 /// entry from the js file, as inlining will have already
2445 /// picked up the impl
2446 fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> {
2447 let mut out = Vec::new();
2448 let mut visited = FxHashSet::default();
2449 let mut work = VecDeque::new();
2451 let mut process_path = |did: DefId| {
2452 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
2453 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
2455 if let Some(path) = fqp {
2456 out.push(path.join("::"));
2460 work.push_back(first_ty);
2462 while let Some(ty) = work.pop_front() {
2463 if !visited.insert(ty.clone()) {
2468 clean::Type::ResolvedPath { did, .. } => process_path(did),
2469 clean::Type::Tuple(tys) => {
2470 work.extend(tys.into_iter());
2472 clean::Type::Slice(ty) => {
2473 work.push_back(*ty);
2475 clean::Type::Array(ty, _) => {
2476 work.push_back(*ty);
2478 clean::Type::RawPointer(_, ty) => {
2479 work.push_back(*ty);
2481 clean::Type::BorrowedRef { type_, .. } => {
2482 work.push_back(*type_);
2484 clean::Type::QPath { self_type, trait_, .. } => {
2485 work.push_back(*self_type);
2486 process_path(trait_.def_id());