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 crate use self::context::*;
38 crate use self::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;
58 use rustc_middle::ty::TyCtxt;
60 symbol::{kw, sym, Symbol},
61 BytePos, FileName, RealFileName,
63 use serde::ser::SerializeSeq;
64 use serde::{Serialize, Serializer};
66 use crate::clean::{self, ItemId, RenderedLink, SelfTy};
67 use crate::docfs::PathError;
68 use crate::error::Error;
69 use crate::formats::cache::Cache;
70 use crate::formats::item_type::ItemType;
71 use crate::formats::{AssocItemRender, Impl, RenderMode};
72 use crate::html::escape::Escape;
73 use crate::html::format::{
74 href, print_abi_with_space, print_constness_with_space, print_default_space,
75 print_generic_bounds, print_where_clause, Buffer, HrefError, PrintWithSpace,
77 use crate::html::highlight;
78 use crate::html::markdown::{HeadingOffset, Markdown, MarkdownHtml, MarkdownSummaryLine};
79 use crate::html::sources;
80 use crate::scrape_examples::{CallData, CallLocation};
83 /// A pair of name and its optional document.
84 crate type NameDoc = (String, Option<String>);
86 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
87 crate::html::format::display_fn(move |f| {
88 if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { f.write_str(v) }
92 // Helper structs for rendering items/sidebars and carrying along contextual
95 /// Struct representing one entry in the JS search index. These are all emitted
96 /// by hand to a large JS file at the end of cache-creation.
98 crate struct IndexItem {
103 crate parent: Option<DefId>,
104 crate parent_idx: Option<usize>,
105 crate search_type: Option<IndexItemFunctionType>,
106 crate aliases: Box<[String]>,
109 /// A type used for the search index.
111 crate struct RenderType {
112 name: Option<String>,
113 generics: Option<Vec<TypeWithKind>>,
116 /// Full type of functions/methods in the search index.
118 crate struct IndexItemFunctionType {
119 inputs: Vec<TypeWithKind>,
120 output: Option<Vec<TypeWithKind>>,
123 impl Serialize for IndexItemFunctionType {
124 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
128 // If we couldn't figure out a type, just write `null`.
129 let mut iter = self.inputs.iter();
130 if match self.output {
131 Some(ref output) => iter.chain(output.iter()).any(|i| i.ty.name.is_none()),
132 None => iter.any(|i| i.ty.name.is_none()),
134 serializer.serialize_none()
136 let mut seq = serializer.serialize_seq(None)?;
137 seq.serialize_element(&self.inputs)?;
138 if let Some(output) = &self.output {
139 if output.len() > 1 {
140 seq.serialize_element(&output)?;
142 seq.serialize_element(&output[0])?;
151 crate struct TypeWithKind {
156 impl From<(RenderType, ItemType)> for TypeWithKind {
157 fn from(x: (RenderType, ItemType)) -> TypeWithKind {
158 TypeWithKind { ty: x.0, kind: x.1 }
162 impl Serialize for TypeWithKind {
163 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
167 let mut seq = serializer.serialize_seq(None)?;
168 seq.serialize_element(&self.ty.name)?;
169 seq.serialize_element(&self.kind)?;
170 if let Some(generics) = &self.ty.generics {
171 seq.serialize_element(generics)?;
177 #[derive(Debug, Clone)]
178 crate struct StylePath {
179 /// The path to the theme
181 /// What the `disabled` attribute should be set to in the HTML tag
182 crate disabled: bool,
185 fn write_srclink(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) {
186 if let Some(l) = cx.src_href(item) {
187 write!(buf, "<a class=\"srclink\" href=\"{}\" title=\"goto source code\">[src]</a>", l)
191 #[derive(Debug, Eq, PartialEq, Hash)]
198 fn new(mut url: String, name: String) -> ItemEntry {
199 while url.starts_with('/') {
202 ItemEntry { url, name }
207 crate fn print(&self) -> impl fmt::Display + '_ {
208 crate::html::format::display_fn(move |f| {
209 write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name))
214 impl PartialOrd for ItemEntry {
215 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
216 Some(self.cmp(other))
220 impl Ord for ItemEntry {
221 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
222 self.name.cmp(&other.name)
228 structs: FxHashSet<ItemEntry>,
229 enums: FxHashSet<ItemEntry>,
230 unions: FxHashSet<ItemEntry>,
231 primitives: FxHashSet<ItemEntry>,
232 traits: FxHashSet<ItemEntry>,
233 macros: FxHashSet<ItemEntry>,
234 functions: FxHashSet<ItemEntry>,
235 typedefs: FxHashSet<ItemEntry>,
236 opaque_tys: FxHashSet<ItemEntry>,
237 statics: FxHashSet<ItemEntry>,
238 constants: FxHashSet<ItemEntry>,
239 attributes: FxHashSet<ItemEntry>,
240 derives: FxHashSet<ItemEntry>,
241 trait_aliases: FxHashSet<ItemEntry>,
245 fn new() -> AllTypes {
246 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
248 structs: new_set(100),
250 unions: new_set(100),
251 primitives: new_set(26),
252 traits: new_set(100),
253 macros: new_set(100),
254 functions: new_set(100),
255 typedefs: new_set(100),
256 opaque_tys: new_set(100),
257 statics: new_set(100),
258 constants: new_set(100),
259 attributes: new_set(100),
260 derives: new_set(100),
261 trait_aliases: new_set(100),
265 fn append(&mut self, item_name: String, item_type: &ItemType) {
266 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
267 if let Some(name) = url.pop() {
268 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
270 let name = url.join("::");
272 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
273 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
274 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
275 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
276 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
277 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
278 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
279 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
280 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
281 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
282 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
283 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
284 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
285 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
293 fn print(self, f: &mut Buffer) {
294 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
296 let mut e: Vec<&ItemEntry> = e.iter().collect();
300 "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">",
301 title.replace(' ', "-"), // IDs cannot contain whitespaces.
307 write!(f, "<li>{}</li>", s.print());
310 f.write_str("</ul>");
316 <span class=\"in-band\">List of all items</span>\
317 <span class=\"out-of-band\">\
318 <span id=\"render-detail\">\
319 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
320 title=\"collapse all docs\">\
321 [<span class=\"inner\">−</span>]\
327 // Note: print_entries does not escape the title, because we know the current set of titles
328 // doesn't require escaping.
329 print_entries(f, &self.structs, "Structs", "structs");
330 print_entries(f, &self.enums, "Enums", "enums");
331 print_entries(f, &self.unions, "Unions", "unions");
332 print_entries(f, &self.primitives, "Primitives", "primitives");
333 print_entries(f, &self.traits, "Traits", "traits");
334 print_entries(f, &self.macros, "Macros", "macros");
335 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
336 print_entries(f, &self.derives, "Derive Macros", "derives");
337 print_entries(f, &self.functions, "Functions", "functions");
338 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
339 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
340 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
341 print_entries(f, &self.statics, "Statics", "statics");
342 print_entries(f, &self.constants, "Constants", "constants")
349 description: &'static str,
350 sub_settings: Vec<Setting>,
353 js_data_name: &'static str,
354 description: &'static str,
358 js_data_name: &'static str,
359 description: &'static str,
360 default_value: &'static str,
361 options: Vec<(String, String)>,
366 fn display(&self, root_path: &str, suffix: &str) -> String {
368 Setting::Section { description, ref sub_settings } => format!(
369 "<div class=\"setting-line\">\
370 <div class=\"title\">{}</div>\
371 <div class=\"sub-settings\">{}</div>
374 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
376 Setting::Toggle { js_data_name, description, default_value } => format!(
377 "<div class=\"setting-line\">\
378 <label class=\"toggle\">\
379 <input type=\"checkbox\" id=\"{}\" {}>\
380 <span class=\"slider\"></span>\
385 if default_value { " checked" } else { "" },
388 Setting::Select { js_data_name, description, default_value, ref options } => format!(
389 "<div class=\"setting-line\">\
391 <label class=\"select-wrapper\">\
392 <select id=\"{}\" autocomplete=\"off\">{}</select>\
393 <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
401 "<option value=\"{}\" {}>{}</option>",
403 if opt.0 == default_value { "selected" } else { "" },
406 .collect::<String>(),
414 impl From<(&'static str, &'static str, bool)> for Setting {
415 fn from(values: (&'static str, &'static str, bool)) -> Setting {
416 Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
420 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
421 fn from(values: (&'static str, Vec<T>)) -> Setting {
423 description: values.0,
424 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
429 fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
430 let theme_names: Vec<(String, String)> = themes
434 try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
437 Ok((theme.clone(), theme))
439 .collect::<Result<_, Error>>()?;
441 // (id, explanation, default value)
442 let settings: &[Setting] = &[
446 Setting::from(("use-system-theme", "Use system theme", true)),
448 js_data_name: "preferred-dark-theme",
449 description: "Preferred dark theme",
450 default_value: "dark",
451 options: theme_names.clone(),
454 js_data_name: "preferred-light-theme",
455 description: "Preferred light theme",
456 default_value: "light",
457 options: theme_names,
462 ("auto-hide-large-items", "Auto-hide item contents for large items.", true).into(),
463 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
464 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", false)
466 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
468 ("line-numbers", "Show line numbers on code examples", false).into(),
469 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
474 <span class=\"in-band\">Rustdoc settings</span>\
476 <div class=\"settings\">{}</div>\
477 <script src=\"{}settings{}.js\"></script>",
478 settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
488 parent: Option<&clean::Item>,
489 heading_offset: HeadingOffset,
491 if let Some(ref name) = item.name {
492 info!("Documenting {}", name);
494 document_item_info(w, cx, item, parent);
495 if parent.is_none() {
496 document_full_collapsible(w, item, cx, heading_offset);
498 document_full(w, item, cx, heading_offset);
502 /// Render md_text as markdown.
507 links: Vec<RenderedLink>,
508 heading_offset: HeadingOffset,
510 let mut ids = cx.id_map.borrow_mut();
513 "<div class=\"docblock\">{}</div>",
518 error_codes: cx.shared.codes,
519 edition: cx.shared.edition(),
520 playground: &cx.shared.playground,
527 /// Writes a documentation block containing only the first paragraph of the documentation. If the
528 /// docs are longer, a "Read more" link is appended to the end.
533 link: AssocItemLink<'_>,
534 parent: &clean::Item,
537 document_item_info(w, cx, item, Some(parent));
541 if let Some(s) = item.doc_value() {
542 let mut summary_html = MarkdownSummaryLine(&s, &item.links(cx)).into_string();
544 if s.contains('\n') {
545 let link = format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link, cx));
547 if let Some(idx) = summary_html.rfind("</p>") {
548 summary_html.insert_str(idx, &link);
550 summary_html.push_str(&link);
554 write!(w, "<div class='docblock'>{}</div>", summary_html,);
558 fn document_full_collapsible(
562 heading_offset: HeadingOffset,
564 document_full_inner(w, item, cx, true, heading_offset);
571 heading_offset: HeadingOffset,
573 document_full_inner(w, item, cx, false, heading_offset);
576 fn document_full_inner(
580 is_collapsible: bool,
581 heading_offset: HeadingOffset,
583 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
584 debug!("Doc block: =====\n{}\n=====", s);
587 "<details class=\"rustdoc-toggle top-doc\" open>\
588 <summary class=\"hideme\">\
589 <span>Expand description</span>\
592 render_markdown(w, cx, &s, item.links(cx), heading_offset);
593 w.write_str("</details>");
595 render_markdown(w, cx, &s, item.links(cx), heading_offset);
599 let kind = match &*item.kind {
600 clean::ItemKind::StrippedItem(box kind) | kind => kind,
603 if let clean::ItemKind::FunctionItem(..) | clean::ItemKind::MethodItem(..) = kind {
604 render_call_locations(w, cx, item);
608 /// Add extra information about an item such as:
612 /// * Required features (through the `doc_cfg` feature)
613 fn document_item_info(
617 parent: Option<&clean::Item>,
619 let item_infos = short_item_info(item, cx, parent);
620 if !item_infos.is_empty() {
621 w.write_str("<div class=\"item-info\">");
622 for info in item_infos {
625 w.write_str("</div>");
629 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
630 let cfg = match (&item.cfg, parent.and_then(|p| p.cfg.as_ref())) {
631 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
632 (cfg, _) => cfg.as_deref().cloned(),
635 debug!("Portability {:?} - {:?} = {:?}", item.cfg, parent.and_then(|p| p.cfg.as_ref()), cfg);
637 Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
640 /// Render the stability, deprecation and portability information that is displayed at the top of
641 /// the item's documentation.
645 parent: Option<&clean::Item>,
647 let mut extra_info = vec![];
648 let error_codes = cx.shared.codes;
650 if let Some(depr @ Deprecation { note, since, is_since_rustc_version: _, suggestion: _ }) =
651 item.deprecation(cx.tcx())
653 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
654 // but only display the future-deprecation messages for #[rustc_deprecated].
655 let mut message = if let Some(since) = since {
656 let since = &since.as_str();
657 if !stability::deprecation_in_effect(&depr) {
659 String::from("Deprecating in a future Rust version")
661 format!("Deprecating in {}", Escape(since))
664 format!("Deprecated since {}", Escape(since))
667 String::from("Deprecated")
670 if let Some(note) = note {
671 let note = note.as_str();
672 let mut ids = cx.id_map.borrow_mut();
673 let html = MarkdownHtml(
678 &cx.shared.playground,
680 message.push_str(&format!(": {}", html.into_string()));
682 extra_info.push(format!(
683 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
688 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
689 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
690 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
693 .filter(|stab| stab.feature != sym::rustc_private)
694 .map(|stab| (stab.level, stab.feature))
697 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
699 let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
700 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
701 feature.push_str(&format!(
702 " <a href=\"{url}{issue}\">#{issue}</a>",
708 message.push_str(&format!(" ({})", feature));
710 if let Some(unstable_reason) = reason {
711 let mut ids = cx.id_map.borrow_mut();
713 "<details><summary>{}</summary>{}</details>",
716 &unstable_reason.as_str(),
720 &cx.shared.playground,
726 extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
729 if let Some(portability) = portability(item, parent) {
730 extra_info.push(portability);
736 // Render the list of items inside one of the sections "Trait Implementations",
737 // "Auto Trait Implementations," "Blanket Trait Implementations" (on struct/enum pages).
738 fn render_impls(cx: &Context<'_>, w: &mut Buffer, impls: &[&&Impl], containing_item: &clean::Item) {
740 let mut rendered_impls = impls
743 let did = i.trait_did().unwrap();
744 let provided_trait_methods = i.inner_impl().provided_trait_methods(tcx);
745 let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_trait_methods);
746 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
756 ImplRenderingParameters {
758 is_on_foreign_type: false,
759 show_default_items: true,
760 show_non_assoc_items: true,
761 toggle_open_by_default: true,
766 .collect::<Vec<_>>();
767 rendered_impls.sort();
768 w.write_str(&rendered_impls.join(""));
771 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>, cx: &Context<'_>) -> String {
772 use crate::formats::item_type::ItemType::*;
774 let name = it.name.as_ref().unwrap();
775 let ty = match it.type_() {
776 Typedef | AssocType => AssocType,
780 let anchor = format!("#{}.{}", ty, name);
782 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
783 AssocItemLink::Anchor(None) => anchor,
784 AssocItemLink::GotoSource(did, _) => {
785 href(did.expect_def_id(), cx).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
794 _default: Option<&String>,
795 link: AssocItemLink<'_>,
801 "{}{}const <a href=\"{}\" class=\"constant\">{}</a>: {}",
803 it.visibility.print_with_space(it.def_id, cx),
804 naive_assoc_href(it, link, cx),
805 it.name.as_ref().unwrap(),
813 bounds: &[clean::GenericBound],
814 default: Option<&clean::Type>,
815 link: AssocItemLink<'_>,
821 "{}type <a href=\"{}\" class=\"type\">{}</a>",
823 naive_assoc_href(it, link, cx),
824 it.name.as_ref().unwrap()
826 if !bounds.is_empty() {
827 write!(w, ": {}", print_generic_bounds(bounds, cx))
829 if let Some(default) = default {
830 write!(w, " = {}", default.print(cx))
834 fn render_stability_since_raw(
837 const_stability: Option<&ConstStability>,
838 containing_ver: Option<&str>,
839 containing_const_ver: Option<&str>,
841 let ver = ver.filter(|inner| !inner.is_empty());
843 match (ver, const_stability) {
844 // stable and const stable
845 (Some(v), Some(ConstStability { level: StabilityLevel::Stable { since }, .. }))
846 if Some(since.as_str()).as_deref() != containing_const_ver =>
850 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
854 // stable and const unstable
857 Some(ConstStability { level: StabilityLevel::Unstable { issue, .. }, feature, .. }),
861 "<span class=\"since\" title=\"Stable since Rust version {0}, const unstable\">{0} (const: ",
864 if let Some(n) = issue {
867 "<a href=\"https://github.com/rust-lang/rust/issues/{}\" title=\"Tracking issue for {}\">unstable</a>",
871 write!(w, "unstable");
873 write!(w, ")</span>");
876 (Some(v), _) if ver != containing_ver => {
879 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
887 fn render_assoc_item(
890 link: AssocItemLink<'_>,
897 header: hir::FnHeader,
900 link: AssocItemLink<'_>,
904 let name = meth.name.as_ref().unwrap();
905 let href = match link {
906 AssocItemLink::Anchor(Some(ref id)) => Some(format!("#{}", id)),
907 AssocItemLink::Anchor(None) => Some(format!("#{}.{}", meth.type_(), name)),
908 AssocItemLink::GotoSource(did, provided_methods) => {
909 // We're creating a link from an impl-item to the corresponding
910 // trait-item and need to map the anchored type accordingly.
911 let ty = if provided_methods.contains(name) {
917 match (href(did.expect_def_id(), cx), ty) {
918 (Ok(p), ty) => Some(format!("{}#{}.{}", p.0, ty, name)),
919 (Err(HrefError::DocumentationNotBuilt), ItemType::TyMethod) => None,
920 (Err(_), ty) => Some(format!("#{}.{}", ty, name)),
924 let vis = meth.visibility.print_with_space(meth.def_id, cx).to_string();
926 print_constness_with_space(&header.constness, meth.const_stability(cx.tcx()));
927 let asyncness = header.asyncness.print_with_space();
928 let unsafety = header.unsafety.print_with_space();
929 let defaultness = print_default_space(meth.is_default());
930 let abi = print_abi_with_space(header.abi).to_string();
932 // NOTE: `{:#}` does not print HTML formatting, `{}` does. So `g.print` can't be reused between the length calculation and `write!`.
933 let generics_len = format!("{:#}", g.print(cx)).len();
934 let mut header_len = "fn ".len()
941 + name.as_str().len()
944 let (indent, indent_str, end_newline) = if parent == ItemType::Trait {
946 let indent_str = " ";
947 render_attributes_in_pre(w, meth, indent_str);
948 (4, indent_str, false)
950 render_attributes_in_code(w, meth);
953 w.reserve(header_len + "<a href=\"\" class=\"fnname\">{".len() + "</a>".len());
956 "{indent}{vis}{constness}{asyncness}{unsafety}{defaultness}{abi}fn <a {href} class=\"fnname\">{name}</a>\
957 {generics}{decl}{notable_traits}{where_clause}",
960 constness = constness,
961 asyncness = asyncness,
963 defaultness = defaultness,
965 // links without a href are valid - https://www.w3schools.com/tags/att_a_href.asp
966 href = href.map(|href| format!("href=\"{}\"", href)).unwrap_or_else(|| "".to_string()),
968 generics = g.print(cx),
969 decl = d.full_print(header_len, indent, header.asyncness, cx),
970 notable_traits = notable_traits_decl(d, cx),
971 where_clause = print_where_clause(g, cx, indent, end_newline),
975 clean::StrippedItem(..) => {}
976 clean::TyMethodItem(ref m) => {
977 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
979 clean::MethodItem(ref m, _) => {
980 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
982 clean::AssocConstItem(ref ty, ref default) => assoc_const(
988 if parent == ItemType::Trait { " " } else { "" },
991 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
997 if parent == ItemType::Trait { " " } else { "" },
1000 _ => panic!("render_assoc_item called on non-associated-item"),
1004 const ALLOWED_ATTRIBUTES: &[Symbol] =
1005 &[sym::export_name, sym::link_section, sym::no_mangle, sym::repr, sym::non_exhaustive];
1007 fn attributes(it: &clean::Item) -> Vec<String> {
1011 .filter_map(|attr| {
1012 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
1013 Some(pprust::attribute_to_string(attr).replace("\n", "").replace(" ", " "))
1021 // When an attribute is rendered inside a `<pre>` tag, it is formatted using
1022 // a whitespace prefix and newline.
1023 fn render_attributes_in_pre(w: &mut Buffer, it: &clean::Item, prefix: &str) {
1024 for a in attributes(it) {
1025 writeln!(w, "{}{}", prefix, a);
1029 // When an attribute is rendered inside a <code> tag, it is formatted using
1030 // a div to produce a newline after it.
1031 fn render_attributes_in_code(w: &mut Buffer, it: &clean::Item) {
1032 for a in attributes(it) {
1033 write!(w, "<div class=\"code-attribute\">{}</div>", a);
1037 #[derive(Copy, Clone)]
1038 enum AssocItemLink<'a> {
1039 Anchor(Option<&'a str>),
1040 GotoSource(ItemId, &'a FxHashSet<Symbol>),
1043 impl<'a> AssocItemLink<'a> {
1044 fn anchor(&self, id: &'a str) -> Self {
1046 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(id)),
1047 ref other => *other,
1052 fn render_assoc_items(
1055 containing_item: &clean::Item,
1057 what: AssocItemRender<'_>,
1059 let mut derefs = FxHashSet::default();
1061 render_assoc_items_inner(w, cx, containing_item, it, what, &mut derefs)
1064 fn render_assoc_items_inner(
1067 containing_item: &clean::Item,
1069 what: AssocItemRender<'_>,
1070 derefs: &mut FxHashSet<DefId>,
1072 info!("Documenting associated items of {:?}", containing_item.name);
1073 let cache = cx.cache();
1074 let v = match cache.impls.get(&it) {
1078 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
1079 if !non_trait.is_empty() {
1080 let mut tmp_buf = Buffer::empty_from(w);
1081 let render_mode = match what {
1082 AssocItemRender::All => {
1084 "<h2 id=\"implementations\" class=\"small-section-header\">\
1085 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
1090 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
1092 cx.derive_id(small_url_encode(format!("deref-methods-{:#}", type_.print(cx))));
1093 if let Some(def_id) = type_.def_id(cx.cache()) {
1094 cx.deref_id_map.borrow_mut().insert(def_id, id.clone());
1098 "<h2 id=\"{id}\" class=\"small-section-header\">\
1099 <span>Methods from {trait_}<Target = {type_}></span>\
1100 <a href=\"#{id}\" class=\"anchor\"></a>\
1103 trait_ = trait_.print(cx),
1104 type_ = type_.print(cx),
1106 RenderMode::ForDeref { mut_: deref_mut_ }
1109 let mut impls_buf = Buffer::empty_from(w);
1110 for i in &non_trait {
1116 AssocItemLink::Anchor(None),
1120 ImplRenderingParameters {
1121 show_def_docs: true,
1122 is_on_foreign_type: false,
1123 show_default_items: true,
1124 show_non_assoc_items: true,
1125 toggle_open_by_default: true,
1129 if !impls_buf.is_empty() {
1130 w.push_buffer(tmp_buf);
1131 w.push_buffer(impls_buf);
1135 if !traits.is_empty() {
1137 traits.iter().find(|t| t.trait_did() == cx.tcx().lang_items().deref_trait());
1138 if let Some(impl_) = deref_impl {
1140 traits.iter().any(|t| t.trait_did() == cx.tcx().lang_items().deref_mut_trait());
1141 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut, derefs);
1144 // If we were already one level into rendering deref methods, we don't want to render
1145 // anything after recursing into any further deref methods above.
1146 if let AssocItemRender::DerefFor { .. } = what {
1150 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
1151 traits.iter().partition(|t| t.inner_impl().kind.is_auto());
1152 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
1153 concrete.into_iter().partition(|t| t.inner_impl().kind.is_blanket());
1155 let mut impls = Buffer::empty_from(w);
1156 render_impls(cx, &mut impls, &concrete, containing_item);
1157 let impls = impls.into_inner();
1158 if !impls.is_empty() {
1161 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
1162 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
1164 <div id=\"trait-implementations-list\">{}</div>",
1169 if !synthetic.is_empty() {
1171 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
1172 Auto Trait Implementations\
1173 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
1175 <div id=\"synthetic-implementations-list\">",
1177 render_impls(cx, w, &synthetic, containing_item);
1178 w.write_str("</div>");
1181 if !blanket_impl.is_empty() {
1183 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
1184 Blanket Implementations\
1185 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
1187 <div id=\"blanket-implementations-list\">",
1189 render_impls(cx, w, &blanket_impl, containing_item);
1190 w.write_str("</div>");
1195 fn render_deref_methods(
1199 container_item: &clean::Item,
1201 derefs: &mut FxHashSet<DefId>,
1203 let cache = cx.cache();
1204 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
1205 let (target, real_target) = impl_
1209 .find_map(|item| match *item.kind {
1210 clean::TypedefItem(ref t, true) => Some(match *t {
1211 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
1212 _ => (&t.type_, &t.type_),
1216 .expect("Expected associated type binding");
1217 debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target);
1219 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
1220 if let Some(did) = target.def_id(cache) {
1221 if let Some(type_did) = impl_.inner_impl().for_.def_id(cache) {
1222 // `impl Deref<Target = S> for S`
1223 if did == type_did || !derefs.insert(did) {
1224 // Avoid infinite cycles
1228 render_assoc_items_inner(w, cx, container_item, did, what, derefs);
1230 if let Some(prim) = target.primitive_type() {
1231 if let Some(&did) = cache.primitive_locations.get(&prim) {
1232 render_assoc_items_inner(w, cx, container_item, did, what, derefs);
1238 fn should_render_item(item: &clean::Item, deref_mut_: bool, tcx: TyCtxt<'_>) -> bool {
1239 let self_type_opt = match *item.kind {
1240 clean::MethodItem(ref method, _) => method.decl.self_type(),
1241 clean::TyMethodItem(ref method) => method.decl.self_type(),
1245 if let Some(self_ty) = self_type_opt {
1246 let (by_mut_ref, by_box, by_value) = match self_ty {
1247 SelfTy::SelfBorrowed(_, mutability)
1248 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
1249 (mutability == Mutability::Mut, false, false)
1251 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
1252 (false, Some(did) == tcx.lang_items().owned_box(), false)
1254 SelfTy::SelfValue => (false, false, true),
1255 _ => (false, false, false),
1258 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
1264 fn notable_traits_decl(decl: &clean::FnDecl, cx: &Context<'_>) -> String {
1265 let mut out = Buffer::html();
1267 if let Some(did) = decl.output.as_return().and_then(|t| t.def_id(cx.cache())) {
1268 if let Some(impls) = cx.cache().impls.get(&did) {
1270 let impl_ = i.inner_impl();
1271 if let Some(trait_) = &impl_.trait_ {
1272 let trait_did = trait_.def_id();
1274 if cx.cache().traits.get(&trait_did).map_or(false, |t| t.is_notable) {
1278 "<div class=\"notable\">Notable traits for {}</div>\
1279 <code class=\"content\">",
1280 impl_.for_.print(cx)
1284 //use the "where" class here to make it small
1287 "<span class=\"where fmt-newline\">{}</span>",
1288 impl_.print(false, cx)
1290 for it in &impl_.items {
1291 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1292 out.push_str("<span class=\"where fmt-newline\"> ");
1293 let empty_set = FxHashSet::default();
1295 AssocItemLink::GotoSource(trait_did.into(), &empty_set);
1296 assoc_type(&mut out, it, &[], Some(&tydef.type_), src_link, "", cx);
1297 out.push_str(";</span>");
1306 if !out.is_empty() {
1309 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
1310 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
1312 out.push_str("</code></span></div></span></span>");
1318 #[derive(Clone, Copy, Debug)]
1319 struct ImplRenderingParameters {
1320 show_def_docs: bool,
1321 is_on_foreign_type: bool,
1322 show_default_items: bool,
1323 /// Whether or not to show methods.
1324 show_non_assoc_items: bool,
1325 toggle_open_by_default: bool,
1332 parent: &clean::Item,
1333 link: AssocItemLink<'_>,
1334 render_mode: RenderMode,
1335 use_absolute: Option<bool>,
1337 rendering_params: ImplRenderingParameters,
1339 let cache = cx.cache();
1340 let traits = &cache.traits;
1341 let trait_ = i.trait_did().map(|did| &traits[&did]);
1342 let mut close_tags = String::new();
1344 // For trait implementations, the `interesting` output contains all methods that have doc
1345 // comments, and the `boring` output contains all methods that do not. The distinction is
1346 // used to allow hiding the boring methods.
1347 // `containing_item` is used for rendering stability info. If the parent is a trait impl,
1348 // `containing_item` will the grandparent, since trait impls can't have stability attached.
1350 boring: &mut Buffer,
1351 interesting: &mut Buffer,
1354 parent: &clean::Item,
1355 containing_item: &clean::Item,
1356 link: AssocItemLink<'_>,
1357 render_mode: RenderMode,
1358 is_default_item: bool,
1359 trait_: Option<&clean::Trait>,
1360 rendering_params: ImplRenderingParameters,
1362 let item_type = item.type_();
1363 let name = item.name.as_ref().unwrap();
1365 let render_method_item = rendering_params.show_non_assoc_items
1366 && match render_mode {
1367 RenderMode::Normal => true,
1368 RenderMode::ForDeref { mut_: deref_mut_ } => {
1369 should_render_item(item, deref_mut_, cx.tcx())
1373 let in_trait_class = if trait_.is_some() { " trait-impl" } else { "" };
1375 let mut doc_buffer = Buffer::empty_from(boring);
1376 let mut info_buffer = Buffer::empty_from(boring);
1377 let mut short_documented = true;
1379 if render_method_item {
1380 if !is_default_item {
1381 if let Some(t) = trait_ {
1382 // The trait item may have been stripped so we might not
1383 // find any documentation or stability for it.
1384 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
1385 // We need the stability of the item from the trait
1386 // because impls can't have a stability.
1387 if item.doc_value().is_some() {
1388 document_item_info(&mut info_buffer, cx, it, Some(parent));
1389 document_full(&mut doc_buffer, item, cx, HeadingOffset::H5);
1390 short_documented = false;
1392 // In case the item isn't documented,
1393 // provide short documentation from the trait.
1400 rendering_params.show_def_docs,
1405 document_item_info(&mut info_buffer, cx, item, Some(parent));
1406 if rendering_params.show_def_docs {
1407 document_full(&mut doc_buffer, item, cx, HeadingOffset::H5);
1408 short_documented = false;
1418 rendering_params.show_def_docs,
1422 let w = if short_documented && trait_.is_some() { interesting } else { boring };
1424 let toggled = !doc_buffer.is_empty();
1426 let method_toggle_class =
1427 if item_type == ItemType::Method { " method-toggle" } else { "" };
1428 write!(w, "<details class=\"rustdoc-toggle{}\" open><summary>", method_toggle_class);
1431 clean::MethodItem(..) | clean::TyMethodItem(_) => {
1432 // Only render when the method is not static or we allow static methods
1433 if render_method_item {
1434 let id = cx.derive_id(format!("{}.{}", item_type, name));
1435 let source_id = trait_
1436 .and_then(|trait_| {
1437 trait_.items.iter().find(|item| {
1438 item.name.map(|n| n.as_str().eq(&name.as_str())).unwrap_or(false)
1441 .map(|item| format!("{}.{}", item.type_(), name));
1444 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1445 id, item_type, in_trait_class,
1447 render_rightside(w, cx, item, containing_item);
1448 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1449 w.write_str("<h4 class=\"code-header\">");
1453 link.anchor(source_id.as_ref().unwrap_or(&id)),
1457 w.write_str("</h4>");
1458 w.write_str("</div>");
1461 clean::TypedefItem(ref tydef, _) => {
1462 let source_id = format!("{}.{}", ItemType::AssocType, name);
1463 let id = cx.derive_id(source_id.clone());
1466 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1467 id, item_type, in_trait_class
1469 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1470 w.write_str("<h4 class=\"code-header\">");
1476 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1480 w.write_str("</h4>");
1481 w.write_str("</div>");
1483 clean::AssocConstItem(ref ty, ref default) => {
1484 let source_id = format!("{}.{}", item_type, name);
1485 let id = cx.derive_id(source_id.clone());
1488 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1489 id, item_type, in_trait_class
1491 render_rightside(w, cx, item, containing_item);
1492 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1493 w.write_str("<h4 class=\"code-header\">");
1499 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1503 w.write_str("</h4>");
1504 w.write_str("</div>");
1506 clean::AssocTypeItem(ref bounds, ref default) => {
1507 let source_id = format!("{}.{}", item_type, name);
1508 let id = cx.derive_id(source_id.clone());
1509 write!(w, "<div id=\"{}\" class=\"{}{}\">", id, item_type, in_trait_class,);
1510 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1511 w.write_str("<h4 class=\"code-header\">");
1517 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1521 w.write_str("</h4>");
1522 w.write_str("</div>");
1524 clean::StrippedItem(..) => return,
1525 _ => panic!("can't make docs for trait item with name {:?}", item.name),
1528 w.push_buffer(info_buffer);
1530 w.write_str("</summary>");
1531 w.push_buffer(doc_buffer);
1532 w.push_str("</details>");
1536 let mut impl_items = Buffer::empty_from(w);
1537 let mut default_impl_items = Buffer::empty_from(w);
1539 for trait_item in &i.inner_impl().items {
1541 &mut default_impl_items,
1545 if trait_.is_some() { &i.impl_item } else { parent },
1550 trait_.map(|t| &t.trait_),
1555 fn render_default_items(
1556 boring: &mut Buffer,
1557 interesting: &mut Buffer,
1561 parent: &clean::Item,
1562 containing_item: &clean::Item,
1563 render_mode: RenderMode,
1564 rendering_params: ImplRenderingParameters,
1566 for trait_item in &t.items {
1567 let n = trait_item.name;
1568 if i.items.iter().any(|m| m.name == n) {
1571 let did = i.trait_.as_ref().unwrap().def_id();
1572 let provided_methods = i.provided_trait_methods(cx.tcx());
1573 let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_methods);
1591 // If we've implemented a trait, then also emit documentation for all
1592 // default items which weren't overridden in the implementation block.
1593 // We don't emit documentation for default items if they appear in the
1594 // Implementations on Foreign Types or Implementors sections.
1595 if rendering_params.show_default_items {
1596 if let Some(t) = trait_ {
1597 render_default_items(
1598 &mut default_impl_items,
1610 if render_mode == RenderMode::Normal {
1611 let toggled = !(impl_items.is_empty() && default_impl_items.is_empty());
1613 close_tags.insert_str(0, "</details>");
1616 "<details class=\"rustdoc-toggle implementors-toggle\"{}>",
1617 if rendering_params.toggle_open_by_default { " open" } else { "" }
1619 write!(w, "<summary>")
1621 render_impl_summary(
1627 rendering_params.show_def_docs,
1629 rendering_params.is_on_foreign_type,
1633 write!(w, "</summary>")
1636 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
1637 let mut ids = cx.id_map.borrow_mut();
1640 "<div class=\"docblock\">{}</div>",
1643 links: &i.impl_item.links(cx),
1645 error_codes: cx.shared.codes,
1646 edition: cx.shared.edition(),
1647 playground: &cx.shared.playground,
1648 heading_offset: HeadingOffset::H4
1654 if !default_impl_items.is_empty() || !impl_items.is_empty() {
1655 w.write_str("<div class=\"impl-items\">");
1656 w.push_buffer(default_impl_items);
1657 w.push_buffer(impl_items);
1658 close_tags.insert_str(0, "</div>");
1660 w.write_str(&close_tags);
1663 // Render the items that appear on the right side of methods, impls, and
1664 // associated types. For example "1.0.0 (const: 1.39.0) [src]".
1665 fn render_rightside(
1669 containing_item: &clean::Item,
1673 write!(w, "<div class=\"rightside\">");
1674 render_stability_since_raw(
1676 item.stable_since(tcx).as_deref(),
1677 item.const_stability(tcx),
1678 containing_item.stable_since(tcx).as_deref(),
1679 containing_item.const_stable_since(tcx).as_deref(),
1682 write_srclink(cx, item, w);
1683 w.write_str("</div>");
1686 pub(crate) fn render_impl_summary(
1690 parent: &clean::Item,
1691 containing_item: &clean::Item,
1692 show_def_docs: bool,
1693 use_absolute: Option<bool>,
1694 is_on_foreign_type: bool,
1695 // This argument is used to reference same type with different paths to avoid duplication
1696 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
1699 let id = cx.derive_id(match i.inner_impl().trait_ {
1701 if is_on_foreign_type {
1702 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t, cx)
1704 format!("impl-{}", small_url_encode(format!("{:#}", t.print(cx))))
1707 None => "impl".to_string(),
1709 let aliases = if aliases.is_empty() {
1712 format!(" data-aliases=\"{}\"", aliases.join(","))
1714 write!(w, "<div id=\"{}\" class=\"impl has-srclink\"{}>", id, aliases);
1715 render_rightside(w, cx, &i.impl_item, containing_item);
1716 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1717 write!(w, "<h3 class=\"code-header in-band\">");
1719 if let Some(use_absolute) = use_absolute {
1720 write!(w, "{}", i.inner_impl().print(use_absolute, cx));
1722 for it in &i.inner_impl().items {
1723 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1724 w.write_str("<span class=\"where fmt-newline\"> ");
1725 assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "", cx);
1726 w.write_str(";</span>");
1731 write!(w, "{}", i.inner_impl().print(false, cx));
1735 let is_trait = i.inner_impl().trait_.is_some();
1737 if let Some(portability) = portability(&i.impl_item, Some(parent)) {
1738 write!(w, "<div class=\"item-info\">{}</div>", portability);
1742 w.write_str("</div>");
1745 fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) {
1746 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
1750 || it.is_primitive()
1758 "<h2 class=\"location\">{}{}</h2>",
1760 clean::StructItem(..) => "Struct ",
1761 clean::TraitItem(..) => "Trait ",
1762 clean::PrimitiveItem(..) => "Primitive Type ",
1763 clean::UnionItem(..) => "Union ",
1764 clean::EnumItem(..) => "Enum ",
1765 clean::TypedefItem(..) => "Type Definition ",
1766 clean::ForeignTypeItem => "Foreign Type ",
1767 clean::ModuleItem(..) =>
1775 it.name.as_ref().unwrap()
1780 if let Some(ref version) = cx.cache().crate_version {
1783 "<div class=\"block version\">\
1784 <div class=\"narrow-helper\"></div>\
1792 buffer.write_str("<div class=\"sidebar-elems\">");
1796 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
1797 it.name.as_ref().expect("crates always have a name"),
1802 clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s),
1803 clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t),
1804 clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it),
1805 clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u),
1806 clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e),
1807 clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it),
1808 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
1809 clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, it),
1813 // The sidebar is designed to display sibling functions, modules and
1814 // other miscellaneous information. since there are lots of sibling
1815 // items (and that causes quadratic growth in large modules),
1816 // we refactor common parts into a shared JavaScript file per module.
1817 // still, we don't move everything into JS because we want to preserve
1818 // as much HTML as possible in order to allow non-JS-enabled browsers
1819 // to navigate the documentation (though slightly inefficiently).
1822 buffer.write_str("<h2 class=\"location\">Other items in<br>");
1823 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
1825 buffer.write_str("::<wbr>");
1829 "<a href=\"{}index.html\">{}</a>",
1830 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
1834 buffer.write_str("</h2>");
1837 // Sidebar refers to the enclosing module, not this module.
1838 let relpath = if it.is_mod() && parentlen != 0 { "./" } else { "" };
1841 "<div id=\"sidebar-vars\" data-name=\"{name}\" data-ty=\"{ty}\" data-relpath=\"{path}\">\
1843 name = it.name.unwrap_or(kw::Empty),
1847 write!(buffer, "<script defer src=\"{}sidebar-items.js\"></script>", relpath);
1848 // Closes sidebar-elems div.
1849 buffer.write_str("</div>");
1852 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
1853 if used_links.insert(url.clone()) {
1857 while !used_links.insert(format!("{}-{}", url, add)) {
1860 format!("{}-{}", url, add)
1863 struct SidebarLink {
1868 impl fmt::Display for SidebarLink {
1869 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1870 write!(f, "<a href=\"#{}\">{}</a>", self.url, self.name)
1874 impl PartialEq for SidebarLink {
1875 fn eq(&self, other: &Self) -> bool {
1876 self.url == other.url
1880 impl Eq for SidebarLink {}
1882 impl PartialOrd for SidebarLink {
1883 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1884 Some(self.cmp(other))
1888 impl Ord for SidebarLink {
1889 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1890 self.url.cmp(&other.url)
1897 used_links: &mut FxHashSet<String>,
1900 ) -> Vec<SidebarLink> {
1903 .filter_map(|item| match item.name {
1904 Some(name) if !name.is_empty() && item.is_method() => {
1905 if !for_deref || should_render_item(item, deref_mut, tcx) {
1908 url: get_next_url(used_links, format!("method.{}", name)),
1916 .collect::<Vec<_>>()
1919 fn get_associated_constants(
1921 used_links: &mut FxHashSet<String>,
1922 ) -> Vec<SidebarLink> {
1925 .filter_map(|item| match item.name {
1926 Some(name) if !name.is_empty() && item.is_associated_const() => Some(SidebarLink {
1928 url: get_next_url(used_links, format!("associatedconstant.{}", name)),
1932 .collect::<Vec<_>>()
1935 // The point is to url encode any potential character from a type with genericity.
1936 fn small_url_encode(s: String) -> String {
1937 let mut st = String::new();
1938 let mut last_match = 0;
1939 for (idx, c) in s.char_indices() {
1940 let escaped = match c {
1956 st += &s[last_match..idx];
1958 // NOTE: we only expect single byte characters here - which is fine as long as we
1959 // only match single byte characters
1960 last_match = idx + 1;
1963 if last_match != 0 {
1964 st += &s[last_match..];
1971 fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) {
1972 let did = it.def_id.expect_def_id();
1973 let cache = cx.cache();
1974 if let Some(v) = cache.impls.get(&did) {
1975 let mut used_links = FxHashSet::default();
1978 let used_links_bor = &mut used_links;
1979 let mut assoc_consts = v
1981 .flat_map(|i| get_associated_constants(i.inner_impl(), used_links_bor))
1982 .collect::<Vec<_>>();
1983 if !assoc_consts.is_empty() {
1984 // We want links' order to be reproducible so we don't use unstable sort.
1985 assoc_consts.sort();
1988 "<h3 class=\"sidebar-title\">\
1989 <a href=\"#implementations\">Associated Constants</a>\
1991 <div class=\"sidebar-links\">",
1993 for line in assoc_consts {
1994 write!(out, "{}", line);
1996 out.push_str("</div>");
2000 .filter(|i| i.inner_impl().trait_.is_none())
2001 .flat_map(|i| get_methods(i.inner_impl(), false, used_links_bor, false, cx.tcx()))
2002 .collect::<Vec<_>>();
2003 if !methods.is_empty() {
2004 // We want links' order to be reproducible so we don't use unstable sort.
2008 "<h3 class=\"sidebar-title\"><a href=\"#implementations\">Methods</a></h3>\
2009 <div class=\"sidebar-links\">",
2011 for line in methods {
2012 write!(out, "{}", line);
2014 out.push_str("</div>");
2018 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
2019 if let Some(impl_) =
2020 v.iter().find(|i| i.trait_did() == cx.tcx().lang_items().deref_trait())
2022 let mut derefs = FxHashSet::default();
2024 sidebar_deref_methods(cx, out, impl_, v, &mut derefs);
2027 let format_impls = |impls: Vec<&Impl>| {
2028 let mut links = FxHashSet::default();
2033 if let Some(ref i) = it.inner_impl().trait_ {
2034 let i_display = format!("{:#}", i.print(cx));
2035 let out = Escape(&i_display);
2036 let encoded = small_url_encode(format!("{:#}", i.print(cx)));
2037 let prefix = match it.inner_impl().polarity {
2038 ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => "",
2039 ty::ImplPolarity::Negative => "!",
2042 format!("<a href=\"#impl-{}\">{}{}</a>", encoded, prefix, out);
2043 if links.insert(generated.clone()) { Some(generated) } else { None }
2048 .collect::<Vec<String>>();
2053 let write_sidebar_links = |out: &mut Buffer, links: Vec<String>| {
2054 out.push_str("<div class=\"sidebar-links\">");
2056 out.push_str(&link);
2058 out.push_str("</div>");
2061 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
2062 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().kind.is_auto());
2063 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) =
2064 concrete.into_iter().partition::<Vec<_>, _>(|i| i.inner_impl().kind.is_blanket());
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>");