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, GetDefId, 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;
81 /// A pair of name and its optional document.
82 crate type NameDoc = (String, Option<String>);
84 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
85 crate::html::format::display_fn(move |f| {
86 if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { f.write_str(v) }
90 // Helper structs for rendering items/sidebars and carrying along contextual
93 /// Struct representing one entry in the JS search index. These are all emitted
94 /// by hand to a large JS file at the end of cache-creation.
96 crate struct IndexItem {
101 crate parent: Option<DefId>,
102 crate parent_idx: Option<usize>,
103 crate search_type: Option<IndexItemFunctionType>,
104 crate aliases: Box<[String]>,
107 /// A type used for the search index.
109 crate struct RenderType {
110 name: Option<String>,
111 generics: Option<Vec<String>>,
114 /// Full type of functions/methods in the search index.
116 crate struct IndexItemFunctionType {
117 inputs: Vec<TypeWithKind>,
118 output: Option<Vec<TypeWithKind>>,
121 impl Serialize for IndexItemFunctionType {
122 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
126 // If we couldn't figure out a type, just write `null`.
127 let mut iter = self.inputs.iter();
128 if match self.output {
129 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
130 None => iter.any(|ref i| i.ty.name.is_none()),
132 serializer.serialize_none()
134 let mut seq = serializer.serialize_seq(None)?;
135 seq.serialize_element(&self.inputs)?;
136 if let Some(output) = &self.output {
137 if output.len() > 1 {
138 seq.serialize_element(&output)?;
140 seq.serialize_element(&output[0])?;
149 crate struct TypeWithKind {
154 impl From<(RenderType, ItemType)> for TypeWithKind {
155 fn from(x: (RenderType, ItemType)) -> TypeWithKind {
156 TypeWithKind { ty: x.0, kind: x.1 }
160 impl Serialize for TypeWithKind {
161 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
165 let mut seq = serializer.serialize_seq(None)?;
166 seq.serialize_element(&self.ty.name)?;
167 seq.serialize_element(&self.kind)?;
168 if let Some(generics) = &self.ty.generics {
169 seq.serialize_element(generics)?;
175 #[derive(Debug, Clone)]
176 crate struct StylePath {
177 /// The path to the theme
179 /// What the `disabled` attribute should be set to in the HTML tag
180 crate disabled: bool,
183 fn write_srclink(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) {
184 if let Some(l) = cx.src_href(item) {
185 write!(buf, "<a class=\"srclink\" href=\"{}\" title=\"goto source code\">[src]</a>", l)
189 #[derive(Debug, Eq, PartialEq, Hash)]
196 fn new(mut url: String, name: String) -> ItemEntry {
197 while url.starts_with('/') {
200 ItemEntry { url, name }
205 crate fn print(&self) -> impl fmt::Display + '_ {
206 crate::html::format::display_fn(move |f| {
207 write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name))
212 impl PartialOrd for ItemEntry {
213 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
214 Some(self.cmp(other))
218 impl Ord for ItemEntry {
219 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
220 self.name.cmp(&other.name)
226 structs: FxHashSet<ItemEntry>,
227 enums: FxHashSet<ItemEntry>,
228 unions: FxHashSet<ItemEntry>,
229 primitives: FxHashSet<ItemEntry>,
230 traits: FxHashSet<ItemEntry>,
231 macros: FxHashSet<ItemEntry>,
232 functions: FxHashSet<ItemEntry>,
233 typedefs: FxHashSet<ItemEntry>,
234 opaque_tys: FxHashSet<ItemEntry>,
235 statics: FxHashSet<ItemEntry>,
236 constants: FxHashSet<ItemEntry>,
237 attributes: FxHashSet<ItemEntry>,
238 derives: FxHashSet<ItemEntry>,
239 trait_aliases: FxHashSet<ItemEntry>,
243 fn new() -> AllTypes {
244 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
246 structs: new_set(100),
248 unions: new_set(100),
249 primitives: new_set(26),
250 traits: new_set(100),
251 macros: new_set(100),
252 functions: new_set(100),
253 typedefs: new_set(100),
254 opaque_tys: new_set(100),
255 statics: new_set(100),
256 constants: new_set(100),
257 attributes: new_set(100),
258 derives: new_set(100),
259 trait_aliases: new_set(100),
263 fn append(&mut self, item_name: String, item_type: &ItemType) {
264 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
265 if let Some(name) = url.pop() {
266 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
268 let name = url.join("::");
270 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
271 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
272 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
273 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
274 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
275 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
276 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
277 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
278 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
279 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
280 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
281 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
282 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
283 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
291 fn print(self, f: &mut Buffer) {
292 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
294 let mut e: Vec<&ItemEntry> = e.iter().collect();
298 "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">",
299 title.replace(' ', "-"), // IDs cannot contain whitespaces.
305 write!(f, "<li>{}</li>", s.print());
308 f.write_str("</ul>");
314 <span class=\"in-band\">List of all items</span>\
315 <span class=\"out-of-band\">\
316 <span id=\"render-detail\">\
317 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
318 title=\"collapse all docs\">\
319 [<span class=\"inner\">−</span>]\
325 // Note: print_entries does not escape the title, because we know the current set of titles
326 // doesn't require escaping.
327 print_entries(f, &self.structs, "Structs", "structs");
328 print_entries(f, &self.enums, "Enums", "enums");
329 print_entries(f, &self.unions, "Unions", "unions");
330 print_entries(f, &self.primitives, "Primitives", "primitives");
331 print_entries(f, &self.traits, "Traits", "traits");
332 print_entries(f, &self.macros, "Macros", "macros");
333 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
334 print_entries(f, &self.derives, "Derive Macros", "derives");
335 print_entries(f, &self.functions, "Functions", "functions");
336 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
337 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
338 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
339 print_entries(f, &self.statics, "Statics", "statics");
340 print_entries(f, &self.constants, "Constants", "constants")
347 description: &'static str,
348 sub_settings: Vec<Setting>,
351 js_data_name: &'static str,
352 description: &'static str,
356 js_data_name: &'static str,
357 description: &'static str,
358 default_value: &'static str,
359 options: Vec<(String, String)>,
364 fn display(&self, root_path: &str, suffix: &str) -> String {
366 Setting::Section { description, ref sub_settings } => format!(
367 "<div class=\"setting-line\">\
368 <div class=\"title\">{}</div>\
369 <div class=\"sub-settings\">{}</div>
372 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
374 Setting::Toggle { js_data_name, description, default_value } => format!(
375 "<div class=\"setting-line\">\
376 <label class=\"toggle\">\
377 <input type=\"checkbox\" id=\"{}\" {}>\
378 <span class=\"slider\"></span>\
383 if default_value { " checked" } else { "" },
386 Setting::Select { js_data_name, description, default_value, ref options } => format!(
387 "<div class=\"setting-line\">\
389 <label class=\"select-wrapper\">\
390 <select id=\"{}\" autocomplete=\"off\">{}</select>\
391 <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
399 "<option value=\"{}\" {}>{}</option>",
401 if opt.0 == default_value { "selected" } else { "" },
404 .collect::<String>(),
412 impl From<(&'static str, &'static str, bool)> for Setting {
413 fn from(values: (&'static str, &'static str, bool)) -> Setting {
414 Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
418 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
419 fn from(values: (&'static str, Vec<T>)) -> Setting {
421 description: values.0,
422 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
427 fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
428 let theme_names: Vec<(String, String)> = themes
432 try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
435 Ok((theme.clone(), theme))
437 .collect::<Result<_, Error>>()?;
439 // (id, explanation, default value)
440 let settings: &[Setting] = &[
444 Setting::from(("use-system-theme", "Use system theme", true)),
446 js_data_name: "preferred-dark-theme",
447 description: "Preferred dark theme",
448 default_value: "dark",
449 options: theme_names.clone(),
452 js_data_name: "preferred-light-theme",
453 description: "Preferred light theme",
454 default_value: "light",
455 options: theme_names,
460 ("auto-hide-large-items", "Auto-hide item contents for large items.", true).into(),
461 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
462 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", false)
464 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
466 ("line-numbers", "Show line numbers on code examples", false).into(),
467 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
472 <span class=\"in-band\">Rustdoc settings</span>\
474 <div class=\"settings\">{}</div>\
475 <script src=\"{}settings{}.js\"></script>",
476 settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
486 parent: Option<&clean::Item>,
487 heading_offset: HeadingOffset,
489 if let Some(ref name) = item.name {
490 info!("Documenting {}", name);
492 document_item_info(w, cx, item, parent);
493 if parent.is_none() {
494 document_full_collapsible(w, item, cx, heading_offset);
496 document_full(w, item, cx, heading_offset);
500 /// Render md_text as markdown.
505 links: Vec<RenderedLink>,
506 heading_offset: HeadingOffset,
508 let mut ids = cx.id_map.borrow_mut();
511 "<div class=\"docblock\">{}</div>",
516 error_codes: cx.shared.codes,
517 edition: cx.shared.edition(),
518 playground: &cx.shared.playground,
525 /// Writes a documentation block containing only the first paragraph of the documentation. If the
526 /// docs are longer, a "Read more" link is appended to the end.
531 link: AssocItemLink<'_>,
532 parent: &clean::Item,
535 document_item_info(w, cx, item, Some(parent));
539 if let Some(s) = item.doc_value() {
540 let mut summary_html = MarkdownSummaryLine(&s, &item.links(cx)).into_string();
542 if s.contains('\n') {
543 let link = format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link, cx));
545 if let Some(idx) = summary_html.rfind("</p>") {
546 summary_html.insert_str(idx, &link);
548 summary_html.push_str(&link);
552 write!(w, "<div class='docblock'>{}</div>", summary_html,);
556 fn document_full_collapsible(
560 heading_offset: HeadingOffset,
562 document_full_inner(w, item, cx, true, heading_offset);
569 heading_offset: HeadingOffset,
571 document_full_inner(w, item, cx, false, heading_offset);
574 fn document_full_inner(
578 is_collapsible: bool,
579 heading_offset: HeadingOffset,
581 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
582 debug!("Doc block: =====\n{}\n=====", s);
585 "<details class=\"rustdoc-toggle top-doc\" open>\
586 <summary class=\"hideme\">\
587 <span>Expand description</span>\
590 render_markdown(w, cx, &s, item.links(cx), heading_offset);
591 w.write_str("</details>");
593 render_markdown(w, cx, &s, item.links(cx), heading_offset);
597 let kind = match &*item.kind {
598 clean::ItemKind::StrippedItem(box kind) | kind => kind,
601 if let clean::ItemKind::FunctionItem(..) | clean::ItemKind::MethodItem(..) = kind {
602 render_call_locations(w, cx, item);
606 /// Add extra information about an item such as:
610 /// * Required features (through the `doc_cfg` feature)
611 fn document_item_info(
615 parent: Option<&clean::Item>,
617 let item_infos = short_item_info(item, cx, parent);
618 if !item_infos.is_empty() {
619 w.write_str("<div class=\"item-info\">");
620 for info in item_infos {
623 w.write_str("</div>");
627 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
628 let cfg = match (&item.cfg, parent.and_then(|p| p.cfg.as_ref())) {
629 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
630 (cfg, _) => cfg.as_deref().cloned(),
633 debug!("Portability {:?} - {:?} = {:?}", item.cfg, parent.and_then(|p| p.cfg.as_ref()), cfg);
635 Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
638 /// Render the stability, deprecation and portability information that is displayed at the top of
639 /// the item's documentation.
643 parent: Option<&clean::Item>,
645 let mut extra_info = vec![];
646 let error_codes = cx.shared.codes;
648 if let Some(depr @ Deprecation { note, since, is_since_rustc_version: _, suggestion: _ }) =
649 item.deprecation(cx.tcx())
651 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
652 // but only display the future-deprecation messages for #[rustc_deprecated].
653 let mut message = if let Some(since) = since {
654 let since = &since.as_str();
655 if !stability::deprecation_in_effect(&depr) {
657 String::from("Deprecating in a future Rust version")
659 format!("Deprecating in {}", Escape(since))
662 format!("Deprecated since {}", Escape(since))
665 String::from("Deprecated")
668 if let Some(note) = note {
669 let note = note.as_str();
670 let mut ids = cx.id_map.borrow_mut();
671 let html = MarkdownHtml(
676 &cx.shared.playground,
678 message.push_str(&format!(": {}", html.into_string()));
680 extra_info.push(format!(
681 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
686 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
687 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
688 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
691 .filter(|stab| stab.feature != sym::rustc_private)
692 .map(|stab| (stab.level, stab.feature))
695 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
697 let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
698 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
699 feature.push_str(&format!(
700 " <a href=\"{url}{issue}\">#{issue}</a>",
706 message.push_str(&format!(" ({})", feature));
708 if let Some(unstable_reason) = reason {
709 let mut ids = cx.id_map.borrow_mut();
711 "<details><summary>{}</summary>{}</details>",
714 &unstable_reason.as_str(),
718 &cx.shared.playground,
724 extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
727 if let Some(portability) = portability(item, parent) {
728 extra_info.push(portability);
734 // Render the list of items inside one of the sections "Trait Implementations",
735 // "Auto Trait Implementations," "Blanket Trait Implementations" (on struct/enum pages).
736 fn render_impls(cx: &Context<'_>, w: &mut Buffer, impls: &[&&Impl], containing_item: &clean::Item) {
738 let mut rendered_impls = impls
741 let did = i.trait_did().unwrap();
742 let provided_trait_methods = i.inner_impl().provided_trait_methods(tcx);
743 let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_trait_methods);
744 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
754 ImplRenderingParameters {
756 is_on_foreign_type: false,
757 show_default_items: true,
758 show_non_assoc_items: true,
759 toggle_open_by_default: true,
764 .collect::<Vec<_>>();
765 rendered_impls.sort();
766 w.write_str(&rendered_impls.join(""));
769 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>, cx: &Context<'_>) -> String {
770 use crate::formats::item_type::ItemType::*;
772 let name = it.name.as_ref().unwrap();
773 let ty = match it.type_() {
774 Typedef | AssocType => AssocType,
778 let anchor = format!("#{}.{}", ty, name);
780 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
781 AssocItemLink::Anchor(None) => anchor,
782 AssocItemLink::GotoSource(did, _) => {
783 href(did.expect_def_id(), cx).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
792 _default: Option<&String>,
793 link: AssocItemLink<'_>,
799 "{}{}const <a href=\"{}\" class=\"constant\">{}</a>: {}",
801 it.visibility.print_with_space(it.def_id, cx),
802 naive_assoc_href(it, link, cx),
803 it.name.as_ref().unwrap(),
811 bounds: &[clean::GenericBound],
812 default: Option<&clean::Type>,
813 link: AssocItemLink<'_>,
819 "{}type <a href=\"{}\" class=\"type\">{}</a>",
821 naive_assoc_href(it, link, cx),
822 it.name.as_ref().unwrap()
824 if !bounds.is_empty() {
825 write!(w, ": {}", print_generic_bounds(bounds, cx))
827 if let Some(default) = default {
828 write!(w, " = {}", default.print(cx))
832 fn render_stability_since_raw(
835 const_stability: Option<&ConstStability>,
836 containing_ver: Option<&str>,
837 containing_const_ver: Option<&str>,
839 let ver = ver.filter(|inner| !inner.is_empty());
841 match (ver, const_stability) {
842 // stable and const stable
843 (Some(v), Some(ConstStability { level: StabilityLevel::Stable { since }, .. }))
844 if Some(since.as_str()).as_deref() != containing_const_ver =>
848 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
852 // stable and const unstable
855 Some(ConstStability { level: StabilityLevel::Unstable { issue, .. }, feature, .. }),
859 "<span class=\"since\" title=\"Stable since Rust version {0}, const unstable\">{0} (const: ",
862 if let Some(n) = issue {
865 "<a href=\"https://github.com/rust-lang/rust/issues/{}\" title=\"Tracking issue for {}\">unstable</a>",
869 write!(w, "unstable");
871 write!(w, ")</span>");
874 (Some(v), _) if ver != containing_ver => {
877 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
885 fn render_assoc_item(
888 link: AssocItemLink<'_>,
895 header: hir::FnHeader,
898 link: AssocItemLink<'_>,
902 let name = meth.name.as_ref().unwrap();
903 let href = match link {
904 AssocItemLink::Anchor(Some(ref id)) => Some(format!("#{}", id)),
905 AssocItemLink::Anchor(None) => Some(format!("#{}.{}", meth.type_(), name)),
906 AssocItemLink::GotoSource(did, provided_methods) => {
907 // We're creating a link from an impl-item to the corresponding
908 // trait-item and need to map the anchored type accordingly.
909 let ty = if provided_methods.contains(&name) {
915 match (href(did.expect_def_id(), cx), ty) {
916 (Ok(p), ty) => Some(format!("{}#{}.{}", p.0, ty, name)),
917 (Err(HrefError::DocumentationNotBuilt), ItemType::TyMethod) => None,
918 (Err(_), ty) => Some(format!("#{}.{}", ty, name)),
922 let vis = meth.visibility.print_with_space(meth.def_id, cx).to_string();
924 print_constness_with_space(&header.constness, meth.const_stability(cx.tcx()));
925 let asyncness = header.asyncness.print_with_space();
926 let unsafety = header.unsafety.print_with_space();
927 let defaultness = print_default_space(meth.is_default());
928 let abi = print_abi_with_space(header.abi).to_string();
930 // NOTE: `{:#}` does not print HTML formatting, `{}` does. So `g.print` can't be reused between the length calculation and `write!`.
931 let generics_len = format!("{:#}", g.print(cx)).len();
932 let mut header_len = "fn ".len()
939 + name.as_str().len()
942 let (indent, indent_str, end_newline) = if parent == ItemType::Trait {
944 let indent_str = " ";
945 render_attributes_in_pre(w, meth, indent_str);
946 (4, indent_str, false)
948 render_attributes_in_code(w, meth);
951 w.reserve(header_len + "<a href=\"\" class=\"fnname\">{".len() + "</a>".len());
954 "{indent}{vis}{constness}{asyncness}{unsafety}{defaultness}{abi}fn <a {href} class=\"fnname\">{name}</a>\
955 {generics}{decl}{notable_traits}{where_clause}",
958 constness = constness,
959 asyncness = asyncness,
961 defaultness = defaultness,
963 // links without a href are valid - https://www.w3schools.com/tags/att_a_href.asp
964 href = href.map(|href| format!("href=\"{}\"", href)).unwrap_or_else(|| "".to_string()),
966 generics = g.print(cx),
967 decl = d.full_print(header_len, indent, header.asyncness, cx),
968 notable_traits = notable_traits_decl(&d, cx),
969 where_clause = print_where_clause(g, cx, indent, end_newline),
973 clean::StrippedItem(..) => {}
974 clean::TyMethodItem(ref m) => {
975 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
977 clean::MethodItem(ref m, _) => {
978 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
980 clean::AssocConstItem(ref ty, ref default) => assoc_const(
986 if parent == ItemType::Trait { " " } else { "" },
989 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
995 if parent == ItemType::Trait { " " } else { "" },
998 _ => panic!("render_assoc_item called on non-associated-item"),
1002 const ALLOWED_ATTRIBUTES: &[Symbol] =
1003 &[sym::export_name, sym::link_section, sym::no_mangle, sym::repr, sym::non_exhaustive];
1005 fn attributes(it: &clean::Item) -> Vec<String> {
1009 .filter_map(|attr| {
1010 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
1011 Some(pprust::attribute_to_string(&attr).replace("\n", "").replace(" ", " "))
1019 // When an attribute is rendered inside a `<pre>` tag, it is formatted using
1020 // a whitespace prefix and newline.
1021 fn render_attributes_in_pre(w: &mut Buffer, it: &clean::Item, prefix: &str) {
1022 for a in attributes(it) {
1023 writeln!(w, "{}{}", prefix, a);
1027 // When an attribute is rendered inside a <code> tag, it is formatted using
1028 // a div to produce a newline after it.
1029 fn render_attributes_in_code(w: &mut Buffer, it: &clean::Item) {
1030 for a in attributes(it) {
1031 write!(w, "<div class=\"code-attribute\">{}</div>", a);
1035 #[derive(Copy, Clone)]
1036 enum AssocItemLink<'a> {
1037 Anchor(Option<&'a str>),
1038 GotoSource(ItemId, &'a FxHashSet<Symbol>),
1041 impl<'a> AssocItemLink<'a> {
1042 fn anchor(&self, id: &'a str) -> Self {
1044 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
1045 ref other => *other,
1050 fn render_assoc_items(
1053 containing_item: &clean::Item,
1055 what: AssocItemRender<'_>,
1057 info!("Documenting associated items of {:?}", containing_item.name);
1058 let cache = cx.cache();
1059 let v = match cache.impls.get(&it) {
1063 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
1064 if !non_trait.is_empty() {
1065 let render_mode = match what {
1066 AssocItemRender::All => {
1068 "<h2 id=\"implementations\" class=\"small-section-header\">\
1069 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
1074 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
1077 "<h2 id=\"deref-methods\" class=\"small-section-header\">\
1078 <span>Methods from {trait_}<Target = {type_}></span>\
1079 <a href=\"#deref-methods\" class=\"anchor\"></a>\
1081 trait_ = trait_.print(cx),
1082 type_ = type_.print(cx),
1084 RenderMode::ForDeref { mut_: deref_mut_ }
1087 for i in &non_trait {
1093 AssocItemLink::Anchor(None),
1097 ImplRenderingParameters {
1098 show_def_docs: true,
1099 is_on_foreign_type: false,
1100 show_default_items: true,
1101 show_non_assoc_items: true,
1102 toggle_open_by_default: true,
1107 if let AssocItemRender::DerefFor { .. } = what {
1110 if !traits.is_empty() {
1112 traits.iter().find(|t| t.trait_did() == cx.tcx().lang_items().deref_trait());
1113 if let Some(impl_) = deref_impl {
1115 traits.iter().any(|t| t.trait_did() == cx.tcx().lang_items().deref_mut_trait());
1116 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut);
1118 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
1119 traits.iter().partition(|t| t.inner_impl().synthetic);
1120 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
1121 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
1123 let mut impls = Buffer::empty_from(&w);
1124 render_impls(cx, &mut impls, &concrete, containing_item);
1125 let impls = impls.into_inner();
1126 if !impls.is_empty() {
1129 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
1130 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
1132 <div id=\"trait-implementations-list\">{}</div>",
1137 if !synthetic.is_empty() {
1139 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
1140 Auto Trait Implementations\
1141 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
1143 <div id=\"synthetic-implementations-list\">",
1145 render_impls(cx, w, &synthetic, containing_item);
1146 w.write_str("</div>");
1149 if !blanket_impl.is_empty() {
1151 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
1152 Blanket Implementations\
1153 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
1155 <div id=\"blanket-implementations-list\">",
1157 render_impls(cx, w, &blanket_impl, containing_item);
1158 w.write_str("</div>");
1163 fn render_deref_methods(
1167 container_item: &clean::Item,
1170 let cache = cx.cache();
1171 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
1172 let (target, real_target) = impl_
1176 .find_map(|item| match *item.kind {
1177 clean::TypedefItem(ref t, true) => Some(match *t {
1178 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
1179 _ => (&t.type_, &t.type_),
1183 .expect("Expected associated type binding");
1184 debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target);
1186 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
1187 if let Some(did) = target.def_id_full(cache) {
1188 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cache) {
1189 // `impl Deref<Target = S> for S`
1190 if did == type_did {
1191 // Avoid infinite cycles
1195 render_assoc_items(w, cx, container_item, did, what);
1197 if let Some(prim) = target.primitive_type() {
1198 if let Some(&did) = cache.primitive_locations.get(&prim) {
1199 render_assoc_items(w, cx, container_item, did, what);
1205 fn should_render_item(item: &clean::Item, deref_mut_: bool, tcx: TyCtxt<'_>) -> bool {
1206 let self_type_opt = match *item.kind {
1207 clean::MethodItem(ref method, _) => method.decl.self_type(),
1208 clean::TyMethodItem(ref method) => method.decl.self_type(),
1212 if let Some(self_ty) = self_type_opt {
1213 let (by_mut_ref, by_box, by_value) = match self_ty {
1214 SelfTy::SelfBorrowed(_, mutability)
1215 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
1216 (mutability == Mutability::Mut, false, false)
1218 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
1219 (false, Some(did) == tcx.lang_items().owned_box(), false)
1221 SelfTy::SelfValue => (false, false, true),
1222 _ => (false, false, false),
1225 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
1231 fn notable_traits_decl(decl: &clean::FnDecl, cx: &Context<'_>) -> String {
1232 let mut out = Buffer::html();
1234 if let Some(did) = decl.output.def_id_full(cx.cache()) {
1235 if let Some(impls) = cx.cache().impls.get(&did) {
1237 let impl_ = i.inner_impl();
1238 if let Some(trait_) = &impl_.trait_ {
1239 let trait_did = trait_.def_id();
1241 if cx.cache().traits.get(&trait_did).map_or(false, |t| t.is_notable) {
1245 "<div class=\"notable\">Notable traits for {}</div>\
1246 <code class=\"content\">",
1247 impl_.for_.print(cx)
1251 //use the "where" class here to make it small
1254 "<span class=\"where fmt-newline\">{}</span>",
1255 impl_.print(false, cx)
1257 for it in &impl_.items {
1258 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1259 out.push_str("<span class=\"where fmt-newline\"> ");
1260 let empty_set = FxHashSet::default();
1262 AssocItemLink::GotoSource(trait_did.into(), &empty_set);
1263 assoc_type(&mut out, it, &[], Some(&tydef.type_), src_link, "", cx);
1264 out.push_str(";</span>");
1273 if !out.is_empty() {
1276 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
1277 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
1279 out.push_str("</code></span></div></span></span>");
1285 #[derive(Clone, Copy, Debug)]
1286 struct ImplRenderingParameters {
1287 show_def_docs: bool,
1288 is_on_foreign_type: bool,
1289 show_default_items: bool,
1290 /// Whether or not to show methods.
1291 show_non_assoc_items: bool,
1292 toggle_open_by_default: bool,
1299 parent: &clean::Item,
1300 link: AssocItemLink<'_>,
1301 render_mode: RenderMode,
1302 use_absolute: Option<bool>,
1304 rendering_params: ImplRenderingParameters,
1306 let cache = cx.cache();
1307 let traits = &cache.traits;
1308 let trait_ = i.trait_did().map(|did| &traits[&did]);
1309 let mut close_tags = String::new();
1311 // For trait implementations, the `interesting` output contains all methods that have doc
1312 // comments, and the `boring` output contains all methods that do not. The distinction is
1313 // used to allow hiding the boring methods.
1314 // `containing_item` is used for rendering stability info. If the parent is a trait impl,
1315 // `containing_item` will the grandparent, since trait impls can't have stability attached.
1317 boring: &mut Buffer,
1318 interesting: &mut Buffer,
1321 parent: &clean::Item,
1322 containing_item: &clean::Item,
1323 link: AssocItemLink<'_>,
1324 render_mode: RenderMode,
1325 is_default_item: bool,
1326 trait_: Option<&clean::Trait>,
1327 rendering_params: ImplRenderingParameters,
1329 let item_type = item.type_();
1330 let name = item.name.as_ref().unwrap();
1332 let render_method_item = rendering_params.show_non_assoc_items
1333 && match render_mode {
1334 RenderMode::Normal => true,
1335 RenderMode::ForDeref { mut_: deref_mut_ } => {
1336 should_render_item(&item, deref_mut_, cx.tcx())
1340 let in_trait_class = if trait_.is_some() { " trait-impl" } else { "" };
1342 let mut doc_buffer = Buffer::empty_from(boring);
1343 let mut info_buffer = Buffer::empty_from(boring);
1344 let mut short_documented = true;
1346 if render_method_item {
1347 if !is_default_item {
1348 if let Some(t) = trait_ {
1349 // The trait item may have been stripped so we might not
1350 // find any documentation or stability for it.
1351 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
1352 // We need the stability of the item from the trait
1353 // because impls can't have a stability.
1354 if item.doc_value().is_some() {
1355 document_item_info(&mut info_buffer, cx, it, Some(parent));
1356 document_full(&mut doc_buffer, item, cx, HeadingOffset::H5);
1357 short_documented = false;
1359 // In case the item isn't documented,
1360 // provide short documentation from the trait.
1367 rendering_params.show_def_docs,
1372 document_item_info(&mut info_buffer, cx, item, Some(parent));
1373 if rendering_params.show_def_docs {
1374 document_full(&mut doc_buffer, item, cx, HeadingOffset::H5);
1375 short_documented = false;
1385 rendering_params.show_def_docs,
1389 let w = if short_documented && trait_.is_some() { interesting } else { boring };
1391 let toggled = !doc_buffer.is_empty();
1393 let method_toggle_class =
1394 if item_type == ItemType::Method { " method-toggle" } else { "" };
1395 write!(w, "<details class=\"rustdoc-toggle{}\" open><summary>", method_toggle_class);
1398 clean::MethodItem(..) | clean::TyMethodItem(_) => {
1399 // Only render when the method is not static or we allow static methods
1400 if render_method_item {
1401 let id = cx.derive_id(format!("{}.{}", item_type, name));
1402 let source_id = trait_
1403 .and_then(|trait_| {
1404 trait_.items.iter().find(|item| {
1405 item.name.map(|n| n.as_str().eq(&name.as_str())).unwrap_or(false)
1408 .map(|item| format!("{}.{}", item.type_(), name));
1411 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1412 id, item_type, in_trait_class,
1414 render_rightside(w, cx, item, containing_item);
1415 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1416 w.write_str("<h4 class=\"code-header\">");
1420 link.anchor(source_id.as_ref().unwrap_or(&id)),
1424 w.write_str("</h4>");
1425 w.write_str("</div>");
1428 clean::TypedefItem(ref tydef, _) => {
1429 let source_id = format!("{}.{}", ItemType::AssocType, name);
1430 let id = cx.derive_id(source_id.clone());
1433 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1434 id, item_type, in_trait_class
1436 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1437 w.write_str("<h4 class=\"code-header\">");
1443 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1447 w.write_str("</h4>");
1448 w.write_str("</div>");
1450 clean::AssocConstItem(ref ty, ref default) => {
1451 let source_id = format!("{}.{}", item_type, name);
1452 let id = cx.derive_id(source_id.clone());
1455 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1456 id, item_type, in_trait_class
1458 render_rightside(w, cx, item, containing_item);
1459 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1460 w.write_str("<h4 class=\"code-header\">");
1466 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1470 w.write_str("</h4>");
1471 w.write_str("</div>");
1473 clean::AssocTypeItem(ref bounds, ref default) => {
1474 let source_id = format!("{}.{}", item_type, name);
1475 let id = cx.derive_id(source_id.clone());
1476 write!(w, "<div id=\"{}\" class=\"{}{}\">", id, item_type, in_trait_class,);
1477 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1478 w.write_str("<h4 class=\"code-header\">");
1484 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1488 w.write_str("</h4>");
1489 w.write_str("</div>");
1491 clean::StrippedItem(..) => return,
1492 _ => panic!("can't make docs for trait item with name {:?}", item.name),
1495 w.push_buffer(info_buffer);
1497 w.write_str("</summary>");
1498 w.push_buffer(doc_buffer);
1499 w.push_str("</details>");
1503 let mut impl_items = Buffer::empty_from(w);
1504 let mut default_impl_items = Buffer::empty_from(w);
1506 for trait_item in &i.inner_impl().items {
1508 &mut default_impl_items,
1512 if trait_.is_some() { &i.impl_item } else { parent },
1517 trait_.map(|t| &t.trait_),
1522 fn render_default_items(
1523 boring: &mut Buffer,
1524 interesting: &mut Buffer,
1528 parent: &clean::Item,
1529 containing_item: &clean::Item,
1530 render_mode: RenderMode,
1531 rendering_params: ImplRenderingParameters,
1533 for trait_item in &t.items {
1534 let n = trait_item.name;
1535 if i.items.iter().any(|m| m.name == n) {
1538 let did = i.trait_.as_ref().unwrap().def_id();
1539 let provided_methods = i.provided_trait_methods(cx.tcx());
1540 let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_methods);
1558 // If we've implemented a trait, then also emit documentation for all
1559 // default items which weren't overridden in the implementation block.
1560 // We don't emit documentation for default items if they appear in the
1561 // Implementations on Foreign Types or Implementors sections.
1562 if rendering_params.show_default_items {
1563 if let Some(t) = trait_ {
1564 render_default_items(
1565 &mut default_impl_items,
1577 if render_mode == RenderMode::Normal {
1578 let toggled = !(impl_items.is_empty() && default_impl_items.is_empty());
1580 close_tags.insert_str(0, "</details>");
1583 "<details class=\"rustdoc-toggle implementors-toggle\"{}>",
1584 if rendering_params.toggle_open_by_default { " open" } else { "" }
1586 write!(w, "<summary>")
1588 render_impl_summary(
1594 rendering_params.show_def_docs,
1596 rendering_params.is_on_foreign_type,
1600 write!(w, "</summary>")
1603 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
1604 let mut ids = cx.id_map.borrow_mut();
1607 "<div class=\"docblock\">{}</div>",
1610 links: &i.impl_item.links(cx),
1612 error_codes: cx.shared.codes,
1613 edition: cx.shared.edition(),
1614 playground: &cx.shared.playground,
1615 heading_offset: HeadingOffset::H2
1621 if !default_impl_items.is_empty() || !impl_items.is_empty() {
1622 w.write_str("<div class=\"impl-items\">");
1623 w.push_buffer(default_impl_items);
1624 w.push_buffer(impl_items);
1625 close_tags.insert_str(0, "</div>");
1627 w.write_str(&close_tags);
1630 // Render the items that appear on the right side of methods, impls, and
1631 // associated types. For example "1.0.0 (const: 1.39.0) [src]".
1632 fn render_rightside(
1636 containing_item: &clean::Item,
1640 write!(w, "<div class=\"rightside\">");
1641 render_stability_since_raw(
1643 item.stable_since(tcx).as_deref(),
1644 item.const_stability(tcx),
1645 containing_item.stable_since(tcx).as_deref(),
1646 containing_item.const_stable_since(tcx).as_deref(),
1649 write_srclink(cx, item, w);
1650 w.write_str("</div>");
1653 pub(crate) fn render_impl_summary(
1657 parent: &clean::Item,
1658 containing_item: &clean::Item,
1659 show_def_docs: bool,
1660 use_absolute: Option<bool>,
1661 is_on_foreign_type: bool,
1662 // This argument is used to reference same type with different paths to avoid duplication
1663 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
1666 let id = cx.derive_id(match i.inner_impl().trait_ {
1668 if is_on_foreign_type {
1669 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t, cx)
1671 format!("impl-{}", small_url_encode(format!("{:#}", t.print(cx))))
1674 None => "impl".to_string(),
1676 let aliases = if aliases.is_empty() {
1679 format!(" data-aliases=\"{}\"", aliases.join(","))
1681 write!(w, "<div id=\"{}\" class=\"impl has-srclink\"{}>", id, aliases);
1682 render_rightside(w, cx, &i.impl_item, containing_item);
1683 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1684 write!(w, "<h3 class=\"code-header in-band\">");
1686 if let Some(use_absolute) = use_absolute {
1687 write!(w, "{}", i.inner_impl().print(use_absolute, cx));
1689 for it in &i.inner_impl().items {
1690 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1691 w.write_str("<span class=\"where fmt-newline\"> ");
1692 assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "", cx);
1693 w.write_str(";</span>");
1698 write!(w, "{}", i.inner_impl().print(false, cx));
1702 let is_trait = i.inner_impl().trait_.is_some();
1704 if let Some(portability) = portability(&i.impl_item, Some(parent)) {
1705 write!(w, "<div class=\"item-info\">{}</div>", portability);
1709 w.write_str("</div>");
1712 fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) {
1713 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
1717 || it.is_primitive()
1725 "<h2 class=\"location\">{}{}</h2>",
1727 clean::StructItem(..) => "Struct ",
1728 clean::TraitItem(..) => "Trait ",
1729 clean::PrimitiveItem(..) => "Primitive Type ",
1730 clean::UnionItem(..) => "Union ",
1731 clean::EnumItem(..) => "Enum ",
1732 clean::TypedefItem(..) => "Type Definition ",
1733 clean::ForeignTypeItem => "Foreign Type ",
1734 clean::ModuleItem(..) =>
1742 it.name.as_ref().unwrap()
1747 if let Some(ref version) = cx.cache().crate_version {
1750 "<div class=\"block version\">\
1751 <div class=\"narrow-helper\"></div>\
1759 buffer.write_str("<div class=\"sidebar-elems\">");
1763 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
1764 it.name.as_ref().expect("crates always have a name"),
1769 clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s),
1770 clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t),
1771 clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it),
1772 clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u),
1773 clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e),
1774 clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it),
1775 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
1776 clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, it),
1780 // The sidebar is designed to display sibling functions, modules and
1781 // other miscellaneous information. since there are lots of sibling
1782 // items (and that causes quadratic growth in large modules),
1783 // we refactor common parts into a shared JavaScript file per module.
1784 // still, we don't move everything into JS because we want to preserve
1785 // as much HTML as possible in order to allow non-JS-enabled browsers
1786 // to navigate the documentation (though slightly inefficiently).
1789 buffer.write_str("<h2 class=\"location\">Other items in<br>");
1790 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
1792 buffer.write_str("::<wbr>");
1796 "<a href=\"{}index.html\">{}</a>",
1797 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
1801 buffer.write_str("</h2>");
1804 // Sidebar refers to the enclosing module, not this module.
1805 let relpath = if it.is_mod() && parentlen != 0 { "./" } else { "" };
1808 "<div id=\"sidebar-vars\" data-name=\"{name}\" data-ty=\"{ty}\" data-relpath=\"{path}\">\
1810 name = it.name.unwrap_or(kw::Empty),
1814 write!(buffer, "<script defer src=\"{}sidebar-items.js\"></script>", relpath);
1815 // Closes sidebar-elems div.
1816 buffer.write_str("</div>");
1819 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
1820 if used_links.insert(url.clone()) {
1824 while !used_links.insert(format!("{}-{}", url, add)) {
1827 format!("{}-{}", url, add)
1830 struct SidebarLink {
1835 impl fmt::Display for SidebarLink {
1836 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1837 write!(f, "<a href=\"#{}\">{}</a>", self.url, self.name)
1841 impl PartialEq for SidebarLink {
1842 fn eq(&self, other: &Self) -> bool {
1843 self.url == other.url
1847 impl Eq for SidebarLink {}
1849 impl PartialOrd for SidebarLink {
1850 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1851 Some(self.cmp(other))
1855 impl Ord for SidebarLink {
1856 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1857 self.url.cmp(&other.url)
1864 used_links: &mut FxHashSet<String>,
1867 ) -> Vec<SidebarLink> {
1870 .filter_map(|item| match item.name {
1871 Some(name) if !name.is_empty() && item.is_method() => {
1872 if !for_deref || should_render_item(item, deref_mut, tcx) {
1875 url: get_next_url(used_links, format!("method.{}", name)),
1883 .collect::<Vec<_>>()
1886 fn get_associated_constants(
1888 used_links: &mut FxHashSet<String>,
1889 ) -> Vec<SidebarLink> {
1892 .filter_map(|item| match item.name {
1893 Some(name) if !name.is_empty() && item.is_associated_const() => Some(SidebarLink {
1895 url: get_next_url(used_links, format!("associatedconstant.{}", name)),
1899 .collect::<Vec<_>>()
1902 // The point is to url encode any potential character from a type with genericity.
1903 fn small_url_encode(s: String) -> String {
1904 let mut st = String::new();
1905 let mut last_match = 0;
1906 for (idx, c) in s.char_indices() {
1907 let escaped = match c {
1923 st += &s[last_match..idx];
1925 // NOTE: we only expect single byte characters here - which is fine as long as we
1926 // only match single byte characters
1927 last_match = idx + 1;
1930 if last_match != 0 {
1931 st += &s[last_match..];
1938 fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) {
1939 let did = it.def_id.expect_def_id();
1940 let cache = cx.cache();
1941 if let Some(v) = cache.impls.get(&did) {
1942 let mut used_links = FxHashSet::default();
1945 let used_links_bor = &mut used_links;
1946 let mut assoc_consts = v
1948 .flat_map(|i| get_associated_constants(i.inner_impl(), used_links_bor))
1949 .collect::<Vec<_>>();
1950 if !assoc_consts.is_empty() {
1951 // We want links' order to be reproducible so we don't use unstable sort.
1952 assoc_consts.sort();
1955 "<h3 class=\"sidebar-title\">\
1956 <a href=\"#implementations\">Associated Constants</a>\
1958 <div class=\"sidebar-links\">",
1960 for line in assoc_consts {
1961 write!(out, "{}", line);
1963 out.push_str("</div>");
1967 .filter(|i| i.inner_impl().trait_.is_none())
1968 .flat_map(|i| get_methods(i.inner_impl(), false, used_links_bor, false, cx.tcx()))
1969 .collect::<Vec<_>>();
1970 if !methods.is_empty() {
1971 // We want links' order to be reproducible so we don't use unstable sort.
1975 "<h3 class=\"sidebar-title\"><a href=\"#implementations\">Methods</a></h3>\
1976 <div class=\"sidebar-links\">",
1978 for line in methods {
1979 write!(out, "{}", line);
1981 out.push_str("</div>");
1985 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
1986 if let Some(impl_) =
1987 v.iter().find(|i| i.trait_did() == cx.tcx().lang_items().deref_trait())
1989 sidebar_deref_methods(cx, out, impl_, v);
1992 let format_impls = |impls: Vec<&Impl>| {
1993 let mut links = FxHashSet::default();
1998 if let Some(ref i) = it.inner_impl().trait_ {
1999 let i_display = format!("{:#}", i.print(cx));
2000 let out = Escape(&i_display);
2001 let encoded = small_url_encode(format!("{:#}", i.print(cx)));
2002 let generated = format!(
2003 "<a href=\"#impl-{}\">{}{}</a>",
2005 if it.inner_impl().negative_polarity { "!" } else { "" },
2008 if links.insert(generated.clone()) { Some(generated) } else { None }
2013 .collect::<Vec<String>>();
2018 let write_sidebar_links = |out: &mut Buffer, links: Vec<String>| {
2019 out.push_str("<div class=\"sidebar-links\">");
2021 out.push_str(&link);
2023 out.push_str("</div>");
2026 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
2027 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
2028 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
2030 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
2032 let concrete_format = format_impls(concrete);
2033 let synthetic_format = format_impls(synthetic);
2034 let blanket_format = format_impls(blanket_impl);
2036 if !concrete_format.is_empty() {
2038 "<h3 class=\"sidebar-title\"><a href=\"#trait-implementations\">\
2039 Trait Implementations</a></h3>",
2041 write_sidebar_links(out, concrete_format);
2044 if !synthetic_format.is_empty() {
2046 "<h3 class=\"sidebar-title\"><a href=\"#synthetic-implementations\">\
2047 Auto Trait Implementations</a></h3>",
2049 write_sidebar_links(out, synthetic_format);
2052 if !blanket_format.is_empty() {
2054 "<h3 class=\"sidebar-title\"><a href=\"#blanket-implementations\">\
2055 Blanket Implementations</a></h3>",
2057 write_sidebar_links(out, blanket_format);
2063 fn sidebar_deref_methods(cx: &Context<'_>, out: &mut Buffer, impl_: &Impl, v: &Vec<Impl>) {
2066 debug!("found Deref: {:?}", impl_);
2067 if let Some((target, real_target)) =
2068 impl_.inner_impl().items.iter().find_map(|item| match *item.kind {
2069 clean::TypedefItem(ref t, true) => Some(match *t {
2070 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
2071 _ => (&t.type_, &t.type_),
2076 debug!("found target, real_target: {:?} {:?}", target, real_target);
2077 if let Some(did) = target.def_id_full(c) {
2078 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(c) {
2079 // `impl Deref<Target = S> for S`
2080 if did == type_did {
2081 // Avoid infinite cycles
2086 let deref_mut = v.iter().any(|i| i.trait_did() == cx.tcx().lang_items().deref_mut_trait());
2087 let inner_impl = target
2090 target.primitive_type().and_then(|prim| c.primitive_locations.get(&prim).cloned())
2092 .and_then(|did| c.impls.get(&did));
2093 if let Some(impls) = inner_impl {
2094 debug!("found inner_impl: {:?}", impls);
2095 let mut used_links = FxHashSet::default();
2098 .filter(|i| i.inner_impl().trait_.is_none())
2100 get_methods(i.inner_impl(), true, &mut used_links, deref_mut, cx.tcx())
2102 .collect::<Vec<_>>();
2103 if !ret.is_empty() {
2106 "<h3 class=\"sidebar-title\"><a href=\"#deref-methods\">Methods from {}<Target={}></a></h3>",
2107 Escape(&format!("{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print(cx))),
2108 Escape(&format!("{:#}", real_target.print(cx))),
2110 // We want links' order to be reproducible so we don't use unstable sort.
2112 out.push_str("<div class=\"sidebar-links\">");
2114 write!(out, "{}", link);
2116 out.push_str("</div>");
2122 fn sidebar_struct(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
2123 let mut sidebar = Buffer::new();
2124 let fields = get_struct_fields_name(&s.fields);
2126 if !fields.is_empty() {
2127 if let CtorKind::Fictive = s.struct_type {
2129 "<h3 class=\"sidebar-title\"><a href=\"#fields\">Fields</a></h3>\
2130 <div class=\"sidebar-links\">",
2133 for field in fields {
2134 sidebar.push_str(&field);
2137 sidebar.push_str("</div>");
2138 } else if let CtorKind::Fn = s.struct_type {
2140 .push_str("<h3 class=\"sidebar-title\"><a href=\"#fields\">Tuple Fields</a></h3>");
2144 sidebar_assoc_items(cx, &mut sidebar, it);
2146 if !sidebar.is_empty() {
2147 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2151 fn get_id_for_impl_on_foreign_type(
2153 trait_: &clean::Path,
2156 small_url_encode(format!("impl-{:#}-for-{:#}", trait_.print(cx), for_.print(cx)))
2159 fn extract_for_impl_name(item: &clean::Item, cx: &Context<'_>) -> Option<(String, String)> {
2161 clean::ItemKind::ImplItem(ref i) => {
2162 if let Some(ref trait_) = i.trait_ {
2163 // Alternative format produces no URLs,
2164 // so this parameter does nothing.
2166 format!("{:#}", i.for_.print(cx)),
2167 get_id_for_impl_on_foreign_type(&i.for_, trait_, cx),
2177 fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
2178 buf.write_str("<div class=\"block items\">");
2180 fn print_sidebar_section(
2182 items: &[clean::Item],
2184 filter: impl Fn(&clean::Item) -> bool,
2185 write: impl Fn(&mut Buffer, &str),
2188 let mut items = items
2190 .filter_map(|m| match m.name {
2191 Some(ref name) if filter(m) => Some(name.as_str()),
2194 .collect::<Vec<_>>();
2196 if !items.is_empty() {
2197 items.sort_unstable();
2198 out.push_str(before);
2199 for item in items.into_iter() {
2202 out.push_str(after);
2206 print_sidebar_section(
2209 "<h3 class=\"sidebar-title\"><a href=\"#associated-types\">\
2210 Associated Types</a></h3><div class=\"sidebar-links\">",
2211 |m| m.is_associated_type(),
2212 |out, sym| write!(out, "<a href=\"#associatedtype.{0}\">{0}</a>", sym),
2216 print_sidebar_section(
2219 "<h3 class=\"sidebar-title\"><a href=\"#associated-const\">\
2220 Associated Constants</a></h3><div class=\"sidebar-links\">",
2221 |m| m.is_associated_const(),
2222 |out, sym| write!(out, "<a href=\"#associatedconstant.{0}\">{0}</a>", sym),
2226 print_sidebar_section(
2229 "<h3 class=\"sidebar-title\"><a href=\"#required-methods\">\
2230 Required Methods</a></h3><div class=\"sidebar-links\">",
2231 |m| m.is_ty_method(),
2232 |out, sym| write!(out, "<a href=\"#tymethod.{0}\">{0}</a>", sym),
2236 print_sidebar_section(
2239 "<h3 class=\"sidebar-title\"><a href=\"#provided-methods\">\
2240 Provided Methods</a></h3><div class=\"sidebar-links\">",
2242 |out, sym| write!(out, "<a href=\"#method.{0}\">{0}</a>", sym),
2246 let cache = cx.cache();
2247 if let Some(implementors) = cache.implementors.get(&it.def_id.expect_def_id()) {
2248 let mut res = implementors
2254 .map_or(false, |d| !cache.paths.contains_key(&d))
2256 .filter_map(|i| extract_for_impl_name(&i.impl_item, cx))
2257 .collect::<Vec<_>>();
2259 if !res.is_empty() {
2262 "<h3 class=\"sidebar-title\"><a href=\"#foreign-impls\">\
2263 Implementations on Foreign Types</a></h3>\
2264 <div class=\"sidebar-links\">",
2266 for (name, id) in res.into_iter() {
2267 write!(buf, "<a href=\"#{}\">{}</a>", id, Escape(&name));
2269 buf.push_str("</div>");
2273 sidebar_assoc_items(cx, buf, it);
2275 buf.push_str("<h3 class=\"sidebar-title\"><a href=\"#implementors\">Implementors</a></h3>");
2278 "<h3 class=\"sidebar-title\"><a \
2279 href=\"#synthetic-implementors\">Auto Implementors</a></h3>",
2283 buf.push_str("</div>")
2286 fn sidebar_primitive(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2287 let mut sidebar = Buffer::new();
2288 sidebar_assoc_items(cx, &mut sidebar, it);
2290 if !sidebar.is_empty() {
2291 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2295 fn sidebar_typedef(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2296 let mut sidebar = Buffer::new();
2297 sidebar_assoc_items(cx, &mut sidebar, it);
2299 if !sidebar.is_empty() {
2300 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2304 fn get_struct_fields_name(fields: &[clean::Item]) -> Vec<String> {
2305 let mut fields = fields
2307 .filter(|f| matches!(*f.kind, clean::StructFieldItem(..)))
2309 f.name.map(|name| format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
2311 .collect::<Vec<_>>();
2316 fn sidebar_union(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
2317 let mut sidebar = Buffer::new();
2318 let fields = get_struct_fields_name(&u.fields);
2320 if !fields.is_empty() {
2322 "<h3 class=\"sidebar-title\"><a href=\"#fields\">Fields</a></h3>\
2323 <div class=\"sidebar-links\">",
2326 for field in fields {
2327 sidebar.push_str(&field);
2330 sidebar.push_str("</div>");
2333 sidebar_assoc_items(cx, &mut sidebar, it);
2335 if !sidebar.is_empty() {
2336 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2340 fn sidebar_enum(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
2341 let mut sidebar = Buffer::new();
2343 let mut variants = e
2346 .filter_map(|v| match v.name {
2347 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
2350 .collect::<Vec<_>>();
2351 if !variants.is_empty() {
2352 variants.sort_unstable();
2353 sidebar.push_str(&format!(
2354 "<h3 class=\"sidebar-title\"><a href=\"#variants\">Variants</a></h3>\
2355 <div class=\"sidebar-links\">{}</div>",
2360 sidebar_assoc_items(cx, &mut sidebar, it);
2362 if !sidebar.is_empty() {
2363 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2367 fn item_ty_to_strs(ty: ItemType) -> (&'static str, &'static str) {
2369 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
2370 ItemType::Module => ("modules", "Modules"),
2371 ItemType::Struct => ("structs", "Structs"),
2372 ItemType::Union => ("unions", "Unions"),
2373 ItemType::Enum => ("enums", "Enums"),
2374 ItemType::Function => ("functions", "Functions"),
2375 ItemType::Typedef => ("types", "Type Definitions"),
2376 ItemType::Static => ("statics", "Statics"),
2377 ItemType::Constant => ("constants", "Constants"),
2378 ItemType::Trait => ("traits", "Traits"),
2379 ItemType::Impl => ("impls", "Implementations"),
2380 ItemType::TyMethod => ("tymethods", "Type Methods"),
2381 ItemType::Method => ("methods", "Methods"),
2382 ItemType::StructField => ("fields", "Struct Fields"),
2383 ItemType::Variant => ("variants", "Variants"),
2384 ItemType::Macro => ("macros", "Macros"),
2385 ItemType::Primitive => ("primitives", "Primitive Types"),
2386 ItemType::AssocType => ("associated-types", "Associated Types"),
2387 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
2388 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
2389 ItemType::Keyword => ("keywords", "Keywords"),
2390 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
2391 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
2392 ItemType::ProcDerive => ("derives", "Derive Macros"),
2393 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
2397 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
2398 let mut sidebar = String::new();
2400 // Re-exports are handled a bit differently because they can be extern crates or imports.
2401 if items.iter().any(|it| {
2403 && (it.type_() == ItemType::ExternCrate
2404 || (it.type_() == ItemType::Import && !it.is_stripped()))
2406 let (id, name) = item_ty_to_strs(ItemType::Import);
2407 sidebar.push_str(&format!("<li><a href=\"#{}\">{}</a></li>", id, name));
2410 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
2411 // to print its headings
2413 ItemType::Primitive,
2427 ItemType::StructField,
2429 ItemType::AssocType,
2430 ItemType::AssocConst,
2431 ItemType::ForeignType,
2434 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty && it.name.is_some()) {
2435 let (id, name) = item_ty_to_strs(myty);
2436 sidebar.push_str(&format!("<li><a href=\"#{}\">{}</a></li>", id, name));
2440 if !sidebar.is_empty() {
2441 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
2445 fn sidebar_foreign_type(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2446 let mut sidebar = Buffer::new();
2447 sidebar_assoc_items(cx, &mut sidebar, it);
2449 if !sidebar.is_empty() {
2450 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2454 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
2456 /// Returns a list of all paths used in the type.
2457 /// This is used to help deduplicate imported impls
2458 /// for reexported types. If any of the contained
2459 /// types are re-exported, we don't use the corresponding
2460 /// entry from the js file, as inlining will have already
2461 /// picked up the impl
2462 fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> {
2463 let mut out = Vec::new();
2464 let mut visited = FxHashSet::default();
2465 let mut work = VecDeque::new();
2467 let mut process_path = |did: DefId| {
2468 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
2469 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
2471 if let Some(path) = fqp {
2472 out.push(path.join("::"));
2476 work.push_back(first_ty);
2478 while let Some(ty) = work.pop_front() {
2479 if !visited.insert(ty.clone()) {
2484 clean::Type::ResolvedPath { did, .. } => process_path(did),
2485 clean::Type::Tuple(tys) => {
2486 work.extend(tys.into_iter());
2488 clean::Type::Slice(ty) => {
2489 work.push_back(*ty);
2491 clean::Type::Array(ty, _) => {
2492 work.push_back(*ty);
2494 clean::Type::RawPointer(_, ty) => {
2495 work.push_back(*ty);
2497 clean::Type::BorrowedRef { type_, .. } => {
2498 work.push_back(*type_);
2500 clean::Type::QPath { self_type, trait_, .. } => {
2501 work.push_back(*self_type);
2502 process_path(trait_.def_id());
2510 const MAX_FULL_EXAMPLES: usize = 5;
2511 const NUM_VISIBLE_LINES: usize = 10;
2513 /// Generates the HTML for example call locations generated via the --scrape-examples flag.
2514 fn render_call_locations(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item) {
2516 let def_id = item.def_id.expect_def_id();
2517 let key = tcx.def_path_hash(def_id);
2518 let call_locations = match cx.shared.call_locations.get(&key) {
2519 Some(call_locations) => call_locations,
2525 // Generate a unique ID so users can link to this section for a given method
2526 let id = cx.id_map.borrow_mut().derive("scraped-examples");
2529 "<div class=\"docblock scraped-example-list\">\
2531 <h5 id=\"{id}\" class=\"section-header\">\
2532 <a href=\"#{id}\">Examples found in repository</a>\
2537 // Generate the HTML for a single example, being the title and code block
2538 let write_example = |w: &mut Buffer, (path, call_data): (&PathBuf, &CallData)| -> bool {
2539 let contents = match fs::read_to_string(&path) {
2540 Ok(contents) => contents,
2542 let span = item.span(tcx).inner();
2544 .span_err(span, &format!("failed to read file {}: {}", path.display(), err));
2549 // To reduce file sizes, we only want to embed the source code needed to understand the example, not
2550 // the entire file. So we find the smallest byte range that covers all items enclosing examples.
2551 assert!(!call_data.locations.is_empty());
2553 call_data.locations.iter().min_by_key(|loc| loc.enclosing_item.byte_span.0).unwrap();
2554 let byte_min = min_loc.enclosing_item.byte_span.0;
2555 let line_min = min_loc.enclosing_item.line_span.0;
2557 call_data.locations.iter().max_by_key(|loc| loc.enclosing_item.byte_span.1).unwrap();
2558 let byte_max = max_loc.enclosing_item.byte_span.1;
2559 let line_max = max_loc.enclosing_item.line_span.1;
2561 // The output code is limited to that byte range.
2562 let contents_subset = &contents[(byte_min as usize)..(byte_max as usize)];
2564 // The call locations need to be updated to reflect that the size of the program has changed.
2565 // Specifically, the ranges are all subtracted by `byte_min` since that's the new zero point.
2566 let (mut byte_ranges, line_ranges): (Vec<_>, Vec<_>) = call_data
2570 let (byte_lo, byte_hi) = loc.call_expr.byte_span;
2571 let (line_lo, line_hi) = loc.call_expr.line_span;
2572 let byte_range = (byte_lo - byte_min, byte_hi - byte_min);
2573 let line_range = (line_lo - line_min, line_hi - line_min);
2574 let (anchor, line_title) = if line_lo == line_hi {
2575 (format!("{}", line_lo + 1), format!("line {}", line_lo + 1))
2578 format!("{}-{}", line_lo + 1, line_hi + 1),
2579 format!("lines {}-{}", line_lo + 1, line_hi + 1),
2582 let line_url = format!("{}{}#{}", cx.root_path(), call_data.url, anchor);
2584 (byte_range, (line_range, line_url, line_title))
2588 let (_, init_url, init_title) = &line_ranges[0];
2589 let needs_expansion = line_max - line_min > NUM_VISIBLE_LINES;
2590 let locations_encoded = serde_json::to_string(&line_ranges).unwrap();
2594 "<div class=\"scraped-example {expanded_cls}\" data-locs=\"{locations}\">\
2595 <div class=\"scraped-example-title\">\
2596 {name} (<a href=\"{url}\">{title}</a>)\
2598 <div class=\"code-wrapper\">",
2599 expanded_cls = if needs_expansion { "" } else { "expanded" },
2600 name = call_data.display_name,
2603 // The locations are encoded as a data attribute, so they can be read
2604 // later by the JS for interactions.
2605 locations = Escape(&locations_encoded)
2608 if line_ranges.len() > 1 {
2609 write!(w, r#"<span class="prev">≺</span> <span class="next">≻</span>"#);
2612 if needs_expansion {
2613 write!(w, r#"<span class="expand">↕</span>"#);
2616 // Look for the example file in the source map if it exists, otherwise return a dummy span
2617 let file_span = (|| {
2618 let source_map = tcx.sess.source_map();
2619 let crate_src = tcx.sess.local_crate_source_file.as_ref()?;
2620 let abs_crate_src = crate_src.canonicalize().ok()?;
2621 let crate_root = abs_crate_src.parent()?.parent()?;
2622 let rel_path = path.strip_prefix(crate_root).ok()?;
2623 let files = source_map.files();
2624 let file = files.iter().find(|file| match &file.name {
2625 FileName::Real(RealFileName::LocalPath(other_path)) => rel_path == other_path,
2628 Some(rustc_span::Span::with_root_ctxt(
2629 file.start_pos + BytePos(byte_min),
2630 file.start_pos + BytePos(byte_max),
2633 .unwrap_or(rustc_span::DUMMY_SP);
2635 // The root path is the inverse of Context::current
2636 let root_path = vec!["../"; cx.current.len() - 1].join("");
2638 let mut decoration_info = FxHashMap::default();
2639 decoration_info.insert("highlight focus", vec![byte_ranges.remove(0)]);
2640 decoration_info.insert("highlight", byte_ranges);
2649 Some(highlight::DecorationInfo(decoration_info)),
2650 sources::SourceContext::Embedded { offset: line_min },
2652 write!(w, "</div></div>");
2657 // The call locations are output in sequence, so that sequence needs to be determined.
2658 // Ideally the most "relevant" examples would be shown first, but there's no general algorithm
2659 // for determining relevance. Instead, we prefer the smallest examples being likely the easiest to
2660 // understand at a glance.
2661 let ordered_locations = {
2662 let sort_criterion = |(_, call_data): &(_, &CallData)| {
2663 // Use the first location because that's what the user will see initially
2664 let (lo, hi) = call_data.locations[0].enclosing_item.byte_span;
2668 let mut locs = call_locations.into_iter().collect::<Vec<_>>();
2669 locs.sort_by_key(sort_criterion);
2673 let mut it = ordered_locations.into_iter().peekable();
2675 // An example may fail to write if its source can't be read for some reason, so this method
2676 // continues iterating until a write suceeds
2677 let write_and_skip_failure = |w: &mut Buffer, it: &mut Peekable<_>| {
2678 while let Some(example) = it.next() {
2679 if write_example(&mut *w, example) {
2685 // Write just one example that's visible by default in the method's description.
2686 write_and_skip_failure(w, &mut it);
2688 // Then add the remaining examples in a hidden section.
2689 if it.peek().is_some() {
2692 "<details class=\"rustdoc-toggle more-examples-toggle\">\
2693 <summary class=\"hideme\">\
2694 <span>More examples</span>\
2696 <div class=\"more-scraped-examples\">\
2697 <div class=\"toggle-line\"><div class=\"toggle-line-inner\"></div></div>\
2698 <div class=\"more-scraped-examples-inner\">"
2701 // Only generate inline code for MAX_FULL_EXAMPLES number of examples. Otherwise we could
2702 // make the page arbitrarily huge!
2703 for _ in 0..MAX_FULL_EXAMPLES {
2704 write_and_skip_failure(w, &mut it);
2707 // For the remaining examples, generate a <ul> containing links to the source files.
2708 if it.peek().is_some() {
2709 write!(w, r#"<div class="example-links">Additional examples can be found in:<br><ul>"#);
2710 it.for_each(|(_, call_data)| {
2713 r#"<li><a href="{root}{url}">{name}</a></li>"#,
2714 root = cx.root_path(),
2715 url = call_data.url,
2716 name = call_data.display_name
2719 write!(w, "</ul></div>");
2722 write!(w, "</div></div></details>");
2725 write!(w, "</div>");