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 {
101 /// Full type of functions/methods in the search index.
103 crate struct IndexItemFunctionType {
104 inputs: Vec<TypeWithKind>,
105 output: Option<Vec<TypeWithKind>>,
108 impl Serialize for IndexItemFunctionType {
109 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
113 // If we couldn't figure out a type, just write `null`.
114 let mut iter = self.inputs.iter();
115 if match self.output {
116 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
117 None => iter.any(|ref i| i.ty.name.is_none()),
119 serializer.serialize_none()
121 let mut seq = serializer.serialize_seq(None)?;
122 seq.serialize_element(&self.inputs)?;
123 if let Some(output) = &self.output {
124 if output.len() > 1 {
125 seq.serialize_element(&output)?;
127 seq.serialize_element(&output[0])?;
136 crate struct TypeWithKind {
141 impl From<(RenderType, ItemType)> for TypeWithKind {
142 fn from(x: (RenderType, ItemType)) -> TypeWithKind {
143 TypeWithKind { ty: x.0, kind: x.1 }
147 impl Serialize for TypeWithKind {
148 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
152 (&self.ty.name, self.kind).serialize(serializer)
156 #[derive(Debug, Clone)]
157 crate struct StylePath {
158 /// The path to the theme
160 /// What the `disabled` attribute should be set to in the HTML tag
161 crate disabled: bool,
164 fn write_srclink(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) {
165 if let Some(l) = cx.src_href(item) {
166 write!(buf, "<a class=\"srclink\" href=\"{}\" title=\"goto source code\">[src]</a>", l)
170 #[derive(Debug, Eq, PartialEq, Hash)]
177 fn new(mut url: String, name: String) -> ItemEntry {
178 while url.starts_with('/') {
181 ItemEntry { url, name }
186 crate fn print(&self) -> impl fmt::Display + '_ {
187 crate::html::format::display_fn(move |f| {
188 write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name))
193 impl PartialOrd for ItemEntry {
194 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
195 Some(self.cmp(other))
199 impl Ord for ItemEntry {
200 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
201 self.name.cmp(&other.name)
207 structs: FxHashSet<ItemEntry>,
208 enums: FxHashSet<ItemEntry>,
209 unions: FxHashSet<ItemEntry>,
210 primitives: FxHashSet<ItemEntry>,
211 traits: FxHashSet<ItemEntry>,
212 macros: FxHashSet<ItemEntry>,
213 functions: FxHashSet<ItemEntry>,
214 typedefs: FxHashSet<ItemEntry>,
215 opaque_tys: FxHashSet<ItemEntry>,
216 statics: FxHashSet<ItemEntry>,
217 constants: FxHashSet<ItemEntry>,
218 keywords: FxHashSet<ItemEntry>,
219 attributes: FxHashSet<ItemEntry>,
220 derives: FxHashSet<ItemEntry>,
221 trait_aliases: FxHashSet<ItemEntry>,
225 fn new() -> AllTypes {
226 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
228 structs: new_set(100),
230 unions: new_set(100),
231 primitives: new_set(26),
232 traits: new_set(100),
233 macros: new_set(100),
234 functions: new_set(100),
235 typedefs: new_set(100),
236 opaque_tys: new_set(100),
237 statics: new_set(100),
238 constants: new_set(100),
239 keywords: new_set(100),
240 attributes: new_set(100),
241 derives: new_set(100),
242 trait_aliases: new_set(100),
246 fn append(&mut self, item_name: String, item_type: &ItemType) {
247 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
248 if let Some(name) = url.pop() {
249 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
251 let name = url.join("::");
253 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
254 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
255 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
256 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
257 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
258 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
259 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
260 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
261 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
262 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
263 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
264 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
265 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
266 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
274 fn print(self, f: &mut Buffer) {
275 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
277 let mut e: Vec<&ItemEntry> = e.iter().collect();
281 "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">",
282 title.replace(' ', "-"), // IDs cannot contain whitespaces.
288 write!(f, "<li>{}</li>", s.print());
291 f.write_str("</ul>");
297 <span class=\"in-band\">List of all items</span>\
298 <span class=\"out-of-band\">\
299 <span id=\"render-detail\">\
300 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
301 title=\"collapse all docs\">\
302 [<span class=\"inner\">−</span>]\
308 // Note: print_entries does not escape the title, because we know the current set of titles
309 // doesn't require escaping.
310 print_entries(f, &self.structs, "Structs", "structs");
311 print_entries(f, &self.enums, "Enums", "enums");
312 print_entries(f, &self.unions, "Unions", "unions");
313 print_entries(f, &self.primitives, "Primitives", "primitives");
314 print_entries(f, &self.traits, "Traits", "traits");
315 print_entries(f, &self.macros, "Macros", "macros");
316 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
317 print_entries(f, &self.derives, "Derive Macros", "derives");
318 print_entries(f, &self.functions, "Functions", "functions");
319 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
320 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
321 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
322 print_entries(f, &self.statics, "Statics", "statics");
323 print_entries(f, &self.constants, "Constants", "constants")
330 description: &'static str,
331 sub_settings: Vec<Setting>,
334 js_data_name: &'static str,
335 description: &'static str,
339 js_data_name: &'static str,
340 description: &'static str,
341 default_value: &'static str,
342 options: Vec<(String, String)>,
347 fn display(&self, root_path: &str, suffix: &str) -> String {
349 Setting::Section { description, ref sub_settings } => format!(
350 "<div class=\"setting-line\">\
351 <div class=\"title\">{}</div>\
352 <div class=\"sub-settings\">{}</div>
355 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
357 Setting::Toggle { js_data_name, description, default_value } => format!(
358 "<div class=\"setting-line\">\
359 <label class=\"toggle\">\
360 <input type=\"checkbox\" id=\"{}\" {}>\
361 <span class=\"slider\"></span>\
366 if default_value { " checked" } else { "" },
369 Setting::Select { js_data_name, description, default_value, ref options } => format!(
370 "<div class=\"setting-line\">\
372 <label class=\"select-wrapper\">\
373 <select id=\"{}\" autocomplete=\"off\">{}</select>\
374 <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
382 "<option value=\"{}\" {}>{}</option>",
384 if opt.0 == default_value { "selected" } else { "" },
387 .collect::<String>(),
395 impl From<(&'static str, &'static str, bool)> for Setting {
396 fn from(values: (&'static str, &'static str, bool)) -> Setting {
397 Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
401 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
402 fn from(values: (&'static str, Vec<T>)) -> Setting {
404 description: values.0,
405 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
410 fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
411 let theme_names: Vec<(String, String)> = themes
415 try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
418 Ok((theme.clone(), theme))
420 .collect::<Result<_, Error>>()?;
422 // (id, explanation, default value)
423 let settings: &[Setting] = &[
427 Setting::from(("use-system-theme", "Use system theme", true)),
429 js_data_name: "preferred-dark-theme",
430 description: "Preferred dark theme",
431 default_value: "dark",
432 options: theme_names.clone(),
435 js_data_name: "preferred-light-theme",
436 description: "Preferred light theme",
437 default_value: "light",
438 options: theme_names,
443 ("auto-hide-large-items", "Auto-hide item contents for large items.", true).into(),
444 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
445 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", false)
447 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
449 ("line-numbers", "Show line numbers on code examples", false).into(),
450 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
455 <span class=\"in-band\">Rustdoc settings</span>\
457 <div class=\"settings\">{}</div>\
458 <script src=\"{}settings{}.js\"></script>",
459 settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
465 fn document(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, parent: Option<&clean::Item>) {
466 if let Some(ref name) = item.name {
467 info!("Documenting {}", name);
469 document_item_info(w, cx, item, parent);
470 if parent.is_none() {
471 document_full_collapsible(w, item, cx);
473 document_full(w, item, cx);
477 /// Render md_text as markdown.
478 fn render_markdown(w: &mut Buffer, cx: &Context<'_>, md_text: &str, links: Vec<RenderedLink>) {
479 let mut ids = cx.id_map.borrow_mut();
482 "<div class=\"docblock\">{}</div>",
489 &cx.shared.playground
495 /// Writes a documentation block containing only the first paragraph of the documentation. If the
496 /// docs are longer, a "Read more" link is appended to the end.
501 link: AssocItemLink<'_>,
502 parent: &clean::Item,
505 document_item_info(w, cx, item, Some(parent));
509 if let Some(s) = item.doc_value() {
510 let mut summary_html = MarkdownSummaryLine(&s, &item.links(cx)).into_string();
512 if s.contains('\n') {
513 let link = format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link, cx));
515 if let Some(idx) = summary_html.rfind("</p>") {
516 summary_html.insert_str(idx, &link);
518 summary_html.push_str(&link);
522 write!(w, "<div class='docblock'>{}</div>", summary_html,);
526 fn document_full_collapsible(w: &mut Buffer, item: &clean::Item, cx: &Context<'_>) {
527 document_full_inner(w, item, cx, true);
530 fn document_full(w: &mut Buffer, item: &clean::Item, cx: &Context<'_>) {
531 document_full_inner(w, item, cx, false);
534 fn document_full_inner(w: &mut Buffer, item: &clean::Item, cx: &Context<'_>, is_collapsible: bool) {
535 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
536 debug!("Doc block: =====\n{}\n=====", s);
539 "<details class=\"rustdoc-toggle top-doc\" open>\
540 <summary class=\"hideme\">\
541 <span>Expand description</span>\
544 render_markdown(w, cx, &s, item.links(cx));
545 w.write_str("</details>");
547 render_markdown(w, cx, &s, item.links(cx));
552 /// Add extra information about an item such as:
556 /// * Required features (through the `doc_cfg` feature)
557 fn document_item_info(
561 parent: Option<&clean::Item>,
563 let item_infos = short_item_info(item, cx, parent);
564 if !item_infos.is_empty() {
565 w.write_str("<div class=\"item-info\">");
566 for info in item_infos {
569 w.write_str("</div>");
573 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
574 let cfg = match (&item.cfg, parent.and_then(|p| p.cfg.as_ref())) {
575 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
576 (cfg, _) => cfg.as_deref().cloned(),
579 debug!("Portability {:?} - {:?} = {:?}", item.cfg, parent.and_then(|p| p.cfg.as_ref()), cfg);
581 Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
584 /// Render the stability, deprecation and portability information that is displayed at the top of
585 /// the item's documentation.
589 parent: Option<&clean::Item>,
591 let mut extra_info = vec![];
592 let error_codes = cx.shared.codes;
594 if let Some(Deprecation { note, since, is_since_rustc_version, suggestion: _ }) =
595 item.deprecation(cx.tcx())
597 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
598 // but only display the future-deprecation messages for #[rustc_deprecated].
599 let mut message = if let Some(since) = since {
600 let since = &since.as_str();
601 if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
603 String::from("Deprecating in a future Rust version")
605 format!("Deprecating in {}", Escape(since))
608 format!("Deprecated since {}", Escape(since))
611 String::from("Deprecated")
614 if let Some(note) = note {
615 let note = note.as_str();
616 let mut ids = cx.id_map.borrow_mut();
617 let html = MarkdownHtml(
622 &cx.shared.playground,
624 message.push_str(&format!(": {}", html.into_string()));
626 extra_info.push(format!(
627 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
632 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
633 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
634 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
637 .filter(|stab| stab.feature != sym::rustc_private)
638 .map(|stab| (stab.level, stab.feature))
641 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
643 let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
644 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
645 feature.push_str(&format!(
646 " <a href=\"{url}{issue}\">#{issue}</a>",
652 message.push_str(&format!(" ({})", feature));
654 if let Some(unstable_reason) = reason {
655 let mut ids = cx.id_map.borrow_mut();
657 "<details><summary>{}</summary>{}</details>",
660 &unstable_reason.as_str(),
664 &cx.shared.playground,
670 extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
673 if let Some(portability) = portability(item, parent) {
674 extra_info.push(portability);
680 // Render the list of items inside one of the sections "Trait Implementations",
681 // "Auto Trait Implementations," "Blanket Trait Implementations" (on struct/enum pages).
686 containing_item: &clean::Item,
688 let cache = cx.cache();
690 let mut impls = traits
693 let did = i.trait_did_full(cache).unwrap();
694 let provided_trait_methods = i.inner_impl().provided_trait_methods(tcx);
695 let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_trait_methods);
696 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
712 .collect::<Vec<_>>();
714 w.write_str(&impls.join(""));
717 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>, cx: &Context<'_>) -> String {
718 use crate::formats::item_type::ItemType::*;
720 let name = it.name.as_ref().unwrap();
721 let ty = match it.type_() {
722 Typedef | AssocType => AssocType,
726 let anchor = format!("#{}.{}", ty, name);
728 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
729 AssocItemLink::Anchor(None) => anchor,
730 AssocItemLink::GotoSource(did, _) => {
731 href(did.expect_real(), cx).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
740 _default: Option<&String>,
741 link: AssocItemLink<'_>,
747 "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
749 it.visibility.print_with_space(it.def_id, cx),
750 naive_assoc_href(it, link, cx),
751 it.name.as_ref().unwrap(),
759 bounds: &[clean::GenericBound],
760 default: Option<&clean::Type>,
761 link: AssocItemLink<'_>,
767 "{}type <a href=\"{}\" class=\"type\">{}</a>",
769 naive_assoc_href(it, link, cx),
770 it.name.as_ref().unwrap()
772 if !bounds.is_empty() {
773 write!(w, ": {}", print_generic_bounds(bounds, cx))
775 if let Some(default) = default {
776 write!(w, " = {}", default.print(cx))
780 fn render_stability_since_raw(
783 const_stability: Option<&ConstStability>,
784 containing_ver: Option<&str>,
785 containing_const_ver: Option<&str>,
787 let ver = ver.filter(|inner| !inner.is_empty());
789 match (ver, const_stability) {
790 // stable and const stable
791 (Some(v), Some(ConstStability { level: StabilityLevel::Stable { since }, .. }))
792 if Some(since.as_str()).as_deref() != containing_const_ver =>
796 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
800 // stable and const unstable
803 Some(ConstStability { level: StabilityLevel::Unstable { issue, .. }, feature, .. }),
807 "<span class=\"since\" title=\"Stable since Rust version {0}, const unstable\">{0} (const: ",
810 if let Some(n) = issue {
813 "<a href=\"https://github.com/rust-lang/rust/issues/{}\" title=\"Tracking issue for {}\">unstable</a>",
817 write!(w, "unstable");
819 write!(w, ")</span>");
822 (Some(v), _) if ver != containing_ver => {
825 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
833 fn render_assoc_item(
836 link: AssocItemLink<'_>,
843 header: hir::FnHeader,
846 link: AssocItemLink<'_>,
850 let name = meth.name.as_ref().unwrap();
851 let href = match link {
852 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
853 AssocItemLink::Anchor(None) => format!("#{}.{}", meth.type_(), name),
854 AssocItemLink::GotoSource(did, provided_methods) => {
855 // We're creating a link from an impl-item to the corresponding
856 // trait-item and need to map the anchored type accordingly.
857 let ty = if provided_methods.contains(&name) {
863 href(did.expect_real(), cx)
864 .map(|p| format!("{}#{}.{}", p.0, ty, name))
865 .unwrap_or_else(|| format!("#{}.{}", ty, name))
868 let vis = meth.visibility.print_with_space(meth.def_id, cx).to_string();
870 print_constness_with_space(&header.constness, meth.const_stability(cx.tcx()));
871 let asyncness = header.asyncness.print_with_space();
872 let unsafety = header.unsafety.print_with_space();
873 let defaultness = print_default_space(meth.is_default());
874 let abi = print_abi_with_space(header.abi).to_string();
876 // NOTE: `{:#}` does not print HTML formatting, `{}` does. So `g.print` can't be reused between the length calculation and `write!`.
877 let generics_len = format!("{:#}", g.print(cx)).len();
878 let mut header_len = "fn ".len()
885 + name.as_str().len()
888 let (indent, indent_str, end_newline) = if parent == ItemType::Trait {
890 let indent_str = " ";
891 render_attributes_in_pre(w, meth, indent_str);
892 (4, indent_str, false)
894 render_attributes_in_code(w, meth);
897 w.reserve(header_len + "<a href=\"\" class=\"fnname\">{".len() + "</a>".len());
900 "{indent}{vis}{constness}{asyncness}{unsafety}{defaultness}{abi}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
901 {generics}{decl}{notable_traits}{where_clause}",
904 constness = constness,
905 asyncness = asyncness,
907 defaultness = defaultness,
911 generics = g.print(cx),
912 decl = d.full_print(header_len, indent, header.asyncness, cx),
913 notable_traits = notable_traits_decl(&d, cx),
914 where_clause = print_where_clause(g, cx, indent, end_newline),
918 clean::StrippedItem(..) => {}
919 clean::TyMethodItem(ref m) => {
920 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
922 clean::MethodItem(ref m, _) => {
923 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
925 clean::AssocConstItem(ref ty, ref default) => assoc_const(
931 if parent == ItemType::Trait { " " } else { "" },
934 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
940 if parent == ItemType::Trait { " " } else { "" },
943 _ => panic!("render_assoc_item called on non-associated-item"),
947 const ALLOWED_ATTRIBUTES: &[Symbol] =
948 &[sym::export_name, sym::link_section, sym::no_mangle, sym::repr, sym::non_exhaustive];
950 fn attributes(it: &clean::Item) -> Vec<String> {
955 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
956 Some(pprust::attribute_to_string(&attr).replace("\n", "").replace(" ", " "))
964 // When an attribute is rendered inside a `<pre>` tag, it is formatted using
965 // a whitespace prefix and newline.
966 fn render_attributes_in_pre(w: &mut Buffer, it: &clean::Item, prefix: &str) {
967 for a in attributes(it) {
968 writeln!(w, "{}{}", prefix, a);
972 // When an attribute is rendered inside a <code> tag, it is formatted using
973 // a div to produce a newline after it.
974 fn render_attributes_in_code(w: &mut Buffer, it: &clean::Item) {
975 for a in attributes(it) {
976 write!(w, "<div class=\"code-attribute\">{}</div>", a);
980 #[derive(Copy, Clone)]
981 enum AssocItemLink<'a> {
982 Anchor(Option<&'a str>),
983 GotoSource(FakeDefId, &'a FxHashSet<Symbol>),
986 impl<'a> AssocItemLink<'a> {
987 fn anchor(&self, id: &'a str) -> Self {
989 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
995 fn render_assoc_items(
998 containing_item: &clean::Item,
1000 what: AssocItemRender<'_>,
1002 info!("Documenting associated items of {:?}", containing_item.name);
1003 let v = match cx.cache.impls.get(&it) {
1007 let cache = cx.cache();
1008 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
1009 if !non_trait.is_empty() {
1010 let render_mode = match what {
1011 AssocItemRender::All => {
1013 "<h2 id=\"implementations\" class=\"small-section-header\">\
1014 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
1019 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
1022 "<h2 id=\"deref-methods\" class=\"small-section-header\">\
1023 Methods from {trait_}<Target = {type_}>\
1024 <a href=\"#deref-methods\" class=\"anchor\"></a>\
1026 trait_ = trait_.print(cx),
1027 type_ = type_.print(cx),
1029 RenderMode::ForDeref { mut_: deref_mut_ }
1032 for i in &non_trait {
1038 AssocItemLink::Anchor(None),
1048 if let AssocItemRender::DerefFor { .. } = what {
1051 if !traits.is_empty() {
1052 let deref_impl = traits
1054 .find(|t| t.inner_impl().trait_.def_id_full(cache) == cx.cache.deref_trait_did);
1055 if let Some(impl_) = deref_impl {
1056 let has_deref_mut = traits
1058 .any(|t| t.inner_impl().trait_.def_id_full(cache) == cx.cache.deref_mut_trait_did);
1059 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut);
1061 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
1062 traits.iter().partition(|t| t.inner_impl().synthetic);
1063 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
1064 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
1066 let mut impls = Buffer::empty_from(&w);
1067 render_impls(cx, &mut impls, &concrete, containing_item);
1068 let impls = impls.into_inner();
1069 if !impls.is_empty() {
1072 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
1073 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
1075 <div id=\"trait-implementations-list\">{}</div>",
1080 if !synthetic.is_empty() {
1082 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
1083 Auto Trait Implementations\
1084 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
1086 <div id=\"synthetic-implementations-list\">",
1088 render_impls(cx, w, &synthetic, containing_item);
1089 w.write_str("</div>");
1092 if !blanket_impl.is_empty() {
1094 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
1095 Blanket Implementations\
1096 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
1098 <div id=\"blanket-implementations-list\">",
1100 render_impls(cx, w, &blanket_impl, containing_item);
1101 w.write_str("</div>");
1106 fn render_deref_methods(
1110 container_item: &clean::Item,
1113 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
1114 let (target, real_target) = impl_
1118 .find_map(|item| match *item.kind {
1119 clean::TypedefItem(ref t, true) => Some(match *t {
1120 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
1121 _ => (&t.type_, &t.type_),
1125 .expect("Expected associated type binding");
1126 debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target);
1128 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
1129 if let Some(did) = target.def_id_full(cx.cache()) {
1130 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) {
1131 // `impl Deref<Target = S> for S`
1132 if did == type_did {
1133 // Avoid infinite cycles
1137 render_assoc_items(w, cx, container_item, did, what);
1139 if let Some(prim) = target.primitive_type() {
1140 if let Some(&did) = cx.cache.primitive_locations.get(&prim) {
1141 render_assoc_items(w, cx, container_item, did, what);
1147 fn should_render_item(item: &clean::Item, deref_mut_: bool, cache: &Cache) -> bool {
1148 let self_type_opt = match *item.kind {
1149 clean::MethodItem(ref method, _) => method.decl.self_type(),
1150 clean::TyMethodItem(ref method) => method.decl.self_type(),
1154 if let Some(self_ty) = self_type_opt {
1155 let (by_mut_ref, by_box, by_value) = match self_ty {
1156 SelfTy::SelfBorrowed(_, mutability)
1157 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
1158 (mutability == Mutability::Mut, false, false)
1160 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
1161 (false, Some(did) == cache.owned_box_did, false)
1163 SelfTy::SelfValue => (false, false, true),
1164 _ => (false, false, false),
1167 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
1173 fn notable_traits_decl(decl: &clean::FnDecl, cx: &Context<'_>) -> String {
1174 let mut out = Buffer::html();
1175 let mut trait_ = String::new();
1177 if let Some(did) = decl.output.def_id_full(cx.cache()) {
1178 if let Some(impls) = cx.cache().impls.get(&did) {
1180 let impl_ = i.inner_impl();
1181 if impl_.trait_.def_id().map_or(false, |d| {
1182 cx.cache().traits.get(&d).map(|t| t.is_notable).unwrap_or(false)
1187 "<h3 class=\"notable\">Notable traits for {}</h3>\
1188 <code class=\"content\">",
1189 impl_.for_.print(cx)
1191 trait_.push_str(&impl_.for_.print(cx).to_string());
1194 //use the "where" class here to make it small
1197 "<span class=\"where fmt-newline\">{}</span>",
1198 impl_.print(false, cx)
1200 let t_did = impl_.trait_.def_id_full(cx.cache()).unwrap();
1201 for it in &impl_.items {
1202 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1203 out.push_str("<span class=\"where fmt-newline\"> ");
1209 AssocItemLink::GotoSource(t_did.into(), &FxHashSet::default()),
1213 out.push_str(";</span>");
1221 if !out.is_empty() {
1224 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
1225 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
1227 out.push_str("</code></span></div></span></span>");
1237 parent: &clean::Item,
1238 link: AssocItemLink<'_>,
1239 render_mode: RenderMode,
1240 show_def_docs: bool,
1241 use_absolute: Option<bool>,
1242 is_on_foreign_type: bool,
1243 show_default_items: bool,
1244 // This argument is used to reference same type with different paths to avoid duplication
1245 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
1248 let cache = cx.cache();
1249 let traits = &cache.traits;
1250 let trait_ = i.trait_did_full(cache).map(|did| &traits[&did]);
1251 let mut close_tags = String::new();
1253 // For trait implementations, the `interesting` output contains all methods that have doc
1254 // comments, and the `boring` output contains all methods that do not. The distinction is
1255 // used to allow hiding the boring methods.
1256 // `containing_item` is used for rendering stability info. If the parent is a trait impl,
1257 // `containing_item` will the grandparent, since trait impls can't have stability attached.
1259 boring: &mut Buffer,
1260 interesting: &mut Buffer,
1263 parent: &clean::Item,
1264 containing_item: &clean::Item,
1265 link: AssocItemLink<'_>,
1266 render_mode: RenderMode,
1267 is_default_item: bool,
1268 trait_: Option<&clean::Trait>,
1269 show_def_docs: bool,
1271 let item_type = item.type_();
1272 let name = item.name.as_ref().unwrap();
1274 let render_method_item = match render_mode {
1275 RenderMode::Normal => true,
1276 RenderMode::ForDeref { mut_: deref_mut_ } => {
1277 should_render_item(&item, deref_mut_, &cx.cache)
1281 let in_trait_class = if trait_.is_some() { " trait-impl" } else { "" };
1283 let mut doc_buffer = Buffer::empty_from(boring);
1284 let mut info_buffer = Buffer::empty_from(boring);
1285 let mut short_documented = true;
1287 if render_method_item {
1288 if !is_default_item {
1289 if let Some(t) = trait_ {
1290 // The trait item may have been stripped so we might not
1291 // find any documentation or stability for it.
1292 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
1293 // We need the stability of the item from the trait
1294 // because impls can't have a stability.
1295 if item.doc_value().is_some() {
1296 document_item_info(&mut info_buffer, cx, it, Some(parent));
1297 document_full(&mut doc_buffer, item, cx);
1298 short_documented = false;
1300 // In case the item isn't documented,
1301 // provide short documentation from the trait.
1302 document_short(&mut doc_buffer, it, cx, link, parent, show_def_docs);
1306 document_item_info(&mut info_buffer, cx, item, Some(parent));
1308 document_full(&mut doc_buffer, item, cx);
1309 short_documented = false;
1313 document_short(&mut doc_buffer, item, cx, link, parent, show_def_docs);
1316 let w = if short_documented && trait_.is_some() { interesting } else { boring };
1318 let toggled = !doc_buffer.is_empty();
1320 let method_toggle_class =
1321 if item_type == ItemType::Method { " method-toggle" } else { "" };
1322 write!(w, "<details class=\"rustdoc-toggle{}\" open><summary>", method_toggle_class);
1325 clean::MethodItem(..) | clean::TyMethodItem(_) => {
1326 // Only render when the method is not static or we allow static methods
1327 if render_method_item {
1328 let id = cx.derive_id(format!("{}.{}", item_type, name));
1329 let source_id = trait_
1330 .and_then(|trait_| {
1331 trait_.items.iter().find(|item| {
1332 item.name.map(|n| n.as_str().eq(&name.as_str())).unwrap_or(false)
1335 .map(|item| format!("{}.{}", item.type_(), name));
1338 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1339 id, item_type, in_trait_class,
1341 render_rightside(w, cx, item, containing_item);
1342 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1343 w.write_str("<code>");
1347 link.anchor(source_id.as_ref().unwrap_or(&id)),
1351 w.write_str("</code>");
1352 w.write_str("</div>");
1355 clean::TypedefItem(ref tydef, _) => {
1356 let source_id = format!("{}.{}", ItemType::AssocType, name);
1357 let id = cx.derive_id(source_id.clone());
1360 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1361 id, item_type, in_trait_class
1363 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1364 w.write_str("<code>");
1370 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1374 w.write_str("</code>");
1375 w.write_str("</div>");
1377 clean::AssocConstItem(ref ty, ref default) => {
1378 let source_id = format!("{}.{}", item_type, name);
1379 let id = cx.derive_id(source_id.clone());
1382 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1383 id, item_type, in_trait_class
1385 render_rightside(w, cx, item, containing_item);
1386 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1387 w.write_str("<code>");
1393 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1397 w.write_str("</code>");
1398 w.write_str("</div>");
1400 clean::AssocTypeItem(ref bounds, ref default) => {
1401 let source_id = format!("{}.{}", item_type, name);
1402 let id = cx.derive_id(source_id.clone());
1403 write!(w, "<div id=\"{}\" class=\"{}{}\">", id, item_type, in_trait_class,);
1404 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1405 w.write_str("<code>");
1411 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1415 w.write_str("</code>");
1416 w.write_str("</div>");
1418 clean::StrippedItem(..) => return,
1419 _ => panic!("can't make docs for trait item with name {:?}", item.name),
1422 w.push_buffer(info_buffer);
1424 w.write_str("</summary>");
1425 w.push_buffer(doc_buffer);
1426 w.push_str("</details>");
1430 let mut impl_items = Buffer::empty_from(w);
1431 let mut default_impl_items = Buffer::empty_from(w);
1433 for trait_item in &i.inner_impl().items {
1435 &mut default_impl_items,
1439 if trait_.is_some() { &i.impl_item } else { parent },
1444 trait_.map(|t| &t.trait_),
1449 fn render_default_items(
1450 boring: &mut Buffer,
1451 interesting: &mut Buffer,
1455 parent: &clean::Item,
1456 containing_item: &clean::Item,
1457 render_mode: RenderMode,
1458 show_def_docs: bool,
1460 for trait_item in &t.items {
1461 let n = trait_item.name;
1462 if i.items.iter().any(|m| m.name == n) {
1465 let did = i.trait_.as_ref().unwrap().def_id_full(cx.cache()).unwrap();
1466 let provided_methods = i.provided_trait_methods(cx.tcx());
1467 let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_methods);
1485 // If we've implemented a trait, then also emit documentation for all
1486 // default items which weren't overridden in the implementation block.
1487 // We don't emit documentation for default items if they appear in the
1488 // Implementations on Foreign Types or Implementors sections.
1489 if show_default_items {
1490 if let Some(t) = trait_ {
1491 render_default_items(
1492 &mut default_impl_items,
1504 if render_mode == RenderMode::Normal {
1505 let toggled = !(impl_items.is_empty() && default_impl_items.is_empty());
1507 close_tags.insert_str(0, "</details>");
1508 write!(w, "<details class=\"rustdoc-toggle implementors-toggle\" open>");
1509 write!(w, "<summary>")
1511 render_impl_summary(
1523 write!(w, "</summary>")
1526 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
1527 let mut ids = cx.id_map.borrow_mut();
1530 "<div class=\"docblock\">{}</div>",
1533 &i.impl_item.links(cx),
1536 cx.shared.edition(),
1537 &cx.shared.playground
1543 if !default_impl_items.is_empty() || !impl_items.is_empty() {
1544 w.write_str("<div class=\"impl-items\">");
1545 w.push_buffer(default_impl_items);
1546 w.push_buffer(impl_items);
1547 close_tags.insert_str(0, "</div>");
1549 w.write_str(&close_tags);
1552 // Render the items that appear on the right side of methods, impls, and
1553 // associated types. For example "1.0.0 (const: 1.39.0) [src]".
1554 fn render_rightside(
1558 containing_item: &clean::Item,
1562 write!(w, "<div class=\"rightside\">");
1563 render_stability_since_raw(
1565 item.stable_since(tcx).as_deref(),
1566 item.const_stability(tcx),
1567 containing_item.stable_since(tcx).as_deref(),
1568 containing_item.const_stable_since(tcx).as_deref(),
1571 write_srclink(cx, item, w);
1572 w.write_str("</div>");
1575 pub(crate) fn render_impl_summary(
1579 parent: &clean::Item,
1580 containing_item: &clean::Item,
1581 show_def_docs: bool,
1582 use_absolute: Option<bool>,
1583 is_on_foreign_type: bool,
1584 // This argument is used to reference same type with different paths to avoid duplication
1585 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
1588 let id = cx.derive_id(match i.inner_impl().trait_ {
1590 if is_on_foreign_type {
1591 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t, cx)
1593 format!("impl-{}", small_url_encode(format!("{:#}", t.print(cx))))
1596 None => "impl".to_string(),
1598 let aliases = if aliases.is_empty() {
1601 format!(" data-aliases=\"{}\"", aliases.join(","))
1603 write!(w, "<div id=\"{}\" class=\"impl has-srclink\"{}>", id, aliases);
1604 render_rightside(w, cx, &i.impl_item, containing_item);
1605 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1606 write!(w, "<code class=\"in-band\">");
1608 if let Some(use_absolute) = use_absolute {
1609 write!(w, "{}", i.inner_impl().print(use_absolute, cx));
1611 for it in &i.inner_impl().items {
1612 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1613 w.write_str("<span class=\"where fmt-newline\"> ");
1614 assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "", cx);
1615 w.write_str(";</span>");
1620 write!(w, "{}", i.inner_impl().print(false, cx));
1622 write!(w, "</code>");
1624 let is_trait = i.inner_impl().trait_.is_some();
1626 if let Some(portability) = portability(&i.impl_item, Some(parent)) {
1627 write!(w, "<div class=\"item-info\">{}</div>", portability);
1631 w.write_str("</div>");
1634 fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) {
1635 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
1639 || it.is_primitive()
1647 "<p class=\"location\">{}{}</p>",
1649 clean::StructItem(..) => "Struct ",
1650 clean::TraitItem(..) => "Trait ",
1651 clean::PrimitiveItem(..) => "Primitive Type ",
1652 clean::UnionItem(..) => "Union ",
1653 clean::EnumItem(..) => "Enum ",
1654 clean::TypedefItem(..) => "Type Definition ",
1655 clean::ForeignTypeItem => "Foreign Type ",
1656 clean::ModuleItem(..) =>
1664 it.name.as_ref().unwrap()
1669 if let Some(ref version) = cx.cache.crate_version {
1672 "<div class=\"block version\">\
1673 <div class=\"narrow-helper\"></div>\
1681 buffer.write_str("<div class=\"sidebar-elems\">");
1685 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
1686 it.name.as_ref().expect("crates always have a name"),
1691 clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s),
1692 clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t),
1693 clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it),
1694 clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u),
1695 clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e),
1696 clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it),
1697 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
1698 clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, it),
1702 // The sidebar is designed to display sibling functions, modules and
1703 // other miscellaneous information. since there are lots of sibling
1704 // items (and that causes quadratic growth in large modules),
1705 // we refactor common parts into a shared JavaScript file per module.
1706 // still, we don't move everything into JS because we want to preserve
1707 // as much HTML as possible in order to allow non-JS-enabled browsers
1708 // to navigate the documentation (though slightly inefficiently).
1711 buffer.write_str("<p class=\"location\">Other items in<br>");
1712 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
1714 buffer.write_str("::<wbr>");
1718 "<a href=\"{}index.html\">{}</a>",
1719 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
1723 buffer.write_str("</p>");
1726 // Sidebar refers to the enclosing module, not this module.
1727 let relpath = if it.is_mod() && parentlen != 0 { "./" } else { "" };
1730 "<div id=\"sidebar-vars\" data-name=\"{name}\" data-ty=\"{ty}\" data-relpath=\"{path}\">\
1732 name = it.name.unwrap_or(kw::Empty),
1736 write!(buffer, "<script defer src=\"{}sidebar-items.js\"></script>", relpath);
1737 // Closes sidebar-elems div.
1738 buffer.write_str("</div>");
1741 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
1742 if used_links.insert(url.clone()) {
1746 while !used_links.insert(format!("{}-{}", url, add)) {
1749 format!("{}-{}", url, add)
1755 used_links: &mut FxHashSet<String>,
1761 .filter_map(|item| match item.name {
1762 Some(ref name) if !name.is_empty() && item.is_method() => {
1763 if !for_deref || should_render_item(item, deref_mut, cache) {
1765 "<a href=\"#{}\">{}</a>",
1766 get_next_url(used_links, format!("method.{}", name)),
1775 .collect::<Vec<_>>()
1778 // The point is to url encode any potential character from a type with genericity.
1779 fn small_url_encode(s: String) -> String {
1780 let mut st = String::new();
1781 let mut last_match = 0;
1782 for (idx, c) in s.char_indices() {
1783 let escaped = match c {
1799 st += &s[last_match..idx];
1801 // NOTE: we only expect single byte characters here - which is fine as long as we
1802 // only match single byte characters
1803 last_match = idx + 1;
1806 if last_match != 0 {
1807 st += &s[last_match..];
1814 fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) {
1815 let did = it.def_id.expect_real();
1816 if let Some(v) = cx.cache.impls.get(&did) {
1817 let mut used_links = FxHashSet::default();
1818 let cache = cx.cache();
1821 let used_links_bor = &mut used_links;
1824 .filter(|i| i.inner_impl().trait_.is_none())
1825 .flat_map(move |i| {
1826 get_methods(i.inner_impl(), false, used_links_bor, false, &cx.cache)
1828 .collect::<Vec<_>>();
1829 if !ret.is_empty() {
1830 // We want links' order to be reproducible so we don't use unstable sort.
1834 "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
1835 <div class=\"sidebar-links\">",
1838 out.push_str(&line);
1840 out.push_str("</div>");
1844 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
1845 if let Some(impl_) = v
1847 .filter(|i| i.inner_impl().trait_.is_some())
1848 .find(|i| i.inner_impl().trait_.def_id_full(cache) == cx.cache.deref_trait_did)
1850 sidebar_deref_methods(cx, out, impl_, v);
1853 let format_impls = |impls: Vec<&Impl>| {
1854 let mut links = FxHashSet::default();
1859 if let Some(ref i) = it.inner_impl().trait_ {
1860 let i_display = format!("{:#}", i.print(cx));
1861 let out = Escape(&i_display);
1862 let encoded = small_url_encode(format!("{:#}", i.print(cx)));
1863 let generated = format!(
1864 "<a href=\"#impl-{}\">{}{}</a>",
1866 if it.inner_impl().negative_polarity { "!" } else { "" },
1869 if links.insert(generated.clone()) { Some(generated) } else { None }
1874 .collect::<Vec<String>>();
1879 let write_sidebar_links = |out: &mut Buffer, links: Vec<String>| {
1880 out.push_str("<div class=\"sidebar-links\">");
1882 out.push_str(&link);
1884 out.push_str("</div>");
1887 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
1888 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
1889 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
1891 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
1893 let concrete_format = format_impls(concrete);
1894 let synthetic_format = format_impls(synthetic);
1895 let blanket_format = format_impls(blanket_impl);
1897 if !concrete_format.is_empty() {
1899 "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
1900 Trait Implementations</a>",
1902 write_sidebar_links(out, concrete_format);
1905 if !synthetic_format.is_empty() {
1907 "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
1908 Auto Trait Implementations</a>",
1910 write_sidebar_links(out, synthetic_format);
1913 if !blanket_format.is_empty() {
1915 "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
1916 Blanket Implementations</a>",
1918 write_sidebar_links(out, blanket_format);
1924 fn sidebar_deref_methods(cx: &Context<'_>, out: &mut Buffer, impl_: &Impl, v: &Vec<Impl>) {
1927 debug!("found Deref: {:?}", impl_);
1928 if let Some((target, real_target)) =
1929 impl_.inner_impl().items.iter().find_map(|item| match *item.kind {
1930 clean::TypedefItem(ref t, true) => Some(match *t {
1931 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
1932 _ => (&t.type_, &t.type_),
1937 debug!("found target, real_target: {:?} {:?}", target, real_target);
1938 if let Some(did) = target.def_id_full(c) {
1939 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(c) {
1940 // `impl Deref<Target = S> for S`
1941 if did == type_did {
1942 // Avoid infinite cycles
1949 .filter(|i| i.inner_impl().trait_.is_some())
1950 .any(|i| i.inner_impl().trait_.def_id_full(c) == c.deref_mut_trait_did);
1951 let inner_impl = target
1954 target.primitive_type().and_then(|prim| c.primitive_locations.get(&prim).cloned())
1956 .and_then(|did| c.impls.get(&did));
1957 if let Some(impls) = inner_impl {
1958 debug!("found inner_impl: {:?}", impls);
1959 let mut used_links = FxHashSet::default();
1962 .filter(|i| i.inner_impl().trait_.is_none())
1963 .flat_map(|i| get_methods(i.inner_impl(), true, &mut used_links, deref_mut, c))
1964 .collect::<Vec<_>>();
1965 if !ret.is_empty() {
1968 "<a class=\"sidebar-title\" href=\"#deref-methods\">Methods from {}<Target={}></a>",
1969 Escape(&format!("{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print(cx))),
1970 Escape(&format!("{:#}", real_target.print(cx))),
1972 // We want links' order to be reproducible so we don't use unstable sort.
1974 out.push_str("<div class=\"sidebar-links\">");
1976 out.push_str(&link);
1978 out.push_str("</div>");
1984 fn sidebar_struct(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
1985 let mut sidebar = Buffer::new();
1986 let fields = get_struct_fields_name(&s.fields);
1988 if !fields.is_empty() {
1989 if let CtorKind::Fictive = s.struct_type {
1991 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
1992 <div class=\"sidebar-links\">",
1995 for field in fields {
1996 sidebar.push_str(&field);
1999 sidebar.push_str("</div>");
2003 sidebar_assoc_items(cx, &mut sidebar, it);
2005 if !sidebar.is_empty() {
2006 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2010 fn get_id_for_impl_on_foreign_type(
2012 trait_: &clean::Type,
2015 small_url_encode(format!("impl-{:#}-for-{:#}", trait_.print(cx), for_.print(cx),))
2018 fn extract_for_impl_name(item: &clean::Item, cx: &Context<'_>) -> Option<(String, String)> {
2020 clean::ItemKind::ImplItem(ref i) => {
2021 if let Some(ref trait_) = i.trait_ {
2022 // Alternative format produces no URLs,
2023 // so this parameter does nothing.
2025 format!("{:#}", i.for_.print(cx)),
2026 get_id_for_impl_on_foreign_type(&i.for_, trait_, cx),
2036 fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
2037 buf.write_str("<div class=\"block items\">");
2039 fn print_sidebar_section(
2041 items: &[clean::Item],
2043 filter: impl Fn(&clean::Item) -> bool,
2044 write: impl Fn(&mut Buffer, &str),
2047 let mut items = items
2049 .filter_map(|m| match m.name {
2050 Some(ref name) if filter(m) => Some(name.as_str()),
2053 .collect::<Vec<_>>();
2055 if !items.is_empty() {
2056 items.sort_unstable();
2057 out.push_str(before);
2058 for item in items.into_iter() {
2061 out.push_str(after);
2065 print_sidebar_section(
2068 "<a class=\"sidebar-title\" href=\"#associated-types\">\
2069 Associated Types</a><div class=\"sidebar-links\">",
2070 |m| m.is_associated_type(),
2071 |out, sym| write!(out, "<a href=\"#associatedtype.{0}\">{0}</a>", sym),
2075 print_sidebar_section(
2078 "<a class=\"sidebar-title\" href=\"#associated-const\">\
2079 Associated Constants</a><div class=\"sidebar-links\">",
2080 |m| m.is_associated_const(),
2081 |out, sym| write!(out, "<a href=\"#associatedconstant.{0}\">{0}</a>", sym),
2085 print_sidebar_section(
2088 "<a class=\"sidebar-title\" href=\"#required-methods\">\
2089 Required Methods</a><div class=\"sidebar-links\">",
2090 |m| m.is_ty_method(),
2091 |out, sym| write!(out, "<a href=\"#tymethod.{0}\">{0}</a>", sym),
2095 print_sidebar_section(
2098 "<a class=\"sidebar-title\" href=\"#provided-methods\">\
2099 Provided Methods</a><div class=\"sidebar-links\">",
2101 |out, sym| write!(out, "<a href=\"#method.{0}\">{0}</a>", sym),
2105 if let Some(implementors) = cx.cache.implementors.get(&it.def_id.expect_real()) {
2106 let cache = cx.cache();
2107 let mut res = implementors
2113 .map_or(false, |d| !cx.cache.paths.contains_key(&d))
2115 .filter_map(|i| extract_for_impl_name(&i.impl_item, cx))
2116 .collect::<Vec<_>>();
2118 if !res.is_empty() {
2121 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
2122 Implementations on Foreign Types</a>\
2123 <div class=\"sidebar-links\">",
2125 for (name, id) in res.into_iter() {
2126 write!(buf, "<a href=\"#{}\">{}</a>", id, Escape(&name));
2128 buf.push_str("</div>");
2132 sidebar_assoc_items(cx, buf, it);
2134 buf.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
2137 "<a class=\"sidebar-title\" \
2138 href=\"#synthetic-implementors\">Auto Implementors</a>",
2142 buf.push_str("</div>")
2145 fn sidebar_primitive(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2146 let mut sidebar = Buffer::new();
2147 sidebar_assoc_items(cx, &mut sidebar, it);
2149 if !sidebar.is_empty() {
2150 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2154 fn sidebar_typedef(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2155 let mut sidebar = Buffer::new();
2156 sidebar_assoc_items(cx, &mut sidebar, it);
2158 if !sidebar.is_empty() {
2159 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2163 fn get_struct_fields_name(fields: &[clean::Item]) -> Vec<String> {
2164 let mut fields = fields
2166 .filter(|f| matches!(*f.kind, clean::StructFieldItem(..)))
2168 f.name.map(|name| format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
2170 .collect::<Vec<_>>();
2175 fn sidebar_union(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
2176 let mut sidebar = Buffer::new();
2177 let fields = get_struct_fields_name(&u.fields);
2179 if !fields.is_empty() {
2181 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
2182 <div class=\"sidebar-links\">",
2185 for field in fields {
2186 sidebar.push_str(&field);
2189 sidebar.push_str("</div>");
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_enum(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
2200 let mut sidebar = Buffer::new();
2202 let mut variants = e
2205 .filter_map(|v| match v.name {
2206 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
2209 .collect::<Vec<_>>();
2210 if !variants.is_empty() {
2211 variants.sort_unstable();
2212 sidebar.push_str(&format!(
2213 "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
2214 <div class=\"sidebar-links\">{}</div>",
2219 sidebar_assoc_items(cx, &mut sidebar, it);
2221 if !sidebar.is_empty() {
2222 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2226 fn item_ty_to_strs(ty: ItemType) -> (&'static str, &'static str) {
2228 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
2229 ItemType::Module => ("modules", "Modules"),
2230 ItemType::Struct => ("structs", "Structs"),
2231 ItemType::Union => ("unions", "Unions"),
2232 ItemType::Enum => ("enums", "Enums"),
2233 ItemType::Function => ("functions", "Functions"),
2234 ItemType::Typedef => ("types", "Type Definitions"),
2235 ItemType::Static => ("statics", "Statics"),
2236 ItemType::Constant => ("constants", "Constants"),
2237 ItemType::Trait => ("traits", "Traits"),
2238 ItemType::Impl => ("impls", "Implementations"),
2239 ItemType::TyMethod => ("tymethods", "Type Methods"),
2240 ItemType::Method => ("methods", "Methods"),
2241 ItemType::StructField => ("fields", "Struct Fields"),
2242 ItemType::Variant => ("variants", "Variants"),
2243 ItemType::Macro => ("macros", "Macros"),
2244 ItemType::Primitive => ("primitives", "Primitive Types"),
2245 ItemType::AssocType => ("associated-types", "Associated Types"),
2246 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
2247 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
2248 ItemType::Keyword => ("keywords", "Keywords"),
2249 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
2250 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
2251 ItemType::ProcDerive => ("derives", "Derive Macros"),
2252 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
2256 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
2257 let mut sidebar = String::new();
2259 // Re-exports are handled a bit differently because they can be extern crates or imports.
2260 if items.iter().any(|it| {
2262 && (it.type_() == ItemType::ExternCrate
2263 || (it.type_() == ItemType::Import && !it.is_stripped()))
2265 let (id, name) = item_ty_to_strs(ItemType::Import);
2266 sidebar.push_str(&format!("<li><a href=\"#{}\">{}</a></li>", id, name));
2269 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
2270 // to print its headings
2272 ItemType::Primitive,
2286 ItemType::StructField,
2288 ItemType::AssocType,
2289 ItemType::AssocConst,
2290 ItemType::ForeignType,
2293 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty && it.name.is_some()) {
2294 let (id, name) = item_ty_to_strs(myty);
2295 sidebar.push_str(&format!("<li><a href=\"#{}\">{}</a></li>", id, name));
2299 if !sidebar.is_empty() {
2300 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
2304 fn sidebar_foreign_type(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2305 let mut sidebar = Buffer::new();
2306 sidebar_assoc_items(cx, &mut sidebar, it);
2308 if !sidebar.is_empty() {
2309 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2313 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
2315 /// Returns a list of all paths used in the type.
2316 /// This is used to help deduplicate imported impls
2317 /// for reexported types. If any of the contained
2318 /// types are re-exported, we don't use the corresponding
2319 /// entry from the js file, as inlining will have already
2320 /// picked up the impl
2321 fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> {
2322 let mut out = Vec::new();
2323 let mut visited = FxHashSet::default();
2324 let mut work = VecDeque::new();
2326 work.push_back(first_ty);
2328 while let Some(ty) = work.pop_front() {
2329 if !visited.insert(ty.clone()) {
2334 clean::Type::ResolvedPath { did, .. } => {
2335 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
2336 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
2338 if let Some(path) = fqp {
2339 out.push(path.join("::"));
2342 clean::Type::Tuple(tys) => {
2343 work.extend(tys.into_iter());
2345 clean::Type::Slice(ty) => {
2346 work.push_back(*ty);
2348 clean::Type::Array(ty, _) => {
2349 work.push_back(*ty);
2351 clean::Type::RawPointer(_, ty) => {
2352 work.push_back(*ty);
2354 clean::Type::BorrowedRef { type_, .. } => {
2355 work.push_back(*type_);
2357 clean::Type::QPath { self_type, trait_, .. } => {
2358 work.push_back(*self_type);
2359 work.push_back(*trait_);