1 //! Rustdoc's HTML rendering module.
3 //! This modules contains the bulk of the logic necessary for rendering a
4 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
5 //! rendering process is largely driven by the `format!` syntax extension to
6 //! perform all I/O into files and streams.
8 //! The rendering process is largely driven by the `Context` and `Cache`
9 //! structures. The cache is pre-populated by crawling the crate in question,
10 //! and then it is shared among the various rendering threads. The cache is meant
11 //! to be a fairly large structure not implementing `Clone` (because it's shared
12 //! among threads). The context, however, should be a lightweight structure. This
13 //! is cloned per-thread and contains information about what is currently being
16 //! In order to speed up rendering (mostly because of markdown rendering), the
17 //! rendering process has been parallelized. This parallelization is only
18 //! exposed through the `crate` method on the context, and then also from the
19 //! fact that the shared cache is stored in TLS (and must be accessed as such).
21 //! In addition to rendering the crate itself, this module is also responsible
22 //! for creating the corresponding search index and source file renderings.
23 //! These threads are not parallelized (they haven't been a bottleneck yet), and
24 //! both occur before the crate is rendered.
37 use std::collections::VecDeque;
38 use std::default::Default;
40 use std::path::PathBuf;
42 use std::string::ToString;
44 use rustc_ast_pretty::pprust;
45 use rustc_attr::{ConstStability, Deprecation, StabilityLevel};
46 use rustc_data_structures::fx::FxHashSet;
48 use rustc_hir::def::CtorKind;
49 use rustc_hir::def_id::DefId;
50 use rustc_hir::Mutability;
51 use rustc_middle::middle::stability;
52 use rustc_span::symbol::{kw, sym, Symbol};
53 use serde::ser::SerializeSeq;
54 use serde::{Serialize, Serializer};
56 use crate::clean::{self, FakeDefId, GetDefId, RenderedLink, SelfTy};
57 use crate::docfs::PathError;
58 use crate::error::Error;
59 use crate::formats::cache::Cache;
60 use crate::formats::item_type::ItemType;
61 use crate::formats::{AssocItemRender, Impl, RenderMode};
62 use crate::html::escape::Escape;
63 use crate::html::format::{
64 href, print_abi_with_space, print_constness_with_space, print_default_space,
65 print_generic_bounds, print_where_clause, Buffer, PrintWithSpace,
67 use crate::html::markdown::{Markdown, MarkdownHtml, MarkdownSummaryLine};
69 /// A pair of name and its optional document.
70 crate type NameDoc = (String, Option<String>);
72 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
73 crate::html::format::display_fn(move |f| {
74 if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { f.write_str(v) }
78 // Helper structs for rendering items/sidebars and carrying along contextual
81 /// Struct representing one entry in the JS search index. These are all emitted
82 /// by hand to a large JS file at the end of cache-creation.
84 crate struct IndexItem {
89 crate parent: Option<DefId>,
90 crate parent_idx: Option<usize>,
91 crate search_type: Option<IndexItemFunctionType>,
92 crate aliases: Box<[String]>,
95 /// A type used for the search index.
97 crate struct RenderType {
100 name: Option<String>,
101 generics: Option<Vec<Generic>>,
104 impl Serialize for RenderType {
105 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
109 if let Some(name) = &self.name {
110 let mut seq = serializer.serialize_seq(None)?;
111 if let Some(id) = self.idx {
112 seq.serialize_element(&id)?;
114 seq.serialize_element(&name)?;
116 if let Some(generics) = &self.generics {
117 seq.serialize_element(&generics)?;
121 serializer.serialize_none()
126 /// A type used for the search index.
128 crate struct Generic {
130 defid: Option<DefId>,
134 impl Serialize for Generic {
135 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
139 if let Some(id) = self.idx {
140 serializer.serialize_some(&id)
142 serializer.serialize_some(&self.name)
147 /// Full type of functions/methods in the search index.
149 crate struct IndexItemFunctionType {
150 inputs: Vec<TypeWithKind>,
151 output: Option<Vec<TypeWithKind>>,
154 impl Serialize for IndexItemFunctionType {
155 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
159 // If we couldn't figure out a type, just write `null`.
160 let mut iter = self.inputs.iter();
161 if match self.output {
162 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
163 None => iter.any(|ref i| i.ty.name.is_none()),
165 serializer.serialize_none()
167 let mut seq = serializer.serialize_seq(None)?;
168 seq.serialize_element(&self.inputs)?;
169 if let Some(output) = &self.output {
170 if output.len() > 1 {
171 seq.serialize_element(&output)?;
173 seq.serialize_element(&output[0])?;
182 crate struct TypeWithKind {
187 impl From<(RenderType, ItemType)> for TypeWithKind {
188 fn from(x: (RenderType, ItemType)) -> TypeWithKind {
189 TypeWithKind { ty: x.0, kind: x.1 }
193 impl Serialize for TypeWithKind {
194 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
198 (&self.ty.name, self.kind).serialize(serializer)
202 #[derive(Debug, Clone)]
203 crate struct StylePath {
204 /// The path to the theme
206 /// What the `disabled` attribute should be set to in the HTML tag
207 crate disabled: bool,
210 fn write_srclink(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) {
211 if let Some(l) = cx.src_href(item) {
212 write!(buf, "<a class=\"srclink\" href=\"{}\" title=\"goto source code\">[src]</a>", l)
216 #[derive(Debug, Eq, PartialEq, Hash)]
223 fn new(mut url: String, name: String) -> ItemEntry {
224 while url.starts_with('/') {
227 ItemEntry { url, name }
232 crate fn print(&self) -> impl fmt::Display + '_ {
233 crate::html::format::display_fn(move |f| {
234 write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name))
239 impl PartialOrd for ItemEntry {
240 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
241 Some(self.cmp(other))
245 impl Ord for ItemEntry {
246 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
247 self.name.cmp(&other.name)
253 structs: FxHashSet<ItemEntry>,
254 enums: FxHashSet<ItemEntry>,
255 unions: FxHashSet<ItemEntry>,
256 primitives: FxHashSet<ItemEntry>,
257 traits: FxHashSet<ItemEntry>,
258 macros: FxHashSet<ItemEntry>,
259 functions: FxHashSet<ItemEntry>,
260 typedefs: FxHashSet<ItemEntry>,
261 opaque_tys: FxHashSet<ItemEntry>,
262 statics: FxHashSet<ItemEntry>,
263 constants: FxHashSet<ItemEntry>,
264 keywords: FxHashSet<ItemEntry>,
265 attributes: FxHashSet<ItemEntry>,
266 derives: FxHashSet<ItemEntry>,
267 trait_aliases: FxHashSet<ItemEntry>,
271 fn new() -> AllTypes {
272 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
274 structs: new_set(100),
276 unions: new_set(100),
277 primitives: new_set(26),
278 traits: new_set(100),
279 macros: new_set(100),
280 functions: new_set(100),
281 typedefs: new_set(100),
282 opaque_tys: new_set(100),
283 statics: new_set(100),
284 constants: new_set(100),
285 keywords: new_set(100),
286 attributes: new_set(100),
287 derives: new_set(100),
288 trait_aliases: new_set(100),
292 fn append(&mut self, item_name: String, item_type: &ItemType) {
293 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
294 if let Some(name) = url.pop() {
295 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
297 let name = url.join("::");
299 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
300 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
301 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
302 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
303 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
304 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
305 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
306 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
307 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
308 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
309 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
310 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
311 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
312 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
320 fn print(self, f: &mut Buffer) {
321 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
323 let mut e: Vec<&ItemEntry> = e.iter().collect();
327 "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">",
328 title.replace(' ', "-"), // IDs cannot contain whitespaces.
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 // doesn'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-large-items", "Auto-hide item contents for large items.", true).into(),
490 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
491 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", false)
493 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
495 ("line-numbers", "Show line numbers on code examples", false).into(),
496 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
501 <span class=\"in-band\">Rustdoc settings</span>\
503 <div class=\"settings\">{}</div>\
504 <script src=\"{}settings{}.js\"></script>",
505 settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
511 fn document(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, parent: Option<&clean::Item>) {
512 if let Some(ref name) = item.name {
513 info!("Documenting {}", name);
515 document_item_info(w, cx, item, parent);
516 if parent.is_none() {
517 document_full_collapsible(w, item, cx);
519 document_full(w, item, cx);
523 /// Render md_text as markdown.
524 fn render_markdown(w: &mut Buffer, cx: &Context<'_>, md_text: &str, links: Vec<RenderedLink>) {
525 let mut ids = cx.id_map.borrow_mut();
528 "<div class=\"docblock\">{}</div>",
535 &cx.shared.playground
541 /// Writes a documentation block containing only the first paragraph of the documentation. If the
542 /// docs are longer, a "Read more" link is appended to the end.
547 link: AssocItemLink<'_>,
548 parent: &clean::Item,
551 document_item_info(w, cx, item, 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);
568 write!(w, "<div class='docblock'>{}</div>", summary_html,);
572 fn document_full_collapsible(w: &mut Buffer, item: &clean::Item, cx: &Context<'_>) {
573 document_full_inner(w, item, cx, true);
576 fn document_full(w: &mut Buffer, item: &clean::Item, cx: &Context<'_>) {
577 document_full_inner(w, item, cx, false);
580 fn document_full_inner(w: &mut Buffer, item: &clean::Item, cx: &Context<'_>, is_collapsible: bool) {
581 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
582 debug!("Doc block: =====\n{}\n=====", s);
585 "<details class=\"rustdoc-toggle top-doc\" open>\
586 <summary class=\"hideme\">\
587 <span>Expand description</span>\
590 render_markdown(w, cx, &s, item.links(cx));
591 w.write_str("</details>");
593 render_markdown(w, cx, &s, item.links(cx));
598 /// Add extra information about an item such as:
602 /// * Required features (through the `doc_cfg` feature)
603 fn document_item_info(
607 parent: Option<&clean::Item>,
609 let item_infos = short_item_info(item, cx, parent);
610 if !item_infos.is_empty() {
611 w.write_str("<div class=\"item-info\">");
612 for info in item_infos {
615 w.write_str("</div>");
619 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
620 let cfg = match (&item.cfg, parent.and_then(|p| p.cfg.as_ref())) {
621 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
622 (cfg, _) => cfg.as_deref().cloned(),
625 debug!("Portability {:?} - {:?} = {:?}", item.cfg, parent.and_then(|p| p.cfg.as_ref()), cfg);
627 Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
630 /// Render the stability, deprecation and portability information that is displayed at the top of
631 /// the item's documentation.
635 parent: Option<&clean::Item>,
637 let mut extra_info = vec![];
638 let error_codes = cx.shared.codes;
640 if let Some(Deprecation { note, since, is_since_rustc_version, suggestion: _ }) =
641 item.deprecation(cx.tcx())
643 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
644 // but only display the future-deprecation messages for #[rustc_deprecated].
645 let mut message = if let Some(since) = since {
646 let since = &since.as_str();
647 if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
649 String::from("Deprecating in a future Rust version")
651 format!("Deprecating in {}", Escape(since))
654 format!("Deprecated since {}", Escape(since))
657 String::from("Deprecated")
660 if let Some(note) = note {
661 let note = note.as_str();
662 let mut ids = cx.id_map.borrow_mut();
663 let html = MarkdownHtml(
668 &cx.shared.playground,
670 message.push_str(&format!(": {}", html.into_string()));
672 extra_info.push(format!(
673 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
678 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
679 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
680 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
683 .filter(|stab| stab.feature != sym::rustc_private)
684 .map(|stab| (stab.level, stab.feature))
687 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
689 let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
690 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
691 feature.push_str(&format!(
692 " <a href=\"{url}{issue}\">#{issue}</a>",
698 message.push_str(&format!(" ({})", feature));
700 if let Some(unstable_reason) = reason {
701 let mut ids = cx.id_map.borrow_mut();
703 "<details><summary>{}</summary>{}</details>",
706 &unstable_reason.as_str(),
710 &cx.shared.playground,
716 extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
719 if let Some(portability) = portability(item, parent) {
720 extra_info.push(portability);
726 // Render the list of items inside one of the sections "Trait Implementations",
727 // "Auto Trait Implementations," "Blanket Trait Implementations" (on struct/enum pages).
732 containing_item: &clean::Item,
734 let cache = cx.cache();
736 let mut impls = traits
739 let did = i.trait_did_full(cache).unwrap();
740 let provided_trait_methods = i.inner_impl().provided_trait_methods(tcx);
741 let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_trait_methods);
742 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
758 .collect::<Vec<_>>();
760 w.write_str(&impls.join(""));
763 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>, cx: &Context<'_>) -> String {
764 use crate::formats::item_type::ItemType::*;
766 let name = it.name.as_ref().unwrap();
767 let ty = match it.type_() {
768 Typedef | AssocType => AssocType,
772 let anchor = format!("#{}.{}", ty, name);
774 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
775 AssocItemLink::Anchor(None) => anchor,
776 AssocItemLink::GotoSource(did, _) => {
777 href(did.expect_real(), cx).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
786 _default: Option<&String>,
787 link: AssocItemLink<'_>,
793 "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
795 it.visibility.print_with_space(it.def_id, cx),
796 naive_assoc_href(it, link, cx),
797 it.name.as_ref().unwrap(),
805 bounds: &[clean::GenericBound],
806 default: Option<&clean::Type>,
807 link: AssocItemLink<'_>,
813 "{}type <a href=\"{}\" class=\"type\">{}</a>",
815 naive_assoc_href(it, link, cx),
816 it.name.as_ref().unwrap()
818 if !bounds.is_empty() {
819 write!(w, ": {}", print_generic_bounds(bounds, cx))
821 if let Some(default) = default {
822 write!(w, " = {}", default.print(cx))
826 fn render_stability_since_raw(
829 const_stability: Option<&ConstStability>,
830 containing_ver: Option<&str>,
831 containing_const_ver: Option<&str>,
833 let ver = ver.filter(|inner| !inner.is_empty());
835 match (ver, const_stability) {
836 // stable and const stable
837 (Some(v), Some(ConstStability { level: StabilityLevel::Stable { since }, .. }))
838 if Some(since.as_str()).as_deref() != containing_const_ver =>
842 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
846 // stable and const unstable
849 Some(ConstStability { level: StabilityLevel::Unstable { issue, .. }, feature, .. }),
853 "<span class=\"since\" title=\"Stable since Rust version {0}, const unstable\">{0} (const: ",
856 if let Some(n) = issue {
859 "<a href=\"https://github.com/rust-lang/rust/issues/{}\" title=\"Tracking issue for {}\">unstable</a>",
863 write!(w, "unstable");
865 write!(w, ")</span>");
868 (Some(v), _) if ver != containing_ver => {
871 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
879 fn render_assoc_item(
882 link: AssocItemLink<'_>,
889 header: hir::FnHeader,
892 link: AssocItemLink<'_>,
896 let name = meth.name.as_ref().unwrap();
897 let href = match link {
898 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
899 AssocItemLink::Anchor(None) => format!("#{}.{}", meth.type_(), name),
900 AssocItemLink::GotoSource(did, provided_methods) => {
901 // We're creating a link from an impl-item to the corresponding
902 // trait-item and need to map the anchored type accordingly.
903 let ty = if provided_methods.contains(&name) {
909 href(did.expect_real(), cx)
910 .map(|p| format!("{}#{}.{}", p.0, ty, name))
911 .unwrap_or_else(|| format!("#{}.{}", ty, name))
914 let vis = meth.visibility.print_with_space(meth.def_id, cx).to_string();
916 print_constness_with_space(&header.constness, meth.const_stability(cx.tcx()));
917 let asyncness = header.asyncness.print_with_space();
918 let unsafety = header.unsafety.print_with_space();
919 let defaultness = print_default_space(meth.is_default());
920 let abi = print_abi_with_space(header.abi).to_string();
922 // NOTE: `{:#}` does not print HTML formatting, `{}` does. So `g.print` can't be reused between the length calculation and `write!`.
923 let generics_len = format!("{:#}", g.print(cx)).len();
924 let mut header_len = "fn ".len()
931 + name.as_str().len()
934 let (indent, indent_str, end_newline) = if parent == ItemType::Trait {
936 let indent_str = " ";
937 render_attributes_in_pre(w, meth, indent_str);
938 (4, indent_str, false)
940 render_attributes_in_code(w, meth);
943 w.reserve(header_len + "<a href=\"\" class=\"fnname\">{".len() + "</a>".len());
946 "{indent}{vis}{constness}{asyncness}{unsafety}{defaultness}{abi}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
947 {generics}{decl}{notable_traits}{where_clause}",
950 constness = constness,
951 asyncness = asyncness,
953 defaultness = defaultness,
957 generics = g.print(cx),
958 decl = d.full_print(header_len, indent, header.asyncness, cx),
959 notable_traits = notable_traits_decl(&d, cx),
960 where_clause = print_where_clause(g, cx, indent, end_newline),
964 clean::StrippedItem(..) => {}
965 clean::TyMethodItem(ref m) => {
966 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
968 clean::MethodItem(ref m, _) => {
969 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
971 clean::AssocConstItem(ref ty, ref default) => assoc_const(
977 if parent == ItemType::Trait { " " } else { "" },
980 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
986 if parent == ItemType::Trait { " " } else { "" },
989 _ => panic!("render_assoc_item called on non-associated-item"),
993 const ALLOWED_ATTRIBUTES: &[Symbol] =
994 &[sym::export_name, sym::link_section, sym::no_mangle, sym::repr, sym::non_exhaustive];
996 fn attributes(it: &clean::Item) -> Vec<String> {
1000 .filter_map(|attr| {
1001 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
1002 Some(pprust::attribute_to_string(&attr).replace("\n", "").replace(" ", " "))
1010 // When an attribute is rendered inside a `<pre>` tag, it is formatted using
1011 // a whitespace prefix and newline.
1012 fn render_attributes_in_pre(w: &mut Buffer, it: &clean::Item, prefix: &str) {
1013 for a in attributes(it) {
1014 writeln!(w, "{}{}", prefix, a);
1018 // When an attribute is rendered inside a <code> tag, it is formatted using
1019 // a div to produce a newline after it.
1020 fn render_attributes_in_code(w: &mut Buffer, it: &clean::Item) {
1021 for a in attributes(it) {
1022 write!(w, "<div class=\"code-attribute\">{}</div>", a);
1026 #[derive(Copy, Clone)]
1027 enum AssocItemLink<'a> {
1028 Anchor(Option<&'a str>),
1029 GotoSource(FakeDefId, &'a FxHashSet<Symbol>),
1032 impl<'a> AssocItemLink<'a> {
1033 fn anchor(&self, id: &'a str) -> Self {
1035 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
1036 ref other => *other,
1041 fn render_assoc_items(
1044 containing_item: &clean::Item,
1046 what: AssocItemRender<'_>,
1048 info!("Documenting associated items of {:?}", containing_item.name);
1049 let v = match cx.cache.impls.get(&it) {
1053 let cache = cx.cache();
1054 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
1055 if !non_trait.is_empty() {
1056 let render_mode = match what {
1057 AssocItemRender::All => {
1059 "<h2 id=\"implementations\" class=\"small-section-header\">\
1060 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
1065 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
1068 "<h2 id=\"deref-methods\" class=\"small-section-header\">\
1069 Methods from {trait_}<Target = {type_}>\
1070 <a href=\"#deref-methods\" class=\"anchor\"></a>\
1072 trait_ = trait_.print(cx),
1073 type_ = type_.print(cx),
1075 RenderMode::ForDeref { mut_: deref_mut_ }
1078 for i in &non_trait {
1084 AssocItemLink::Anchor(None),
1094 if let AssocItemRender::DerefFor { .. } = what {
1097 if !traits.is_empty() {
1098 let deref_impl = traits
1100 .find(|t| t.inner_impl().trait_.def_id_full(cache) == cx.cache.deref_trait_did);
1101 if let Some(impl_) = deref_impl {
1102 let has_deref_mut = traits
1104 .any(|t| t.inner_impl().trait_.def_id_full(cache) == cx.cache.deref_mut_trait_did);
1105 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut);
1107 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
1108 traits.iter().partition(|t| t.inner_impl().synthetic);
1109 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
1110 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
1112 let mut impls = Buffer::empty_from(&w);
1113 render_impls(cx, &mut impls, &concrete, containing_item);
1114 let impls = impls.into_inner();
1115 if !impls.is_empty() {
1118 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
1119 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
1121 <div id=\"trait-implementations-list\">{}</div>",
1126 if !synthetic.is_empty() {
1128 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
1129 Auto Trait Implementations\
1130 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
1132 <div id=\"synthetic-implementations-list\">",
1134 render_impls(cx, w, &synthetic, containing_item);
1135 w.write_str("</div>");
1138 if !blanket_impl.is_empty() {
1140 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
1141 Blanket Implementations\
1142 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
1144 <div id=\"blanket-implementations-list\">",
1146 render_impls(cx, w, &blanket_impl, containing_item);
1147 w.write_str("</div>");
1152 fn render_deref_methods(
1156 container_item: &clean::Item,
1159 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
1160 let (target, real_target) = impl_
1164 .find_map(|item| match *item.kind {
1165 clean::TypedefItem(ref t, true) => Some(match *t {
1166 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
1167 _ => (&t.type_, &t.type_),
1171 .expect("Expected associated type binding");
1172 debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target);
1174 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
1175 if let Some(did) = target.def_id_full(cx.cache()) {
1176 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) {
1177 // `impl Deref<Target = S> for S`
1178 if did == type_did {
1179 // Avoid infinite cycles
1183 render_assoc_items(w, cx, container_item, did, what);
1185 if let Some(prim) = target.primitive_type() {
1186 if let Some(&did) = cx.cache.primitive_locations.get(&prim) {
1187 render_assoc_items(w, cx, container_item, did, what);
1193 fn should_render_item(item: &clean::Item, deref_mut_: bool, cache: &Cache) -> bool {
1194 let self_type_opt = match *item.kind {
1195 clean::MethodItem(ref method, _) => method.decl.self_type(),
1196 clean::TyMethodItem(ref method) => method.decl.self_type(),
1200 if let Some(self_ty) = self_type_opt {
1201 let (by_mut_ref, by_box, by_value) = match self_ty {
1202 SelfTy::SelfBorrowed(_, mutability)
1203 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
1204 (mutability == Mutability::Mut, false, false)
1206 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
1207 (false, Some(did) == cache.owned_box_did, false)
1209 SelfTy::SelfValue => (false, false, true),
1210 _ => (false, false, false),
1213 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
1219 fn notable_traits_decl(decl: &clean::FnDecl, cx: &Context<'_>) -> String {
1220 let mut out = Buffer::html();
1221 let mut trait_ = String::new();
1223 if let Some(did) = decl.output.def_id_full(cx.cache()) {
1224 if let Some(impls) = cx.cache().impls.get(&did) {
1226 let impl_ = i.inner_impl();
1227 if impl_.trait_.def_id().map_or(false, |d| {
1228 cx.cache().traits.get(&d).map(|t| t.is_notable).unwrap_or(false)
1233 "<h3 class=\"notable\">Notable traits for {}</h3>\
1234 <code class=\"content\">",
1235 impl_.for_.print(cx)
1237 trait_.push_str(&impl_.for_.print(cx).to_string());
1240 //use the "where" class here to make it small
1243 "<span class=\"where fmt-newline\">{}</span>",
1244 impl_.print(false, cx)
1246 let t_did = impl_.trait_.def_id_full(cx.cache()).unwrap();
1247 for it in &impl_.items {
1248 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1249 out.push_str("<span class=\"where fmt-newline\"> ");
1255 AssocItemLink::GotoSource(t_did.into(), &FxHashSet::default()),
1259 out.push_str(";</span>");
1267 if !out.is_empty() {
1270 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
1271 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
1273 out.push_str("</code></span></div></span></span>");
1283 parent: &clean::Item,
1284 link: AssocItemLink<'_>,
1285 render_mode: RenderMode,
1286 show_def_docs: bool,
1287 use_absolute: Option<bool>,
1288 is_on_foreign_type: bool,
1289 show_default_items: bool,
1290 // This argument is used to reference same type with different paths to avoid duplication
1291 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
1294 let cache = cx.cache();
1295 let traits = &cache.traits;
1296 let trait_ = i.trait_did_full(cache).map(|did| &traits[&did]);
1297 let mut close_tags = String::new();
1299 // For trait implementations, the `interesting` output contains all methods that have doc
1300 // comments, and the `boring` output contains all methods that do not. The distinction is
1301 // used to allow hiding the boring methods.
1302 // `containing_item` is used for rendering stability info. If the parent is a trait impl,
1303 // `containing_item` will the grandparent, since trait impls can't have stability attached.
1305 boring: &mut Buffer,
1306 interesting: &mut Buffer,
1309 parent: &clean::Item,
1310 containing_item: &clean::Item,
1311 link: AssocItemLink<'_>,
1312 render_mode: RenderMode,
1313 is_default_item: bool,
1314 trait_: Option<&clean::Trait>,
1315 show_def_docs: bool,
1317 let item_type = item.type_();
1318 let name = item.name.as_ref().unwrap();
1320 let render_method_item = match render_mode {
1321 RenderMode::Normal => true,
1322 RenderMode::ForDeref { mut_: deref_mut_ } => {
1323 should_render_item(&item, deref_mut_, &cx.cache)
1327 let in_trait_class = if trait_.is_some() { " trait-impl" } else { "" };
1329 let mut doc_buffer = Buffer::empty_from(boring);
1330 let mut info_buffer = Buffer::empty_from(boring);
1331 let mut short_documented = true;
1333 if render_method_item {
1334 if !is_default_item {
1335 if let Some(t) = trait_ {
1336 // The trait item may have been stripped so we might not
1337 // find any documentation or stability for it.
1338 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
1339 // We need the stability of the item from the trait
1340 // because impls can't have a stability.
1341 if item.doc_value().is_some() {
1342 document_item_info(&mut info_buffer, cx, it, Some(parent));
1343 document_full(&mut doc_buffer, item, cx);
1344 short_documented = false;
1346 // In case the item isn't documented,
1347 // provide short documentation from the trait.
1348 document_short(&mut doc_buffer, it, cx, link, parent, show_def_docs);
1352 document_item_info(&mut info_buffer, cx, item, Some(parent));
1354 document_full(&mut doc_buffer, item, cx);
1355 short_documented = false;
1359 document_short(&mut doc_buffer, item, cx, link, parent, show_def_docs);
1362 let w = if short_documented && trait_.is_some() { interesting } else { boring };
1364 let toggled = !doc_buffer.is_empty();
1366 let method_toggle_class =
1367 if item_type == ItemType::Method { " method-toggle" } else { "" };
1368 write!(w, "<details class=\"rustdoc-toggle{}\" open><summary>", method_toggle_class);
1371 clean::MethodItem(..) | clean::TyMethodItem(_) => {
1372 // Only render when the method is not static or we allow static methods
1373 if render_method_item {
1374 let id = cx.derive_id(format!("{}.{}", item_type, name));
1375 let source_id = trait_
1376 .and_then(|trait_| {
1377 trait_.items.iter().find(|item| {
1378 item.name.map(|n| n.as_str().eq(&name.as_str())).unwrap_or(false)
1381 .map(|item| format!("{}.{}", item.type_(), name));
1384 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1385 id, item_type, in_trait_class,
1387 render_rightside(w, cx, item, containing_item);
1388 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1389 w.write_str("<code>");
1393 link.anchor(source_id.as_ref().unwrap_or(&id)),
1397 w.write_str("</code>");
1398 w.write_str("</div>");
1401 clean::TypedefItem(ref tydef, _) => {
1402 let source_id = format!("{}.{}", ItemType::AssocType, name);
1403 let id = cx.derive_id(source_id.clone());
1406 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1407 id, item_type, in_trait_class
1409 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1410 w.write_str("<code>");
1416 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1420 w.write_str("</code>");
1421 w.write_str("</div>");
1423 clean::AssocConstItem(ref ty, ref default) => {
1424 let source_id = format!("{}.{}", item_type, name);
1425 let id = cx.derive_id(source_id.clone());
1428 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1429 id, item_type, in_trait_class
1431 render_rightside(w, cx, item, containing_item);
1432 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1433 w.write_str("<code>");
1439 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1443 w.write_str("</code>");
1444 w.write_str("</div>");
1446 clean::AssocTypeItem(ref bounds, ref default) => {
1447 let source_id = format!("{}.{}", item_type, name);
1448 let id = cx.derive_id(source_id.clone());
1449 write!(w, "<div id=\"{}\" class=\"{}{}\">", id, item_type, in_trait_class,);
1450 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1451 w.write_str("<code>");
1457 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1461 w.write_str("</code>");
1462 w.write_str("</div>");
1464 clean::StrippedItem(..) => return,
1465 _ => panic!("can't make docs for trait item with name {:?}", item.name),
1468 w.push_buffer(info_buffer);
1470 w.write_str("</summary>");
1471 w.push_buffer(doc_buffer);
1472 w.push_str("</details>");
1476 let mut impl_items = Buffer::empty_from(w);
1477 let mut default_impl_items = Buffer::empty_from(w);
1479 for trait_item in &i.inner_impl().items {
1481 &mut default_impl_items,
1485 if trait_.is_some() { &i.impl_item } else { parent },
1490 trait_.map(|t| &t.trait_),
1495 fn render_default_items(
1496 boring: &mut Buffer,
1497 interesting: &mut Buffer,
1501 parent: &clean::Item,
1502 containing_item: &clean::Item,
1503 render_mode: RenderMode,
1504 show_def_docs: bool,
1506 for trait_item in &t.items {
1507 let n = trait_item.name;
1508 if i.items.iter().any(|m| m.name == n) {
1511 let did = i.trait_.as_ref().unwrap().def_id_full(cx.cache()).unwrap();
1512 let provided_methods = i.provided_trait_methods(cx.tcx());
1513 let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_methods);
1531 // If we've implemented a trait, then also emit documentation for all
1532 // default items which weren't overridden in the implementation block.
1533 // We don't emit documentation for default items if they appear in the
1534 // Implementations on Foreign Types or Implementors sections.
1535 if show_default_items {
1536 if let Some(t) = trait_ {
1537 render_default_items(
1538 &mut default_impl_items,
1550 if render_mode == RenderMode::Normal {
1551 let toggled = !(impl_items.is_empty() && default_impl_items.is_empty());
1553 close_tags.insert_str(0, "</details>");
1554 write!(w, "<details class=\"rustdoc-toggle implementors-toggle\" open>");
1555 write!(w, "<summary>")
1557 render_impl_summary(
1569 write!(w, "</summary>")
1572 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
1573 let mut ids = cx.id_map.borrow_mut();
1576 "<div class=\"docblock\">{}</div>",
1579 &i.impl_item.links(cx),
1582 cx.shared.edition(),
1583 &cx.shared.playground
1589 if !default_impl_items.is_empty() || !impl_items.is_empty() {
1590 w.write_str("<div class=\"impl-items\">");
1591 w.push_buffer(default_impl_items);
1592 w.push_buffer(impl_items);
1593 close_tags.insert_str(0, "</div>");
1595 w.write_str(&close_tags);
1598 // Render the items that appear on the right side of methods, impls, and
1599 // associated types. For example "1.0.0 (const: 1.39.0) [src]".
1600 fn render_rightside(
1604 containing_item: &clean::Item,
1608 write!(w, "<div class=\"rightside\">");
1609 render_stability_since_raw(
1611 item.stable_since(tcx).as_deref(),
1612 item.const_stability(tcx),
1613 containing_item.stable_since(tcx).as_deref(),
1614 containing_item.const_stable_since(tcx).as_deref(),
1617 write_srclink(cx, item, w);
1618 w.write_str("</div>");
1621 pub(crate) fn render_impl_summary(
1625 parent: &clean::Item,
1626 containing_item: &clean::Item,
1627 show_def_docs: bool,
1628 use_absolute: Option<bool>,
1629 is_on_foreign_type: bool,
1630 // This argument is used to reference same type with different paths to avoid duplication
1631 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
1634 let id = cx.derive_id(match i.inner_impl().trait_ {
1636 if is_on_foreign_type {
1637 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t, cx)
1639 format!("impl-{}", small_url_encode(format!("{:#}", t.print(cx))))
1642 None => "impl".to_string(),
1644 let aliases = if aliases.is_empty() {
1647 format!(" data-aliases=\"{}\"", aliases.join(","))
1649 write!(w, "<div id=\"{}\" class=\"impl has-srclink\"{}>", id, aliases);
1650 render_rightside(w, cx, &i.impl_item, containing_item);
1651 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1652 write!(w, "<code class=\"in-band\">");
1654 if let Some(use_absolute) = use_absolute {
1655 write!(w, "{}", i.inner_impl().print(use_absolute, cx));
1657 for it in &i.inner_impl().items {
1658 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1659 w.write_str("<span class=\"where fmt-newline\"> ");
1660 assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "", cx);
1661 w.write_str(";</span>");
1666 write!(w, "{}", i.inner_impl().print(false, cx));
1668 write!(w, "</code>");
1670 let is_trait = i.inner_impl().trait_.is_some();
1672 if let Some(portability) = portability(&i.impl_item, Some(parent)) {
1673 write!(w, "<div class=\"item-info\">{}</div>", portability);
1677 w.write_str("</div>");
1680 fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) {
1681 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
1685 || it.is_primitive()
1693 "<p class=\"location\">{}{}</p>",
1695 clean::StructItem(..) => "Struct ",
1696 clean::TraitItem(..) => "Trait ",
1697 clean::PrimitiveItem(..) => "Primitive Type ",
1698 clean::UnionItem(..) => "Union ",
1699 clean::EnumItem(..) => "Enum ",
1700 clean::TypedefItem(..) => "Type Definition ",
1701 clean::ForeignTypeItem => "Foreign Type ",
1702 clean::ModuleItem(..) =>
1710 it.name.as_ref().unwrap()
1715 if let Some(ref version) = cx.cache.crate_version {
1718 "<div class=\"block version\">\
1726 buffer.write_str("<div class=\"sidebar-elems\">");
1730 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
1731 it.name.as_ref().expect("crates always have a name"),
1736 clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s),
1737 clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t),
1738 clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it),
1739 clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u),
1740 clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e),
1741 clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it),
1742 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
1743 clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, it),
1747 // The sidebar is designed to display sibling functions, modules and
1748 // other miscellaneous information. since there are lots of sibling
1749 // items (and that causes quadratic growth in large modules),
1750 // we refactor common parts into a shared JavaScript file per module.
1751 // still, we don't move everything into JS because we want to preserve
1752 // as much HTML as possible in order to allow non-JS-enabled browsers
1753 // to navigate the documentation (though slightly inefficiently).
1756 buffer.write_str("<p class=\"location\">Other items in<br>");
1757 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
1759 buffer.write_str("::<wbr>");
1763 "<a href=\"{}index.html\">{}</a>",
1764 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
1768 buffer.write_str("</p>");
1771 // Sidebar refers to the enclosing module, not this module.
1772 let relpath = if it.is_mod() && parentlen != 0 { "./" } else { "" };
1775 "<div id=\"sidebar-vars\" data-name=\"{name}\" data-ty=\"{ty}\" data-relpath=\"{path}\">\
1777 name = it.name.unwrap_or(kw::Empty),
1781 write!(buffer, "<script defer src=\"{}sidebar-items.js\"></script>", relpath);
1782 // Closes sidebar-elems div.
1783 buffer.write_str("</div>");
1786 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
1787 if used_links.insert(url.clone()) {
1791 while !used_links.insert(format!("{}-{}", url, add)) {
1794 format!("{}-{}", url, add)
1800 used_links: &mut FxHashSet<String>,
1806 .filter_map(|item| match item.name {
1807 Some(ref name) if !name.is_empty() && item.is_method() => {
1808 if !for_deref || should_render_item(item, deref_mut, cache) {
1810 "<a href=\"#{}\">{}</a>",
1811 get_next_url(used_links, format!("method.{}", name)),
1820 .collect::<Vec<_>>()
1823 // The point is to url encode any potential character from a type with genericity.
1824 fn small_url_encode(s: String) -> String {
1825 let mut st = String::new();
1826 let mut last_match = 0;
1827 for (idx, c) in s.char_indices() {
1828 let escaped = match c {
1844 st += &s[last_match..idx];
1846 // NOTE: we only expect single byte characters here - which is fine as long as we
1847 // only match single byte characters
1848 last_match = idx + 1;
1851 if last_match != 0 {
1852 st += &s[last_match..];
1859 fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) {
1860 let did = it.def_id.expect_real();
1861 if let Some(v) = cx.cache.impls.get(&did) {
1862 let mut used_links = FxHashSet::default();
1863 let cache = cx.cache();
1866 let used_links_bor = &mut used_links;
1869 .filter(|i| i.inner_impl().trait_.is_none())
1870 .flat_map(move |i| {
1871 get_methods(i.inner_impl(), false, used_links_bor, false, &cx.cache)
1873 .collect::<Vec<_>>();
1874 if !ret.is_empty() {
1875 // We want links' order to be reproducible so we don't use unstable sort.
1879 "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
1880 <div class=\"sidebar-links\">",
1883 out.push_str(&line);
1885 out.push_str("</div>");
1889 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
1890 let format_impls = |impls: Vec<&Impl>| {
1891 let mut links = FxHashSet::default();
1896 if let Some(ref i) = it.inner_impl().trait_ {
1897 let i_display = format!("{:#}", i.print(cx));
1898 let out = Escape(&i_display);
1899 let encoded = small_url_encode(format!("{:#}", i.print(cx)));
1900 let generated = format!(
1901 "<a href=\"#impl-{}\">{}{}</a>",
1903 if it.inner_impl().negative_polarity { "!" } else { "" },
1906 if links.insert(generated.clone()) { Some(generated) } else { None }
1911 .collect::<Vec<String>>();
1916 let write_sidebar_links = |out: &mut Buffer, links: Vec<String>| {
1917 out.push_str("<div class=\"sidebar-links\">");
1919 out.push_str(&link);
1921 out.push_str("</div>");
1924 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
1925 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
1926 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
1928 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
1930 let concrete_format = format_impls(concrete);
1931 let synthetic_format = format_impls(synthetic);
1932 let blanket_format = format_impls(blanket_impl);
1934 if !concrete_format.is_empty() {
1936 "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
1937 Trait Implementations</a>",
1939 write_sidebar_links(out, concrete_format);
1942 if !synthetic_format.is_empty() {
1944 "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
1945 Auto Trait Implementations</a>",
1947 write_sidebar_links(out, synthetic_format);
1950 if !blanket_format.is_empty() {
1952 "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
1953 Blanket Implementations</a>",
1955 write_sidebar_links(out, blanket_format);
1958 if let Some(impl_) = v
1960 .filter(|i| i.inner_impl().trait_.is_some())
1961 .find(|i| i.inner_impl().trait_.def_id_full(cache) == cx.cache.deref_trait_did)
1963 sidebar_deref_methods(cx, out, impl_, v);
1969 fn sidebar_deref_methods(cx: &Context<'_>, out: &mut Buffer, impl_: &Impl, v: &Vec<Impl>) {
1972 debug!("found Deref: {:?}", impl_);
1973 if let Some((target, real_target)) =
1974 impl_.inner_impl().items.iter().find_map(|item| match *item.kind {
1975 clean::TypedefItem(ref t, true) => Some(match *t {
1976 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
1977 _ => (&t.type_, &t.type_),
1982 debug!("found target, real_target: {:?} {:?}", target, real_target);
1983 if let Some(did) = target.def_id_full(c) {
1984 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(c) {
1985 // `impl Deref<Target = S> for S`
1986 if did == type_did {
1987 // Avoid infinite cycles
1994 .filter(|i| i.inner_impl().trait_.is_some())
1995 .any(|i| i.inner_impl().trait_.def_id_full(c) == c.deref_mut_trait_did);
1996 let inner_impl = target
1999 target.primitive_type().and_then(|prim| c.primitive_locations.get(&prim).cloned())
2001 .and_then(|did| c.impls.get(&did));
2002 if let Some(impls) = inner_impl {
2003 debug!("found inner_impl: {:?}", impls);
2004 let mut used_links = FxHashSet::default();
2007 .filter(|i| i.inner_impl().trait_.is_none())
2008 .flat_map(|i| get_methods(i.inner_impl(), true, &mut used_links, deref_mut, c))
2009 .collect::<Vec<_>>();
2010 if !ret.is_empty() {
2013 "<a class=\"sidebar-title\" href=\"#deref-methods\">Methods from {}<Target={}></a>",
2014 Escape(&format!("{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print(cx))),
2015 Escape(&format!("{:#}", real_target.print(cx))),
2017 // We want links' order to be reproducible so we don't use unstable sort.
2019 out.push_str("<div class=\"sidebar-links\">");
2021 out.push_str(&link);
2023 out.push_str("</div>");
2029 fn sidebar_struct(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
2030 let mut sidebar = Buffer::new();
2031 let fields = get_struct_fields_name(&s.fields);
2033 if !fields.is_empty() {
2034 if let CtorKind::Fictive = s.struct_type {
2036 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
2037 <div class=\"sidebar-links\">",
2040 for field in fields {
2041 sidebar.push_str(&field);
2044 sidebar.push_str("</div>");
2048 sidebar_assoc_items(cx, &mut sidebar, it);
2050 if !sidebar.is_empty() {
2051 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2055 fn get_id_for_impl_on_foreign_type(
2057 trait_: &clean::Type,
2060 small_url_encode(format!("impl-{:#}-for-{:#}", trait_.print(cx), for_.print(cx),))
2063 fn extract_for_impl_name(item: &clean::Item, cx: &Context<'_>) -> Option<(String, String)> {
2065 clean::ItemKind::ImplItem(ref i) => {
2066 if let Some(ref trait_) = i.trait_ {
2067 // Alternative format produces no URLs,
2068 // so this parameter does nothing.
2070 format!("{:#}", i.for_.print(cx)),
2071 get_id_for_impl_on_foreign_type(&i.for_, trait_, cx),
2081 fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
2082 buf.write_str("<div class=\"block items\">");
2084 fn print_sidebar_section(
2086 items: &[clean::Item],
2088 filter: impl Fn(&clean::Item) -> bool,
2089 write: impl Fn(&mut Buffer, &str),
2092 let mut items = items
2094 .filter_map(|m| match m.name {
2095 Some(ref name) if filter(m) => Some(name.as_str()),
2098 .collect::<Vec<_>>();
2100 if !items.is_empty() {
2101 items.sort_unstable();
2102 out.push_str(before);
2103 for item in items.into_iter() {
2106 out.push_str(after);
2110 print_sidebar_section(
2113 "<a class=\"sidebar-title\" href=\"#associated-types\">\
2114 Associated Types</a><div class=\"sidebar-links\">",
2115 |m| m.is_associated_type(),
2116 |out, sym| write!(out, "<a href=\"#associatedtype.{0}\">{0}</a>", sym),
2120 print_sidebar_section(
2123 "<a class=\"sidebar-title\" href=\"#associated-const\">\
2124 Associated Constants</a><div class=\"sidebar-links\">",
2125 |m| m.is_associated_const(),
2126 |out, sym| write!(out, "<a href=\"#associatedconstant.{0}\">{0}</a>", sym),
2130 print_sidebar_section(
2133 "<a class=\"sidebar-title\" href=\"#required-methods\">\
2134 Required Methods</a><div class=\"sidebar-links\">",
2135 |m| m.is_ty_method(),
2136 |out, sym| write!(out, "<a href=\"#tymethod.{0}\">{0}</a>", sym),
2140 print_sidebar_section(
2143 "<a class=\"sidebar-title\" href=\"#provided-methods\">\
2144 Provided Methods</a><div class=\"sidebar-links\">",
2146 |out, sym| write!(out, "<a href=\"#method.{0}\">{0}</a>", sym),
2150 if let Some(implementors) = cx.cache.implementors.get(&it.def_id.expect_real()) {
2151 let cache = cx.cache();
2152 let mut res = implementors
2158 .map_or(false, |d| !cx.cache.paths.contains_key(&d))
2160 .filter_map(|i| extract_for_impl_name(&i.impl_item, cx))
2161 .collect::<Vec<_>>();
2163 if !res.is_empty() {
2166 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
2167 Implementations on Foreign Types</a>\
2168 <div class=\"sidebar-links\">",
2170 for (name, id) in res.into_iter() {
2171 write!(buf, "<a href=\"#{}\">{}</a>", id, Escape(&name));
2173 buf.push_str("</div>");
2177 sidebar_assoc_items(cx, buf, it);
2179 buf.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
2182 "<a class=\"sidebar-title\" \
2183 href=\"#synthetic-implementors\">Auto Implementors</a>",
2187 buf.push_str("</div>")
2190 fn sidebar_primitive(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2191 let mut sidebar = Buffer::new();
2192 sidebar_assoc_items(cx, &mut sidebar, it);
2194 if !sidebar.is_empty() {
2195 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2199 fn sidebar_typedef(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2200 let mut sidebar = Buffer::new();
2201 sidebar_assoc_items(cx, &mut sidebar, it);
2203 if !sidebar.is_empty() {
2204 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2208 fn get_struct_fields_name(fields: &[clean::Item]) -> Vec<String> {
2209 let mut fields = fields
2211 .filter(|f| matches!(*f.kind, clean::StructFieldItem(..)))
2213 f.name.map(|name| format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
2215 .collect::<Vec<_>>();
2220 fn sidebar_union(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
2221 let mut sidebar = Buffer::new();
2222 let fields = get_struct_fields_name(&u.fields);
2224 if !fields.is_empty() {
2226 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
2227 <div class=\"sidebar-links\">",
2230 for field in fields {
2231 sidebar.push_str(&field);
2234 sidebar.push_str("</div>");
2237 sidebar_assoc_items(cx, &mut sidebar, it);
2239 if !sidebar.is_empty() {
2240 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2244 fn sidebar_enum(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
2245 let mut sidebar = Buffer::new();
2247 let mut variants = e
2250 .filter_map(|v| match v.name {
2251 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
2254 .collect::<Vec<_>>();
2255 if !variants.is_empty() {
2256 variants.sort_unstable();
2257 sidebar.push_str(&format!(
2258 "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
2259 <div class=\"sidebar-links\">{}</div>",
2264 sidebar_assoc_items(cx, &mut sidebar, it);
2266 if !sidebar.is_empty() {
2267 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2271 fn item_ty_to_strs(ty: ItemType) -> (&'static str, &'static str) {
2273 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
2274 ItemType::Module => ("modules", "Modules"),
2275 ItemType::Struct => ("structs", "Structs"),
2276 ItemType::Union => ("unions", "Unions"),
2277 ItemType::Enum => ("enums", "Enums"),
2278 ItemType::Function => ("functions", "Functions"),
2279 ItemType::Typedef => ("types", "Type Definitions"),
2280 ItemType::Static => ("statics", "Statics"),
2281 ItemType::Constant => ("constants", "Constants"),
2282 ItemType::Trait => ("traits", "Traits"),
2283 ItemType::Impl => ("impls", "Implementations"),
2284 ItemType::TyMethod => ("tymethods", "Type Methods"),
2285 ItemType::Method => ("methods", "Methods"),
2286 ItemType::StructField => ("fields", "Struct Fields"),
2287 ItemType::Variant => ("variants", "Variants"),
2288 ItemType::Macro => ("macros", "Macros"),
2289 ItemType::Primitive => ("primitives", "Primitive Types"),
2290 ItemType::AssocType => ("associated-types", "Associated Types"),
2291 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
2292 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
2293 ItemType::Keyword => ("keywords", "Keywords"),
2294 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
2295 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
2296 ItemType::ProcDerive => ("derives", "Derive Macros"),
2297 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
2301 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
2302 let mut sidebar = String::new();
2304 // Re-exports are handled a bit differently because they can be extern crates or imports.
2305 if items.iter().any(|it| {
2307 && (it.type_() == ItemType::ExternCrate
2308 || (it.type_() == ItemType::Import && !it.is_stripped()))
2310 let (id, name) = item_ty_to_strs(ItemType::Import);
2311 sidebar.push_str(&format!("<li><a href=\"#{}\">{}</a></li>", id, name));
2314 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
2315 // to print its headings
2317 ItemType::Primitive,
2331 ItemType::StructField,
2333 ItemType::AssocType,
2334 ItemType::AssocConst,
2335 ItemType::ForeignType,
2338 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty && it.name.is_some()) {
2339 let (id, name) = item_ty_to_strs(myty);
2340 sidebar.push_str(&format!("<li><a href=\"#{}\">{}</a></li>", id, name));
2344 if !sidebar.is_empty() {
2345 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
2349 fn sidebar_foreign_type(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2350 let mut sidebar = Buffer::new();
2351 sidebar_assoc_items(cx, &mut sidebar, it);
2353 if !sidebar.is_empty() {
2354 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2358 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
2360 /// Returns a list of all paths used in the type.
2361 /// This is used to help deduplicate imported impls
2362 /// for reexported types. If any of the contained
2363 /// types are re-exported, we don't use the corresponding
2364 /// entry from the js file, as inlining will have already
2365 /// picked up the impl
2366 fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> {
2367 let mut out = Vec::new();
2368 let mut visited = FxHashSet::default();
2369 let mut work = VecDeque::new();
2371 work.push_back(first_ty);
2373 while let Some(ty) = work.pop_front() {
2374 if !visited.insert(ty.clone()) {
2379 clean::Type::ResolvedPath { did, .. } => {
2380 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
2381 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
2383 if let Some(path) = fqp {
2384 out.push(path.join("::"));
2387 clean::Type::Tuple(tys) => {
2388 work.extend(tys.into_iter());
2390 clean::Type::Slice(ty) => {
2391 work.push_back(*ty);
2393 clean::Type::Array(ty, _) => {
2394 work.push_back(*ty);
2396 clean::Type::RawPointer(_, ty) => {
2397 work.push_back(*ty);
2399 clean::Type::BorrowedRef { type_, .. } => {
2400 work.push_back(*type_);
2402 clean::Type::QPath { self_type, trait_, .. } => {
2403 work.push_back(*self_type);
2404 work.push_back(*trait_);