1 //! Rustdoc's HTML rendering module.
3 //! This modules contains the bulk of the logic necessary for rendering a
4 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
5 //! rendering process is largely driven by the `format!` syntax extension to
6 //! perform all I/O into files and streams.
8 //! The rendering process is largely driven by the `Context` and `Cache`
9 //! structures. The cache is pre-populated by crawling the crate in question,
10 //! and then it is shared among the various rendering threads. The cache is meant
11 //! to be a fairly large structure not implementing `Clone` (because it's shared
12 //! among threads). The context, however, should be a lightweight structure. This
13 //! is cloned per-thread and contains information about what is currently being
16 //! In order to speed up rendering (mostly because of markdown rendering), the
17 //! rendering process has been parallelized. This parallelization is only
18 //! exposed through the `crate` method on the context, and then also from the
19 //! fact that the shared cache is stored in TLS (and must be accessed as such).
21 //! In addition to rendering the crate itself, this module is also responsible
22 //! for creating the corresponding search index and source file renderings.
23 //! These threads are not parallelized (they haven't been a bottleneck yet), and
24 //! both occur before the crate is rendered.
38 crate use span_map::{collect_spans_and_sources, LinkFromSrc};
40 use std::collections::VecDeque;
41 use std::default::Default;
44 use std::iter::Peekable;
45 use std::path::PathBuf;
47 use std::string::ToString;
49 use rustc_ast_pretty::pprust;
50 use rustc_attr::{ConstStability, Deprecation, StabilityLevel};
51 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
53 use rustc_hir::def::CtorKind;
54 use rustc_hir::def_id::DefId;
55 use rustc_hir::Mutability;
56 use rustc_middle::middle::stability;
57 use rustc_middle::ty::TyCtxt;
59 symbol::{kw, sym, Symbol},
60 BytePos, FileName, RealFileName,
62 use serde::ser::SerializeSeq;
63 use serde::{Serialize, Serializer};
65 use crate::clean::{self, ItemId, RenderedLink, SelfTy};
66 use crate::docfs::PathError;
67 use crate::error::Error;
68 use crate::formats::cache::Cache;
69 use crate::formats::item_type::ItemType;
70 use crate::formats::{AssocItemRender, Impl, RenderMode};
71 use crate::html::escape::Escape;
72 use crate::html::format::{
73 href, print_abi_with_space, print_constness_with_space, print_default_space,
74 print_generic_bounds, print_where_clause, Buffer, HrefError, PrintWithSpace,
76 use crate::html::highlight;
77 use crate::html::markdown::{HeadingOffset, Markdown, MarkdownHtml, MarkdownSummaryLine};
78 use crate::html::sources;
79 use crate::scrape_examples::{CallData, CallLocation};
82 /// A pair of name and its optional document.
83 crate type NameDoc = (String, Option<String>);
85 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
86 crate::html::format::display_fn(move |f| {
87 if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { f.write_str(v) }
91 // Helper structs for rendering items/sidebars and carrying along contextual
94 /// Struct representing one entry in the JS search index. These are all emitted
95 /// by hand to a large JS file at the end of cache-creation.
97 crate struct IndexItem {
102 crate parent: Option<DefId>,
103 crate parent_idx: Option<usize>,
104 crate search_type: Option<IndexItemFunctionType>,
105 crate aliases: Box<[String]>,
108 /// A type used for the search index.
110 crate struct RenderType {
111 name: Option<String>,
112 generics: Option<Vec<TypeWithKind>>,
115 /// Full type of functions/methods in the search index.
117 crate struct IndexItemFunctionType {
118 inputs: Vec<TypeWithKind>,
119 output: Option<Vec<TypeWithKind>>,
122 impl Serialize for IndexItemFunctionType {
123 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
127 // If we couldn't figure out a type, just write `null`.
128 let mut iter = self.inputs.iter();
129 if match self.output {
130 Some(ref output) => iter.chain(output.iter()).any(|i| i.ty.name.is_none()),
131 None => iter.any(|i| i.ty.name.is_none()),
133 serializer.serialize_none()
135 let mut seq = serializer.serialize_seq(None)?;
136 seq.serialize_element(&self.inputs)?;
137 if let Some(output) = &self.output {
138 if output.len() > 1 {
139 seq.serialize_element(&output)?;
141 seq.serialize_element(&output[0])?;
150 crate struct TypeWithKind {
155 impl From<(RenderType, ItemType)> for TypeWithKind {
156 fn from(x: (RenderType, ItemType)) -> TypeWithKind {
157 TypeWithKind { ty: x.0, kind: x.1 }
161 impl Serialize for TypeWithKind {
162 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
166 let mut seq = serializer.serialize_seq(None)?;
167 seq.serialize_element(&self.ty.name)?;
168 seq.serialize_element(&self.kind)?;
169 if let Some(generics) = &self.ty.generics {
170 seq.serialize_element(generics)?;
176 #[derive(Debug, Clone)]
177 crate struct StylePath {
178 /// The path to the theme
180 /// What the `disabled` attribute should be set to in the HTML tag
181 crate disabled: bool,
184 fn write_srclink(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) {
185 if let Some(l) = cx.src_href(item) {
186 write!(buf, "<a class=\"srclink\" href=\"{}\" title=\"goto source code\">[src]</a>", l)
190 #[derive(Debug, Eq, PartialEq, Hash)]
197 fn new(mut url: String, name: String) -> ItemEntry {
198 while url.starts_with('/') {
201 ItemEntry { url, name }
206 crate fn print(&self) -> impl fmt::Display + '_ {
207 crate::html::format::display_fn(move |f| {
208 write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name))
213 impl PartialOrd for ItemEntry {
214 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
215 Some(self.cmp(other))
219 impl Ord for ItemEntry {
220 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
221 self.name.cmp(&other.name)
227 structs: FxHashSet<ItemEntry>,
228 enums: FxHashSet<ItemEntry>,
229 unions: FxHashSet<ItemEntry>,
230 primitives: FxHashSet<ItemEntry>,
231 traits: FxHashSet<ItemEntry>,
232 macros: FxHashSet<ItemEntry>,
233 functions: FxHashSet<ItemEntry>,
234 typedefs: FxHashSet<ItemEntry>,
235 opaque_tys: FxHashSet<ItemEntry>,
236 statics: FxHashSet<ItemEntry>,
237 constants: FxHashSet<ItemEntry>,
238 attributes: FxHashSet<ItemEntry>,
239 derives: FxHashSet<ItemEntry>,
240 trait_aliases: FxHashSet<ItemEntry>,
244 fn new() -> AllTypes {
245 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
247 structs: new_set(100),
249 unions: new_set(100),
250 primitives: new_set(26),
251 traits: new_set(100),
252 macros: new_set(100),
253 functions: new_set(100),
254 typedefs: new_set(100),
255 opaque_tys: new_set(100),
256 statics: new_set(100),
257 constants: new_set(100),
258 attributes: new_set(100),
259 derives: new_set(100),
260 trait_aliases: new_set(100),
264 fn append(&mut self, item_name: String, item_type: &ItemType) {
265 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
266 if let Some(name) = url.pop() {
267 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
269 let name = url.join("::");
271 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
272 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
273 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
274 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
275 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
276 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
277 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
278 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
279 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
280 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
281 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
282 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
283 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
284 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
292 fn print(self, f: &mut Buffer) {
293 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
295 let mut e: Vec<&ItemEntry> = e.iter().collect();
299 "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">",
300 title.replace(' ', "-"), // IDs cannot contain whitespaces.
306 write!(f, "<li>{}</li>", s.print());
309 f.write_str("</ul>");
315 <span class=\"in-band\">List of all items</span>\
316 <span class=\"out-of-band\">\
317 <span id=\"render-detail\">\
318 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
319 title=\"collapse all docs\">\
320 [<span class=\"inner\">−</span>]\
326 // Note: print_entries does not escape the title, because we know the current set of titles
327 // doesn't require escaping.
328 print_entries(f, &self.structs, "Structs", "structs");
329 print_entries(f, &self.enums, "Enums", "enums");
330 print_entries(f, &self.unions, "Unions", "unions");
331 print_entries(f, &self.primitives, "Primitives", "primitives");
332 print_entries(f, &self.traits, "Traits", "traits");
333 print_entries(f, &self.macros, "Macros", "macros");
334 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
335 print_entries(f, &self.derives, "Derive Macros", "derives");
336 print_entries(f, &self.functions, "Functions", "functions");
337 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
338 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
339 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
340 print_entries(f, &self.statics, "Statics", "statics");
341 print_entries(f, &self.constants, "Constants", "constants")
348 description: &'static str,
349 sub_settings: Vec<Setting>,
352 js_data_name: &'static str,
353 description: &'static str,
357 js_data_name: &'static str,
358 description: &'static str,
359 default_value: &'static str,
360 options: Vec<(String, String)>,
365 fn display(&self, root_path: &str, suffix: &str) -> String {
367 Setting::Section { description, ref sub_settings } => format!(
368 "<div class=\"setting-line\">\
369 <div class=\"title\">{}</div>\
370 <div class=\"sub-settings\">{}</div>
373 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
375 Setting::Toggle { js_data_name, description, default_value } => format!(
376 "<div class=\"setting-line\">\
377 <label class=\"toggle\">\
378 <input type=\"checkbox\" id=\"{}\" {}>\
379 <span class=\"slider\"></span>\
384 if default_value { " checked" } else { "" },
387 Setting::Select { js_data_name, description, default_value, ref options } => format!(
388 "<div class=\"setting-line\">\
390 <label class=\"select-wrapper\">\
391 <select id=\"{}\" autocomplete=\"off\">{}</select>\
392 <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
400 "<option value=\"{}\" {}>{}</option>",
402 if opt.0 == default_value { "selected" } else { "" },
405 .collect::<String>(),
413 impl From<(&'static str, &'static str, bool)> for Setting {
414 fn from(values: (&'static str, &'static str, bool)) -> Setting {
415 Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
419 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
420 fn from(values: (&'static str, Vec<T>)) -> Setting {
422 description: values.0,
423 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
428 fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
429 let theme_names: Vec<(String, String)> = themes
433 try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
436 Ok((theme.clone(), theme))
438 .collect::<Result<_, Error>>()?;
440 // (id, explanation, default value)
441 let settings: &[Setting] = &[
445 Setting::from(("use-system-theme", "Use system theme", true)),
447 js_data_name: "preferred-dark-theme",
448 description: "Preferred dark theme",
449 default_value: "dark",
450 options: theme_names.clone(),
453 js_data_name: "preferred-light-theme",
454 description: "Preferred light theme",
455 default_value: "light",
456 options: theme_names,
461 ("auto-hide-large-items", "Auto-hide item contents for large items.", true).into(),
462 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
463 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", false)
465 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
467 ("line-numbers", "Show line numbers on code examples", false).into(),
468 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
473 <span class=\"in-band\">Rustdoc settings</span>\
475 <div class=\"settings\">{}</div>\
476 <script src=\"{}settings{}.js\"></script>",
477 settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
487 parent: Option<&clean::Item>,
488 heading_offset: HeadingOffset,
490 if let Some(ref name) = item.name {
491 info!("Documenting {}", name);
493 document_item_info(w, cx, item, parent);
494 if parent.is_none() {
495 document_full_collapsible(w, item, cx, heading_offset);
497 document_full(w, item, cx, heading_offset);
501 /// Render md_text as markdown.
506 links: Vec<RenderedLink>,
507 heading_offset: HeadingOffset,
509 let mut ids = cx.id_map.borrow_mut();
512 "<div class=\"docblock\">{}</div>",
517 error_codes: cx.shared.codes,
518 edition: cx.shared.edition(),
519 playground: &cx.shared.playground,
526 /// Writes a documentation block containing only the first paragraph of the documentation. If the
527 /// docs are longer, a "Read more" link is appended to the end.
532 link: AssocItemLink<'_>,
533 parent: &clean::Item,
536 document_item_info(w, cx, item, Some(parent));
540 if let Some(s) = item.doc_value() {
541 let mut summary_html = MarkdownSummaryLine(&s, &item.links(cx)).into_string();
543 if s.contains('\n') {
544 let link = format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link, cx));
546 if let Some(idx) = summary_html.rfind("</p>") {
547 summary_html.insert_str(idx, &link);
549 summary_html.push_str(&link);
553 write!(w, "<div class='docblock'>{}</div>", summary_html,);
557 fn document_full_collapsible(
561 heading_offset: HeadingOffset,
563 document_full_inner(w, item, cx, true, heading_offset);
570 heading_offset: HeadingOffset,
572 document_full_inner(w, item, cx, false, heading_offset);
575 fn document_full_inner(
579 is_collapsible: bool,
580 heading_offset: HeadingOffset,
582 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
583 debug!("Doc block: =====\n{}\n=====", s);
586 "<details class=\"rustdoc-toggle top-doc\" open>\
587 <summary class=\"hideme\">\
588 <span>Expand description</span>\
591 render_markdown(w, cx, &s, item.links(cx), heading_offset);
592 w.write_str("</details>");
594 render_markdown(w, cx, &s, item.links(cx), heading_offset);
598 let kind = match &*item.kind {
599 clean::ItemKind::StrippedItem(box kind) | kind => kind,
602 if let clean::ItemKind::FunctionItem(..) | clean::ItemKind::MethodItem(..) = kind {
603 render_call_locations(w, cx, item);
607 /// Add extra information about an item such as:
611 /// * Required features (through the `doc_cfg` feature)
612 fn document_item_info(
616 parent: Option<&clean::Item>,
618 let item_infos = short_item_info(item, cx, parent);
619 if !item_infos.is_empty() {
620 w.write_str("<div class=\"item-info\">");
621 for info in item_infos {
624 w.write_str("</div>");
628 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
629 let cfg = match (&item.cfg, parent.and_then(|p| p.cfg.as_ref())) {
630 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
631 (cfg, _) => cfg.as_deref().cloned(),
634 debug!("Portability {:?} - {:?} = {:?}", item.cfg, parent.and_then(|p| p.cfg.as_ref()), cfg);
636 Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
639 /// Render the stability, deprecation and portability information that is displayed at the top of
640 /// the item's documentation.
644 parent: Option<&clean::Item>,
646 let mut extra_info = vec![];
647 let error_codes = cx.shared.codes;
649 if let Some(depr @ Deprecation { note, since, is_since_rustc_version: _, suggestion: _ }) =
650 item.deprecation(cx.tcx())
652 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
653 // but only display the future-deprecation messages for #[rustc_deprecated].
654 let mut message = if let Some(since) = since {
655 let since = &since.as_str();
656 if !stability::deprecation_in_effect(&depr) {
658 String::from("Deprecating in a future Rust version")
660 format!("Deprecating in {}", Escape(since))
663 format!("Deprecated since {}", Escape(since))
666 String::from("Deprecated")
669 if let Some(note) = note {
670 let note = note.as_str();
671 let mut ids = cx.id_map.borrow_mut();
672 let html = MarkdownHtml(
677 &cx.shared.playground,
679 message.push_str(&format!(": {}", html.into_string()));
681 extra_info.push(format!(
682 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
687 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
688 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
689 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
692 .filter(|stab| stab.feature != sym::rustc_private)
693 .map(|stab| (stab.level, stab.feature))
696 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
698 let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
699 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
700 feature.push_str(&format!(
701 " <a href=\"{url}{issue}\">#{issue}</a>",
707 message.push_str(&format!(" ({})", feature));
709 if let Some(unstable_reason) = reason {
710 let mut ids = cx.id_map.borrow_mut();
712 "<details><summary>{}</summary>{}</details>",
715 &unstable_reason.as_str(),
719 &cx.shared.playground,
725 extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
728 if let Some(portability) = portability(item, parent) {
729 extra_info.push(portability);
735 // Render the list of items inside one of the sections "Trait Implementations",
736 // "Auto Trait Implementations," "Blanket Trait Implementations" (on struct/enum pages).
737 fn render_impls(cx: &Context<'_>, w: &mut Buffer, impls: &[&&Impl], containing_item: &clean::Item) {
739 let mut rendered_impls = impls
742 let did = i.trait_did().unwrap();
743 let provided_trait_methods = i.inner_impl().provided_trait_methods(tcx);
744 let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_trait_methods);
745 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
755 ImplRenderingParameters {
757 is_on_foreign_type: false,
758 show_default_items: true,
759 show_non_assoc_items: true,
760 toggle_open_by_default: true,
765 .collect::<Vec<_>>();
766 rendered_impls.sort();
767 w.write_str(&rendered_impls.join(""));
770 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>, cx: &Context<'_>) -> String {
771 use crate::formats::item_type::ItemType::*;
773 let name = it.name.as_ref().unwrap();
774 let ty = match it.type_() {
775 Typedef | AssocType => AssocType,
779 let anchor = format!("#{}.{}", ty, name);
781 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
782 AssocItemLink::Anchor(None) => anchor,
783 AssocItemLink::GotoSource(did, _) => {
784 href(did.expect_def_id(), cx).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
793 _default: Option<&String>,
794 link: AssocItemLink<'_>,
800 "{}{}const <a href=\"{}\" class=\"constant\">{}</a>: {}",
802 it.visibility.print_with_space(it.def_id, cx),
803 naive_assoc_href(it, link, cx),
804 it.name.as_ref().unwrap(),
812 bounds: &[clean::GenericBound],
813 default: Option<&clean::Type>,
814 link: AssocItemLink<'_>,
820 "{}type <a href=\"{}\" class=\"type\">{}</a>",
822 naive_assoc_href(it, link, cx),
823 it.name.as_ref().unwrap()
825 if !bounds.is_empty() {
826 write!(w, ": {}", print_generic_bounds(bounds, cx))
828 if let Some(default) = default {
829 write!(w, " = {}", default.print(cx))
833 fn render_stability_since_raw(
836 const_stability: Option<&ConstStability>,
837 containing_ver: Option<&str>,
838 containing_const_ver: Option<&str>,
840 let ver = ver.filter(|inner| !inner.is_empty());
842 match (ver, const_stability) {
843 // stable and const stable
844 (Some(v), Some(ConstStability { level: StabilityLevel::Stable { since }, .. }))
845 if Some(since.as_str()).as_deref() != containing_const_ver =>
849 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
853 // stable and const unstable
856 Some(ConstStability { level: StabilityLevel::Unstable { issue, .. }, feature, .. }),
860 "<span class=\"since\" title=\"Stable since Rust version {0}, const unstable\">{0} (const: ",
863 if let Some(n) = issue {
866 "<a href=\"https://github.com/rust-lang/rust/issues/{}\" title=\"Tracking issue for {}\">unstable</a>",
870 write!(w, "unstable");
872 write!(w, ")</span>");
875 (Some(v), _) if ver != containing_ver => {
878 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
886 fn render_assoc_item(
889 link: AssocItemLink<'_>,
896 header: hir::FnHeader,
899 link: AssocItemLink<'_>,
903 let name = meth.name.as_ref().unwrap();
904 let href = match link {
905 AssocItemLink::Anchor(Some(ref id)) => Some(format!("#{}", id)),
906 AssocItemLink::Anchor(None) => Some(format!("#{}.{}", meth.type_(), name)),
907 AssocItemLink::GotoSource(did, provided_methods) => {
908 // We're creating a link from an impl-item to the corresponding
909 // trait-item and need to map the anchored type accordingly.
910 let ty = if provided_methods.contains(name) {
916 match (href(did.expect_def_id(), cx), ty) {
917 (Ok(p), ty) => Some(format!("{}#{}.{}", p.0, ty, name)),
918 (Err(HrefError::DocumentationNotBuilt), ItemType::TyMethod) => None,
919 (Err(_), ty) => Some(format!("#{}.{}", ty, name)),
923 let vis = meth.visibility.print_with_space(meth.def_id, cx).to_string();
925 print_constness_with_space(&header.constness, meth.const_stability(cx.tcx()));
926 let asyncness = header.asyncness.print_with_space();
927 let unsafety = header.unsafety.print_with_space();
928 let defaultness = print_default_space(meth.is_default());
929 let abi = print_abi_with_space(header.abi).to_string();
931 // NOTE: `{:#}` does not print HTML formatting, `{}` does. So `g.print` can't be reused between the length calculation and `write!`.
932 let generics_len = format!("{:#}", g.print(cx)).len();
933 let mut header_len = "fn ".len()
940 + name.as_str().len()
943 let (indent, indent_str, end_newline) = if parent == ItemType::Trait {
945 let indent_str = " ";
946 render_attributes_in_pre(w, meth, indent_str);
947 (4, indent_str, false)
949 render_attributes_in_code(w, meth);
952 w.reserve(header_len + "<a href=\"\" class=\"fnname\">{".len() + "</a>".len());
955 "{indent}{vis}{constness}{asyncness}{unsafety}{defaultness}{abi}fn <a {href} class=\"fnname\">{name}</a>\
956 {generics}{decl}{notable_traits}{where_clause}",
959 constness = constness,
960 asyncness = asyncness,
962 defaultness = defaultness,
964 // links without a href are valid - https://www.w3schools.com/tags/att_a_href.asp
965 href = href.map(|href| format!("href=\"{}\"", href)).unwrap_or_else(|| "".to_string()),
967 generics = g.print(cx),
968 decl = d.full_print(header_len, indent, header.asyncness, cx),
969 notable_traits = notable_traits_decl(d, cx),
970 where_clause = print_where_clause(g, cx, indent, end_newline),
974 clean::StrippedItem(..) => {}
975 clean::TyMethodItem(ref m) => {
976 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
978 clean::MethodItem(ref m, _) => {
979 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
981 clean::AssocConstItem(ref ty, ref default) => assoc_const(
987 if parent == ItemType::Trait { " " } else { "" },
990 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
996 if parent == ItemType::Trait { " " } else { "" },
999 _ => panic!("render_assoc_item called on non-associated-item"),
1003 const ALLOWED_ATTRIBUTES: &[Symbol] =
1004 &[sym::export_name, sym::link_section, sym::no_mangle, sym::repr, sym::non_exhaustive];
1006 fn attributes(it: &clean::Item) -> Vec<String> {
1010 .filter_map(|attr| {
1011 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
1012 Some(pprust::attribute_to_string(attr).replace("\n", "").replace(" ", " "))
1020 // When an attribute is rendered inside a `<pre>` tag, it is formatted using
1021 // a whitespace prefix and newline.
1022 fn render_attributes_in_pre(w: &mut Buffer, it: &clean::Item, prefix: &str) {
1023 for a in attributes(it) {
1024 writeln!(w, "{}{}", prefix, a);
1028 // When an attribute is rendered inside a <code> tag, it is formatted using
1029 // a div to produce a newline after it.
1030 fn render_attributes_in_code(w: &mut Buffer, it: &clean::Item) {
1031 for a in attributes(it) {
1032 write!(w, "<div class=\"code-attribute\">{}</div>", a);
1036 #[derive(Copy, Clone)]
1037 enum AssocItemLink<'a> {
1038 Anchor(Option<&'a str>),
1039 GotoSource(ItemId, &'a FxHashSet<Symbol>),
1042 impl<'a> AssocItemLink<'a> {
1043 fn anchor(&self, id: &'a str) -> Self {
1045 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(id)),
1046 ref other => *other,
1051 fn render_assoc_items(
1054 containing_item: &clean::Item,
1056 what: AssocItemRender<'_>,
1058 let mut derefs = FxHashSet::default();
1060 render_assoc_items_inner(w, cx, containing_item, it, what, &mut derefs)
1063 fn render_assoc_items_inner(
1066 containing_item: &clean::Item,
1068 what: AssocItemRender<'_>,
1069 derefs: &mut FxHashSet<DefId>,
1071 info!("Documenting associated items of {:?}", containing_item.name);
1072 let cache = cx.cache();
1073 let v = match cache.impls.get(&it) {
1077 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
1078 if !non_trait.is_empty() {
1079 let mut tmp_buf = Buffer::empty_from(w);
1080 let render_mode = match what {
1081 AssocItemRender::All => {
1083 "<h2 id=\"implementations\" class=\"small-section-header\">\
1084 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
1089 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
1091 cx.derive_id(small_url_encode(format!("deref-methods-{:#}", type_.print(cx))));
1092 if let Some(def_id) = type_.def_id(cx.cache()) {
1093 cx.deref_id_map.borrow_mut().insert(def_id, id.clone());
1097 "<h2 id=\"{id}\" class=\"small-section-header\">\
1098 <span>Methods from {trait_}<Target = {type_}></span>\
1099 <a href=\"#{id}\" class=\"anchor\"></a>\
1102 trait_ = trait_.print(cx),
1103 type_ = type_.print(cx),
1105 RenderMode::ForDeref { mut_: deref_mut_ }
1108 let mut impls_buf = Buffer::empty_from(w);
1109 for i in &non_trait {
1115 AssocItemLink::Anchor(None),
1119 ImplRenderingParameters {
1120 show_def_docs: true,
1121 is_on_foreign_type: false,
1122 show_default_items: true,
1123 show_non_assoc_items: true,
1124 toggle_open_by_default: true,
1128 if !impls_buf.is_empty() {
1129 w.push_buffer(tmp_buf);
1130 w.push_buffer(impls_buf);
1134 if !traits.is_empty() {
1136 traits.iter().find(|t| t.trait_did() == cx.tcx().lang_items().deref_trait());
1137 if let Some(impl_) = deref_impl {
1139 traits.iter().any(|t| t.trait_did() == cx.tcx().lang_items().deref_mut_trait());
1140 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut, derefs);
1143 // If we were already one level into rendering deref methods, we don't want to render
1144 // anything after recursing into any further deref methods above.
1145 if let AssocItemRender::DerefFor { .. } = what {
1149 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
1150 traits.iter().partition(|t| t.inner_impl().synthetic);
1151 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
1152 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
1154 let mut impls = Buffer::empty_from(w);
1155 render_impls(cx, &mut impls, &concrete, containing_item);
1156 let impls = impls.into_inner();
1157 if !impls.is_empty() {
1160 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
1161 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
1163 <div id=\"trait-implementations-list\">{}</div>",
1168 if !synthetic.is_empty() {
1170 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
1171 Auto Trait Implementations\
1172 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
1174 <div id=\"synthetic-implementations-list\">",
1176 render_impls(cx, w, &synthetic, containing_item);
1177 w.write_str("</div>");
1180 if !blanket_impl.is_empty() {
1182 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
1183 Blanket Implementations\
1184 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
1186 <div id=\"blanket-implementations-list\">",
1188 render_impls(cx, w, &blanket_impl, containing_item);
1189 w.write_str("</div>");
1194 fn render_deref_methods(
1198 container_item: &clean::Item,
1200 derefs: &mut FxHashSet<DefId>,
1202 let cache = cx.cache();
1203 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
1204 let (target, real_target) = impl_
1208 .find_map(|item| match *item.kind {
1209 clean::TypedefItem(ref t, true) => Some(match *t {
1210 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
1211 _ => (&t.type_, &t.type_),
1215 .expect("Expected associated type binding");
1216 debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target);
1218 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
1219 if let Some(did) = target.def_id(cache) {
1220 if let Some(type_did) = impl_.inner_impl().for_.def_id(cache) {
1221 // `impl Deref<Target = S> for S`
1222 if did == type_did || !derefs.insert(did) {
1223 // Avoid infinite cycles
1227 render_assoc_items_inner(w, cx, container_item, did, what, derefs);
1229 if let Some(prim) = target.primitive_type() {
1230 if let Some(&did) = cache.primitive_locations.get(&prim) {
1231 render_assoc_items_inner(w, cx, container_item, did, what, derefs);
1237 fn should_render_item(item: &clean::Item, deref_mut_: bool, tcx: TyCtxt<'_>) -> bool {
1238 let self_type_opt = match *item.kind {
1239 clean::MethodItem(ref method, _) => method.decl.self_type(),
1240 clean::TyMethodItem(ref method) => method.decl.self_type(),
1244 if let Some(self_ty) = self_type_opt {
1245 let (by_mut_ref, by_box, by_value) = match self_ty {
1246 SelfTy::SelfBorrowed(_, mutability)
1247 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
1248 (mutability == Mutability::Mut, false, false)
1250 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
1251 (false, Some(did) == tcx.lang_items().owned_box(), false)
1253 SelfTy::SelfValue => (false, false, true),
1254 _ => (false, false, false),
1257 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
1263 fn notable_traits_decl(decl: &clean::FnDecl, cx: &Context<'_>) -> String {
1264 let mut out = Buffer::html();
1266 if let Some(did) = decl.output.as_return().and_then(|t| t.def_id(cx.cache())) {
1267 if let Some(impls) = cx.cache().impls.get(&did) {
1269 let impl_ = i.inner_impl();
1270 if let Some(trait_) = &impl_.trait_ {
1271 let trait_did = trait_.def_id();
1273 if cx.cache().traits.get(&trait_did).map_or(false, |t| t.is_notable) {
1277 "<div class=\"notable\">Notable traits for {}</div>\
1278 <code class=\"content\">",
1279 impl_.for_.print(cx)
1283 //use the "where" class here to make it small
1286 "<span class=\"where fmt-newline\">{}</span>",
1287 impl_.print(false, cx)
1289 for it in &impl_.items {
1290 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1291 out.push_str("<span class=\"where fmt-newline\"> ");
1292 let empty_set = FxHashSet::default();
1294 AssocItemLink::GotoSource(trait_did.into(), &empty_set);
1295 assoc_type(&mut out, it, &[], Some(&tydef.type_), src_link, "", cx);
1296 out.push_str(";</span>");
1305 if !out.is_empty() {
1308 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
1309 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
1311 out.push_str("</code></span></div></span></span>");
1317 #[derive(Clone, Copy, Debug)]
1318 struct ImplRenderingParameters {
1319 show_def_docs: bool,
1320 is_on_foreign_type: bool,
1321 show_default_items: bool,
1322 /// Whether or not to show methods.
1323 show_non_assoc_items: bool,
1324 toggle_open_by_default: bool,
1331 parent: &clean::Item,
1332 link: AssocItemLink<'_>,
1333 render_mode: RenderMode,
1334 use_absolute: Option<bool>,
1336 rendering_params: ImplRenderingParameters,
1338 let cache = cx.cache();
1339 let traits = &cache.traits;
1340 let trait_ = i.trait_did().map(|did| &traits[&did]);
1341 let mut close_tags = String::new();
1343 // For trait implementations, the `interesting` output contains all methods that have doc
1344 // comments, and the `boring` output contains all methods that do not. The distinction is
1345 // used to allow hiding the boring methods.
1346 // `containing_item` is used for rendering stability info. If the parent is a trait impl,
1347 // `containing_item` will the grandparent, since trait impls can't have stability attached.
1349 boring: &mut Buffer,
1350 interesting: &mut Buffer,
1353 parent: &clean::Item,
1354 containing_item: &clean::Item,
1355 link: AssocItemLink<'_>,
1356 render_mode: RenderMode,
1357 is_default_item: bool,
1358 trait_: Option<&clean::Trait>,
1359 rendering_params: ImplRenderingParameters,
1361 let item_type = item.type_();
1362 let name = item.name.as_ref().unwrap();
1364 let render_method_item = rendering_params.show_non_assoc_items
1365 && match render_mode {
1366 RenderMode::Normal => true,
1367 RenderMode::ForDeref { mut_: deref_mut_ } => {
1368 should_render_item(item, deref_mut_, cx.tcx())
1372 let in_trait_class = if trait_.is_some() { " trait-impl" } else { "" };
1374 let mut doc_buffer = Buffer::empty_from(boring);
1375 let mut info_buffer = Buffer::empty_from(boring);
1376 let mut short_documented = true;
1378 if render_method_item {
1379 if !is_default_item {
1380 if let Some(t) = trait_ {
1381 // The trait item may have been stripped so we might not
1382 // find any documentation or stability for it.
1383 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
1384 // We need the stability of the item from the trait
1385 // because impls can't have a stability.
1386 if item.doc_value().is_some() {
1387 document_item_info(&mut info_buffer, cx, it, Some(parent));
1388 document_full(&mut doc_buffer, item, cx, HeadingOffset::H5);
1389 short_documented = false;
1391 // In case the item isn't documented,
1392 // provide short documentation from the trait.
1399 rendering_params.show_def_docs,
1404 document_item_info(&mut info_buffer, cx, item, Some(parent));
1405 if rendering_params.show_def_docs {
1406 document_full(&mut doc_buffer, item, cx, HeadingOffset::H5);
1407 short_documented = false;
1417 rendering_params.show_def_docs,
1421 let w = if short_documented && trait_.is_some() { interesting } else { boring };
1423 let toggled = !doc_buffer.is_empty();
1425 let method_toggle_class =
1426 if item_type == ItemType::Method { " method-toggle" } else { "" };
1427 write!(w, "<details class=\"rustdoc-toggle{}\" open><summary>", method_toggle_class);
1430 clean::MethodItem(..) | clean::TyMethodItem(_) => {
1431 // Only render when the method is not static or we allow static methods
1432 if render_method_item {
1433 let id = cx.derive_id(format!("{}.{}", item_type, name));
1434 let source_id = trait_
1435 .and_then(|trait_| {
1436 trait_.items.iter().find(|item| {
1437 item.name.map(|n| n.as_str().eq(&name.as_str())).unwrap_or(false)
1440 .map(|item| format!("{}.{}", item.type_(), name));
1443 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1444 id, item_type, in_trait_class,
1446 render_rightside(w, cx, item, containing_item);
1447 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1448 w.write_str("<h4 class=\"code-header\">");
1452 link.anchor(source_id.as_ref().unwrap_or(&id)),
1456 w.write_str("</h4>");
1457 w.write_str("</div>");
1460 clean::TypedefItem(ref tydef, _) => {
1461 let source_id = format!("{}.{}", ItemType::AssocType, name);
1462 let id = cx.derive_id(source_id.clone());
1465 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1466 id, item_type, in_trait_class
1468 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1469 w.write_str("<h4 class=\"code-header\">");
1475 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1479 w.write_str("</h4>");
1480 w.write_str("</div>");
1482 clean::AssocConstItem(ref ty, ref default) => {
1483 let source_id = format!("{}.{}", item_type, name);
1484 let id = cx.derive_id(source_id.clone());
1487 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1488 id, item_type, in_trait_class
1490 render_rightside(w, cx, item, containing_item);
1491 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1492 w.write_str("<h4 class=\"code-header\">");
1498 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1502 w.write_str("</h4>");
1503 w.write_str("</div>");
1505 clean::AssocTypeItem(ref bounds, ref default) => {
1506 let source_id = format!("{}.{}", item_type, name);
1507 let id = cx.derive_id(source_id.clone());
1508 write!(w, "<div id=\"{}\" class=\"{}{}\">", id, item_type, in_trait_class,);
1509 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1510 w.write_str("<h4 class=\"code-header\">");
1516 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1520 w.write_str("</h4>");
1521 w.write_str("</div>");
1523 clean::StrippedItem(..) => return,
1524 _ => panic!("can't make docs for trait item with name {:?}", item.name),
1527 w.push_buffer(info_buffer);
1529 w.write_str("</summary>");
1530 w.push_buffer(doc_buffer);
1531 w.push_str("</details>");
1535 let mut impl_items = Buffer::empty_from(w);
1536 let mut default_impl_items = Buffer::empty_from(w);
1538 for trait_item in &i.inner_impl().items {
1540 &mut default_impl_items,
1544 if trait_.is_some() { &i.impl_item } else { parent },
1549 trait_.map(|t| &t.trait_),
1554 fn render_default_items(
1555 boring: &mut Buffer,
1556 interesting: &mut Buffer,
1560 parent: &clean::Item,
1561 containing_item: &clean::Item,
1562 render_mode: RenderMode,
1563 rendering_params: ImplRenderingParameters,
1565 for trait_item in &t.items {
1566 let n = trait_item.name;
1567 if i.items.iter().any(|m| m.name == n) {
1570 let did = i.trait_.as_ref().unwrap().def_id();
1571 let provided_methods = i.provided_trait_methods(cx.tcx());
1572 let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_methods);
1590 // If we've implemented a trait, then also emit documentation for all
1591 // default items which weren't overridden in the implementation block.
1592 // We don't emit documentation for default items if they appear in the
1593 // Implementations on Foreign Types or Implementors sections.
1594 if rendering_params.show_default_items {
1595 if let Some(t) = trait_ {
1596 render_default_items(
1597 &mut default_impl_items,
1609 if render_mode == RenderMode::Normal {
1610 let toggled = !(impl_items.is_empty() && default_impl_items.is_empty());
1612 close_tags.insert_str(0, "</details>");
1615 "<details class=\"rustdoc-toggle implementors-toggle\"{}>",
1616 if rendering_params.toggle_open_by_default { " open" } else { "" }
1618 write!(w, "<summary>")
1620 render_impl_summary(
1626 rendering_params.show_def_docs,
1628 rendering_params.is_on_foreign_type,
1632 write!(w, "</summary>")
1635 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
1636 let mut ids = cx.id_map.borrow_mut();
1639 "<div class=\"docblock\">{}</div>",
1642 links: &i.impl_item.links(cx),
1644 error_codes: cx.shared.codes,
1645 edition: cx.shared.edition(),
1646 playground: &cx.shared.playground,
1647 heading_offset: HeadingOffset::H4
1653 if !default_impl_items.is_empty() || !impl_items.is_empty() {
1654 w.write_str("<div class=\"impl-items\">");
1655 w.push_buffer(default_impl_items);
1656 w.push_buffer(impl_items);
1657 close_tags.insert_str(0, "</div>");
1659 w.write_str(&close_tags);
1662 // Render the items that appear on the right side of methods, impls, and
1663 // associated types. For example "1.0.0 (const: 1.39.0) [src]".
1664 fn render_rightside(
1668 containing_item: &clean::Item,
1672 write!(w, "<div class=\"rightside\">");
1673 render_stability_since_raw(
1675 item.stable_since(tcx).as_deref(),
1676 item.const_stability(tcx),
1677 containing_item.stable_since(tcx).as_deref(),
1678 containing_item.const_stable_since(tcx).as_deref(),
1681 write_srclink(cx, item, w);
1682 w.write_str("</div>");
1685 pub(crate) fn render_impl_summary(
1689 parent: &clean::Item,
1690 containing_item: &clean::Item,
1691 show_def_docs: bool,
1692 use_absolute: Option<bool>,
1693 is_on_foreign_type: bool,
1694 // This argument is used to reference same type with different paths to avoid duplication
1695 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
1698 let id = cx.derive_id(match i.inner_impl().trait_ {
1700 if is_on_foreign_type {
1701 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t, cx)
1703 format!("impl-{}", small_url_encode(format!("{:#}", t.print(cx))))
1706 None => "impl".to_string(),
1708 let aliases = if aliases.is_empty() {
1711 format!(" data-aliases=\"{}\"", aliases.join(","))
1713 write!(w, "<div id=\"{}\" class=\"impl has-srclink\"{}>", id, aliases);
1714 render_rightside(w, cx, &i.impl_item, containing_item);
1715 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1716 write!(w, "<h3 class=\"code-header in-band\">");
1718 if let Some(use_absolute) = use_absolute {
1719 write!(w, "{}", i.inner_impl().print(use_absolute, cx));
1721 for it in &i.inner_impl().items {
1722 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1723 w.write_str("<span class=\"where fmt-newline\"> ");
1724 assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "", cx);
1725 w.write_str(";</span>");
1730 write!(w, "{}", i.inner_impl().print(false, cx));
1734 let is_trait = i.inner_impl().trait_.is_some();
1736 if let Some(portability) = portability(&i.impl_item, Some(parent)) {
1737 write!(w, "<div class=\"item-info\">{}</div>", portability);
1741 w.write_str("</div>");
1744 fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) {
1745 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
1749 || it.is_primitive()
1757 "<h2 class=\"location\">{}{}</h2>",
1759 clean::StructItem(..) => "Struct ",
1760 clean::TraitItem(..) => "Trait ",
1761 clean::PrimitiveItem(..) => "Primitive Type ",
1762 clean::UnionItem(..) => "Union ",
1763 clean::EnumItem(..) => "Enum ",
1764 clean::TypedefItem(..) => "Type Definition ",
1765 clean::ForeignTypeItem => "Foreign Type ",
1766 clean::ModuleItem(..) =>
1774 it.name.as_ref().unwrap()
1779 if let Some(ref version) = cx.cache().crate_version {
1782 "<div class=\"block version\">\
1783 <div class=\"narrow-helper\"></div>\
1791 buffer.write_str("<div class=\"sidebar-elems\">");
1795 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
1796 it.name.as_ref().expect("crates always have a name"),
1801 clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s),
1802 clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t),
1803 clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it),
1804 clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u),
1805 clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e),
1806 clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it),
1807 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
1808 clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, it),
1812 // The sidebar is designed to display sibling functions, modules and
1813 // other miscellaneous information. since there are lots of sibling
1814 // items (and that causes quadratic growth in large modules),
1815 // we refactor common parts into a shared JavaScript file per module.
1816 // still, we don't move everything into JS because we want to preserve
1817 // as much HTML as possible in order to allow non-JS-enabled browsers
1818 // to navigate the documentation (though slightly inefficiently).
1821 buffer.write_str("<h2 class=\"location\">Other items in<br>");
1822 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
1824 buffer.write_str("::<wbr>");
1828 "<a href=\"{}index.html\">{}</a>",
1829 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
1833 buffer.write_str("</h2>");
1836 // Sidebar refers to the enclosing module, not this module.
1837 let relpath = if it.is_mod() && parentlen != 0 { "./" } else { "" };
1840 "<div id=\"sidebar-vars\" data-name=\"{name}\" data-ty=\"{ty}\" data-relpath=\"{path}\">\
1842 name = it.name.unwrap_or(kw::Empty),
1846 write!(buffer, "<script defer src=\"{}sidebar-items.js\"></script>", relpath);
1847 // Closes sidebar-elems div.
1848 buffer.write_str("</div>");
1851 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
1852 if used_links.insert(url.clone()) {
1856 while !used_links.insert(format!("{}-{}", url, add)) {
1859 format!("{}-{}", url, add)
1862 struct SidebarLink {
1867 impl fmt::Display for SidebarLink {
1868 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1869 write!(f, "<a href=\"#{}\">{}</a>", self.url, self.name)
1873 impl PartialEq for SidebarLink {
1874 fn eq(&self, other: &Self) -> bool {
1875 self.url == other.url
1879 impl Eq for SidebarLink {}
1881 impl PartialOrd for SidebarLink {
1882 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1883 Some(self.cmp(other))
1887 impl Ord for SidebarLink {
1888 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1889 self.url.cmp(&other.url)
1896 used_links: &mut FxHashSet<String>,
1899 ) -> Vec<SidebarLink> {
1902 .filter_map(|item| match item.name {
1903 Some(name) if !name.is_empty() && item.is_method() => {
1904 if !for_deref || should_render_item(item, deref_mut, tcx) {
1907 url: get_next_url(used_links, format!("method.{}", name)),
1915 .collect::<Vec<_>>()
1918 fn get_associated_constants(
1920 used_links: &mut FxHashSet<String>,
1921 ) -> Vec<SidebarLink> {
1924 .filter_map(|item| match item.name {
1925 Some(name) if !name.is_empty() && item.is_associated_const() => Some(SidebarLink {
1927 url: get_next_url(used_links, format!("associatedconstant.{}", name)),
1931 .collect::<Vec<_>>()
1934 // The point is to url encode any potential character from a type with genericity.
1935 fn small_url_encode(s: String) -> String {
1936 let mut st = String::new();
1937 let mut last_match = 0;
1938 for (idx, c) in s.char_indices() {
1939 let escaped = match c {
1955 st += &s[last_match..idx];
1957 // NOTE: we only expect single byte characters here - which is fine as long as we
1958 // only match single byte characters
1959 last_match = idx + 1;
1962 if last_match != 0 {
1963 st += &s[last_match..];
1970 fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) {
1971 let did = it.def_id.expect_def_id();
1972 let cache = cx.cache();
1973 if let Some(v) = cache.impls.get(&did) {
1974 let mut used_links = FxHashSet::default();
1977 let used_links_bor = &mut used_links;
1978 let mut assoc_consts = v
1980 .flat_map(|i| get_associated_constants(i.inner_impl(), used_links_bor))
1981 .collect::<Vec<_>>();
1982 if !assoc_consts.is_empty() {
1983 // We want links' order to be reproducible so we don't use unstable sort.
1984 assoc_consts.sort();
1987 "<h3 class=\"sidebar-title\">\
1988 <a href=\"#implementations\">Associated Constants</a>\
1990 <div class=\"sidebar-links\">",
1992 for line in assoc_consts {
1993 write!(out, "{}", line);
1995 out.push_str("</div>");
1999 .filter(|i| i.inner_impl().trait_.is_none())
2000 .flat_map(|i| get_methods(i.inner_impl(), false, used_links_bor, false, cx.tcx()))
2001 .collect::<Vec<_>>();
2002 if !methods.is_empty() {
2003 // We want links' order to be reproducible so we don't use unstable sort.
2007 "<h3 class=\"sidebar-title\"><a href=\"#implementations\">Methods</a></h3>\
2008 <div class=\"sidebar-links\">",
2010 for line in methods {
2011 write!(out, "{}", line);
2013 out.push_str("</div>");
2017 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
2018 if let Some(impl_) =
2019 v.iter().find(|i| i.trait_did() == cx.tcx().lang_items().deref_trait())
2021 let mut derefs = FxHashSet::default();
2023 sidebar_deref_methods(cx, out, impl_, v, &mut derefs);
2026 let format_impls = |impls: Vec<&Impl>| {
2027 let mut links = FxHashSet::default();
2032 if let Some(ref i) = it.inner_impl().trait_ {
2033 let i_display = format!("{:#}", i.print(cx));
2034 let out = Escape(&i_display);
2035 let encoded = small_url_encode(format!("{:#}", i.print(cx)));
2036 let generated = format!(
2037 "<a href=\"#impl-{}\">{}{}</a>",
2039 if it.inner_impl().negative_polarity { "!" } else { "" },
2042 if links.insert(generated.clone()) { Some(generated) } else { None }
2047 .collect::<Vec<String>>();
2052 let write_sidebar_links = |out: &mut Buffer, links: Vec<String>| {
2053 out.push_str("<div class=\"sidebar-links\">");
2055 out.push_str(&link);
2057 out.push_str("</div>");
2060 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
2061 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
2062 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
2064 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
2066 let concrete_format = format_impls(concrete);
2067 let synthetic_format = format_impls(synthetic);
2068 let blanket_format = format_impls(blanket_impl);
2070 if !concrete_format.is_empty() {
2072 "<h3 class=\"sidebar-title\"><a href=\"#trait-implementations\">\
2073 Trait Implementations</a></h3>",
2075 write_sidebar_links(out, concrete_format);
2078 if !synthetic_format.is_empty() {
2080 "<h3 class=\"sidebar-title\"><a href=\"#synthetic-implementations\">\
2081 Auto Trait Implementations</a></h3>",
2083 write_sidebar_links(out, synthetic_format);
2086 if !blanket_format.is_empty() {
2088 "<h3 class=\"sidebar-title\"><a href=\"#blanket-implementations\">\
2089 Blanket Implementations</a></h3>",
2091 write_sidebar_links(out, blanket_format);
2097 fn sidebar_deref_methods(
2102 derefs: &mut FxHashSet<DefId>,
2106 debug!("found Deref: {:?}", impl_);
2107 if let Some((target, real_target)) =
2108 impl_.inner_impl().items.iter().find_map(|item| match *item.kind {
2109 clean::TypedefItem(ref t, true) => Some(match *t {
2110 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
2111 _ => (&t.type_, &t.type_),
2116 debug!("found target, real_target: {:?} {:?}", target, real_target);
2117 if let Some(did) = target.def_id(c) {
2118 if let Some(type_did) = impl_.inner_impl().for_.def_id(c) {
2119 // `impl Deref<Target = S> for S`
2120 if did == type_did || !derefs.insert(did) {
2121 // Avoid infinite cycles
2126 let deref_mut = v.iter().any(|i| i.trait_did() == cx.tcx().lang_items().deref_mut_trait());
2127 let inner_impl = target
2130 target.primitive_type().and_then(|prim| c.primitive_locations.get(&prim).cloned())
2132 .and_then(|did| c.impls.get(&did));
2133 if let Some(impls) = inner_impl {
2134 debug!("found inner_impl: {:?}", impls);
2135 let mut used_links = FxHashSet::default();
2138 .filter(|i| i.inner_impl().trait_.is_none())
2140 get_methods(i.inner_impl(), true, &mut used_links, deref_mut, cx.tcx())
2142 .collect::<Vec<_>>();
2143 if !ret.is_empty() {
2145 let id = if let Some(target_def_id) = real_target.def_id(c) {
2146 map = cx.deref_id_map.borrow();
2147 map.get(&target_def_id).expect("Deref section without derived id")
2153 "<h3 class=\"sidebar-title\"><a href=\"#{}\">Methods from {}<Target={}></a></h3>",
2155 Escape(&format!("{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print(cx))),
2156 Escape(&format!("{:#}", real_target.print(cx))),
2158 // We want links' order to be reproducible so we don't use unstable sort.
2160 out.push_str("<div class=\"sidebar-links\">");
2162 write!(out, "{}", link);
2164 out.push_str("</div>");
2168 // Recurse into any further impls that might exist for `target`
2169 if let Some(target_did) = target.def_id_no_primitives() {
2170 if let Some(target_impls) = c.impls.get(&target_did) {
2171 if let Some(target_deref_impl) = target_impls.iter().find(|i| {
2175 .map(|t| Some(t.def_id()) == cx.tcx().lang_items().deref_trait())
2178 sidebar_deref_methods(cx, out, target_deref_impl, target_impls, derefs);
2185 fn sidebar_struct(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
2186 let mut sidebar = Buffer::new();
2187 let fields = get_struct_fields_name(&s.fields);
2189 if !fields.is_empty() {
2190 if let CtorKind::Fictive = s.struct_type {
2192 "<h3 class=\"sidebar-title\"><a href=\"#fields\">Fields</a></h3>\
2193 <div class=\"sidebar-links\">",
2196 for field in fields {
2197 sidebar.push_str(&field);
2200 sidebar.push_str("</div>");
2201 } else if let CtorKind::Fn = s.struct_type {
2203 .push_str("<h3 class=\"sidebar-title\"><a href=\"#fields\">Tuple Fields</a></h3>");
2207 sidebar_assoc_items(cx, &mut sidebar, it);
2209 if !sidebar.is_empty() {
2210 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2214 fn get_id_for_impl_on_foreign_type(
2216 trait_: &clean::Path,
2219 small_url_encode(format!("impl-{:#}-for-{:#}", trait_.print(cx), for_.print(cx)))
2222 fn extract_for_impl_name(item: &clean::Item, cx: &Context<'_>) -> Option<(String, String)> {
2224 clean::ItemKind::ImplItem(ref i) => {
2225 i.trait_.as_ref().map(|trait_| {
2226 // Alternative format produces no URLs,
2227 // so this parameter does nothing.
2229 format!("{:#}", i.for_.print(cx)),
2230 get_id_for_impl_on_foreign_type(&i.for_, trait_, cx),
2238 fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
2239 buf.write_str("<div class=\"block items\">");
2241 fn print_sidebar_section(
2243 items: &[clean::Item],
2245 filter: impl Fn(&clean::Item) -> bool,
2246 write: impl Fn(&mut Buffer, &str),
2249 let mut items = items
2251 .filter_map(|m| match m.name {
2252 Some(ref name) if filter(m) => Some(name.as_str()),
2255 .collect::<Vec<_>>();
2257 if !items.is_empty() {
2258 items.sort_unstable();
2259 out.push_str(before);
2260 for item in items.into_iter() {
2263 out.push_str(after);
2267 print_sidebar_section(
2270 "<h3 class=\"sidebar-title\"><a href=\"#associated-types\">\
2271 Associated Types</a></h3><div class=\"sidebar-links\">",
2272 |m| m.is_associated_type(),
2273 |out, sym| write!(out, "<a href=\"#associatedtype.{0}\">{0}</a>", sym),
2277 print_sidebar_section(
2280 "<h3 class=\"sidebar-title\"><a href=\"#associated-const\">\
2281 Associated Constants</a></h3><div class=\"sidebar-links\">",
2282 |m| m.is_associated_const(),
2283 |out, sym| write!(out, "<a href=\"#associatedconstant.{0}\">{0}</a>", sym),
2287 print_sidebar_section(
2290 "<h3 class=\"sidebar-title\"><a href=\"#required-methods\">\
2291 Required Methods</a></h3><div class=\"sidebar-links\">",
2292 |m| m.is_ty_method(),
2293 |out, sym| write!(out, "<a href=\"#tymethod.{0}\">{0}</a>", sym),
2297 print_sidebar_section(
2300 "<h3 class=\"sidebar-title\"><a href=\"#provided-methods\">\
2301 Provided Methods</a></h3><div class=\"sidebar-links\">",
2303 |out, sym| write!(out, "<a href=\"#method.{0}\">{0}</a>", sym),
2307 let cache = cx.cache();
2308 if let Some(implementors) = cache.implementors.get(&it.def_id.expect_def_id()) {
2309 let mut res = implementors
2312 i.inner_impl().for_.def_id(cache).map_or(false, |d| !cache.paths.contains_key(&d))
2314 .filter_map(|i| extract_for_impl_name(&i.impl_item, cx))
2315 .collect::<Vec<_>>();
2317 if !res.is_empty() {
2320 "<h3 class=\"sidebar-title\"><a href=\"#foreign-impls\">\
2321 Implementations on Foreign Types</a></h3>\
2322 <div class=\"sidebar-links\">",
2324 for (name, id) in res.into_iter() {
2325 write!(buf, "<a href=\"#{}\">{}</a>", id, Escape(&name));
2327 buf.push_str("</div>");
2331 sidebar_assoc_items(cx, buf, it);
2333 buf.push_str("<h3 class=\"sidebar-title\"><a href=\"#implementors\">Implementors</a></h3>");
2336 "<h3 class=\"sidebar-title\"><a \
2337 href=\"#synthetic-implementors\">Auto Implementors</a></h3>",
2341 buf.push_str("</div>")
2344 fn sidebar_primitive(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2345 let mut sidebar = Buffer::new();
2346 sidebar_assoc_items(cx, &mut sidebar, it);
2348 if !sidebar.is_empty() {
2349 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2353 fn sidebar_typedef(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2354 let mut sidebar = Buffer::new();
2355 sidebar_assoc_items(cx, &mut sidebar, it);
2357 if !sidebar.is_empty() {
2358 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2362 fn get_struct_fields_name(fields: &[clean::Item]) -> Vec<String> {
2363 let mut fields = fields
2365 .filter(|f| matches!(*f.kind, clean::StructFieldItem(..)))
2367 f.name.map(|name| format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
2369 .collect::<Vec<_>>();
2374 fn sidebar_union(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
2375 let mut sidebar = Buffer::new();
2376 let fields = get_struct_fields_name(&u.fields);
2378 if !fields.is_empty() {
2380 "<h3 class=\"sidebar-title\"><a href=\"#fields\">Fields</a></h3>\
2381 <div class=\"sidebar-links\">",
2384 for field in fields {
2385 sidebar.push_str(&field);
2388 sidebar.push_str("</div>");
2391 sidebar_assoc_items(cx, &mut sidebar, it);
2393 if !sidebar.is_empty() {
2394 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2398 fn sidebar_enum(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
2399 let mut sidebar = Buffer::new();
2401 let mut variants = e
2407 .map(|name| format!("<a href=\"#variant.{name}\">{name}</a>", name = name))
2409 .collect::<Vec<_>>();
2410 if !variants.is_empty() {
2411 variants.sort_unstable();
2412 sidebar.push_str(&format!(
2413 "<h3 class=\"sidebar-title\"><a href=\"#variants\">Variants</a></h3>\
2414 <div class=\"sidebar-links\">{}</div>",
2419 sidebar_assoc_items(cx, &mut sidebar, it);
2421 if !sidebar.is_empty() {
2422 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2426 fn item_ty_to_strs(ty: ItemType) -> (&'static str, &'static str) {
2428 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
2429 ItemType::Module => ("modules", "Modules"),
2430 ItemType::Struct => ("structs", "Structs"),
2431 ItemType::Union => ("unions", "Unions"),
2432 ItemType::Enum => ("enums", "Enums"),
2433 ItemType::Function => ("functions", "Functions"),
2434 ItemType::Typedef => ("types", "Type Definitions"),
2435 ItemType::Static => ("statics", "Statics"),
2436 ItemType::Constant => ("constants", "Constants"),
2437 ItemType::Trait => ("traits", "Traits"),
2438 ItemType::Impl => ("impls", "Implementations"),
2439 ItemType::TyMethod => ("tymethods", "Type Methods"),
2440 ItemType::Method => ("methods", "Methods"),
2441 ItemType::StructField => ("fields", "Struct Fields"),
2442 ItemType::Variant => ("variants", "Variants"),
2443 ItemType::Macro => ("macros", "Macros"),
2444 ItemType::Primitive => ("primitives", "Primitive Types"),
2445 ItemType::AssocType => ("associated-types", "Associated Types"),
2446 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
2447 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
2448 ItemType::Keyword => ("keywords", "Keywords"),
2449 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
2450 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
2451 ItemType::ProcDerive => ("derives", "Derive Macros"),
2452 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
2453 ItemType::Generic => unreachable!(),
2457 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
2458 let mut sidebar = String::new();
2460 // Re-exports are handled a bit differently because they can be extern crates or imports.
2461 if items.iter().any(|it| {
2463 && (it.type_() == ItemType::ExternCrate
2464 || (it.type_() == ItemType::Import && !it.is_stripped()))
2466 let (id, name) = item_ty_to_strs(ItemType::Import);
2467 sidebar.push_str(&format!("<li><a href=\"#{}\">{}</a></li>", id, name));
2470 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
2471 // to print its headings
2473 ItemType::Primitive,
2487 ItemType::StructField,
2489 ItemType::AssocType,
2490 ItemType::AssocConst,
2491 ItemType::ForeignType,
2494 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty && it.name.is_some()) {
2495 let (id, name) = item_ty_to_strs(myty);
2496 sidebar.push_str(&format!("<li><a href=\"#{}\">{}</a></li>", id, name));
2500 if !sidebar.is_empty() {
2501 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
2505 fn sidebar_foreign_type(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2506 let mut sidebar = Buffer::new();
2507 sidebar_assoc_items(cx, &mut sidebar, it);
2509 if !sidebar.is_empty() {
2510 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2514 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
2516 /// Returns a list of all paths used in the type.
2517 /// This is used to help deduplicate imported impls
2518 /// for reexported types. If any of the contained
2519 /// types are re-exported, we don't use the corresponding
2520 /// entry from the js file, as inlining will have already
2521 /// picked up the impl
2522 fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> {
2523 let mut out = Vec::new();
2524 let mut visited = FxHashSet::default();
2525 let mut work = VecDeque::new();
2527 let mut process_path = |did: DefId| {
2528 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
2529 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
2531 if let Some(path) = fqp {
2532 out.push(path.join("::"));
2536 work.push_back(first_ty);
2538 while let Some(ty) = work.pop_front() {
2539 if !visited.insert(ty.clone()) {
2544 clean::Type::ResolvedPath { did, .. } => process_path(did),
2545 clean::Type::Tuple(tys) => {
2546 work.extend(tys.into_iter());
2548 clean::Type::Slice(ty) => {
2549 work.push_back(*ty);
2551 clean::Type::Array(ty, _) => {
2552 work.push_back(*ty);
2554 clean::Type::RawPointer(_, ty) => {
2555 work.push_back(*ty);
2557 clean::Type::BorrowedRef { type_, .. } => {
2558 work.push_back(*type_);
2560 clean::Type::QPath { self_type, trait_, .. } => {
2561 work.push_back(*self_type);
2562 process_path(trait_.def_id());
2570 const MAX_FULL_EXAMPLES: usize = 5;
2571 const NUM_VISIBLE_LINES: usize = 10;
2573 /// Generates the HTML for example call locations generated via the --scrape-examples flag.
2574 fn render_call_locations(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item) {
2576 let def_id = item.def_id.expect_def_id();
2577 let key = tcx.def_path_hash(def_id);
2578 let call_locations = match cx.shared.call_locations.get(&key) {
2579 Some(call_locations) => call_locations,
2585 // Generate a unique ID so users can link to this section for a given method
2586 let id = cx.id_map.borrow_mut().derive("scraped-examples");
2589 "<div class=\"docblock scraped-example-list\">\
2591 <h5 id=\"{id}\" class=\"section-header\">\
2592 <a href=\"#{id}\">Examples found in repository</a>\
2597 // Create a URL to a particular location in a reverse-dependency's source file
2598 let link_to_loc = |call_data: &CallData, loc: &CallLocation| -> (String, String) {
2599 let (line_lo, line_hi) = loc.call_expr.line_span;
2600 let (anchor, title) = if line_lo == line_hi {
2601 ((line_lo + 1).to_string(), format!("line {}", line_lo + 1))
2604 format!("{}-{}", line_lo + 1, line_hi + 1),
2605 format!("lines {}-{}", line_lo + 1, line_hi + 1),
2608 let url = format!("{}{}#{}", cx.root_path(), call_data.url, anchor);
2612 // Generate the HTML for a single example, being the title and code block
2613 let write_example = |w: &mut Buffer, (path, call_data): (&PathBuf, &CallData)| -> bool {
2614 let contents = match fs::read_to_string(&path) {
2615 Ok(contents) => contents,
2617 let span = item.span(tcx).inner();
2619 .span_err(span, &format!("failed to read file {}: {}", path.display(), err));
2624 // To reduce file sizes, we only want to embed the source code needed to understand the example, not
2625 // the entire file. So we find the smallest byte range that covers all items enclosing examples.
2626 assert!(!call_data.locations.is_empty());
2628 call_data.locations.iter().min_by_key(|loc| loc.enclosing_item.byte_span.0).unwrap();
2629 let byte_min = min_loc.enclosing_item.byte_span.0;
2630 let line_min = min_loc.enclosing_item.line_span.0;
2632 call_data.locations.iter().max_by_key(|loc| loc.enclosing_item.byte_span.1).unwrap();
2633 let byte_max = max_loc.enclosing_item.byte_span.1;
2634 let line_max = max_loc.enclosing_item.line_span.1;
2636 // The output code is limited to that byte range.
2637 let contents_subset = &contents[(byte_min as usize)..(byte_max as usize)];
2639 // The call locations need to be updated to reflect that the size of the program has changed.
2640 // Specifically, the ranges are all subtracted by `byte_min` since that's the new zero point.
2641 let (mut byte_ranges, line_ranges): (Vec<_>, Vec<_>) = call_data
2645 let (byte_lo, byte_hi) = loc.call_expr.byte_span;
2646 let (line_lo, line_hi) = loc.call_expr.line_span;
2647 let byte_range = (byte_lo - byte_min, byte_hi - byte_min);
2648 let line_range = (line_lo - line_min, line_hi - line_min);
2649 let (line_url, line_title) = link_to_loc(call_data, loc);
2651 (byte_range, (line_range, line_url, line_title))
2655 let (_, init_url, init_title) = &line_ranges[0];
2656 let needs_expansion = line_max - line_min > NUM_VISIBLE_LINES;
2657 let locations_encoded = serde_json::to_string(&line_ranges).unwrap();
2661 "<div class=\"scraped-example {expanded_cls}\" data-locs=\"{locations}\">\
2662 <div class=\"scraped-example-title\">\
2663 {name} (<a href=\"{url}\">{title}</a>)\
2665 <div class=\"code-wrapper\">",
2666 expanded_cls = if needs_expansion { "" } else { "expanded" },
2667 name = call_data.display_name,
2670 // The locations are encoded as a data attribute, so they can be read
2671 // later by the JS for interactions.
2672 locations = Escape(&locations_encoded)
2675 if line_ranges.len() > 1 {
2676 write!(w, r#"<span class="prev">≺</span> <span class="next">≻</span>"#);
2679 if needs_expansion {
2680 write!(w, r#"<span class="expand">↕</span>"#);
2683 // Look for the example file in the source map if it exists, otherwise return a dummy span
2684 let file_span = (|| {
2685 let source_map = tcx.sess.source_map();
2686 let crate_src = tcx.sess.local_crate_source_file.as_ref()?;
2687 let abs_crate_src = crate_src.canonicalize().ok()?;
2688 let crate_root = abs_crate_src.parent()?.parent()?;
2689 let rel_path = path.strip_prefix(crate_root).ok()?;
2690 let files = source_map.files();
2691 let file = files.iter().find(|file| match &file.name {
2692 FileName::Real(RealFileName::LocalPath(other_path)) => rel_path == other_path,
2695 Some(rustc_span::Span::with_root_ctxt(
2696 file.start_pos + BytePos(byte_min),
2697 file.start_pos + BytePos(byte_max),
2700 .unwrap_or(rustc_span::DUMMY_SP);
2702 // The root path is the inverse of Context::current
2703 let root_path = vec!["../"; cx.current.len() - 1].join("");
2705 let mut decoration_info = FxHashMap::default();
2706 decoration_info.insert("highlight focus", vec![byte_ranges.remove(0)]);
2707 decoration_info.insert("highlight", byte_ranges);
2716 Some(highlight::DecorationInfo(decoration_info)),
2717 sources::SourceContext::Embedded { offset: line_min },
2719 write!(w, "</div></div>");
2724 // The call locations are output in sequence, so that sequence needs to be determined.
2725 // Ideally the most "relevant" examples would be shown first, but there's no general algorithm
2726 // for determining relevance. Instead, we prefer the smallest examples being likely the easiest to
2727 // understand at a glance.
2728 let ordered_locations = {
2729 let sort_criterion = |(_, call_data): &(_, &CallData)| {
2730 // Use the first location because that's what the user will see initially
2731 let (lo, hi) = call_data.locations[0].enclosing_item.byte_span;
2735 let mut locs = call_locations.into_iter().collect::<Vec<_>>();
2736 locs.sort_by_key(sort_criterion);
2740 let mut it = ordered_locations.into_iter().peekable();
2742 // An example may fail to write if its source can't be read for some reason, so this method
2743 // continues iterating until a write suceeds
2744 let write_and_skip_failure = |w: &mut Buffer, it: &mut Peekable<_>| {
2745 while let Some(example) = it.next() {
2746 if write_example(&mut *w, example) {
2752 // Write just one example that's visible by default in the method's description.
2753 write_and_skip_failure(w, &mut it);
2755 // Then add the remaining examples in a hidden section.
2756 if it.peek().is_some() {
2759 "<details class=\"rustdoc-toggle more-examples-toggle\">\
2760 <summary class=\"hideme\">\
2761 <span>More examples</span>\
2763 <div class=\"more-scraped-examples\">\
2764 <div class=\"toggle-line\"><div class=\"toggle-line-inner\"></div></div>\
2765 <div class=\"more-scraped-examples-inner\">"
2768 // Only generate inline code for MAX_FULL_EXAMPLES number of examples. Otherwise we could
2769 // make the page arbitrarily huge!
2770 for _ in 0..MAX_FULL_EXAMPLES {
2771 write_and_skip_failure(w, &mut it);
2774 // For the remaining examples, generate a <ul> containing links to the source files.
2775 if it.peek().is_some() {
2776 write!(w, r#"<div class="example-links">Additional examples can be found in:<br><ul>"#);
2777 it.for_each(|(_, call_data)| {
2778 let (url, _) = link_to_loc(&call_data, &call_data.locations[0]);
2781 r#"<li><a href="{url}">{name}</a></li>"#,
2783 name = call_data.display_name
2786 write!(w, "</ul></div>");
2789 write!(w, "</div></div></details>");
2792 write!(w, "</div>");