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;
38 use std::collections::VecDeque;
39 use std::default::Default;
41 use std::path::PathBuf;
43 use std::string::ToString;
45 use rustc_ast_pretty::pprust;
46 use rustc_attr::{Deprecation, StabilityLevel};
47 use rustc_data_structures::fx::FxHashSet;
49 use rustc_hir::def::CtorKind;
50 use rustc_hir::def_id::DefId;
51 use rustc_hir::Mutability;
52 use rustc_middle::middle::stability;
53 use rustc_span::symbol::{kw, sym, Symbol};
54 use serde::ser::SerializeSeq;
55 use serde::{Serialize, Serializer};
57 use crate::clean::{self, GetDefId, RenderedLink, SelfTy, TypeKind};
58 use crate::docfs::PathError;
59 use crate::error::Error;
60 use crate::formats::cache::Cache;
61 use crate::formats::item_type::ItemType;
62 use crate::formats::{AssocItemRender, Impl, RenderMode};
63 use crate::html::escape::Escape;
64 use crate::html::format::{
65 href, print_abi_with_space, print_default_space, print_generic_bounds, print_where_clause,
66 Buffer, PrintWithSpace,
68 use crate::html::markdown::{Markdown, MarkdownHtml, MarkdownSummaryLine};
70 /// A pair of name and its optional document.
71 crate type NameDoc = (String, Option<String>);
73 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
74 crate::html::format::display_fn(move |f| {
75 if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { f.write_str(v) }
79 // Helper structs for rendering items/sidebars and carrying along contextual
82 /// Struct representing one entry in the JS search index. These are all emitted
83 /// by hand to a large JS file at the end of cache-creation.
85 crate struct IndexItem {
90 crate parent: Option<DefId>,
91 crate parent_idx: Option<usize>,
92 crate search_type: Option<IndexItemFunctionType>,
93 crate aliases: Box<[String]>,
96 /// A type used for the search index.
98 crate struct RenderType {
101 name: Option<String>,
102 generics: Option<Vec<Generic>>,
105 impl Serialize for RenderType {
106 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
110 if let Some(name) = &self.name {
111 let mut seq = serializer.serialize_seq(None)?;
112 if let Some(id) = self.idx {
113 seq.serialize_element(&id)?;
115 seq.serialize_element(&name)?;
117 if let Some(generics) = &self.generics {
118 seq.serialize_element(&generics)?;
122 serializer.serialize_none()
127 /// A type used for the search index.
129 crate struct Generic {
131 defid: Option<DefId>,
135 impl Serialize for Generic {
136 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
140 if let Some(id) = self.idx {
141 serializer.serialize_some(&id)
143 serializer.serialize_some(&self.name)
148 /// Full type of functions/methods in the search index.
150 crate struct IndexItemFunctionType {
151 inputs: Vec<TypeWithKind>,
152 output: Option<Vec<TypeWithKind>>,
155 impl Serialize for IndexItemFunctionType {
156 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
160 // If we couldn't figure out a type, just write `null`.
161 let mut iter = self.inputs.iter();
162 if match self.output {
163 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
164 None => iter.any(|ref i| i.ty.name.is_none()),
166 serializer.serialize_none()
168 let mut seq = serializer.serialize_seq(None)?;
169 seq.serialize_element(&self.inputs)?;
170 if let Some(output) = &self.output {
171 if output.len() > 1 {
172 seq.serialize_element(&output)?;
174 seq.serialize_element(&output[0])?;
183 crate struct TypeWithKind {
188 impl From<(RenderType, TypeKind)> for TypeWithKind {
189 fn from(x: (RenderType, TypeKind)) -> TypeWithKind {
190 TypeWithKind { ty: x.0, kind: x.1 }
194 impl Serialize for TypeWithKind {
195 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
199 (&self.ty.name, ItemType::from(self.kind)).serialize(serializer)
203 #[derive(Debug, Clone)]
204 crate struct StylePath {
205 /// The path to the theme
207 /// What the `disabled` attribute should be set to in the HTML tag
208 crate disabled: bool,
211 fn write_srclink(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) {
212 if let Some(l) = cx.src_href(item) {
213 write!(buf, "<a class=\"srclink\" href=\"{}\" title=\"goto source code\">[src]</a>", l)
217 #[derive(Debug, Eq, PartialEq, Hash)]
224 fn new(mut url: String, name: String) -> ItemEntry {
225 while url.starts_with('/') {
228 ItemEntry { url, name }
233 crate fn print(&self) -> impl fmt::Display + '_ {
234 crate::html::format::display_fn(move |f| {
235 write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name))
240 impl PartialOrd for ItemEntry {
241 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
242 Some(self.cmp(other))
246 impl Ord for ItemEntry {
247 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
248 self.name.cmp(&other.name)
254 structs: FxHashSet<ItemEntry>,
255 enums: FxHashSet<ItemEntry>,
256 unions: FxHashSet<ItemEntry>,
257 primitives: FxHashSet<ItemEntry>,
258 traits: FxHashSet<ItemEntry>,
259 macros: FxHashSet<ItemEntry>,
260 functions: FxHashSet<ItemEntry>,
261 typedefs: FxHashSet<ItemEntry>,
262 opaque_tys: FxHashSet<ItemEntry>,
263 statics: FxHashSet<ItemEntry>,
264 constants: FxHashSet<ItemEntry>,
265 keywords: FxHashSet<ItemEntry>,
266 attributes: FxHashSet<ItemEntry>,
267 derives: FxHashSet<ItemEntry>,
268 trait_aliases: FxHashSet<ItemEntry>,
272 fn new() -> AllTypes {
273 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
275 structs: new_set(100),
277 unions: new_set(100),
278 primitives: new_set(26),
279 traits: new_set(100),
280 macros: new_set(100),
281 functions: new_set(100),
282 typedefs: new_set(100),
283 opaque_tys: new_set(100),
284 statics: new_set(100),
285 constants: new_set(100),
286 keywords: new_set(100),
287 attributes: new_set(100),
288 derives: new_set(100),
289 trait_aliases: new_set(100),
293 fn append(&mut self, item_name: String, item_type: &ItemType) {
294 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
295 if let Some(name) = url.pop() {
296 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
298 let name = url.join("::");
300 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
301 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
302 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
303 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
304 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
305 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
306 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
307 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
308 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
309 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
310 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
311 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
312 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
313 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
321 fn print(self, f: &mut Buffer) {
322 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
324 let mut e: Vec<&ItemEntry> = e.iter().collect();
326 write!(f, "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">", title, title, class);
329 write!(f, "<li>{}</li>", s.print());
332 f.write_str("</ul>");
338 <span class=\"in-band\">List of all items</span>\
339 <span class=\"out-of-band\">\
340 <span id=\"render-detail\">\
341 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
342 title=\"collapse all docs\">\
343 [<span class=\"inner\">−</span>]\
349 // Note: print_entries does not escape the title, because we know the current set of titles
350 // don't require escaping.
351 print_entries(f, &self.structs, "Structs", "structs");
352 print_entries(f, &self.enums, "Enums", "enums");
353 print_entries(f, &self.unions, "Unions", "unions");
354 print_entries(f, &self.primitives, "Primitives", "primitives");
355 print_entries(f, &self.traits, "Traits", "traits");
356 print_entries(f, &self.macros, "Macros", "macros");
357 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
358 print_entries(f, &self.derives, "Derive Macros", "derives");
359 print_entries(f, &self.functions, "Functions", "functions");
360 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
361 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
362 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
363 print_entries(f, &self.statics, "Statics", "statics");
364 print_entries(f, &self.constants, "Constants", "constants")
371 description: &'static str,
372 sub_settings: Vec<Setting>,
375 js_data_name: &'static str,
376 description: &'static str,
380 js_data_name: &'static str,
381 description: &'static str,
382 default_value: &'static str,
383 options: Vec<(String, String)>,
388 fn display(&self, root_path: &str, suffix: &str) -> String {
390 Setting::Section { description, ref sub_settings } => format!(
391 "<div class=\"setting-line\">\
392 <div class=\"title\">{}</div>\
393 <div class=\"sub-settings\">{}</div>
396 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
398 Setting::Toggle { js_data_name, description, default_value } => format!(
399 "<div class=\"setting-line\">\
400 <label class=\"toggle\">\
401 <input type=\"checkbox\" id=\"{}\" {}>\
402 <span class=\"slider\"></span>\
407 if default_value { " checked" } else { "" },
410 Setting::Select { js_data_name, description, default_value, ref options } => format!(
411 "<div class=\"setting-line\">\
413 <label class=\"select-wrapper\">\
414 <select id=\"{}\" autocomplete=\"off\">{}</select>\
415 <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
423 "<option value=\"{}\" {}>{}</option>",
425 if opt.0 == default_value { "selected" } else { "" },
428 .collect::<String>(),
436 impl From<(&'static str, &'static str, bool)> for Setting {
437 fn from(values: (&'static str, &'static str, bool)) -> Setting {
438 Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
442 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
443 fn from(values: (&'static str, Vec<T>)) -> Setting {
445 description: values.0,
446 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
451 fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
452 let theme_names: Vec<(String, String)> = themes
456 try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
459 Ok((theme.clone(), theme))
461 .collect::<Result<_, Error>>()?;
463 // (id, explanation, default value)
464 let settings: &[Setting] = &[
468 Setting::from(("use-system-theme", "Use system theme", true)),
470 js_data_name: "preferred-dark-theme",
471 description: "Preferred dark theme",
472 default_value: "dark",
473 options: theme_names.clone(),
476 js_data_name: "preferred-light-theme",
477 description: "Preferred light theme",
478 default_value: "light",
479 options: theme_names,
484 ("auto-hide-large-items", "Auto-hide item contents for large items.", true).into(),
485 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
486 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", true)
488 ("auto-collapse-implementors", "Auto-hide implementors of a trait", true).into(),
489 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
491 ("line-numbers", "Show line numbers on code examples", false).into(),
492 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
497 <span class=\"in-band\">Rustdoc settings</span>\
499 <div class=\"settings\">{}</div>\
500 <script src=\"{}settings{}.js\"></script>",
501 settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
507 fn document(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, parent: Option<&clean::Item>) {
508 if let Some(ref name) = item.name {
509 info!("Documenting {}", name);
511 document_item_info(w, cx, item, false, parent);
512 document_full(w, item, cx, false);
515 /// Render md_text as markdown.
520 links: Vec<RenderedLink>,
523 let mut ids = cx.id_map.borrow_mut();
526 "<div class=\"docblock{}\">{}</div>",
527 if is_hidden { " hidden" } else { "" },
534 &cx.shared.playground
540 /// Writes a documentation block containing only the first paragraph of the documentation. If the
541 /// docs are longer, a "Read more" link is appended to the end.
546 link: AssocItemLink<'_>,
548 parent: &clean::Item,
551 document_item_info(w, cx, item, is_hidden, Some(parent));
555 if let Some(s) = item.doc_value() {
556 let mut summary_html = MarkdownSummaryLine(&s, &item.links(cx)).into_string();
558 if s.contains('\n') {
559 let link = format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link, cx));
561 if let Some(idx) = summary_html.rfind("</p>") {
562 summary_html.insert_str(idx, &link);
564 summary_html.push_str(&link);
570 "<div class='docblock{}'>{}</div>",
571 if is_hidden { " hidden" } else { "" },
577 fn document_full(w: &mut Buffer, item: &clean::Item, cx: &Context<'_>, is_hidden: bool) {
578 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
579 debug!("Doc block: =====\n{}\n=====", s);
580 render_markdown(w, cx, &s, item.links(cx), is_hidden);
584 /// Add extra information about an item such as:
588 /// * Required features (through the `doc_cfg` feature)
589 fn document_item_info(
594 parent: Option<&clean::Item>,
596 let item_infos = short_item_info(item, cx, parent);
597 if !item_infos.is_empty() {
599 w.write_str("<div class=\"item-info hidden\">");
601 w.write_str("<div class=\"item-info\">");
603 for info in item_infos {
606 w.write_str("</div>");
610 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
611 let cfg = match (&item.attrs.cfg, parent.and_then(|p| p.attrs.cfg.as_ref())) {
612 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
613 (cfg, _) => cfg.as_deref().cloned(),
617 "Portability {:?} - {:?} = {:?}",
619 parent.and_then(|p| p.attrs.cfg.as_ref()),
623 Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
626 /// Render the stability, deprecation and portability information that is displayed at the top of
627 /// the item's documentation.
631 parent: Option<&clean::Item>,
633 let mut extra_info = vec![];
634 let error_codes = cx.shared.codes;
636 if let Some(Deprecation { note, since, is_since_rustc_version, suggestion: _ }) =
637 item.deprecation(cx.tcx())
639 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
640 // but only display the future-deprecation messages for #[rustc_deprecated].
641 let mut message = if let Some(since) = since {
642 let since = &since.as_str();
643 if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
645 String::from("Deprecating in a future Rust version")
647 format!("Deprecating in {}", Escape(since))
650 format!("Deprecated since {}", Escape(since))
653 String::from("Deprecated")
656 if let Some(note) = note {
657 let note = note.as_str();
658 let mut ids = cx.id_map.borrow_mut();
659 let html = MarkdownHtml(
664 &cx.shared.playground,
666 message.push_str(&format!(": {}", html.into_string()));
668 extra_info.push(format!(
669 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
674 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
675 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
676 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
679 .filter(|stab| stab.feature != sym::rustc_private)
680 .map(|stab| (stab.level, stab.feature))
683 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
685 let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
686 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
687 feature.push_str(&format!(
688 " <a href=\"{url}{issue}\">#{issue}</a>",
694 message.push_str(&format!(" ({})", feature));
696 if let Some(unstable_reason) = reason {
697 let mut ids = cx.id_map.borrow_mut();
699 "<details><summary>{}</summary>{}</details>",
702 &unstable_reason.as_str(),
706 &cx.shared.playground,
712 extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
715 if let Some(portability) = portability(item, parent) {
716 extra_info.push(portability);
726 containing_item: &clean::Item,
728 let cache = cx.cache();
730 let mut impls = traits
733 let did = i.trait_did_full(cache).unwrap();
734 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
735 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
743 containing_item.stable_since(tcx).as_deref(),
744 containing_item.const_stable_since(tcx).as_deref(),
753 .collect::<Vec<_>>();
755 w.write_str(&impls.join(""));
758 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>, cx: &Context<'_>) -> String {
759 use crate::formats::item_type::ItemType::*;
761 let name = it.name.as_ref().unwrap();
762 let ty = match it.type_() {
763 Typedef | AssocType => AssocType,
767 let anchor = format!("#{}.{}", ty, name);
769 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
770 AssocItemLink::Anchor(None) => anchor,
771 AssocItemLink::GotoSource(did, _) => {
772 href(did, cx).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
781 _default: Option<&String>,
782 link: AssocItemLink<'_>,
788 "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
790 it.visibility.print_with_space(it.def_id, cx),
791 naive_assoc_href(it, link, cx),
792 it.name.as_ref().unwrap(),
800 bounds: &[clean::GenericBound],
801 default: Option<&clean::Type>,
802 link: AssocItemLink<'_>,
808 "{}type <a href=\"{}\" class=\"type\">{}</a>",
810 naive_assoc_href(it, link, cx),
811 it.name.as_ref().unwrap()
813 if !bounds.is_empty() {
814 write!(w, ": {}", print_generic_bounds(bounds, cx))
816 if let Some(default) = default {
817 write!(w, " = {}", default.print(cx))
821 fn render_stability_since_raw(
824 const_ver: Option<&str>,
825 containing_ver: Option<&str>,
826 containing_const_ver: Option<&str>,
828 let ver = ver.filter(|inner| !inner.is_empty());
829 let const_ver = const_ver.filter(|inner| !inner.is_empty());
831 match (ver, const_ver) {
832 (Some(v), Some(cv)) if const_ver != containing_const_ver => {
835 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
839 (Some(v), _) if ver != containing_ver => {
842 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
850 fn render_assoc_item(
853 link: AssocItemLink<'_>,
860 header: hir::FnHeader,
863 link: AssocItemLink<'_>,
867 let name = meth.name.as_ref().unwrap();
868 let href = match link {
869 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
870 AssocItemLink::Anchor(None) => format!("#{}.{}", meth.type_(), name),
871 AssocItemLink::GotoSource(did, provided_methods) => {
872 // We're creating a link from an impl-item to the corresponding
873 // trait-item and need to map the anchored type accordingly.
874 let ty = if provided_methods.contains(&name) {
881 .map(|p| format!("{}#{}.{}", p.0, ty, name))
882 .unwrap_or_else(|| format!("#{}.{}", ty, name))
885 let vis = meth.visibility.print_with_space(meth.def_id, cx).to_string();
886 let constness = header.constness.print_with_space();
887 let asyncness = header.asyncness.print_with_space();
888 let unsafety = header.unsafety.print_with_space();
889 let defaultness = print_default_space(meth.is_default());
890 let abi = print_abi_with_space(header.abi).to_string();
891 // NOTE: `{:#}` does not print HTML formatting, `{}` does. So `g.print` can't be reused between the length calculation and `write!`.
892 let generics_len = format!("{:#}", g.print(cx)).len();
893 let mut header_len = "fn ".len()
900 + name.as_str().len()
903 let (indent, indent_str, end_newline) = if parent == ItemType::Trait {
905 let indent_str = " ";
906 render_attributes_in_pre(w, meth, indent_str);
907 (4, indent_str, false)
909 render_attributes_in_code(w, meth);
912 w.reserve(header_len + "<a href=\"\" class=\"fnname\">{".len() + "</a>".len());
915 "{}{}{}{}{}{}{}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
916 {generics}{decl}{notable_traits}{where_clause}",
926 generics = g.print(cx),
927 decl = d.full_print(header_len, indent, header.asyncness, cx),
928 notable_traits = notable_traits_decl(&d, cx),
929 where_clause = print_where_clause(g, cx, indent, end_newline),
933 clean::StrippedItem(..) => {}
934 clean::TyMethodItem(ref m) => {
935 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
937 clean::MethodItem(ref m, _) => {
938 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
940 clean::AssocConstItem(ref ty, ref default) => assoc_const(
946 if parent == ItemType::Trait { " " } else { "" },
949 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
955 if parent == ItemType::Trait { " " } else { "" },
958 _ => panic!("render_assoc_item called on non-associated-item"),
962 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
971 fn attributes(it: &clean::Item) -> Vec<String> {
976 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
977 Some(pprust::attribute_to_string(&attr).replace("\n", "").replace(" ", " "))
985 // When an attribute is rendered inside a `<pre>` tag, it is formatted using
986 // a whitespace prefix and newline.
987 fn render_attributes_in_pre(w: &mut Buffer, it: &clean::Item, prefix: &str) {
988 for a in attributes(it) {
989 write!(w, "{}{}\n", prefix, a);
993 // When an attribute is rendered inside a <code> tag, it is formatted using
994 // a div to produce a newline after it.
995 fn render_attributes_in_code(w: &mut Buffer, it: &clean::Item) {
996 for a in attributes(it) {
997 write!(w, "<div class=\"code-attribute\">{}</div>", a);
1001 #[derive(Copy, Clone)]
1002 enum AssocItemLink<'a> {
1003 Anchor(Option<&'a str>),
1004 GotoSource(DefId, &'a FxHashSet<Symbol>),
1007 impl<'a> AssocItemLink<'a> {
1008 fn anchor(&self, id: &'a str) -> Self {
1010 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
1011 ref other => *other,
1016 fn render_assoc_items(
1019 containing_item: &clean::Item,
1021 what: AssocItemRender<'_>,
1023 info!("Documenting associated items of {:?}", containing_item.name);
1024 let v = match cx.cache.impls.get(&it) {
1029 let cache = cx.cache();
1030 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
1031 if !non_trait.is_empty() {
1032 let render_mode = match what {
1033 AssocItemRender::All => {
1035 "<h2 id=\"implementations\" class=\"small-section-header\">\
1036 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
1041 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
1043 cx.derive_id(small_url_encode(format!("deref-methods-{:#}", type_.print(cx))));
1044 debug!("Adding {} to deref id map", type_.print(cx));
1045 cx.deref_id_map.borrow_mut().insert(type_.def_id_full(cache).unwrap(), id.clone());
1048 "<h2 id=\"{id}\" class=\"small-section-header\">\
1049 Methods from {trait_}<Target = {type_}>\
1050 <a href=\"#{id}\" class=\"anchor\"></a>\
1053 trait_ = trait_.print(cx),
1054 type_ = type_.print(cx),
1056 RenderMode::ForDeref { mut_: deref_mut_ }
1059 for i in &non_trait {
1065 AssocItemLink::Anchor(None),
1067 containing_item.stable_since(tcx).as_deref(),
1068 containing_item.const_stable_since(tcx).as_deref(),
1077 if !traits.is_empty() {
1078 let deref_impl = traits
1080 .find(|t| t.inner_impl().trait_.def_id_full(cache) == cx.cache.deref_trait_did);
1081 if let Some(impl_) = deref_impl {
1082 let has_deref_mut = traits
1084 .any(|t| t.inner_impl().trait_.def_id_full(cache) == cx.cache.deref_mut_trait_did);
1085 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut);
1088 // If we were already one level into rendering deref methods, we don't want to render
1089 // anything after recursing into any further deref methods above.
1090 if let AssocItemRender::DerefFor { .. } = what {
1094 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
1095 traits.iter().partition(|t| t.inner_impl().synthetic);
1096 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
1097 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
1099 let mut impls = Buffer::empty_from(&w);
1100 render_impls(cx, &mut impls, &concrete, containing_item);
1101 let impls = impls.into_inner();
1102 if !impls.is_empty() {
1105 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
1106 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
1108 <div id=\"trait-implementations-list\">{}</div>",
1113 if !synthetic.is_empty() {
1115 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
1116 Auto Trait Implementations\
1117 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
1119 <div id=\"synthetic-implementations-list\">",
1121 render_impls(cx, w, &synthetic, containing_item);
1122 w.write_str("</div>");
1125 if !blanket_impl.is_empty() {
1127 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
1128 Blanket Implementations\
1129 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
1131 <div id=\"blanket-implementations-list\">",
1133 render_impls(cx, w, &blanket_impl, containing_item);
1134 w.write_str("</div>");
1139 fn render_deref_methods(
1143 container_item: &clean::Item,
1146 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
1147 let (target, real_target) = impl_
1151 .find_map(|item| match *item.kind {
1152 clean::TypedefItem(ref t, true) => Some(match *t {
1153 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
1154 _ => (&t.type_, &t.type_),
1158 .expect("Expected associated type binding");
1159 debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target);
1161 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
1162 if let Some(did) = target.def_id_full(cx.cache()) {
1163 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) {
1164 // `impl Deref<Target = S> for S`
1165 if did == type_did {
1166 // Avoid infinite cycles
1170 render_assoc_items(w, cx, container_item, did, what);
1172 if let Some(prim) = target.primitive_type() {
1173 if let Some(&did) = cx.cache.primitive_locations.get(&prim) {
1174 render_assoc_items(w, cx, container_item, did, what);
1180 fn should_render_item(item: &clean::Item, deref_mut_: bool, cache: &Cache) -> bool {
1181 let self_type_opt = match *item.kind {
1182 clean::MethodItem(ref method, _) => method.decl.self_type(),
1183 clean::TyMethodItem(ref method) => method.decl.self_type(),
1187 if let Some(self_ty) = self_type_opt {
1188 let (by_mut_ref, by_box, by_value) = match self_ty {
1189 SelfTy::SelfBorrowed(_, mutability)
1190 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
1191 (mutability == Mutability::Mut, false, false)
1193 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
1194 (false, Some(did) == cache.owned_box_did, false)
1196 SelfTy::SelfValue => (false, false, true),
1197 _ => (false, false, false),
1200 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
1206 fn notable_traits_decl(decl: &clean::FnDecl, cx: &Context<'_>) -> String {
1207 let mut out = Buffer::html();
1208 let mut trait_ = String::new();
1210 if let Some(did) = decl.output.def_id_full(cx.cache()) {
1211 if let Some(impls) = cx.cache().impls.get(&did) {
1213 let impl_ = i.inner_impl();
1214 if impl_.trait_.def_id().map_or(false, |d| {
1215 cx.cache().traits.get(&d).map(|t| t.is_notable).unwrap_or(false)
1220 "<h3 class=\"notable\">Notable traits for {}</h3>\
1221 <code class=\"content\">",
1222 impl_.for_.print(cx)
1224 trait_.push_str(&impl_.for_.print(cx).to_string());
1227 //use the "where" class here to make it small
1230 "<span class=\"where fmt-newline\">{}</span>",
1231 impl_.print(false, cx)
1233 let t_did = impl_.trait_.def_id_full(cx.cache()).unwrap();
1234 for it in &impl_.items {
1235 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1236 out.push_str("<span class=\"where fmt-newline\"> ");
1242 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
1246 out.push_str(";</span>");
1254 if !out.is_empty() {
1257 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
1258 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
1260 out.push_str("</code></span></div></span></span>");
1270 parent: &clean::Item,
1271 link: AssocItemLink<'_>,
1272 render_mode: RenderMode,
1273 outer_version: Option<&str>,
1274 outer_const_version: Option<&str>,
1275 show_def_docs: bool,
1276 use_absolute: Option<bool>,
1277 is_on_foreign_type: bool,
1278 show_default_items: bool,
1279 // This argument is used to reference same type with different paths to avoid duplication
1280 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
1284 let cache = cx.cache();
1285 let traits = &cache.traits;
1286 let trait_ = i.trait_did_full(cache).map(|did| &traits[&did]);
1288 if render_mode == RenderMode::Normal {
1289 let id = cx.derive_id(match i.inner_impl().trait_ {
1291 if is_on_foreign_type {
1292 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t, cx)
1294 format!("impl-{}", small_url_encode(format!("{:#}", t.print(cx))))
1297 None => "impl".to_string(),
1299 let aliases = if aliases.is_empty() {
1302 format!(" aliases=\"{}\"", aliases.join(","))
1304 if let Some(use_absolute) = use_absolute {
1305 write!(w, "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">", id, aliases);
1306 write!(w, "{}", i.inner_impl().print(use_absolute, cx));
1308 for it in &i.inner_impl().items {
1309 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1310 w.write_str("<span class=\"where fmt-newline\"> ");
1316 AssocItemLink::Anchor(None),
1320 w.write_str(";</span>");
1324 w.write_str("</code>");
1328 "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">{}</code>",
1331 i.inner_impl().print(false, cx)
1334 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1335 render_stability_since_raw(
1337 i.impl_item.stable_since(tcx).as_deref(),
1338 i.impl_item.const_stable_since(tcx).as_deref(),
1340 outer_const_version,
1342 write_srclink(cx, &i.impl_item, w);
1343 w.write_str("</h3>");
1345 if trait_.is_some() {
1346 if let Some(portability) = portability(&i.impl_item, Some(parent)) {
1347 write!(w, "<div class=\"item-info\">{}</div>", portability);
1351 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
1352 let mut ids = cx.id_map.borrow_mut();
1355 "<div class=\"docblock\">{}</div>",
1358 &i.impl_item.links(cx),
1362 &cx.shared.playground
1373 parent: &clean::Item,
1374 link: AssocItemLink<'_>,
1375 render_mode: RenderMode,
1376 is_default_item: bool,
1377 outer_version: Option<&str>,
1378 outer_const_version: Option<&str>,
1379 trait_: Option<&clean::Trait>,
1380 show_def_docs: bool,
1382 let item_type = item.type_();
1383 let name = item.name.as_ref().unwrap();
1386 let render_method_item = match render_mode {
1387 RenderMode::Normal => true,
1388 RenderMode::ForDeref { mut_: deref_mut_ } => {
1389 should_render_item(&item, deref_mut_, &cx.cache)
1393 let (is_hidden, extra_class) =
1394 if (trait_.is_none() || item.doc_value().is_some() || item.kind.is_type_alias())
1401 let in_trait_class = if trait_.is_some() { " trait-impl" } else { "" };
1403 clean::MethodItem(..) | clean::TyMethodItem(_) => {
1404 // Only render when the method is not static or we allow static methods
1405 if render_method_item {
1406 let id = cx.derive_id(format!("{}.{}", item_type, name));
1407 let source_id = trait_
1408 .and_then(|trait_| {
1409 trait_.items.iter().find(|item| {
1410 item.name.map(|n| n.as_str().eq(&name.as_str())).unwrap_or(false)
1413 .map(|item| format!("{}.{}", item.type_(), name));
1416 "<h4 id=\"{}\" class=\"{}{}{}\">",
1417 id, item_type, extra_class, in_trait_class,
1419 w.write_str("<code>");
1423 link.anchor(source_id.as_ref().unwrap_or(&id)),
1427 w.write_str("</code>");
1428 render_stability_since_raw(
1430 item.stable_since(tcx).as_deref(),
1431 item.const_stable_since(tcx).as_deref(),
1433 outer_const_version,
1435 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1436 write_srclink(cx, item, w);
1437 w.write_str("</h4>");
1440 clean::TypedefItem(ref tydef, _) => {
1441 let source_id = format!("{}.{}", ItemType::AssocType, name);
1442 let id = cx.derive_id(source_id.clone());
1445 "<h4 id=\"{}\" class=\"{}{}{}\"><code>",
1446 id, item_type, extra_class, in_trait_class
1453 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1457 w.write_str("</code>");
1458 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1459 w.write_str("</h4>");
1461 clean::AssocConstItem(ref ty, ref default) => {
1462 let source_id = format!("{}.{}", item_type, name);
1463 let id = cx.derive_id(source_id.clone());
1466 "<h4 id=\"{}\" class=\"{}{}{}\"><code>",
1467 id, item_type, extra_class, in_trait_class
1474 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1478 w.write_str("</code>");
1479 render_stability_since_raw(
1481 item.stable_since(tcx).as_deref(),
1482 item.const_stable_since(tcx).as_deref(),
1484 outer_const_version,
1486 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1487 write_srclink(cx, item, w);
1488 w.write_str("</h4>");
1490 clean::AssocTypeItem(ref bounds, ref default) => {
1491 let source_id = format!("{}.{}", item_type, name);
1492 let id = cx.derive_id(source_id.clone());
1495 "<h4 id=\"{}\" class=\"{}{}{}\"><code>",
1496 id, item_type, extra_class, in_trait_class
1503 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1507 w.write_str("</code>");
1508 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1509 w.write_str("</h4>");
1511 clean::StrippedItem(..) => return,
1512 _ => panic!("can't make docs for trait item with name {:?}", item.name),
1515 if render_method_item {
1516 if !is_default_item {
1517 if let Some(t) = trait_ {
1518 // The trait item may have been stripped so we might not
1519 // find any documentation or stability for it.
1520 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
1521 // We need the stability of the item from the trait
1522 // because impls can't have a stability.
1523 if item.doc_value().is_some() {
1524 document_item_info(w, cx, it, is_hidden, Some(parent));
1525 document_full(w, item, cx, is_hidden);
1527 // In case the item isn't documented,
1528 // provide short documentation from the trait.
1529 document_short(w, it, cx, link, is_hidden, parent, show_def_docs);
1533 document_item_info(w, cx, item, is_hidden, Some(parent));
1535 document_full(w, item, cx, is_hidden);
1539 document_short(w, item, cx, link, is_hidden, parent, show_def_docs);
1544 w.write_str("<div class=\"impl-items\">");
1545 for trait_item in &i.inner_impl().items {
1550 if trait_.is_some() { &i.impl_item } else { parent },
1555 outer_const_version,
1556 trait_.map(|t| &t.trait_),
1561 fn render_default_items(
1566 parent: &clean::Item,
1567 render_mode: RenderMode,
1568 outer_version: Option<&str>,
1569 outer_const_version: Option<&str>,
1570 show_def_docs: bool,
1572 for trait_item in &t.items {
1573 let n = trait_item.name;
1574 if i.items.iter().any(|m| m.name == n) {
1577 let did = i.trait_.as_ref().unwrap().def_id_full(cx.cache()).unwrap();
1578 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
1589 outer_const_version,
1596 // If we've implemented a trait, then also emit documentation for all
1597 // default items which weren't overridden in the implementation block.
1598 // We don't emit documentation for default items if they appear in the
1599 // Implementations on Foreign Types or Implementors sections.
1600 if show_default_items {
1601 if let Some(t) = trait_ {
1602 render_default_items(
1610 outer_const_version,
1615 w.write_str("</div>");
1618 fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) {
1619 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
1623 || it.is_primitive()
1631 "<p class=\"location\">{}{}</p>",
1633 clean::StructItem(..) => "Struct ",
1634 clean::TraitItem(..) => "Trait ",
1635 clean::PrimitiveItem(..) => "Primitive Type ",
1636 clean::UnionItem(..) => "Union ",
1637 clean::EnumItem(..) => "Enum ",
1638 clean::TypedefItem(..) => "Type Definition ",
1639 clean::ForeignTypeItem => "Foreign Type ",
1640 clean::ModuleItem(..) =>
1648 it.name.as_ref().unwrap()
1653 if let Some(ref version) = cx.cache.crate_version {
1656 "<div class=\"block version\">\
1664 buffer.write_str("<div class=\"sidebar-elems\">");
1668 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
1669 it.name.as_ref().expect("crates always have a name")
1673 clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s),
1674 clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t),
1675 clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it),
1676 clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u),
1677 clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e),
1678 clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it),
1679 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
1680 clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, it),
1684 // The sidebar is designed to display sibling functions, modules and
1685 // other miscellaneous information. since there are lots of sibling
1686 // items (and that causes quadratic growth in large modules),
1687 // we refactor common parts into a shared JavaScript file per module.
1688 // still, we don't move everything into JS because we want to preserve
1689 // as much HTML as possible in order to allow non-JS-enabled browsers
1690 // to navigate the documentation (though slightly inefficiently).
1692 buffer.write_str("<p class=\"location\">");
1693 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
1695 buffer.write_str("::<wbr>");
1699 "<a href=\"{}index.html\">{}</a>",
1700 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
1704 buffer.write_str("</p>");
1706 // Sidebar refers to the enclosing module, not this module.
1707 let relpath = if it.is_mod() { "../" } else { "" };
1710 "<div id=\"sidebar-vars\" data-name=\"{name}\" data-ty=\"{ty}\" data-relpath=\"{path}\">\
1712 name = it.name.unwrap_or(kw::Empty),
1717 // There is no sidebar-items.js beyond the crate root path
1718 // FIXME maybe dynamic crate loading can be merged here
1720 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
1722 // Closes sidebar-elems div.
1723 buffer.write_str("</div>");
1726 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
1727 if used_links.insert(url.clone()) {
1731 while !used_links.insert(format!("{}-{}", url, add)) {
1734 format!("{}-{}", url, add)
1740 used_links: &mut FxHashSet<String>,
1746 .filter_map(|item| match item.name {
1747 Some(ref name) if !name.is_empty() && item.is_method() => {
1748 if !for_deref || should_render_item(item, deref_mut, cache) {
1750 "<a href=\"#{}\">{}</a>",
1751 get_next_url(used_links, format!("method.{}", name)),
1760 .collect::<Vec<_>>()
1763 // The point is to url encode any potential character from a type with genericity.
1764 fn small_url_encode(s: String) -> String {
1765 let mut st = String::new();
1766 let mut last_match = 0;
1767 for (idx, c) in s.char_indices() {
1768 let escaped = match c {
1784 st += &s[last_match..idx];
1786 // NOTE: we only expect single byte characters here - which is fine as long as we
1787 // only match single byte characters
1788 last_match = idx + 1;
1791 if last_match != 0 {
1792 st += &s[last_match..];
1799 fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) {
1800 if let Some(v) = cx.cache.impls.get(&it.def_id) {
1801 let mut used_links = FxHashSet::default();
1802 let cache = cx.cache();
1805 let used_links_bor = &mut used_links;
1808 .filter(|i| i.inner_impl().trait_.is_none())
1809 .flat_map(move |i| {
1810 get_methods(i.inner_impl(), false, used_links_bor, false, &cx.cache)
1812 .collect::<Vec<_>>();
1813 if !ret.is_empty() {
1814 // We want links' order to be reproducible so we don't use unstable sort.
1818 "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
1819 <div class=\"sidebar-links\">",
1822 out.push_str(&line);
1824 out.push_str("</div>");
1828 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
1829 let format_impls = |impls: Vec<&Impl>| {
1830 let mut links = FxHashSet::default();
1835 if let Some(ref i) = it.inner_impl().trait_ {
1836 let i_display = format!("{:#}", i.print(cx));
1837 let out = Escape(&i_display);
1838 let encoded = small_url_encode(format!("{:#}", i.print(cx)));
1839 let generated = format!(
1840 "<a href=\"#impl-{}\">{}{}</a>",
1842 if it.inner_impl().negative_polarity { "!" } else { "" },
1845 if links.insert(generated.clone()) { Some(generated) } else { None }
1850 .collect::<Vec<String>>();
1855 let write_sidebar_links = |out: &mut Buffer, links: Vec<String>| {
1856 out.push_str("<div class=\"sidebar-links\">");
1858 out.push_str(&link);
1860 out.push_str("</div>");
1863 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
1864 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
1865 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
1867 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
1869 let concrete_format = format_impls(concrete);
1870 let synthetic_format = format_impls(synthetic);
1871 let blanket_format = format_impls(blanket_impl);
1873 if !concrete_format.is_empty() {
1875 "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
1876 Trait Implementations</a>",
1878 write_sidebar_links(out, concrete_format);
1881 if !synthetic_format.is_empty() {
1883 "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
1884 Auto Trait Implementations</a>",
1886 write_sidebar_links(out, synthetic_format);
1889 if !blanket_format.is_empty() {
1891 "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
1892 Blanket Implementations</a>",
1894 write_sidebar_links(out, blanket_format);
1897 if let Some(impl_) = v
1899 .filter(|i| i.inner_impl().trait_.is_some())
1900 .find(|i| i.inner_impl().trait_.def_id_full(cache) == cx.cache.deref_trait_did)
1902 sidebar_deref_methods(cx, out, impl_, v);
1908 fn sidebar_deref_methods(cx: &Context<'_>, out: &mut Buffer, impl_: &Impl, v: &Vec<Impl>) {
1911 debug!("found Deref: {:?}", impl_);
1912 if let Some((target, real_target)) =
1913 impl_.inner_impl().items.iter().find_map(|item| match *item.kind {
1914 clean::TypedefItem(ref t, true) => Some(match *t {
1915 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
1916 _ => (&t.type_, &t.type_),
1921 debug!("found target, real_target: {:?} {:?}", target, real_target);
1922 if let Some(did) = target.def_id_full(c) {
1923 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(c) {
1924 // `impl Deref<Target = S> for S`
1925 if did == type_did {
1926 // Avoid infinite cycles
1933 .filter(|i| i.inner_impl().trait_.is_some())
1934 .any(|i| i.inner_impl().trait_.def_id_full(c) == c.deref_mut_trait_did);
1935 let inner_impl = target
1938 target.primitive_type().and_then(|prim| c.primitive_locations.get(&prim).cloned())
1940 .and_then(|did| c.impls.get(&did));
1941 if let Some(impls) = inner_impl {
1942 debug!("found inner_impl: {:?}", impls);
1943 let mut used_links = FxHashSet::default();
1946 .filter(|i| i.inner_impl().trait_.is_none())
1947 .flat_map(|i| get_methods(i.inner_impl(), true, &mut used_links, deref_mut, c))
1948 .collect::<Vec<_>>();
1949 if !ret.is_empty() {
1950 let deref_id_map = cx.deref_id_map.borrow();
1951 let id = deref_id_map
1952 .get(&real_target.def_id_full(c).unwrap())
1953 .expect("Deref section without derived id");
1956 "<a class=\"sidebar-title\" href=\"#{}\">Methods from {}<Target={}></a>",
1958 Escape(&format!("{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print(cx))),
1959 Escape(&format!("{:#}", real_target.print(cx))),
1961 // We want links' order to be reproducible so we don't use unstable sort.
1963 out.push_str("<div class=\"sidebar-links\">");
1965 out.push_str(&link);
1967 out.push_str("</div>");
1971 // Recurse into any further impls that might exist for `target`
1972 if let Some(target_did) = target.def_id_full(c) {
1973 if let Some(target_impls) = c.impls.get(&target_did) {
1974 if let Some(target_deref_impl) = target_impls
1976 .filter(|i| i.inner_impl().trait_.is_some())
1977 .find(|i| i.inner_impl().trait_.def_id_full(c) == c.deref_trait_did)
1979 sidebar_deref_methods(cx, out, target_deref_impl, target_impls);
1986 fn sidebar_struct(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
1987 let mut sidebar = Buffer::new();
1988 let fields = get_struct_fields_name(&s.fields);
1990 if !fields.is_empty() {
1991 if let CtorKind::Fictive = s.struct_type {
1993 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
1994 <div class=\"sidebar-links\">",
1997 for field in fields {
1998 sidebar.push_str(&field);
2001 sidebar.push_str("</div>");
2005 sidebar_assoc_items(cx, &mut sidebar, it);
2007 if !sidebar.is_empty() {
2008 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2012 fn get_id_for_impl_on_foreign_type(
2014 trait_: &clean::Type,
2017 small_url_encode(format!("impl-{:#}-for-{:#}", trait_.print(cx), for_.print(cx),))
2020 fn extract_for_impl_name(item: &clean::Item, cx: &Context<'_>) -> Option<(String, String)> {
2022 clean::ItemKind::ImplItem(ref i) => {
2023 if let Some(ref trait_) = i.trait_ {
2024 // Alternative format produces no URLs,
2025 // so this parameter does nothing.
2027 format!("{:#}", i.for_.print(cx)),
2028 get_id_for_impl_on_foreign_type(&i.for_, trait_, cx),
2038 fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
2039 buf.write_str("<div class=\"block items\">");
2041 fn print_sidebar_section(
2043 items: &[clean::Item],
2045 filter: impl Fn(&clean::Item) -> bool,
2046 write: impl Fn(&mut Buffer, &str),
2049 let mut items = items
2051 .filter_map(|m| match m.name {
2052 Some(ref name) if filter(m) => Some(name.as_str()),
2055 .collect::<Vec<_>>();
2057 if !items.is_empty() {
2058 items.sort_unstable();
2059 out.push_str(before);
2060 for item in items.into_iter() {
2063 out.push_str(after);
2067 print_sidebar_section(
2070 "<a class=\"sidebar-title\" href=\"#associated-types\">\
2071 Associated Types</a><div class=\"sidebar-links\">",
2072 |m| m.is_associated_type(),
2073 |out, sym| write!(out, "<a href=\"#associatedtype.{0}\">{0}</a>", sym),
2077 print_sidebar_section(
2080 "<a class=\"sidebar-title\" href=\"#associated-const\">\
2081 Associated Constants</a><div class=\"sidebar-links\">",
2082 |m| m.is_associated_const(),
2083 |out, sym| write!(out, "<a href=\"#associatedconstant.{0}\">{0}</a>", sym),
2087 print_sidebar_section(
2090 "<a class=\"sidebar-title\" href=\"#required-methods\">\
2091 Required Methods</a><div class=\"sidebar-links\">",
2092 |m| m.is_ty_method(),
2093 |out, sym| write!(out, "<a href=\"#tymethod.{0}\">{0}</a>", sym),
2097 print_sidebar_section(
2100 "<a class=\"sidebar-title\" href=\"#provided-methods\">\
2101 Provided Methods</a><div class=\"sidebar-links\">",
2103 |out, sym| write!(out, "<a href=\"#method.{0}\">{0}</a>", sym),
2107 if let Some(implementors) = cx.cache.implementors.get(&it.def_id) {
2108 let cache = cx.cache();
2109 let mut res = implementors
2115 .map_or(false, |d| !cx.cache.paths.contains_key(&d))
2117 .filter_map(|i| extract_for_impl_name(&i.impl_item, cx))
2118 .collect::<Vec<_>>();
2120 if !res.is_empty() {
2123 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
2124 Implementations on Foreign Types</a>\
2125 <div class=\"sidebar-links\">",
2127 for (name, id) in res.into_iter() {
2128 write!(buf, "<a href=\"#{}\">{}</a>", id, Escape(&name));
2130 buf.push_str("</div>");
2134 sidebar_assoc_items(cx, buf, it);
2136 buf.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
2139 "<a class=\"sidebar-title\" \
2140 href=\"#synthetic-implementors\">Auto Implementors</a>",
2144 buf.push_str("</div>")
2147 fn sidebar_primitive(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2148 let mut sidebar = Buffer::new();
2149 sidebar_assoc_items(cx, &mut sidebar, it);
2151 if !sidebar.is_empty() {
2152 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2156 fn sidebar_typedef(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2157 let mut sidebar = Buffer::new();
2158 sidebar_assoc_items(cx, &mut sidebar, it);
2160 if !sidebar.is_empty() {
2161 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2165 fn get_struct_fields_name(fields: &[clean::Item]) -> Vec<String> {
2166 let mut fields = fields
2168 .filter(|f| matches!(*f.kind, clean::StructFieldItem(..)))
2170 f.name.map(|name| format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
2172 .collect::<Vec<_>>();
2177 fn sidebar_union(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
2178 let mut sidebar = Buffer::new();
2179 let fields = get_struct_fields_name(&u.fields);
2181 if !fields.is_empty() {
2183 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
2184 <div class=\"sidebar-links\">",
2187 for field in fields {
2188 sidebar.push_str(&field);
2191 sidebar.push_str("</div>");
2194 sidebar_assoc_items(cx, &mut sidebar, it);
2196 if !sidebar.is_empty() {
2197 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2201 fn sidebar_enum(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
2202 let mut sidebar = Buffer::new();
2204 let mut variants = e
2207 .filter_map(|v| match v.name {
2208 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
2211 .collect::<Vec<_>>();
2212 if !variants.is_empty() {
2213 variants.sort_unstable();
2214 sidebar.push_str(&format!(
2215 "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
2216 <div class=\"sidebar-links\">{}</div>",
2221 sidebar_assoc_items(cx, &mut sidebar, it);
2223 if !sidebar.is_empty() {
2224 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2228 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
2230 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
2231 ItemType::Module => ("modules", "Modules"),
2232 ItemType::Struct => ("structs", "Structs"),
2233 ItemType::Union => ("unions", "Unions"),
2234 ItemType::Enum => ("enums", "Enums"),
2235 ItemType::Function => ("functions", "Functions"),
2236 ItemType::Typedef => ("types", "Type Definitions"),
2237 ItemType::Static => ("statics", "Statics"),
2238 ItemType::Constant => ("constants", "Constants"),
2239 ItemType::Trait => ("traits", "Traits"),
2240 ItemType::Impl => ("impls", "Implementations"),
2241 ItemType::TyMethod => ("tymethods", "Type Methods"),
2242 ItemType::Method => ("methods", "Methods"),
2243 ItemType::StructField => ("fields", "Struct Fields"),
2244 ItemType::Variant => ("variants", "Variants"),
2245 ItemType::Macro => ("macros", "Macros"),
2246 ItemType::Primitive => ("primitives", "Primitive Types"),
2247 ItemType::AssocType => ("associated-types", "Associated Types"),
2248 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
2249 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
2250 ItemType::Keyword => ("keywords", "Keywords"),
2251 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
2252 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
2253 ItemType::ProcDerive => ("derives", "Derive Macros"),
2254 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
2258 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
2259 let mut sidebar = String::new();
2261 if items.iter().any(|it| {
2262 it.type_() == ItemType::ExternCrate || (it.type_() == ItemType::Import && !it.is_stripped())
2264 sidebar.push_str("<li><a href=\"#reexports\">Re-exports</a></li>");
2267 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
2268 // to print its headings
2270 ItemType::Primitive,
2284 ItemType::StructField,
2286 ItemType::AssocType,
2287 ItemType::AssocConst,
2288 ItemType::ForeignType,
2291 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
2292 let (short, name) = item_ty_to_strs(&myty);
2293 sidebar.push_str(&format!(
2294 "<li><a href=\"#{id}\">{name}</a></li>",
2301 if !sidebar.is_empty() {
2302 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
2306 fn sidebar_foreign_type(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2307 let mut sidebar = Buffer::new();
2308 sidebar_assoc_items(cx, &mut sidebar, it);
2310 if !sidebar.is_empty() {
2311 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2315 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
2317 /// Returns a list of all paths used in the type.
2318 /// This is used to help deduplicate imported impls
2319 /// for reexported types. If any of the contained
2320 /// types are re-exported, we don't use the corresponding
2321 /// entry from the js file, as inlining will have already
2322 /// picked up the impl
2323 fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> {
2324 let mut out = Vec::new();
2325 let mut visited = FxHashSet::default();
2326 let mut work = VecDeque::new();
2328 work.push_back(first_ty);
2330 while let Some(ty) = work.pop_front() {
2331 if !visited.insert(ty.clone()) {
2336 clean::Type::ResolvedPath { did, .. } => {
2337 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
2338 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
2340 if let Some(path) = fqp {
2341 out.push(path.join("::"));
2344 clean::Type::Tuple(tys) => {
2345 work.extend(tys.into_iter());
2347 clean::Type::Slice(ty) => {
2348 work.push_back(*ty);
2350 clean::Type::Array(ty, _) => {
2351 work.push_back(*ty);
2353 clean::Type::RawPointer(_, ty) => {
2354 work.push_back(*ty);
2356 clean::Type::BorrowedRef { type_, .. } => {
2357 work.push_back(*type_);
2359 clean::Type::QPath { self_type, trait_, .. } => {
2360 work.push_back(*self_type);
2361 work.push_back(*trait_);