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.
36 crate use write_shared::FILES_UNVERSIONED;
39 use std::collections::VecDeque;
40 use std::default::Default;
42 use std::path::PathBuf;
44 use std::string::ToString;
46 use itertools::Itertools;
47 use rustc_ast_pretty::pprust;
48 use rustc_attr::{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, RenderedLink, SelfTy, TypeKind};
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, FormatRenderer, Impl, RenderMode};
66 use crate::html::escape::Escape;
67 use crate::html::format::{
68 href, print_abi_with_space, print_default_space, print_generic_bounds, print_where_clause,
69 Buffer, PrintWithSpace,
71 use crate::html::markdown::{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 {
104 name: Option<String>,
105 generics: Option<Vec<Generic>>,
108 impl Serialize for RenderType {
109 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
113 if let Some(name) = &self.name {
114 let mut seq = serializer.serialize_seq(None)?;
115 if let Some(id) = self.idx {
116 seq.serialize_element(&id)?;
118 seq.serialize_element(&name)?;
120 if let Some(generics) = &self.generics {
121 seq.serialize_element(&generics)?;
125 serializer.serialize_none()
130 /// A type used for the search index.
132 crate struct Generic {
134 defid: Option<DefId>,
138 impl Serialize for Generic {
139 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
143 if let Some(id) = self.idx {
144 serializer.serialize_some(&id)
146 serializer.serialize_some(&self.name)
151 /// Full type of functions/methods in the search index.
153 crate struct IndexItemFunctionType {
154 inputs: Vec<TypeWithKind>,
155 output: Option<Vec<TypeWithKind>>,
158 impl Serialize for IndexItemFunctionType {
159 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
163 // If we couldn't figure out a type, just write `null`.
164 let mut iter = self.inputs.iter();
165 if match self.output {
166 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
167 None => iter.any(|ref i| i.ty.name.is_none()),
169 serializer.serialize_none()
171 let mut seq = serializer.serialize_seq(None)?;
172 seq.serialize_element(&self.inputs)?;
173 if let Some(output) = &self.output {
174 if output.len() > 1 {
175 seq.serialize_element(&output)?;
177 seq.serialize_element(&output[0])?;
186 crate struct TypeWithKind {
191 impl From<(RenderType, TypeKind)> for TypeWithKind {
192 fn from(x: (RenderType, TypeKind)) -> TypeWithKind {
193 TypeWithKind { ty: x.0, kind: x.1 }
197 impl Serialize for TypeWithKind {
198 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
202 (&self.ty.name, ItemType::from(self.kind)).serialize(serializer)
206 #[derive(Debug, Clone)]
207 crate struct StylePath {
208 /// The path to the theme
210 /// What the `disabled` attribute should be set to in the HTML tag
211 crate disabled: bool,
214 thread_local!(crate static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
216 fn write_srclink(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) {
217 if let Some(l) = cx.src_href(item) {
218 write!(buf, "<a class=\"srclink\" href=\"{}\" title=\"goto source code\">[src]</a>", l)
222 #[derive(Debug, Eq, PartialEq, Hash)]
229 fn new(mut url: String, name: String) -> ItemEntry {
230 while url.starts_with('/') {
233 ItemEntry { url, name }
238 crate fn print(&self) -> impl fmt::Display + '_ {
239 crate::html::format::display_fn(move |f| {
240 write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name))
245 impl PartialOrd for ItemEntry {
246 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
247 Some(self.cmp(other))
251 impl Ord for ItemEntry {
252 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
253 self.name.cmp(&other.name)
259 structs: FxHashSet<ItemEntry>,
260 enums: FxHashSet<ItemEntry>,
261 unions: FxHashSet<ItemEntry>,
262 primitives: FxHashSet<ItemEntry>,
263 traits: FxHashSet<ItemEntry>,
264 macros: FxHashSet<ItemEntry>,
265 functions: FxHashSet<ItemEntry>,
266 typedefs: FxHashSet<ItemEntry>,
267 opaque_tys: FxHashSet<ItemEntry>,
268 statics: FxHashSet<ItemEntry>,
269 constants: FxHashSet<ItemEntry>,
270 keywords: FxHashSet<ItemEntry>,
271 attributes: FxHashSet<ItemEntry>,
272 derives: FxHashSet<ItemEntry>,
273 trait_aliases: FxHashSet<ItemEntry>,
277 fn new() -> AllTypes {
278 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
280 structs: new_set(100),
282 unions: new_set(100),
283 primitives: new_set(26),
284 traits: new_set(100),
285 macros: new_set(100),
286 functions: new_set(100),
287 typedefs: new_set(100),
288 opaque_tys: new_set(100),
289 statics: new_set(100),
290 constants: new_set(100),
291 keywords: new_set(100),
292 attributes: new_set(100),
293 derives: new_set(100),
294 trait_aliases: new_set(100),
298 fn append(&mut self, item_name: String, item_type: &ItemType) {
299 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
300 if let Some(name) = url.pop() {
301 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
303 let name = url.join("::");
305 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
306 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
307 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
308 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
309 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
310 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
311 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
312 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
313 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
314 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
315 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
316 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
317 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
318 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
326 fn print(self, f: &mut Buffer) {
327 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
329 let mut e: Vec<&ItemEntry> = e.iter().collect();
331 write!(f, "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">", title, title, class);
334 write!(f, "<li>{}</li>", s.print());
337 f.write_str("</ul>");
343 <span class=\"in-band\">List of all items</span>\
344 <span class=\"out-of-band\">\
345 <span id=\"render-detail\">\
346 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
347 title=\"collapse all docs\">\
348 [<span class=\"inner\">−</span>]\
354 // Note: print_entries does not escape the title, because we know the current set of titles
355 // don't require escaping.
356 print_entries(f, &self.structs, "Structs", "structs");
357 print_entries(f, &self.enums, "Enums", "enums");
358 print_entries(f, &self.unions, "Unions", "unions");
359 print_entries(f, &self.primitives, "Primitives", "primitives");
360 print_entries(f, &self.traits, "Traits", "traits");
361 print_entries(f, &self.macros, "Macros", "macros");
362 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
363 print_entries(f, &self.derives, "Derive Macros", "derives");
364 print_entries(f, &self.functions, "Functions", "functions");
365 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
366 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
367 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
368 print_entries(f, &self.statics, "Statics", "statics");
369 print_entries(f, &self.constants, "Constants", "constants")
376 description: &'static str,
377 sub_settings: Vec<Setting>,
380 js_data_name: &'static str,
381 description: &'static str,
385 js_data_name: &'static str,
386 description: &'static str,
387 default_value: &'static str,
388 options: Vec<(String, String)>,
393 fn display(&self, root_path: &str, suffix: &str) -> String {
395 Setting::Section { description, ref sub_settings } => format!(
396 "<div class=\"setting-line\">\
397 <div class=\"title\">{}</div>\
398 <div class=\"sub-settings\">{}</div>
401 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
403 Setting::Toggle { js_data_name, description, default_value } => format!(
404 "<div class=\"setting-line\">\
405 <label class=\"toggle\">\
406 <input type=\"checkbox\" id=\"{}\" {}>\
407 <span class=\"slider\"></span>\
412 if default_value { " checked" } else { "" },
415 Setting::Select { js_data_name, description, default_value, ref options } => format!(
416 "<div class=\"setting-line\">\
418 <label class=\"select-wrapper\">\
419 <select id=\"{}\" autocomplete=\"off\">{}</select>\
420 <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
428 "<option value=\"{}\" {}>{}</option>",
430 if opt.0 == default_value { "selected" } else { "" },
433 .collect::<String>(),
441 impl From<(&'static str, &'static str, bool)> for Setting {
442 fn from(values: (&'static str, &'static str, bool)) -> Setting {
443 Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
447 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
448 fn from(values: (&'static str, Vec<T>)) -> Setting {
450 description: values.0,
451 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
456 fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
457 let theme_names: Vec<(String, String)> = themes
461 try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
464 Ok((theme.clone(), theme))
466 .collect::<Result<_, Error>>()?;
468 // (id, explanation, default value)
469 let settings: &[Setting] = &[
473 Setting::from(("use-system-theme", "Use system theme", true)),
475 js_data_name: "preferred-dark-theme",
476 description: "Preferred dark theme",
477 default_value: "dark",
478 options: theme_names.clone(),
481 js_data_name: "preferred-light-theme",
482 description: "Preferred light theme",
483 default_value: "light",
484 options: theme_names,
489 ("auto-hide-attributes", "Auto-hide item attributes.", true).into(),
490 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
491 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", true)
493 ("auto-collapse-implementors", "Auto-hide implementors of a trait", true).into(),
494 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
496 ("line-numbers", "Show line numbers on code examples", false).into(),
497 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
502 <span class=\"in-band\">Rustdoc settings</span>\
504 <div class=\"settings\">{}</div>\
505 <script src=\"{}settings{}.js\"></script>",
506 settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
512 fn document(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, parent: Option<&clean::Item>) {
513 if let Some(ref name) = item.name {
514 info!("Documenting {}", name);
516 document_item_info(w, cx, item, false, parent);
517 document_full(w, item, cx, "", false);
520 /// Render md_text as markdown.
525 links: Vec<RenderedLink>,
529 let mut ids = cx.id_map.borrow_mut();
532 "<div class=\"docblock{}\">{}{}</div>",
533 if is_hidden { " hidden" } else { "" },
541 &cx.shared.playground
547 /// Writes a documentation block containing only the first paragraph of the documentation. If the
548 /// docs are longer, a "Read more" link is appended to the end.
553 link: AssocItemLink<'_>,
556 parent: Option<&clean::Item>,
559 document_item_info(w, cx, item, is_hidden, parent);
563 if let Some(s) = item.doc_value() {
564 let mut summary_html = MarkdownSummaryLine(&s, &item.links(&cx.cache)).into_string();
566 if s.contains('\n') {
568 format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link, cx.cache()));
570 if let Some(idx) = summary_html.rfind("</p>") {
571 summary_html.insert_str(idx, &link);
573 summary_html.push_str(&link);
579 "<div class='docblock{}'>{}{}</div>",
580 if is_hidden { " hidden" } else { "" },
584 } else if !prefix.is_empty() {
587 "<div class=\"docblock{}\">{}</div>",
588 if is_hidden { " hidden" } else { "" },
601 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
602 debug!("Doc block: =====\n{}\n=====", s);
603 render_markdown(w, cx, &*s, item.links(&cx.cache), prefix, is_hidden);
604 } else if !prefix.is_empty() {
606 w.write_str("<div class=\"docblock hidden\">");
608 w.write_str("<div class=\"docblock\">");
611 w.write_str("</div>");
615 /// Add extra information about an item such as:
619 /// * Required features (through the `doc_cfg` feature)
620 fn document_item_info(
625 parent: Option<&clean::Item>,
627 let item_infos = short_item_info(item, cx, parent);
628 if !item_infos.is_empty() {
630 w.write_str("<div class=\"item-info hidden\">");
632 w.write_str("<div class=\"item-info\">");
634 for info in item_infos {
637 w.write_str("</div>");
641 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
642 let cfg = match (&item.attrs.cfg, parent.and_then(|p| p.attrs.cfg.as_ref())) {
643 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
644 (cfg, _) => cfg.as_deref().cloned(),
648 "Portability {:?} - {:?} = {:?}",
650 parent.and_then(|p| p.attrs.cfg.as_ref()),
654 Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
657 /// Render the stability, deprecation and portability information that is displayed at the top of
658 /// the item's documentation.
662 parent: Option<&clean::Item>,
664 let mut extra_info = vec![];
665 let error_codes = cx.shared.codes;
667 if let Some(Deprecation { note, since, is_since_rustc_version, suggestion: _ }) =
668 item.deprecation(cx.tcx())
670 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
671 // but only display the future-deprecation messages for #[rustc_deprecated].
672 let mut message = if let Some(since) = since {
673 let since = &since.as_str();
674 if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
676 String::from("Deprecating in a future Rust version")
678 format!("Deprecating in {}", Escape(since))
681 format!("Deprecated since {}", Escape(since))
684 String::from("Deprecated")
687 if let Some(note) = note {
688 let note = note.as_str();
689 let mut ids = cx.id_map.borrow_mut();
690 let html = MarkdownHtml(
695 &cx.shared.playground,
697 message.push_str(&format!(": {}", html.into_string()));
699 extra_info.push(format!(
700 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
705 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
706 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
707 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
710 .filter(|stab| stab.feature != sym::rustc_private)
711 .map(|stab| (stab.level, stab.feature))
714 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
716 let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
717 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
718 feature.push_str(&format!(
719 " <a href=\"{url}{issue}\">#{issue}</a>",
725 message.push_str(&format!(" ({})", feature));
727 if let Some(unstable_reason) = reason {
728 let mut ids = cx.id_map.borrow_mut();
730 "<details><summary>{}</summary>{}</details>",
733 &unstable_reason.as_str(),
737 &cx.shared.playground,
743 extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
746 if let Some(portability) = portability(item, parent) {
747 extra_info.push(portability);
757 containing_item: &clean::Item,
759 let cache = cx.cache();
761 let mut impls = traits
764 let did = i.trait_did_full(cache).unwrap();
765 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
766 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
774 containing_item.stable_since(tcx).as_deref(),
775 containing_item.const_stable_since(tcx).as_deref(),
784 .collect::<Vec<_>>();
786 w.write_str(&impls.join(""));
789 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>, cache: &Cache) -> String {
790 use crate::formats::item_type::ItemType::*;
792 let name = it.name.as_ref().unwrap();
793 let ty = match it.type_() {
794 Typedef | AssocType => AssocType,
798 let anchor = format!("#{}.{}", ty, name);
800 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
801 AssocItemLink::Anchor(None) => anchor,
802 AssocItemLink::GotoSource(did, _) => {
803 href(did, cache).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
812 _default: Option<&String>,
813 link: AssocItemLink<'_>,
817 let cache = cx.cache();
821 "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
823 it.visibility.print_with_space(tcx, it.def_id, cache),
824 naive_assoc_href(it, link, cache),
825 it.name.as_ref().unwrap(),
833 bounds: &[clean::GenericBound],
834 default: Option<&clean::Type>,
835 link: AssocItemLink<'_>,
842 "{}type <a href=\"{}\" class=\"type\">{}</a>",
844 naive_assoc_href(it, link, cache),
845 it.name.as_ref().unwrap()
847 if !bounds.is_empty() {
848 write!(w, ": {}", print_generic_bounds(bounds, cache, tcx))
850 if let Some(default) = default {
851 write!(w, " = {}", default.print(cache, tcx))
855 fn render_stability_since_raw(
858 const_ver: Option<&str>,
859 containing_ver: Option<&str>,
860 containing_const_ver: Option<&str>,
862 let ver = ver.filter(|inner| !inner.is_empty());
863 let const_ver = const_ver.filter(|inner| !inner.is_empty());
865 match (ver, const_ver) {
866 (Some(v), Some(cv)) if const_ver != containing_const_ver => {
869 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
873 (Some(v), _) if ver != containing_ver => {
876 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
884 fn render_assoc_item(
887 link: AssocItemLink<'_>,
894 header: hir::FnHeader,
897 link: AssocItemLink<'_>,
901 let cache = cx.cache();
903 let name = meth.name.as_ref().unwrap();
904 let anchor = format!("#{}.{}", meth.type_(), name);
905 let href = match link {
906 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
907 AssocItemLink::Anchor(None) => anchor,
908 AssocItemLink::GotoSource(did, provided_methods) => {
909 // We're creating a link from an impl-item to the corresponding
910 // trait-item and need to map the anchored type accordingly.
911 let ty = if provided_methods.contains(&name) {
917 href(did, cache).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
920 let vis = meth.visibility.print_with_space(tcx, meth.def_id, cache).to_string();
921 let constness = header.constness.print_with_space();
922 let asyncness = header.asyncness.print_with_space();
923 let unsafety = header.unsafety.print_with_space();
924 let defaultness = print_default_space(meth.is_default());
925 let abi = print_abi_with_space(header.abi).to_string();
926 // NOTE: `{:#}` does not print HTML formatting, `{}` does. So `g.print` can't be reused between the length calculation and `write!`.
927 let generics_len = format!("{:#}", g.print(cache, tcx)).len();
928 let mut header_len = "fn ".len()
935 + name.as_str().len()
938 let (indent, end_newline) = if parent == ItemType::Trait {
944 render_attributes(w, meth, false);
945 w.reserve(header_len + "<a href=\"\" class=\"fnname\">{".len() + "</a>".len());
948 "{}{}{}{}{}{}{}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
949 {generics}{decl}{notable_traits}{where_clause}",
950 if parent == ItemType::Trait { " " } else { "" },
959 generics = g.print(cache, tcx),
960 decl = d.full_print(cache, tcx, header_len, indent, header.asyncness),
961 notable_traits = notable_traits_decl(&d, cache, tcx),
962 where_clause = print_where_clause(g, cache, tcx, indent, end_newline),
966 clean::StrippedItem(..) => {}
967 clean::TyMethodItem(ref m) => {
968 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
970 clean::MethodItem(ref m, _) => {
971 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
973 clean::AssocConstItem(ref ty, ref default) => assoc_const(
979 if parent == ItemType::Trait { " " } else { "" },
982 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
988 if parent == ItemType::Trait { " " } else { "" },
992 _ => panic!("render_assoc_item called on non-associated-item"),
996 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
1003 sym::non_exhaustive,
1006 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
1007 // left padding. For example:
1009 // #[foo] <----- "top" attribute
1011 // #[bar] <---- not "top" attribute
1014 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
1019 .filter_map(|attr| {
1020 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
1021 Some(pprust::attribute_to_string(&attr))
1028 if !attrs.is_empty() {
1031 "<span class=\"docblock attributes{}\">{}</span>",
1032 if top { " top-attr" } else { "" },
1038 #[derive(Copy, Clone)]
1039 enum AssocItemLink<'a> {
1040 Anchor(Option<&'a str>),
1041 GotoSource(DefId, &'a FxHashSet<Symbol>),
1044 impl<'a> AssocItemLink<'a> {
1045 fn anchor(&self, id: &'a str) -> Self {
1047 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
1048 ref other => *other,
1053 fn render_assoc_items(
1056 containing_item: &clean::Item,
1058 what: AssocItemRender<'_>,
1060 info!("Documenting associated items of {:?}", containing_item.name);
1061 let v = match cx.cache.impls.get(&it) {
1066 let cache = cx.cache();
1067 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
1068 if !non_trait.is_empty() {
1069 let render_mode = match what {
1070 AssocItemRender::All => {
1072 "<h2 id=\"implementations\" class=\"small-section-header\">\
1073 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
1078 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
1079 let id = cx.derive_id(small_url_encode(format!(
1080 "deref-methods-{:#}",
1081 type_.print(cache, tcx)
1083 debug!("Adding {} to deref id map", type_.print(cache, tcx));
1084 cx.deref_id_map.borrow_mut().insert(type_.def_id_full(cache).unwrap(), id.clone());
1087 "<h2 id=\"{id}\" class=\"small-section-header\">\
1088 Methods from {trait_}<Target = {type_}>\
1089 <a href=\"#{id}\" class=\"anchor\"></a>\
1092 trait_ = trait_.print(cache, tcx),
1093 type_ = type_.print(cache, tcx),
1095 RenderMode::ForDeref { mut_: deref_mut_ }
1098 for i in &non_trait {
1104 AssocItemLink::Anchor(None),
1106 containing_item.stable_since(tcx).as_deref(),
1107 containing_item.const_stable_since(tcx).as_deref(),
1116 if !traits.is_empty() {
1117 let deref_impl = traits
1119 .find(|t| t.inner_impl().trait_.def_id_full(cache) == cx.cache.deref_trait_did);
1120 if let Some(impl_) = deref_impl {
1121 let has_deref_mut = traits
1123 .any(|t| t.inner_impl().trait_.def_id_full(cache) == cx.cache.deref_mut_trait_did);
1124 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut);
1127 // If we were already one level into rendering deref methods, we don't want to render
1128 // anything after recursing into any further deref methods above.
1129 if let AssocItemRender::DerefFor { .. } = what {
1133 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
1134 traits.iter().partition(|t| t.inner_impl().synthetic);
1135 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
1136 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
1138 let mut impls = Buffer::empty_from(&w);
1139 render_impls(cx, &mut impls, &concrete, containing_item);
1140 let impls = impls.into_inner();
1141 if !impls.is_empty() {
1144 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
1145 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
1147 <div id=\"trait-implementations-list\">{}</div>",
1152 if !synthetic.is_empty() {
1154 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
1155 Auto Trait Implementations\
1156 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
1158 <div id=\"synthetic-implementations-list\">",
1160 render_impls(cx, w, &synthetic, containing_item);
1161 w.write_str("</div>");
1164 if !blanket_impl.is_empty() {
1166 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
1167 Blanket Implementations\
1168 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
1170 <div id=\"blanket-implementations-list\">",
1172 render_impls(cx, w, &blanket_impl, containing_item);
1173 w.write_str("</div>");
1178 fn render_deref_methods(
1182 container_item: &clean::Item,
1185 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
1186 let (target, real_target) = impl_
1190 .find_map(|item| match *item.kind {
1191 clean::TypedefItem(ref t, true) => Some(match *t {
1192 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
1193 _ => (&t.type_, &t.type_),
1197 .expect("Expected associated type binding");
1198 debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target);
1200 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
1201 if let Some(did) = target.def_id_full(cx.cache()) {
1202 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) {
1203 // `impl Deref<Target = S> for S`
1204 if did == type_did {
1205 // Avoid infinite cycles
1209 render_assoc_items(w, cx, container_item, did, what);
1211 if let Some(prim) = target.primitive_type() {
1212 if let Some(&did) = cx.cache.primitive_locations.get(&prim) {
1213 render_assoc_items(w, cx, container_item, did, what);
1219 fn should_render_item(item: &clean::Item, deref_mut_: bool, cache: &Cache) -> bool {
1220 let self_type_opt = match *item.kind {
1221 clean::MethodItem(ref method, _) => method.decl.self_type(),
1222 clean::TyMethodItem(ref method) => method.decl.self_type(),
1226 if let Some(self_ty) = self_type_opt {
1227 let (by_mut_ref, by_box, by_value) = match self_ty {
1228 SelfTy::SelfBorrowed(_, mutability)
1229 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
1230 (mutability == Mutability::Mut, false, false)
1232 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
1233 (false, Some(did) == cache.owned_box_did, false)
1235 SelfTy::SelfValue => (false, false, true),
1236 _ => (false, false, false),
1239 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
1245 fn notable_traits_decl(decl: &clean::FnDecl, cache: &Cache, tcx: TyCtxt<'_>) -> String {
1246 let mut out = Buffer::html();
1247 let mut trait_ = String::new();
1249 if let Some(did) = decl.output.def_id_full(cache) {
1250 if let Some(impls) = cache.impls.get(&did) {
1252 let impl_ = i.inner_impl();
1256 .map_or(false, |d| cache.traits.get(&d).map(|t| t.is_notable).unwrap_or(false))
1261 "<h3 class=\"notable\">Notable traits for {}</h3>\
1262 <code class=\"content\">",
1263 impl_.for_.print(cache, tcx)
1265 trait_.push_str(&impl_.for_.print(cache, tcx).to_string());
1268 //use the "where" class here to make it small
1271 "<span class=\"where fmt-newline\">{}</span>",
1272 impl_.print(cache, false, tcx)
1274 let t_did = impl_.trait_.def_id_full(cache).unwrap();
1275 for it in &impl_.items {
1276 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1277 out.push_str("<span class=\"where fmt-newline\"> ");
1283 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
1288 out.push_str(";</span>");
1296 if !out.is_empty() {
1299 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
1300 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
1302 out.push_str("</code></span></div></span></span>");
1312 parent: &clean::Item,
1313 link: AssocItemLink<'_>,
1314 render_mode: RenderMode,
1315 outer_version: Option<&str>,
1316 outer_const_version: Option<&str>,
1317 show_def_docs: bool,
1318 use_absolute: Option<bool>,
1319 is_on_foreign_type: bool,
1320 show_default_items: bool,
1321 // This argument is used to reference same type with different paths to avoid duplication
1322 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
1325 let traits = &cx.cache.traits;
1327 let cache = cx.cache();
1328 let trait_ = i.trait_did_full(cache).map(|did| &traits[&did]);
1330 if render_mode == RenderMode::Normal {
1331 let id = cx.derive_id(match i.inner_impl().trait_ {
1333 if is_on_foreign_type {
1334 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t, cache, tcx)
1336 format!("impl-{}", small_url_encode(format!("{:#}", t.print(cache, tcx))))
1339 None => "impl".to_string(),
1341 let aliases = if aliases.is_empty() {
1344 format!(" aliases=\"{}\"", aliases.join(","))
1346 if let Some(use_absolute) = use_absolute {
1347 write!(w, "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">", id, aliases);
1348 write!(w, "{}", i.inner_impl().print(cache, use_absolute, tcx));
1350 for it in &i.inner_impl().items {
1351 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1352 w.write_str("<span class=\"where fmt-newline\"> ");
1358 AssocItemLink::Anchor(None),
1363 w.write_str(";</span>");
1367 w.write_str("</code>");
1371 "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">{}</code>",
1374 i.inner_impl().print(cache, false, tcx)
1377 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1378 render_stability_since_raw(
1380 i.impl_item.stable_since(tcx).as_deref(),
1381 i.impl_item.const_stable_since(tcx).as_deref(),
1383 outer_const_version,
1385 write_srclink(cx, &i.impl_item, w);
1386 w.write_str("</h3>");
1388 if trait_.is_some() {
1389 if let Some(portability) = portability(&i.impl_item, Some(parent)) {
1390 write!(w, "<div class=\"item-info\">{}</div>", portability);
1394 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
1395 let mut ids = cx.id_map.borrow_mut();
1398 "<div class=\"docblock\">{}</div>",
1401 &i.impl_item.links(&cx.cache),
1405 &cx.shared.playground
1416 parent: &clean::Item,
1417 link: AssocItemLink<'_>,
1418 render_mode: RenderMode,
1419 is_default_item: bool,
1420 outer_version: Option<&str>,
1421 outer_const_version: Option<&str>,
1422 trait_: Option<&clean::Trait>,
1423 show_def_docs: bool,
1425 let item_type = item.type_();
1426 let name = item.name.as_ref().unwrap();
1429 let render_method_item = match render_mode {
1430 RenderMode::Normal => true,
1431 RenderMode::ForDeref { mut_: deref_mut_ } => {
1432 should_render_item(&item, deref_mut_, &cx.cache)
1436 let (is_hidden, extra_class) =
1437 if (trait_.is_none() || item.doc_value().is_some() || item.kind.is_type_alias())
1445 clean::MethodItem(..) | clean::TyMethodItem(_) => {
1446 // Only render when the method is not static or we allow static methods
1447 if render_method_item {
1448 let id = cx.derive_id(format!("{}.{}", item_type, name));
1449 write!(w, "<h4 id=\"{}\" class=\"{}{}\">", id, item_type, extra_class);
1450 w.write_str("<code>");
1451 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl, cx);
1452 w.write_str("</code>");
1453 render_stability_since_raw(
1455 item.stable_since(tcx).as_deref(),
1456 item.const_stable_since(tcx).as_deref(),
1458 outer_const_version,
1460 write_srclink(cx, item, w);
1461 w.write_str("</h4>");
1464 clean::TypedefItem(ref tydef, _) => {
1465 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
1466 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
1477 w.write_str("</code></h4>");
1479 clean::AssocConstItem(ref ty, ref default) => {
1480 let id = cx.derive_id(format!("{}.{}", item_type, name));
1481 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
1482 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "", cx);
1483 w.write_str("</code>");
1484 render_stability_since_raw(
1486 item.stable_since(tcx).as_deref(),
1487 item.const_stable_since(tcx).as_deref(),
1489 outer_const_version,
1491 write_srclink(cx, item, w);
1492 w.write_str("</h4>");
1494 clean::AssocTypeItem(ref bounds, ref default) => {
1495 let id = cx.derive_id(format!("{}.{}", item_type, name));
1496 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
1507 w.write_str("</code></h4>");
1509 clean::StrippedItem(..) => return,
1510 _ => panic!("can't make docs for trait item with name {:?}", item.name),
1513 if render_method_item {
1514 if !is_default_item {
1515 if let Some(t) = trait_ {
1516 // The trait item may have been stripped so we might not
1517 // find any documentation or stability for it.
1518 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
1519 // We need the stability of the item from the trait
1520 // because impls can't have a stability.
1521 if item.doc_value().is_some() {
1522 document_item_info(w, cx, it, is_hidden, Some(parent));
1523 document_full(w, item, cx, "", is_hidden);
1525 // In case the item isn't documented,
1526 // provide short documentation from the trait.
1540 document_item_info(w, cx, item, is_hidden, Some(parent));
1542 document_full(w, item, cx, "", is_hidden);
1546 document_short(w, item, cx, link, "", is_hidden, Some(parent), show_def_docs);
1551 w.write_str("<div class=\"impl-items\">");
1552 for trait_item in &i.inner_impl().items {
1557 if trait_.is_some() { &i.impl_item } else { parent },
1562 outer_const_version,
1563 trait_.map(|t| &t.trait_),
1568 fn render_default_items(
1573 parent: &clean::Item,
1574 render_mode: RenderMode,
1575 outer_version: Option<&str>,
1576 outer_const_version: Option<&str>,
1577 show_def_docs: bool,
1579 for trait_item in &t.items {
1580 let n = trait_item.name;
1581 if i.items.iter().any(|m| m.name == n) {
1584 let did = i.trait_.as_ref().unwrap().def_id_full(cx.cache()).unwrap();
1585 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
1596 outer_const_version,
1603 // If we've implemented a trait, then also emit documentation for all
1604 // default items which weren't overridden in the implementation block.
1605 // We don't emit documentation for default items if they appear in the
1606 // Implementations on Foreign Types or Implementors sections.
1607 if show_default_items {
1608 if let Some(t) = trait_ {
1609 render_default_items(
1617 outer_const_version,
1622 w.write_str("</div>");
1625 fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) {
1626 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
1630 || it.is_primitive()
1638 "<p class=\"location\">{}{}</p>",
1640 clean::StructItem(..) => "Struct ",
1641 clean::TraitItem(..) => "Trait ",
1642 clean::PrimitiveItem(..) => "Primitive Type ",
1643 clean::UnionItem(..) => "Union ",
1644 clean::EnumItem(..) => "Enum ",
1645 clean::TypedefItem(..) => "Type Definition ",
1646 clean::ForeignTypeItem => "Foreign Type ",
1647 clean::ModuleItem(..) =>
1655 it.name.as_ref().unwrap()
1660 if let Some(ref version) = cx.cache.crate_version {
1663 "<div class=\"block version\">\
1671 buffer.write_str("<div class=\"sidebar-elems\">");
1675 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
1676 it.name.as_ref().expect("crates always have a name")
1680 clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s),
1681 clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t),
1682 clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it),
1683 clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u),
1684 clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e),
1685 clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it),
1686 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
1687 clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, it),
1691 // The sidebar is designed to display sibling functions, modules and
1692 // other miscellaneous information. since there are lots of sibling
1693 // items (and that causes quadratic growth in large modules),
1694 // we refactor common parts into a shared JavaScript file per module.
1695 // still, we don't move everything into JS because we want to preserve
1696 // as much HTML as possible in order to allow non-JS-enabled browsers
1697 // to navigate the documentation (though slightly inefficiently).
1699 buffer.write_str("<p class=\"location\">");
1700 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
1702 buffer.write_str("::<wbr>");
1706 "<a href=\"{}index.html\">{}</a>",
1707 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
1711 buffer.write_str("</p>");
1713 // Sidebar refers to the enclosing module, not this module.
1714 let relpath = if it.is_mod() { "../" } else { "" };
1717 "<div id=\"sidebar-vars\" data-name=\"{name}\" data-ty=\"{ty}\" data-relpath=\"{path}\">\
1719 name = it.name.unwrap_or(kw::Empty),
1724 // There is no sidebar-items.js beyond the crate root path
1725 // FIXME maybe dynamic crate loading can be merged here
1727 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
1729 // Closes sidebar-elems div.
1730 buffer.write_str("</div>");
1733 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
1734 if used_links.insert(url.clone()) {
1738 while !used_links.insert(format!("{}-{}", url, add)) {
1741 format!("{}-{}", url, add)
1747 used_links: &mut FxHashSet<String>,
1753 .filter_map(|item| match item.name {
1754 Some(ref name) if !name.is_empty() && item.is_method() => {
1755 if !for_deref || should_render_item(item, deref_mut, cache) {
1757 "<a href=\"#{}\">{}</a>",
1758 get_next_url(used_links, format!("method.{}", name)),
1767 .collect::<Vec<_>>()
1770 // The point is to url encode any potential character from a type with genericity.
1771 fn small_url_encode(s: String) -> String {
1772 let mut st = String::new();
1773 let mut last_match = 0;
1774 for (idx, c) in s.char_indices() {
1775 let escaped = match c {
1791 st += &s[last_match..idx];
1793 // NOTE: we only expect single byte characters here - which is fine as long as we
1794 // only match single byte characters
1795 last_match = idx + 1;
1798 if last_match != 0 {
1799 st += &s[last_match..];
1806 fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) {
1807 if let Some(v) = cx.cache.impls.get(&it.def_id) {
1808 let mut used_links = FxHashSet::default();
1810 let cache = cx.cache();
1813 let used_links_bor = &mut used_links;
1816 .filter(|i| i.inner_impl().trait_.is_none())
1817 .flat_map(move |i| {
1818 get_methods(i.inner_impl(), false, used_links_bor, false, &cx.cache)
1820 .collect::<Vec<_>>();
1821 if !ret.is_empty() {
1822 // We want links' order to be reproducible so we don't use unstable sort.
1826 "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
1827 <div class=\"sidebar-links\">",
1830 out.push_str(&line);
1832 out.push_str("</div>");
1836 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
1837 let format_impls = |impls: Vec<&Impl>| {
1838 let mut links = FxHashSet::default();
1843 if let Some(ref i) = it.inner_impl().trait_ {
1844 let i_display = format!("{:#}", i.print(cache, tcx));
1845 let out = Escape(&i_display);
1846 let encoded = small_url_encode(format!("{:#}", i.print(cache, tcx)));
1847 let generated = format!(
1848 "<a href=\"#impl-{}\">{}{}</a>",
1850 if it.inner_impl().negative_polarity { "!" } else { "" },
1853 if links.insert(generated.clone()) { Some(generated) } else { None }
1858 .collect::<Vec<String>>();
1863 let write_sidebar_links = |out: &mut Buffer, links: Vec<String>| {
1864 out.push_str("<div class=\"sidebar-links\">");
1866 out.push_str(&link);
1868 out.push_str("</div>");
1871 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
1872 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
1873 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
1875 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
1877 let concrete_format = format_impls(concrete);
1878 let synthetic_format = format_impls(synthetic);
1879 let blanket_format = format_impls(blanket_impl);
1881 if !concrete_format.is_empty() {
1883 "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
1884 Trait Implementations</a>",
1886 write_sidebar_links(out, concrete_format);
1889 if !synthetic_format.is_empty() {
1891 "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
1892 Auto Trait Implementations</a>",
1894 write_sidebar_links(out, synthetic_format);
1897 if !blanket_format.is_empty() {
1899 "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
1900 Blanket Implementations</a>",
1902 write_sidebar_links(out, blanket_format);
1905 if let Some(impl_) = v
1907 .filter(|i| i.inner_impl().trait_.is_some())
1908 .find(|i| i.inner_impl().trait_.def_id_full(cache) == cx.cache.deref_trait_did)
1910 sidebar_deref_methods(cx, out, impl_, v);
1916 fn sidebar_deref_methods(cx: &Context<'_>, out: &mut Buffer, impl_: &Impl, v: &Vec<Impl>) {
1920 debug!("found Deref: {:?}", impl_);
1921 if let Some((target, real_target)) =
1922 impl_.inner_impl().items.iter().find_map(|item| match *item.kind {
1923 clean::TypedefItem(ref t, true) => Some(match *t {
1924 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
1925 _ => (&t.type_, &t.type_),
1930 debug!("found target, real_target: {:?} {:?}", target, real_target);
1931 if let Some(did) = target.def_id_full(c) {
1932 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(c) {
1933 // `impl Deref<Target = S> for S`
1934 if did == type_did {
1935 // Avoid infinite cycles
1942 .filter(|i| i.inner_impl().trait_.is_some())
1943 .any(|i| i.inner_impl().trait_.def_id_full(c) == c.deref_mut_trait_did);
1944 let inner_impl = target
1947 target.primitive_type().and_then(|prim| c.primitive_locations.get(&prim).cloned())
1949 .and_then(|did| c.impls.get(&did));
1950 if let Some(impls) = inner_impl {
1951 debug!("found inner_impl: {:?}", impls);
1952 let mut used_links = FxHashSet::default();
1955 .filter(|i| i.inner_impl().trait_.is_none())
1956 .flat_map(|i| get_methods(i.inner_impl(), true, &mut used_links, deref_mut, c))
1957 .collect::<Vec<_>>();
1958 if !ret.is_empty() {
1959 let deref_id_map = cx.deref_id_map.borrow();
1960 let id = deref_id_map
1961 .get(&real_target.def_id_full(c).unwrap())
1962 .expect("Deref section without derived id");
1965 "<a class=\"sidebar-title\" href=\"#{}\">Methods from {}<Target={}></a>",
1969 impl_.inner_impl().trait_.as_ref().unwrap().print(c, tcx)
1971 Escape(&format!("{:#}", real_target.print(c, tcx))),
1973 // We want links' order to be reproducible so we don't use unstable sort.
1975 out.push_str("<div class=\"sidebar-links\">");
1977 out.push_str(&link);
1979 out.push_str("</div>");
1983 // Recurse into any further impls that might exist for `target`
1984 if let Some(target_did) = target.def_id_full(c) {
1985 if let Some(target_impls) = c.impls.get(&target_did) {
1986 if let Some(target_deref_impl) = target_impls
1988 .filter(|i| i.inner_impl().trait_.is_some())
1989 .find(|i| i.inner_impl().trait_.def_id_full(c) == c.deref_trait_did)
1991 sidebar_deref_methods(cx, out, target_deref_impl, target_impls);
1998 fn sidebar_struct(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
1999 let mut sidebar = Buffer::new();
2000 let fields = get_struct_fields_name(&s.fields);
2002 if !fields.is_empty() {
2003 if let CtorKind::Fictive = s.struct_type {
2005 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
2006 <div class=\"sidebar-links\">",
2009 for field in fields {
2010 sidebar.push_str(&field);
2013 sidebar.push_str("</div>");
2017 sidebar_assoc_items(cx, &mut sidebar, it);
2019 if !sidebar.is_empty() {
2020 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2024 fn get_id_for_impl_on_foreign_type(
2026 trait_: &clean::Type,
2030 small_url_encode(format!(
2031 "impl-{:#}-for-{:#}",
2032 trait_.print(cache, tcx),
2033 for_.print(cache, tcx)
2037 fn extract_for_impl_name(
2041 ) -> Option<(String, String)> {
2043 clean::ItemKind::ImplItem(ref i) => {
2044 if let Some(ref trait_) = i.trait_ {
2046 format!("{:#}", i.for_.print(cache, tcx)),
2047 get_id_for_impl_on_foreign_type(&i.for_, trait_, cache, tcx),
2057 fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
2058 buf.write_str("<div class=\"block items\">");
2060 fn print_sidebar_section(
2062 items: &[clean::Item],
2064 filter: impl Fn(&clean::Item) -> bool,
2065 write: impl Fn(&mut Buffer, &str),
2068 let mut items = items
2070 .filter_map(|m| match m.name {
2071 Some(ref name) if filter(m) => Some(name.as_str()),
2074 .collect::<Vec<_>>();
2076 if !items.is_empty() {
2077 items.sort_unstable();
2078 out.push_str(before);
2079 for item in items.into_iter() {
2082 out.push_str(after);
2086 print_sidebar_section(
2089 "<a class=\"sidebar-title\" href=\"#associated-types\">\
2090 Associated Types</a><div class=\"sidebar-links\">",
2091 |m| m.is_associated_type(),
2092 |out, sym| write!(out, "<a href=\"#associatedtype.{0}\">{0}</a>", sym),
2096 print_sidebar_section(
2099 "<a class=\"sidebar-title\" href=\"#associated-const\">\
2100 Associated Constants</a><div class=\"sidebar-links\">",
2101 |m| m.is_associated_const(),
2102 |out, sym| write!(out, "<a href=\"#associatedconstant.{0}\">{0}</a>", sym),
2106 print_sidebar_section(
2109 "<a class=\"sidebar-title\" href=\"#required-methods\">\
2110 Required Methods</a><div class=\"sidebar-links\">",
2111 |m| m.is_ty_method(),
2112 |out, sym| write!(out, "<a href=\"#tymethod.{0}\">{0}</a>", sym),
2116 print_sidebar_section(
2119 "<a class=\"sidebar-title\" href=\"#provided-methods\">\
2120 Provided Methods</a><div class=\"sidebar-links\">",
2122 |out, sym| write!(out, "<a href=\"#method.{0}\">{0}</a>", sym),
2126 if let Some(implementors) = cx.cache.implementors.get(&it.def_id) {
2127 let cache = cx.cache();
2129 let mut res = implementors
2135 .map_or(false, |d| !cx.cache.paths.contains_key(&d))
2137 .filter_map(|i| extract_for_impl_name(&i.impl_item, cache, tcx))
2138 .collect::<Vec<_>>();
2140 if !res.is_empty() {
2143 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
2144 Implementations on Foreign Types</a>\
2145 <div class=\"sidebar-links\">",
2147 for (name, id) in res.into_iter() {
2148 write!(buf, "<a href=\"#{}\">{}</a>", id, Escape(&name));
2150 buf.push_str("</div>");
2154 sidebar_assoc_items(cx, buf, it);
2156 buf.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
2159 "<a class=\"sidebar-title\" \
2160 href=\"#synthetic-implementors\">Auto Implementors</a>",
2164 buf.push_str("</div>")
2167 fn sidebar_primitive(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2168 let mut sidebar = Buffer::new();
2169 sidebar_assoc_items(cx, &mut sidebar, it);
2171 if !sidebar.is_empty() {
2172 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2176 fn sidebar_typedef(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2177 let mut sidebar = Buffer::new();
2178 sidebar_assoc_items(cx, &mut sidebar, it);
2180 if !sidebar.is_empty() {
2181 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2185 fn get_struct_fields_name(fields: &[clean::Item]) -> Vec<String> {
2186 let mut fields = fields
2188 .filter(|f| matches!(*f.kind, clean::StructFieldItem(..)))
2190 f.name.map(|name| format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
2192 .collect::<Vec<_>>();
2197 fn sidebar_union(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
2198 let mut sidebar = Buffer::new();
2199 let fields = get_struct_fields_name(&u.fields);
2201 if !fields.is_empty() {
2203 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
2204 <div class=\"sidebar-links\">",
2207 for field in fields {
2208 sidebar.push_str(&field);
2211 sidebar.push_str("</div>");
2214 sidebar_assoc_items(cx, &mut sidebar, it);
2216 if !sidebar.is_empty() {
2217 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2221 fn sidebar_enum(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
2222 let mut sidebar = Buffer::new();
2224 let mut variants = e
2227 .filter_map(|v| match v.name {
2228 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
2231 .collect::<Vec<_>>();
2232 if !variants.is_empty() {
2233 variants.sort_unstable();
2234 sidebar.push_str(&format!(
2235 "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
2236 <div class=\"sidebar-links\">{}</div>",
2241 sidebar_assoc_items(cx, &mut sidebar, it);
2243 if !sidebar.is_empty() {
2244 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2248 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
2250 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
2251 ItemType::Module => ("modules", "Modules"),
2252 ItemType::Struct => ("structs", "Structs"),
2253 ItemType::Union => ("unions", "Unions"),
2254 ItemType::Enum => ("enums", "Enums"),
2255 ItemType::Function => ("functions", "Functions"),
2256 ItemType::Typedef => ("types", "Type Definitions"),
2257 ItemType::Static => ("statics", "Statics"),
2258 ItemType::Constant => ("constants", "Constants"),
2259 ItemType::Trait => ("traits", "Traits"),
2260 ItemType::Impl => ("impls", "Implementations"),
2261 ItemType::TyMethod => ("tymethods", "Type Methods"),
2262 ItemType::Method => ("methods", "Methods"),
2263 ItemType::StructField => ("fields", "Struct Fields"),
2264 ItemType::Variant => ("variants", "Variants"),
2265 ItemType::Macro => ("macros", "Macros"),
2266 ItemType::Primitive => ("primitives", "Primitive Types"),
2267 ItemType::AssocType => ("associated-types", "Associated Types"),
2268 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
2269 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
2270 ItemType::Keyword => ("keywords", "Keywords"),
2271 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
2272 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
2273 ItemType::ProcDerive => ("derives", "Derive Macros"),
2274 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
2278 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
2279 let mut sidebar = String::new();
2281 if items.iter().any(|it| {
2282 it.type_() == ItemType::ExternCrate || (it.type_() == ItemType::Import && !it.is_stripped())
2284 sidebar.push_str("<li><a href=\"#reexports\">Re-exports</a></li>");
2287 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
2288 // to print its headings
2290 ItemType::Primitive,
2304 ItemType::StructField,
2306 ItemType::AssocType,
2307 ItemType::AssocConst,
2308 ItemType::ForeignType,
2311 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
2312 let (short, name) = item_ty_to_strs(&myty);
2313 sidebar.push_str(&format!(
2314 "<li><a href=\"#{id}\">{name}</a></li>",
2321 if !sidebar.is_empty() {
2322 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
2326 fn sidebar_foreign_type(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2327 let mut sidebar = Buffer::new();
2328 sidebar_assoc_items(cx, &mut sidebar, it);
2330 if !sidebar.is_empty() {
2331 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2335 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
2337 /// Returns a list of all paths used in the type.
2338 /// This is used to help deduplicate imported impls
2339 /// for reexported types. If any of the contained
2340 /// types are re-exported, we don't use the corresponding
2341 /// entry from the js file, as inlining will have already
2342 /// picked up the impl
2343 fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> {
2344 let mut out = Vec::new();
2345 let mut visited = FxHashSet::default();
2346 let mut work = VecDeque::new();
2348 work.push_back(first_ty);
2350 while let Some(ty) = work.pop_front() {
2351 if !visited.insert(ty.clone()) {
2356 clean::Type::ResolvedPath { did, .. } => {
2357 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
2358 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
2360 if let Some(path) = fqp {
2361 out.push(path.join("::"));
2364 clean::Type::Tuple(tys) => {
2365 work.extend(tys.into_iter());
2367 clean::Type::Slice(ty) => {
2368 work.push_back(*ty);
2370 clean::Type::Array(ty, _) => {
2371 work.push_back(*ty);
2373 clean::Type::RawPointer(_, ty) => {
2374 work.push_back(*ty);
2376 clean::Type::BorrowedRef { type_, .. } => {
2377 work.push_back(*type_);
2379 clean::Type::QPath { self_type, trait_, .. } => {
2380 work.push_back(*self_type);
2381 work.push_back(*trait_);