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.
26 crate mod search_index;
36 crate use self::context::*;
37 crate use self::span_map::{collect_spans_and_sources, LinkFromSrc};
39 use std::collections::VecDeque;
40 use std::default::Default;
43 use std::iter::Peekable;
44 use std::path::PathBuf;
46 use std::string::ToString;
48 use rustc_ast_pretty::pprust;
49 use rustc_attr::{ConstStability, Deprecation, StabilityLevel};
50 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
52 use rustc_hir::def::CtorKind;
53 use rustc_hir::def_id::DefId;
54 use rustc_hir::Mutability;
55 use rustc_middle::middle::stability;
57 use rustc_middle::ty::TyCtxt;
59 symbol::{kw, sym, Symbol},
60 BytePos, FileName, RealFileName,
62 use serde::ser::SerializeSeq;
63 use serde::{Serialize, Serializer};
65 use crate::clean::{self, ItemId, RenderedLink, SelfTy};
66 use crate::error::Error;
67 use crate::formats::cache::Cache;
68 use crate::formats::item_type::ItemType;
69 use crate::formats::{AssocItemRender, Impl, RenderMode};
70 use crate::html::escape::Escape;
71 use crate::html::format::{
72 href, print_abi_with_space, print_constness_with_space, print_default_space,
73 print_generic_bounds, print_where_clause, Buffer, HrefError, PrintWithSpace,
75 use crate::html::highlight;
76 use crate::html::markdown::{HeadingOffset, Markdown, MarkdownHtml, MarkdownSummaryLine};
77 use crate::html::sources;
78 use crate::scrape_examples::{CallData, CallLocation};
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<[Symbol]>,
107 /// A type used for the search index.
109 crate struct RenderType {
110 name: Option<String>,
111 generics: Option<Vec<TypeWithKind>>,
114 /// Full type of functions/methods in the search index.
116 crate struct IndexItemFunctionType {
117 inputs: Vec<TypeWithKind>,
118 output: 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 has_missing = self.inputs.iter().chain(self.output.iter()).any(|i| i.ty.name.is_none());
129 serializer.serialize_none()
131 let mut seq = serializer.serialize_seq(None)?;
132 seq.serialize_element(&self.inputs)?;
133 match self.output.as_slice() {
135 [one] => seq.serialize_element(one)?,
136 all => seq.serialize_element(all)?,
144 crate struct TypeWithKind {
149 impl From<(RenderType, ItemType)> for TypeWithKind {
150 fn from(x: (RenderType, ItemType)) -> TypeWithKind {
151 TypeWithKind { ty: x.0, kind: x.1 }
155 impl Serialize for TypeWithKind {
156 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
160 let mut seq = serializer.serialize_seq(None)?;
161 seq.serialize_element(&self.ty.name)?;
162 seq.serialize_element(&self.kind)?;
163 if let Some(generics) = &self.ty.generics {
164 seq.serialize_element(generics)?;
170 #[derive(Debug, Clone)]
171 crate struct StylePath {
172 /// The path to the theme
177 pub fn basename(&self) -> Result<String, Error> {
178 Ok(try_none!(try_none!(self.path.file_stem(), &self.path).to_str(), &self.path).to_string())
182 fn write_srclink(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) {
183 if let Some(l) = cx.src_href(item) {
184 write!(buf, "<a class=\"srclink\" href=\"{}\" title=\"goto source code\">source</a>", l)
188 #[derive(Debug, Eq, PartialEq, Hash)]
195 fn new(mut url: String, name: String) -> ItemEntry {
196 while url.starts_with('/') {
199 ItemEntry { url, name }
204 crate fn print(&self) -> impl fmt::Display + '_ {
205 crate::html::format::display_fn(move |f| {
206 write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name))
211 impl PartialOrd for ItemEntry {
212 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
213 Some(self.cmp(other))
217 impl Ord for ItemEntry {
218 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
219 self.name.cmp(&other.name)
225 structs: FxHashSet<ItemEntry>,
226 enums: FxHashSet<ItemEntry>,
227 unions: FxHashSet<ItemEntry>,
228 primitives: FxHashSet<ItemEntry>,
229 traits: FxHashSet<ItemEntry>,
230 macros: FxHashSet<ItemEntry>,
231 functions: FxHashSet<ItemEntry>,
232 typedefs: FxHashSet<ItemEntry>,
233 opaque_tys: FxHashSet<ItemEntry>,
234 statics: FxHashSet<ItemEntry>,
235 constants: FxHashSet<ItemEntry>,
236 attributes: FxHashSet<ItemEntry>,
237 derives: FxHashSet<ItemEntry>,
238 trait_aliases: FxHashSet<ItemEntry>,
242 fn new() -> AllTypes {
243 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
245 structs: new_set(100),
247 unions: new_set(100),
248 primitives: new_set(26),
249 traits: new_set(100),
250 macros: new_set(100),
251 functions: new_set(100),
252 typedefs: new_set(100),
253 opaque_tys: new_set(100),
254 statics: new_set(100),
255 constants: new_set(100),
256 attributes: new_set(100),
257 derives: new_set(100),
258 trait_aliases: new_set(100),
262 fn append(&mut self, item_name: String, item_type: &ItemType) {
263 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
264 if let Some(name) = url.pop() {
265 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
267 let name = url.join("::");
269 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
270 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
271 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
272 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
273 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
274 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
275 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
276 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
277 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
278 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
279 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
280 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
281 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
282 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
290 fn print(self, f: &mut Buffer) {
291 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
293 let mut e: Vec<&ItemEntry> = e.iter().collect();
297 "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">",
298 title.replace(' ', "-"), // IDs cannot contain whitespaces.
304 write!(f, "<li>{}</li>", s.print());
307 f.write_str("</ul>");
313 <span class=\"in-band\">List of all items</span>\
316 // Note: print_entries does not escape the title, because we know the current set of titles
317 // doesn't require escaping.
318 print_entries(f, &self.structs, "Structs", "structs");
319 print_entries(f, &self.enums, "Enums", "enums");
320 print_entries(f, &self.unions, "Unions", "unions");
321 print_entries(f, &self.primitives, "Primitives", "primitives");
322 print_entries(f, &self.traits, "Traits", "traits");
323 print_entries(f, &self.macros, "Macros", "macros");
324 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
325 print_entries(f, &self.derives, "Derive Macros", "derives");
326 print_entries(f, &self.functions, "Functions", "functions");
327 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
328 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
329 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
330 print_entries(f, &self.statics, "Statics", "statics");
331 print_entries(f, &self.constants, "Constants", "constants")
338 description: &'static str,
339 sub_settings: Vec<Setting>,
342 js_data_name: &'static str,
343 description: &'static str,
347 js_data_name: &'static str,
348 description: &'static str,
349 default_value: &'static str,
350 options: Vec<String>,
355 fn display(&self, root_path: &str, suffix: &str) -> String {
357 Setting::Section { description, ref sub_settings } => format!(
358 "<div class=\"setting-line\">\
359 <div class=\"title\">{}</div>\
360 <div class=\"sub-settings\">{}</div>
363 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
365 Setting::Toggle { js_data_name, description, default_value } => format!(
366 "<div class=\"setting-line\">\
367 <label class=\"toggle\">\
368 <input type=\"checkbox\" id=\"{}\" {}>\
369 <span class=\"slider\"></span>\
374 if default_value { " checked" } else { "" },
377 Setting::Select { js_data_name, description, default_value, ref options } => format!(
378 "<div class=\"setting-line\">\
380 <label class=\"select-wrapper\">\
381 <select id=\"{}\" autocomplete=\"off\">{}</select>\
382 <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
390 "<option value=\"{name}\" {}>{name}</option>",
391 if opt == default_value { "selected" } else { "" },
394 .collect::<String>(),
402 impl From<(&'static str, &'static str, bool)> for Setting {
403 fn from(values: (&'static str, &'static str, bool)) -> Setting {
404 Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
408 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
409 fn from(values: (&'static str, Vec<T>)) -> Setting {
411 description: values.0,
412 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
417 fn settings(root_path: &str, suffix: &str, theme_names: Vec<String>) -> Result<String, Error> {
418 // (id, explanation, default value)
419 let settings: &[Setting] = &[
423 Setting::from(("use-system-theme", "Use system theme", true)),
425 js_data_name: "preferred-dark-theme",
426 description: "Preferred dark theme",
427 default_value: "dark",
428 options: theme_names.clone(),
431 js_data_name: "preferred-light-theme",
432 description: "Preferred light theme",
433 default_value: "light",
434 options: theme_names,
439 ("auto-hide-large-items", "Auto-hide item contents for large items.", true).into(),
440 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
441 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", false)
443 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
445 ("line-numbers", "Show line numbers on code examples", false).into(),
446 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
451 <span class=\"in-band\">Rustdoc settings</span>\
453 <div class=\"settings\">{}</div>\
454 <link rel=\"stylesheet\" href=\"{root_path}settings{suffix}.css\">\
455 <script src=\"{root_path}settings{suffix}.js\"></script>",
456 settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
457 root_path = root_path,
466 parent: Option<&clean::Item>,
467 heading_offset: HeadingOffset,
469 if let Some(ref name) = item.name {
470 info!("Documenting {}", name);
472 document_item_info(w, cx, item, parent);
473 if parent.is_none() {
474 document_full_collapsible(w, item, cx, heading_offset);
476 document_full(w, item, cx, heading_offset);
480 /// Render md_text as markdown.
485 links: Vec<RenderedLink>,
486 heading_offset: HeadingOffset,
488 let mut ids = cx.id_map.borrow_mut();
491 "<div class=\"docblock\">{}</div>",
496 error_codes: cx.shared.codes,
497 edition: cx.shared.edition(),
498 playground: &cx.shared.playground,
505 /// Writes a documentation block containing only the first paragraph of the documentation. If the
506 /// docs are longer, a "Read more" link is appended to the end.
511 link: AssocItemLink<'_>,
512 parent: &clean::Item,
515 document_item_info(w, cx, item, Some(parent));
519 if let Some(s) = item.doc_value() {
520 let mut summary_html = MarkdownSummaryLine(&s, &item.links(cx)).into_string();
522 if s.contains('\n') {
523 let link = format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link, cx));
525 if let Some(idx) = summary_html.rfind("</p>") {
526 summary_html.insert_str(idx, &link);
528 summary_html.push_str(&link);
532 write!(w, "<div class='docblock'>{}</div>", summary_html,);
536 fn document_full_collapsible(
540 heading_offset: HeadingOffset,
542 document_full_inner(w, item, cx, true, heading_offset);
549 heading_offset: HeadingOffset,
551 document_full_inner(w, item, cx, false, heading_offset);
554 fn document_full_inner(
558 is_collapsible: bool,
559 heading_offset: HeadingOffset,
561 if let Some(s) = item.collapsed_doc_value() {
562 debug!("Doc block: =====\n{}\n=====", s);
565 "<details class=\"rustdoc-toggle top-doc\" open>\
566 <summary class=\"hideme\">\
567 <span>Expand description</span>\
570 render_markdown(w, cx, &s, item.links(cx), heading_offset);
571 w.write_str("</details>");
573 render_markdown(w, cx, &s, item.links(cx), heading_offset);
577 let kind = match &*item.kind {
578 clean::ItemKind::StrippedItem(box kind) | kind => kind,
581 if let clean::ItemKind::FunctionItem(..) | clean::ItemKind::MethodItem(..) = kind {
582 render_call_locations(w, cx, item);
586 /// Add extra information about an item such as:
590 /// * Required features (through the `doc_cfg` feature)
591 fn document_item_info(
595 parent: Option<&clean::Item>,
597 let item_infos = short_item_info(item, cx, parent);
598 if !item_infos.is_empty() {
599 w.write_str("<div class=\"item-info\">");
600 for info in item_infos {
603 w.write_str("</div>");
607 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
608 let cfg = match (&item.cfg, parent.and_then(|p| p.cfg.as_ref())) {
609 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
610 (cfg, _) => cfg.as_deref().cloned(),
613 debug!("Portability {:?} - {:?} = {:?}", item.cfg, parent.and_then(|p| p.cfg.as_ref()), cfg);
615 Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
618 /// Render the stability, deprecation and portability information that is displayed at the top of
619 /// the item's documentation.
623 parent: Option<&clean::Item>,
625 let mut extra_info = vec![];
626 let error_codes = cx.shared.codes;
628 if let Some(depr @ Deprecation { note, since, is_since_rustc_version: _, suggestion: _ }) =
629 item.deprecation(cx.tcx())
631 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
632 // but only display the future-deprecation messages for #[rustc_deprecated].
633 let mut message = if let Some(since) = since {
634 let since = since.as_str();
635 if !stability::deprecation_in_effect(&depr) {
637 String::from("Deprecating in a future Rust version")
639 format!("Deprecating in {}", Escape(since))
642 format!("Deprecated since {}", Escape(since))
645 String::from("Deprecated")
648 if let Some(note) = note {
649 let note = note.as_str();
650 let mut ids = cx.id_map.borrow_mut();
651 let html = MarkdownHtml(
656 &cx.shared.playground,
658 message.push_str(&format!(": {}", html.into_string()));
660 extra_info.push(format!(
661 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
666 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
667 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
668 if let Some((StabilityLevel::Unstable { reason: _, issue, .. }, feature)) = item
671 .filter(|stab| stab.feature != sym::rustc_private)
672 .map(|stab| (stab.level, stab.feature))
675 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
677 let mut feature = format!("<code>{}</code>", Escape(feature.as_str()));
678 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
679 feature.push_str(&format!(
680 " <a href=\"{url}{issue}\">#{issue}</a>",
686 message.push_str(&format!(" ({})", feature));
688 extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
691 if let Some(portability) = portability(item, parent) {
692 extra_info.push(portability);
698 // Render the list of items inside one of the sections "Trait Implementations",
699 // "Auto Trait Implementations," "Blanket Trait Implementations" (on struct/enum pages).
700 fn render_impls(cx: &Context<'_>, w: &mut Buffer, impls: &[&&Impl], containing_item: &clean::Item) {
702 let mut rendered_impls = impls
705 let did = i.trait_did().unwrap();
706 let provided_trait_methods = i.inner_impl().provided_trait_methods(tcx);
707 let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_trait_methods);
708 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
718 ImplRenderingParameters {
720 is_on_foreign_type: false,
721 show_default_items: true,
722 show_non_assoc_items: true,
723 toggle_open_by_default: true,
728 .collect::<Vec<_>>();
729 rendered_impls.sort();
730 w.write_str(&rendered_impls.join(""));
733 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>, cx: &Context<'_>) -> String {
734 use crate::formats::item_type::ItemType::*;
736 let name = it.name.as_ref().unwrap();
737 let ty = match it.type_() {
738 Typedef | AssocType => AssocType,
742 let anchor = format!("#{}.{}", ty, name);
744 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
745 AssocItemLink::Anchor(None) => anchor,
746 AssocItemLink::GotoSource(did, _) => {
747 href(did.expect_def_id(), cx).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
756 link: AssocItemLink<'_>,
762 "{}{}const <a href=\"{}\" class=\"constant\">{}</a>: {}",
764 it.visibility.print_with_space(it.def_id, cx),
765 naive_assoc_href(it, link, cx),
766 it.name.as_ref().unwrap(),
774 bounds: &[clean::GenericBound],
775 default: Option<&clean::Type>,
776 link: AssocItemLink<'_>,
782 "{}type <a href=\"{}\" class=\"associatedtype\">{}</a>",
784 naive_assoc_href(it, link, cx),
785 it.name.as_ref().unwrap()
787 if !bounds.is_empty() {
788 write!(w, ": {}", print_generic_bounds(bounds, cx))
790 if let Some(default) = default {
791 write!(w, " = {}", default.print(cx))
795 /// Writes a span containing the versions at which an item became stable and/or const-stable. For
796 /// example, if the item became stable at 1.0.0, and const-stable at 1.45.0, this function would
797 /// write a span containing "1.0.0 (const: 1.45.0)".
799 /// Returns `true` if a stability annotation was rendered.
801 /// Stability and const-stability are considered separately. If the item is unstable, no version
802 /// will be written. If the item is const-unstable, "const: unstable" will be appended to the
803 /// span, with a link to the tracking issue if present. If an item's stability or const-stability
804 /// version matches the version of its enclosing item, that version will be omitted.
806 /// Note that it is possible for an unstable function to be const-stable. In that case, the span
807 /// will include the const-stable version, but no stable version will be emitted, as a natural
808 /// consequence of the above rules.
809 fn render_stability_since_raw(
812 const_stability: Option<ConstStability>,
813 containing_ver: Option<Symbol>,
814 containing_const_ver: Option<Symbol>,
816 let stable_version = ver.filter(|inner| !inner.is_empty() && Some(*inner) != containing_ver);
818 let mut title = String::new();
819 let mut stability = String::new();
821 if let Some(ver) = stable_version {
822 stability.push_str(&ver.as_str());
823 title.push_str(&format!("Stable since Rust version {}", ver));
826 let const_title_and_stability = match const_stability {
827 Some(ConstStability { level: StabilityLevel::Stable { since }, .. })
828 if Some(since) != containing_const_ver =>
830 Some((format!("const since {}", since), format!("const: {}", since)))
832 Some(ConstStability { level: StabilityLevel::Unstable { issue, .. }, feature, .. }) => {
833 let unstable = if let Some(n) = issue {
835 r#"<a href="https://github.com/rust-lang/rust/issues/{}" title="Tracking issue for {}">unstable</a>"#,
839 String::from("unstable")
842 Some((String::from("const unstable"), format!("const: {}", unstable)))
847 if let Some((const_title, const_stability)) = const_title_and_stability {
848 if !title.is_empty() {
849 title.push_str(&format!(", {}", const_title));
851 title.push_str(&const_title);
854 if !stability.is_empty() {
855 stability.push_str(&format!(" ({})", const_stability));
857 stability.push_str(&const_stability);
861 if !stability.is_empty() {
862 write!(w, r#"<span class="since" title="{}">{}</span>"#, title, stability);
865 !stability.is_empty()
868 fn render_assoc_item(
871 link: AssocItemLink<'_>,
874 render_mode: RenderMode,
879 header: hir::FnHeader,
882 link: AssocItemLink<'_>,
885 render_mode: RenderMode,
887 let name = meth.name.as_ref().unwrap();
888 let href = match link {
889 AssocItemLink::Anchor(Some(ref id)) => Some(format!("#{}", id)),
890 AssocItemLink::Anchor(None) => Some(format!("#{}.{}", meth.type_(), name)),
891 AssocItemLink::GotoSource(did, provided_methods) => {
892 // We're creating a link from an impl-item to the corresponding
893 // trait-item and need to map the anchored type accordingly.
894 let ty = if provided_methods.contains(name) {
900 match (href(did.expect_def_id(), cx), ty) {
901 (Ok(p), ty) => Some(format!("{}#{}.{}", p.0, ty, name)),
902 (Err(HrefError::DocumentationNotBuilt), ItemType::TyMethod) => None,
903 (Err(_), ty) => Some(format!("#{}.{}", ty, name)),
907 let vis = meth.visibility.print_with_space(meth.def_id, cx).to_string();
908 // FIXME: Once https://github.com/rust-lang/rust/issues/67792 is implemented, we can remove
910 let constness = match render_mode {
911 RenderMode::Normal => {
912 print_constness_with_space(&header.constness, meth.const_stability(cx.tcx()))
914 RenderMode::ForDeref { .. } => "",
916 let asyncness = header.asyncness.print_with_space();
917 let unsafety = header.unsafety.print_with_space();
918 let defaultness = print_default_space(meth.is_default());
919 let abi = print_abi_with_space(header.abi).to_string();
921 // NOTE: `{:#}` does not print HTML formatting, `{}` does. So `g.print` can't be reused between the length calculation and `write!`.
922 let generics_len = format!("{:#}", g.print(cx)).len();
923 let mut header_len = "fn ".len()
930 + name.as_str().len()
933 let (indent, indent_str, end_newline) = if parent == ItemType::Trait {
935 let indent_str = " ";
936 render_attributes_in_pre(w, meth, indent_str);
937 (4, indent_str, false)
939 render_attributes_in_code(w, meth);
942 w.reserve(header_len + "<a href=\"\" class=\"fnname\">{".len() + "</a>".len());
945 "{indent}{vis}{constness}{asyncness}{unsafety}{defaultness}{abi}fn <a {href} class=\"fnname\">{name}</a>\
946 {generics}{decl}{notable_traits}{where_clause}",
949 constness = constness,
950 asyncness = asyncness,
952 defaultness = defaultness,
954 // links without a href are valid - https://www.w3schools.com/tags/att_a_href.asp
955 href = href.map(|href| format!("href=\"{}\"", href)).unwrap_or_else(|| "".to_string()),
957 generics = g.print(cx),
958 decl = d.full_print(header_len, indent, header.asyncness, cx),
959 notable_traits = notable_traits_decl(d, cx),
960 where_clause = print_where_clause(g, cx, indent, end_newline),
964 clean::StrippedItem(..) => {}
965 clean::TyMethodItem(ref m) => {
966 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx, render_mode)
968 clean::MethodItem(ref m, _) => {
969 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx, render_mode)
971 clean::AssocConstItem(ref ty, _) => {
972 assoc_const(w, item, ty, link, if parent == ItemType::Trait { " " } else { "" }, cx)
974 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
980 if parent == ItemType::Trait { " " } else { "" },
983 _ => panic!("render_assoc_item called on non-associated-item"),
987 const ALLOWED_ATTRIBUTES: &[Symbol] =
988 &[sym::export_name, sym::link_section, sym::no_mangle, sym::repr, sym::non_exhaustive];
990 fn attributes(it: &clean::Item) -> Vec<String> {
995 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
996 Some(pprust::attribute_to_string(attr).replace('\n', "").replace(" ", " "))
1004 // When an attribute is rendered inside a `<pre>` tag, it is formatted using
1005 // a whitespace prefix and newline.
1006 fn render_attributes_in_pre(w: &mut Buffer, it: &clean::Item, prefix: &str) {
1007 for a in attributes(it) {
1008 writeln!(w, "{}{}", prefix, a);
1012 // When an attribute is rendered inside a <code> tag, it is formatted using
1013 // a div to produce a newline after it.
1014 fn render_attributes_in_code(w: &mut Buffer, it: &clean::Item) {
1015 for a in attributes(it) {
1016 write!(w, "<div class=\"code-attribute\">{}</div>", a);
1020 #[derive(Copy, Clone)]
1021 enum AssocItemLink<'a> {
1022 Anchor(Option<&'a str>),
1023 GotoSource(ItemId, &'a FxHashSet<Symbol>),
1026 impl<'a> AssocItemLink<'a> {
1027 fn anchor(&self, id: &'a str) -> Self {
1029 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(id)),
1030 ref other => *other,
1035 fn render_assoc_items(
1038 containing_item: &clean::Item,
1040 what: AssocItemRender<'_>,
1042 let mut derefs = FxHashSet::default();
1044 render_assoc_items_inner(w, cx, containing_item, it, what, &mut derefs)
1047 fn render_assoc_items_inner(
1050 containing_item: &clean::Item,
1052 what: AssocItemRender<'_>,
1053 derefs: &mut FxHashSet<DefId>,
1055 info!("Documenting associated items of {:?}", containing_item.name);
1056 let cache = cx.cache();
1057 let v = match cache.impls.get(&it) {
1061 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
1062 if !non_trait.is_empty() {
1063 let mut tmp_buf = Buffer::empty_from(w);
1064 let render_mode = match what {
1065 AssocItemRender::All => {
1067 "<h2 id=\"implementations\" class=\"small-section-header\">\
1068 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
1073 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
1075 cx.derive_id(small_url_encode(format!("deref-methods-{:#}", type_.print(cx))));
1076 if let Some(def_id) = type_.def_id(cx.cache()) {
1077 cx.deref_id_map.borrow_mut().insert(def_id, id.clone());
1081 "<h2 id=\"{id}\" class=\"small-section-header\">\
1082 <span>Methods from {trait_}<Target = {type_}></span>\
1083 <a href=\"#{id}\" class=\"anchor\"></a>\
1086 trait_ = trait_.print(cx),
1087 type_ = type_.print(cx),
1089 RenderMode::ForDeref { mut_: deref_mut_ }
1092 let mut impls_buf = Buffer::empty_from(w);
1093 for i in &non_trait {
1099 AssocItemLink::Anchor(None),
1103 ImplRenderingParameters {
1104 show_def_docs: true,
1105 is_on_foreign_type: false,
1106 show_default_items: true,
1107 show_non_assoc_items: true,
1108 toggle_open_by_default: true,
1112 if !impls_buf.is_empty() {
1113 w.push_buffer(tmp_buf);
1114 w.push_buffer(impls_buf);
1118 if !traits.is_empty() {
1120 traits.iter().find(|t| t.trait_did() == cx.tcx().lang_items().deref_trait());
1121 if let Some(impl_) = deref_impl {
1123 traits.iter().any(|t| t.trait_did() == cx.tcx().lang_items().deref_mut_trait());
1124 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut, derefs);
1127 // If we were already one level into rendering deref methods, we don't want to render
1128 // anything after recursing into any further deref methods above.
1129 if let AssocItemRender::DerefFor { .. } = what {
1133 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
1134 traits.iter().partition(|t| t.inner_impl().kind.is_auto());
1135 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
1136 concrete.into_iter().partition(|t| t.inner_impl().kind.is_blanket());
1138 let mut impls = Buffer::empty_from(w);
1139 render_impls(cx, &mut impls, &concrete, containing_item);
1140 let impls = impls.into_inner();
1141 if !impls.is_empty() {
1144 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
1145 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
1147 <div id=\"trait-implementations-list\">{}</div>",
1152 if !synthetic.is_empty() {
1154 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
1155 Auto Trait Implementations\
1156 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
1158 <div id=\"synthetic-implementations-list\">",
1160 render_impls(cx, w, &synthetic, containing_item);
1161 w.write_str("</div>");
1164 if !blanket_impl.is_empty() {
1166 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
1167 Blanket Implementations\
1168 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
1170 <div id=\"blanket-implementations-list\">",
1172 render_impls(cx, w, &blanket_impl, containing_item);
1173 w.write_str("</div>");
1178 fn render_deref_methods(
1182 container_item: &clean::Item,
1184 derefs: &mut FxHashSet<DefId>,
1186 let cache = cx.cache();
1187 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
1188 let (target, real_target) = impl_
1192 .find_map(|item| match *item.kind {
1193 clean::TypedefItem(ref t, true) => Some(match *t {
1194 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
1195 _ => (&t.type_, &t.type_),
1199 .expect("Expected associated type binding");
1200 debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target);
1202 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
1203 if let Some(did) = target.def_id(cache) {
1204 if let Some(type_did) = impl_.inner_impl().for_.def_id(cache) {
1205 // `impl Deref<Target = S> for S`
1206 if did == type_did || !derefs.insert(did) {
1207 // Avoid infinite cycles
1211 render_assoc_items_inner(w, cx, container_item, did, what, derefs);
1213 if let Some(prim) = target.primitive_type() {
1214 if let Some(&did) = cache.primitive_locations.get(&prim) {
1215 render_assoc_items_inner(w, cx, container_item, did, what, derefs);
1221 fn should_render_item(item: &clean::Item, deref_mut_: bool, tcx: TyCtxt<'_>) -> bool {
1222 let self_type_opt = match *item.kind {
1223 clean::MethodItem(ref method, _) => method.decl.self_type(),
1224 clean::TyMethodItem(ref method) => method.decl.self_type(),
1228 if let Some(self_ty) = self_type_opt {
1229 let (by_mut_ref, by_box, by_value) = match self_ty {
1230 SelfTy::SelfBorrowed(_, mutability)
1231 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
1232 (mutability == Mutability::Mut, false, false)
1234 SelfTy::SelfExplicit(clean::Type::Path { path }) => {
1235 (false, Some(path.def_id()) == tcx.lang_items().owned_box(), false)
1237 SelfTy::SelfValue => (false, false, true),
1238 _ => (false, false, false),
1241 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
1247 fn notable_traits_decl(decl: &clean::FnDecl, cx: &Context<'_>) -> String {
1248 let mut out = Buffer::html();
1250 if let Some((did, ty)) = decl.output.as_return().and_then(|t| Some((t.def_id(cx.cache())?, t)))
1252 if let Some(impls) = cx.cache().impls.get(&did) {
1254 let impl_ = i.inner_impl();
1255 if !impl_.for_.without_borrowed_ref().is_same(ty.without_borrowed_ref(), cx.cache())
1257 // Two different types might have the same did,
1258 // without actually being the same.
1261 if let Some(trait_) = &impl_.trait_ {
1262 let trait_did = trait_.def_id();
1264 if cx.cache().traits.get(&trait_did).map_or(false, |t| t.is_notable) {
1268 "<div class=\"notable\">Notable traits for {}</div>\
1269 <code class=\"content\">",
1270 impl_.for_.print(cx)
1274 //use the "where" class here to make it small
1277 "<span class=\"where fmt-newline\">{}</span>",
1278 impl_.print(false, cx)
1280 for it in &impl_.items {
1281 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1282 out.push_str("<span class=\"where fmt-newline\"> ");
1283 let empty_set = FxHashSet::default();
1285 AssocItemLink::GotoSource(trait_did.into(), &empty_set);
1286 assoc_type(&mut out, it, &[], Some(&tydef.type_), src_link, "", cx);
1287 out.push_str(";</span>");
1296 if !out.is_empty() {
1299 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
1300 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
1302 out.push_str("</code></span></div></span></span>");
1308 #[derive(Clone, Copy, Debug)]
1309 struct ImplRenderingParameters {
1310 show_def_docs: bool,
1311 is_on_foreign_type: bool,
1312 show_default_items: bool,
1313 /// Whether or not to show methods.
1314 show_non_assoc_items: bool,
1315 toggle_open_by_default: bool,
1322 parent: &clean::Item,
1323 link: AssocItemLink<'_>,
1324 render_mode: RenderMode,
1325 use_absolute: Option<bool>,
1327 rendering_params: ImplRenderingParameters,
1329 let cache = cx.cache();
1330 let traits = &cache.traits;
1331 let trait_ = i.trait_did().map(|did| &traits[&did]);
1332 let mut close_tags = String::new();
1334 // For trait implementations, the `interesting` output contains all methods that have doc
1335 // comments, and the `boring` output contains all methods that do not. The distinction is
1336 // used to allow hiding the boring methods.
1337 // `containing_item` is used for rendering stability info. If the parent is a trait impl,
1338 // `containing_item` will the grandparent, since trait impls can't have stability attached.
1340 boring: &mut Buffer,
1341 interesting: &mut Buffer,
1344 parent: &clean::Item,
1345 containing_item: &clean::Item,
1346 link: AssocItemLink<'_>,
1347 render_mode: RenderMode,
1348 is_default_item: bool,
1349 trait_: Option<&clean::Trait>,
1350 rendering_params: ImplRenderingParameters,
1352 let item_type = item.type_();
1353 let name = item.name.as_ref().unwrap();
1355 let render_method_item = rendering_params.show_non_assoc_items
1356 && match render_mode {
1357 RenderMode::Normal => true,
1358 RenderMode::ForDeref { mut_: deref_mut_ } => {
1359 should_render_item(item, deref_mut_, cx.tcx())
1363 let in_trait_class = if trait_.is_some() { " trait-impl" } else { "" };
1365 let mut doc_buffer = Buffer::empty_from(boring);
1366 let mut info_buffer = Buffer::empty_from(boring);
1367 let mut short_documented = true;
1369 if render_method_item {
1370 if !is_default_item {
1371 if let Some(t) = trait_ {
1372 // The trait item may have been stripped so we might not
1373 // find any documentation or stability for it.
1374 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
1375 // We need the stability of the item from the trait
1376 // because impls can't have a stability.
1377 if item.doc_value().is_some() {
1378 document_item_info(&mut info_buffer, cx, it, Some(parent));
1379 document_full(&mut doc_buffer, item, cx, HeadingOffset::H5);
1380 short_documented = false;
1382 // In case the item isn't documented,
1383 // provide short documentation from the trait.
1390 rendering_params.show_def_docs,
1395 document_item_info(&mut info_buffer, cx, item, Some(parent));
1396 if rendering_params.show_def_docs {
1397 document_full(&mut doc_buffer, item, cx, HeadingOffset::H5);
1398 short_documented = false;
1408 rendering_params.show_def_docs,
1412 let w = if short_documented && trait_.is_some() { interesting } else { boring };
1414 let toggled = !doc_buffer.is_empty();
1416 let method_toggle_class =
1417 if item_type == ItemType::Method { " method-toggle" } else { "" };
1418 write!(w, "<details class=\"rustdoc-toggle{}\" open><summary>", method_toggle_class);
1421 clean::MethodItem(..) | clean::TyMethodItem(_) => {
1422 // Only render when the method is not static or we allow static methods
1423 if render_method_item {
1424 let id = cx.derive_id(format!("{}.{}", item_type, name));
1425 let source_id = trait_
1426 .and_then(|trait_| {
1427 trait_.items.iter().find(|item| {
1428 item.name.map(|n| n.as_str().eq(name.as_str())).unwrap_or(false)
1431 .map(|item| format!("{}.{}", item.type_(), name));
1434 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1435 id, item_type, in_trait_class,
1437 render_rightside(w, cx, item, containing_item, render_mode);
1438 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1439 w.write_str("<h4 class=\"code-header\">");
1443 link.anchor(source_id.as_ref().unwrap_or(&id)),
1448 w.write_str("</h4>");
1449 w.write_str("</div>");
1452 clean::TypedefItem(ref tydef, _) => {
1453 let source_id = format!("{}.{}", ItemType::AssocType, name);
1454 let id = cx.derive_id(source_id.clone());
1457 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1458 id, item_type, in_trait_class
1460 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1461 w.write_str("<h4 class=\"code-header\">");
1467 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1471 w.write_str("</h4>");
1472 w.write_str("</div>");
1474 clean::AssocConstItem(ref ty, _) => {
1475 let source_id = format!("{}.{}", item_type, name);
1476 let id = cx.derive_id(source_id.clone());
1479 "<div id=\"{}\" class=\"{}{} has-srclink\">",
1480 id, item_type, in_trait_class
1482 render_rightside(w, cx, item, containing_item, render_mode);
1483 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1484 w.write_str("<h4 class=\"code-header\">");
1489 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1493 w.write_str("</h4>");
1494 w.write_str("</div>");
1496 clean::AssocTypeItem(ref bounds, ref default) => {
1497 let source_id = format!("{}.{}", item_type, name);
1498 let id = cx.derive_id(source_id.clone());
1499 write!(w, "<div id=\"{}\" class=\"{}{}\">", id, item_type, in_trait_class,);
1500 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1501 w.write_str("<h4 class=\"code-header\">");
1507 link.anchor(if trait_.is_some() { &source_id } else { &id }),
1511 w.write_str("</h4>");
1512 w.write_str("</div>");
1514 clean::StrippedItem(..) => return,
1515 _ => panic!("can't make docs for trait item with name {:?}", item.name),
1518 w.push_buffer(info_buffer);
1520 w.write_str("</summary>");
1521 w.push_buffer(doc_buffer);
1522 w.push_str("</details>");
1526 let mut impl_items = Buffer::empty_from(w);
1527 let mut default_impl_items = Buffer::empty_from(w);
1529 for trait_item in &i.inner_impl().items {
1531 &mut default_impl_items,
1535 if trait_.is_some() { &i.impl_item } else { parent },
1540 trait_.map(|t| &t.trait_),
1545 fn render_default_items(
1546 boring: &mut Buffer,
1547 interesting: &mut Buffer,
1551 parent: &clean::Item,
1552 containing_item: &clean::Item,
1553 render_mode: RenderMode,
1554 rendering_params: ImplRenderingParameters,
1556 for trait_item in &t.items {
1557 let n = trait_item.name;
1558 if i.items.iter().any(|m| m.name == n) {
1561 let did = i.trait_.as_ref().unwrap().def_id();
1562 let provided_methods = i.provided_trait_methods(cx.tcx());
1563 let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_methods);
1581 // If we've implemented a trait, then also emit documentation for all
1582 // default items which weren't overridden in the implementation block.
1583 // We don't emit documentation for default items if they appear in the
1584 // Implementations on Foreign Types or Implementors sections.
1585 if rendering_params.show_default_items {
1586 if let Some(t) = trait_ {
1587 render_default_items(
1588 &mut default_impl_items,
1600 if render_mode == RenderMode::Normal {
1601 let toggled = !(impl_items.is_empty() && default_impl_items.is_empty());
1603 close_tags.insert_str(0, "</details>");
1606 "<details class=\"rustdoc-toggle implementors-toggle\"{}>",
1607 if rendering_params.toggle_open_by_default { " open" } else { "" }
1609 write!(w, "<summary>")
1611 render_impl_summary(
1617 rendering_params.show_def_docs,
1619 rendering_params.is_on_foreign_type,
1623 write!(w, "</summary>")
1626 if let Some(ref dox) = i.impl_item.collapsed_doc_value() {
1627 let mut ids = cx.id_map.borrow_mut();
1630 "<div class=\"docblock\">{}</div>",
1633 links: &i.impl_item.links(cx),
1635 error_codes: cx.shared.codes,
1636 edition: cx.shared.edition(),
1637 playground: &cx.shared.playground,
1638 heading_offset: HeadingOffset::H4
1644 if !default_impl_items.is_empty() || !impl_items.is_empty() {
1645 w.write_str("<div class=\"impl-items\">");
1646 w.push_buffer(default_impl_items);
1647 w.push_buffer(impl_items);
1648 close_tags.insert_str(0, "</div>");
1650 w.write_str(&close_tags);
1653 // Render the items that appear on the right side of methods, impls, and
1654 // associated types. For example "1.0.0 (const: 1.39.0) · source".
1655 fn render_rightside(
1659 containing_item: &clean::Item,
1660 render_mode: RenderMode,
1664 // FIXME: Once https://github.com/rust-lang/rust/issues/67792 is implemented, we can remove
1666 let (const_stability, const_stable_since) = match render_mode {
1667 RenderMode::Normal => (item.const_stability(tcx), containing_item.const_stable_since(tcx)),
1668 RenderMode::ForDeref { .. } => (None, None),
1671 write!(w, "<div class=\"rightside\">");
1672 let has_stability = render_stability_since_raw(
1674 item.stable_since(tcx),
1676 containing_item.stable_since(tcx),
1680 w.write_str(" · ");
1683 write_srclink(cx, item, w);
1684 w.write_str("</div>");
1687 pub(crate) fn render_impl_summary(
1691 parent: &clean::Item,
1692 containing_item: &clean::Item,
1693 show_def_docs: bool,
1694 use_absolute: Option<bool>,
1695 is_on_foreign_type: bool,
1696 // This argument is used to reference same type with different paths to avoid duplication
1697 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
1700 let id = cx.derive_id(match i.inner_impl().trait_ {
1702 if is_on_foreign_type {
1703 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t, cx)
1705 format!("impl-{}", small_url_encode(format!("{:#}", t.print(cx))))
1708 None => "impl".to_string(),
1710 let aliases = if aliases.is_empty() {
1713 format!(" data-aliases=\"{}\"", aliases.join(","))
1715 write!(w, "<div id=\"{}\" class=\"impl has-srclink\"{}>", id, aliases);
1716 render_rightside(w, cx, &i.impl_item, containing_item, RenderMode::Normal);
1717 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1718 write!(w, "<h3 class=\"code-header in-band\">");
1720 if let Some(use_absolute) = use_absolute {
1721 write!(w, "{}", i.inner_impl().print(use_absolute, cx));
1723 for it in &i.inner_impl().items {
1724 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1725 w.write_str("<span class=\"where fmt-newline\"> ");
1726 assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "", cx);
1727 w.write_str(";</span>");
1732 write!(w, "{}", i.inner_impl().print(false, cx));
1736 let is_trait = i.inner_impl().trait_.is_some();
1738 if let Some(portability) = portability(&i.impl_item, Some(parent)) {
1739 write!(w, "<div class=\"item-info\">{}</div>", portability);
1743 w.write_str("</div>");
1746 fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) {
1747 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
1751 || it.is_primitive()
1759 "<h2 class=\"location\">{}{}</h2>",
1761 clean::StructItem(..) => "Struct ",
1762 clean::TraitItem(..) => "Trait ",
1763 clean::PrimitiveItem(..) => "Primitive Type ",
1764 clean::UnionItem(..) => "Union ",
1765 clean::EnumItem(..) => "Enum ",
1766 clean::TypedefItem(..) => "Type Definition ",
1767 clean::ForeignTypeItem => "Foreign Type ",
1768 clean::ModuleItem(..) =>
1776 it.name.as_ref().unwrap()
1781 if let Some(ref version) = cx.cache().crate_version {
1784 "<div class=\"block version\">\
1785 <div class=\"narrow-helper\"></div>\
1793 buffer.write_str("<div class=\"sidebar-elems\">");
1797 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
1798 it.name.as_ref().expect("crates always have a name"),
1803 clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s),
1804 clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t),
1805 clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it),
1806 clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u),
1807 clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e),
1808 clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it),
1809 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
1810 clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, it),
1814 // The sidebar is designed to display sibling functions, modules and
1815 // other miscellaneous information. since there are lots of sibling
1816 // items (and that causes quadratic growth in large modules),
1817 // we refactor common parts into a shared JavaScript file per module.
1818 // still, we don't move everything into JS because we want to preserve
1819 // as much HTML as possible in order to allow non-JS-enabled browsers
1820 // to navigate the documentation (though slightly inefficiently).
1823 buffer.write_str("<h2 class=\"location\">Other items in<br>");
1824 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
1826 buffer.write_str("::<wbr>");
1830 "<a href=\"{}index.html\">{}</a>",
1831 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
1835 buffer.write_str("</h2>");
1838 // Sidebar refers to the enclosing module, not this module.
1839 let relpath = if it.is_mod() && parentlen != 0 { "./" } else { "" };
1842 "<div id=\"sidebar-vars\" data-name=\"{name}\" data-ty=\"{ty}\" data-relpath=\"{path}\">\
1844 name = it.name.unwrap_or(kw::Empty),
1850 "<script defer src=\"{}sidebar-items{}.js\"></script>",
1851 relpath, cx.shared.resource_suffix
1853 // Closes sidebar-elems div.
1854 buffer.write_str("</div>");
1857 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
1858 if used_links.insert(url.clone()) {
1862 while !used_links.insert(format!("{}-{}", url, add)) {
1865 format!("{}-{}", url, add)
1868 struct SidebarLink {
1873 impl fmt::Display for SidebarLink {
1874 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1875 write!(f, "<a href=\"#{}\">{}</a>", self.url, self.name)
1879 impl PartialEq for SidebarLink {
1880 fn eq(&self, other: &Self) -> bool {
1881 self.url == other.url
1885 impl Eq for SidebarLink {}
1887 impl PartialOrd for SidebarLink {
1888 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1889 Some(self.cmp(other))
1893 impl Ord for SidebarLink {
1894 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1895 self.url.cmp(&other.url)
1902 used_links: &mut FxHashSet<String>,
1905 ) -> Vec<SidebarLink> {
1908 .filter_map(|item| match item.name {
1909 Some(name) if !name.is_empty() && item.is_method() => {
1910 if !for_deref || should_render_item(item, deref_mut, tcx) {
1913 url: get_next_url(used_links, format!("method.{}", name)),
1921 .collect::<Vec<_>>()
1924 fn get_associated_constants(
1926 used_links: &mut FxHashSet<String>,
1927 ) -> Vec<SidebarLink> {
1930 .filter_map(|item| match item.name {
1931 Some(name) if !name.is_empty() && item.is_associated_const() => Some(SidebarLink {
1933 url: get_next_url(used_links, format!("associatedconstant.{}", name)),
1937 .collect::<Vec<_>>()
1940 // The point is to url encode any potential character from a type with genericity.
1941 fn small_url_encode(s: String) -> String {
1942 let mut st = String::new();
1943 let mut last_match = 0;
1944 for (idx, c) in s.char_indices() {
1945 let escaped = match c {
1961 st += &s[last_match..idx];
1963 // NOTE: we only expect single byte characters here - which is fine as long as we
1964 // only match single byte characters
1965 last_match = idx + 1;
1968 if last_match != 0 {
1969 st += &s[last_match..];
1976 fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) {
1977 let did = it.def_id.expect_def_id();
1978 let cache = cx.cache();
1979 if let Some(v) = cache.impls.get(&did) {
1980 let mut used_links = FxHashSet::default();
1983 let used_links_bor = &mut used_links;
1984 let mut assoc_consts = v
1986 .flat_map(|i| get_associated_constants(i.inner_impl(), used_links_bor))
1987 .collect::<Vec<_>>();
1988 if !assoc_consts.is_empty() {
1989 // We want links' order to be reproducible so we don't use unstable sort.
1990 assoc_consts.sort();
1993 "<h3 class=\"sidebar-title\">\
1994 <a href=\"#implementations\">Associated Constants</a>\
1996 <div class=\"sidebar-links\">",
1998 for line in assoc_consts {
1999 write!(out, "{}", line);
2001 out.push_str("</div>");
2005 .filter(|i| i.inner_impl().trait_.is_none())
2006 .flat_map(|i| get_methods(i.inner_impl(), false, used_links_bor, false, cx.tcx()))
2007 .collect::<Vec<_>>();
2008 if !methods.is_empty() {
2009 // We want links' order to be reproducible so we don't use unstable sort.
2013 "<h3 class=\"sidebar-title\"><a href=\"#implementations\">Methods</a></h3>\
2014 <div class=\"sidebar-links\">",
2016 for line in methods {
2017 write!(out, "{}", line);
2019 out.push_str("</div>");
2023 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
2024 if let Some(impl_) =
2025 v.iter().find(|i| i.trait_did() == cx.tcx().lang_items().deref_trait())
2027 let mut derefs = FxHashSet::default();
2029 sidebar_deref_methods(cx, out, impl_, v, &mut derefs);
2032 let format_impls = |impls: Vec<&Impl>| {
2033 let mut links = FxHashSet::default();
2038 if let Some(ref i) = it.inner_impl().trait_ {
2039 let i_display = format!("{:#}", i.print(cx));
2040 let out = Escape(&i_display);
2041 let encoded = small_url_encode(format!("{:#}", i.print(cx)));
2042 let prefix = match it.inner_impl().polarity {
2043 ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => "",
2044 ty::ImplPolarity::Negative => "!",
2047 format!("<a href=\"#impl-{}\">{}{}</a>", encoded, prefix, out);
2048 if links.insert(generated.clone()) { Some(generated) } else { None }
2053 .collect::<Vec<String>>();
2058 let write_sidebar_links = |out: &mut Buffer, links: Vec<String>| {
2059 out.push_str("<div class=\"sidebar-links\">");
2061 out.push_str(&link);
2063 out.push_str("</div>");
2066 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
2067 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().kind.is_auto());
2068 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) =
2069 concrete.into_iter().partition::<Vec<_>, _>(|i| i.inner_impl().kind.is_blanket());
2071 let concrete_format = format_impls(concrete);
2072 let synthetic_format = format_impls(synthetic);
2073 let blanket_format = format_impls(blanket_impl);
2075 if !concrete_format.is_empty() {
2077 "<h3 class=\"sidebar-title\"><a href=\"#trait-implementations\">\
2078 Trait Implementations</a></h3>",
2080 write_sidebar_links(out, concrete_format);
2083 if !synthetic_format.is_empty() {
2085 "<h3 class=\"sidebar-title\"><a href=\"#synthetic-implementations\">\
2086 Auto Trait Implementations</a></h3>",
2088 write_sidebar_links(out, synthetic_format);
2091 if !blanket_format.is_empty() {
2093 "<h3 class=\"sidebar-title\"><a href=\"#blanket-implementations\">\
2094 Blanket Implementations</a></h3>",
2096 write_sidebar_links(out, blanket_format);
2102 fn sidebar_deref_methods(
2107 derefs: &mut FxHashSet<DefId>,
2111 debug!("found Deref: {:?}", impl_);
2112 if let Some((target, real_target)) =
2113 impl_.inner_impl().items.iter().find_map(|item| match *item.kind {
2114 clean::TypedefItem(ref t, true) => Some(match *t {
2115 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
2116 _ => (&t.type_, &t.type_),
2121 debug!("found target, real_target: {:?} {:?}", target, real_target);
2122 if let Some(did) = target.def_id(c) {
2123 if let Some(type_did) = impl_.inner_impl().for_.def_id(c) {
2124 // `impl Deref<Target = S> for S`
2125 if did == type_did || !derefs.insert(did) {
2126 // Avoid infinite cycles
2131 let deref_mut = v.iter().any(|i| i.trait_did() == cx.tcx().lang_items().deref_mut_trait());
2132 let inner_impl = target
2135 target.primitive_type().and_then(|prim| c.primitive_locations.get(&prim).cloned())
2137 .and_then(|did| c.impls.get(&did));
2138 if let Some(impls) = inner_impl {
2139 debug!("found inner_impl: {:?}", impls);
2140 let mut used_links = FxHashSet::default();
2143 .filter(|i| i.inner_impl().trait_.is_none())
2145 get_methods(i.inner_impl(), true, &mut used_links, deref_mut, cx.tcx())
2147 .collect::<Vec<_>>();
2148 if !ret.is_empty() {
2150 let id = if let Some(target_def_id) = real_target.def_id(c) {
2151 map = cx.deref_id_map.borrow();
2152 map.get(&target_def_id).expect("Deref section without derived id")
2158 "<h3 class=\"sidebar-title\"><a href=\"#{}\">Methods from {}<Target={}></a></h3>",
2160 Escape(&format!("{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print(cx))),
2161 Escape(&format!("{:#}", real_target.print(cx))),
2163 // We want links' order to be reproducible so we don't use unstable sort.
2165 out.push_str("<div class=\"sidebar-links\">");
2167 write!(out, "{}", link);
2169 out.push_str("</div>");
2173 // Recurse into any further impls that might exist for `target`
2174 if let Some(target_did) = target.def_id(c) {
2175 if let Some(target_impls) = c.impls.get(&target_did) {
2176 if let Some(target_deref_impl) = target_impls.iter().find(|i| {
2180 .map(|t| Some(t.def_id()) == cx.tcx().lang_items().deref_trait())
2183 sidebar_deref_methods(cx, out, target_deref_impl, target_impls, derefs);
2190 fn sidebar_struct(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
2191 let mut sidebar = Buffer::new();
2192 let fields = get_struct_fields_name(&s.fields);
2194 if !fields.is_empty() {
2195 if let CtorKind::Fictive = s.struct_type {
2197 "<h3 class=\"sidebar-title\"><a href=\"#fields\">Fields</a></h3>\
2198 <div class=\"sidebar-links\">",
2201 for field in fields {
2202 sidebar.push_str(&field);
2205 sidebar.push_str("</div>");
2206 } else if let CtorKind::Fn = s.struct_type {
2208 .push_str("<h3 class=\"sidebar-title\"><a href=\"#fields\">Tuple Fields</a></h3>");
2212 sidebar_assoc_items(cx, &mut sidebar, it);
2214 if !sidebar.is_empty() {
2215 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2219 fn get_id_for_impl_on_foreign_type(
2221 trait_: &clean::Path,
2224 small_url_encode(format!("impl-{:#}-for-{:#}", trait_.print(cx), for_.print(cx)))
2227 fn extract_for_impl_name(item: &clean::Item, cx: &Context<'_>) -> Option<(String, String)> {
2229 clean::ItemKind::ImplItem(ref i) => {
2230 i.trait_.as_ref().map(|trait_| {
2231 // Alternative format produces no URLs,
2232 // so this parameter does nothing.
2234 format!("{:#}", i.for_.print(cx)),
2235 get_id_for_impl_on_foreign_type(&i.for_, trait_, cx),
2243 fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
2244 buf.write_str("<div class=\"block items\">");
2246 fn print_sidebar_section(
2248 items: &[clean::Item],
2250 filter: impl Fn(&clean::Item) -> bool,
2251 write: impl Fn(&mut Buffer, &str),
2254 let mut items = items
2256 .filter_map(|m| match m.name {
2257 Some(ref name) if filter(m) => Some(name.as_str()),
2260 .collect::<Vec<_>>();
2262 if !items.is_empty() {
2263 items.sort_unstable();
2264 out.push_str(before);
2265 for item in items.into_iter() {
2268 out.push_str(after);
2272 print_sidebar_section(
2275 "<h3 class=\"sidebar-title\"><a href=\"#associated-types\">\
2276 Associated Types</a></h3><div class=\"sidebar-links\">",
2277 |m| m.is_associated_type(),
2278 |out, sym| write!(out, "<a href=\"#associatedtype.{0}\">{0}</a>", sym),
2282 print_sidebar_section(
2285 "<h3 class=\"sidebar-title\"><a href=\"#associated-const\">\
2286 Associated Constants</a></h3><div class=\"sidebar-links\">",
2287 |m| m.is_associated_const(),
2288 |out, sym| write!(out, "<a href=\"#associatedconstant.{0}\">{0}</a>", sym),
2292 print_sidebar_section(
2295 "<h3 class=\"sidebar-title\"><a href=\"#required-methods\">\
2296 Required Methods</a></h3><div class=\"sidebar-links\">",
2297 |m| m.is_ty_method(),
2298 |out, sym| write!(out, "<a href=\"#tymethod.{0}\">{0}</a>", sym),
2302 print_sidebar_section(
2305 "<h3 class=\"sidebar-title\"><a href=\"#provided-methods\">\
2306 Provided Methods</a></h3><div class=\"sidebar-links\">",
2308 |out, sym| write!(out, "<a href=\"#method.{0}\">{0}</a>", sym),
2312 let cache = cx.cache();
2313 if let Some(implementors) = cache.implementors.get(&it.def_id.expect_def_id()) {
2314 let mut res = implementors
2317 i.inner_impl().for_.def_id(cache).map_or(false, |d| !cache.paths.contains_key(&d))
2319 .filter_map(|i| extract_for_impl_name(&i.impl_item, cx))
2320 .collect::<Vec<_>>();
2322 if !res.is_empty() {
2325 "<h3 class=\"sidebar-title\"><a href=\"#foreign-impls\">\
2326 Implementations on Foreign Types</a></h3>\
2327 <div class=\"sidebar-links\">",
2329 for (name, id) in res.into_iter() {
2330 write!(buf, "<a href=\"#{}\">{}</a>", id, Escape(&name));
2332 buf.push_str("</div>");
2336 sidebar_assoc_items(cx, buf, it);
2338 buf.push_str("<h3 class=\"sidebar-title\"><a href=\"#implementors\">Implementors</a></h3>");
2341 "<h3 class=\"sidebar-title\"><a \
2342 href=\"#synthetic-implementors\">Auto Implementors</a></h3>",
2346 buf.push_str("</div>")
2349 fn sidebar_primitive(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2350 let mut sidebar = Buffer::new();
2351 sidebar_assoc_items(cx, &mut sidebar, it);
2353 if !sidebar.is_empty() {
2354 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2358 fn sidebar_typedef(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2359 let mut sidebar = Buffer::new();
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 get_struct_fields_name(fields: &[clean::Item]) -> Vec<String> {
2368 let mut fields = fields
2370 .filter(|f| matches!(*f.kind, clean::StructFieldItem(..)))
2372 f.name.map(|name| format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
2374 .collect::<Vec<_>>();
2379 fn sidebar_union(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
2380 let mut sidebar = Buffer::new();
2381 let fields = get_struct_fields_name(&u.fields);
2383 if !fields.is_empty() {
2385 "<h3 class=\"sidebar-title\"><a href=\"#fields\">Fields</a></h3>\
2386 <div class=\"sidebar-links\">",
2389 for field in fields {
2390 sidebar.push_str(&field);
2393 sidebar.push_str("</div>");
2396 sidebar_assoc_items(cx, &mut sidebar, it);
2398 if !sidebar.is_empty() {
2399 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2403 fn sidebar_enum(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
2404 let mut sidebar = Buffer::new();
2406 let mut variants = e
2412 .map(|name| format!("<a href=\"#variant.{name}\">{name}</a>", name = name))
2414 .collect::<Vec<_>>();
2415 if !variants.is_empty() {
2416 variants.sort_unstable();
2417 sidebar.push_str(&format!(
2418 "<h3 class=\"sidebar-title\"><a href=\"#variants\">Variants</a></h3>\
2419 <div class=\"sidebar-links\">{}</div>",
2424 sidebar_assoc_items(cx, &mut sidebar, it);
2426 if !sidebar.is_empty() {
2427 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2431 fn item_ty_to_strs(ty: ItemType) -> (&'static str, &'static str) {
2433 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
2434 ItemType::Module => ("modules", "Modules"),
2435 ItemType::Struct => ("structs", "Structs"),
2436 ItemType::Union => ("unions", "Unions"),
2437 ItemType::Enum => ("enums", "Enums"),
2438 ItemType::Function => ("functions", "Functions"),
2439 ItemType::Typedef => ("types", "Type Definitions"),
2440 ItemType::Static => ("statics", "Statics"),
2441 ItemType::Constant => ("constants", "Constants"),
2442 ItemType::Trait => ("traits", "Traits"),
2443 ItemType::Impl => ("impls", "Implementations"),
2444 ItemType::TyMethod => ("tymethods", "Type Methods"),
2445 ItemType::Method => ("methods", "Methods"),
2446 ItemType::StructField => ("fields", "Struct Fields"),
2447 ItemType::Variant => ("variants", "Variants"),
2448 ItemType::Macro => ("macros", "Macros"),
2449 ItemType::Primitive => ("primitives", "Primitive Types"),
2450 ItemType::AssocType => ("associated-types", "Associated Types"),
2451 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
2452 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
2453 ItemType::Keyword => ("keywords", "Keywords"),
2454 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
2455 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
2456 ItemType::ProcDerive => ("derives", "Derive Macros"),
2457 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
2458 ItemType::Generic => unreachable!(),
2462 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
2463 let mut sidebar = String::new();
2465 // Re-exports are handled a bit differently because they can be extern crates or imports.
2466 if items.iter().any(|it| {
2468 && (it.type_() == ItemType::ExternCrate
2469 || (it.type_() == ItemType::Import && !it.is_stripped()))
2471 let (id, name) = item_ty_to_strs(ItemType::Import);
2472 sidebar.push_str(&format!("<li><a href=\"#{}\">{}</a></li>", id, name));
2475 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
2476 // to print its headings
2478 ItemType::Primitive,
2492 ItemType::StructField,
2494 ItemType::AssocType,
2495 ItemType::AssocConst,
2496 ItemType::ForeignType,
2499 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty && it.name.is_some()) {
2500 let (id, name) = item_ty_to_strs(myty);
2501 sidebar.push_str(&format!("<li><a href=\"#{}\">{}</a></li>", id, name));
2505 if !sidebar.is_empty() {
2506 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
2510 fn sidebar_foreign_type(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2511 let mut sidebar = Buffer::new();
2512 sidebar_assoc_items(cx, &mut sidebar, it);
2514 if !sidebar.is_empty() {
2515 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2519 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
2521 /// Returns a list of all paths used in the type.
2522 /// This is used to help deduplicate imported impls
2523 /// for reexported types. If any of the contained
2524 /// types are re-exported, we don't use the corresponding
2525 /// entry from the js file, as inlining will have already
2526 /// picked up the impl
2527 fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> {
2528 let mut out = Vec::new();
2529 let mut visited = FxHashSet::default();
2530 let mut work = VecDeque::new();
2532 let mut process_path = |did: DefId| {
2533 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
2534 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
2536 if let Some(path) = fqp {
2537 out.push(path.join("::"));
2541 work.push_back(first_ty);
2543 while let Some(ty) = work.pop_front() {
2544 if !visited.insert(ty.clone()) {
2549 clean::Type::Path { path } => process_path(path.def_id()),
2550 clean::Type::Tuple(tys) => {
2551 work.extend(tys.into_iter());
2553 clean::Type::Slice(ty) => {
2554 work.push_back(*ty);
2556 clean::Type::Array(ty, _) => {
2557 work.push_back(*ty);
2559 clean::Type::RawPointer(_, ty) => {
2560 work.push_back(*ty);
2562 clean::Type::BorrowedRef { type_, .. } => {
2563 work.push_back(*type_);
2565 clean::Type::QPath { self_type, trait_, .. } => {
2566 work.push_back(*self_type);
2567 process_path(trait_.def_id());
2575 const MAX_FULL_EXAMPLES: usize = 5;
2576 const NUM_VISIBLE_LINES: usize = 10;
2578 /// Generates the HTML for example call locations generated via the --scrape-examples flag.
2579 fn render_call_locations(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item) {
2581 let def_id = item.def_id.expect_def_id();
2582 let key = tcx.def_path_hash(def_id);
2583 let call_locations = match cx.shared.call_locations.get(&key) {
2584 Some(call_locations) => call_locations,
2590 // Generate a unique ID so users can link to this section for a given method
2591 let id = cx.id_map.borrow_mut().derive("scraped-examples");
2594 "<div class=\"docblock scraped-example-list\">\
2596 <h5 id=\"{id}\" class=\"section-header\">\
2597 <a href=\"#{id}\">Examples found in repository</a>\
2602 // Create a URL to a particular location in a reverse-dependency's source file
2603 let link_to_loc = |call_data: &CallData, loc: &CallLocation| -> (String, String) {
2604 let (line_lo, line_hi) = loc.call_expr.line_span;
2605 let (anchor, title) = if line_lo == line_hi {
2606 ((line_lo + 1).to_string(), format!("line {}", line_lo + 1))
2609 format!("{}-{}", line_lo + 1, line_hi + 1),
2610 format!("lines {}-{}", line_lo + 1, line_hi + 1),
2613 let url = format!("{}{}#{}", cx.root_path(), call_data.url, anchor);
2617 // Generate the HTML for a single example, being the title and code block
2618 let write_example = |w: &mut Buffer, (path, call_data): (&PathBuf, &CallData)| -> bool {
2619 let contents = match fs::read_to_string(&path) {
2620 Ok(contents) => contents,
2622 let span = item.span(tcx).inner();
2624 .span_err(span, &format!("failed to read file {}: {}", path.display(), err));
2629 // To reduce file sizes, we only want to embed the source code needed to understand the example, not
2630 // the entire file. So we find the smallest byte range that covers all items enclosing examples.
2631 assert!(!call_data.locations.is_empty());
2633 call_data.locations.iter().min_by_key(|loc| loc.enclosing_item.byte_span.0).unwrap();
2634 let byte_min = min_loc.enclosing_item.byte_span.0;
2635 let line_min = min_loc.enclosing_item.line_span.0;
2637 call_data.locations.iter().max_by_key(|loc| loc.enclosing_item.byte_span.1).unwrap();
2638 let byte_max = max_loc.enclosing_item.byte_span.1;
2639 let line_max = max_loc.enclosing_item.line_span.1;
2641 // The output code is limited to that byte range.
2642 let contents_subset = &contents[(byte_min as usize)..(byte_max as usize)];
2644 // The call locations need to be updated to reflect that the size of the program has changed.
2645 // Specifically, the ranges are all subtracted by `byte_min` since that's the new zero point.
2646 let (mut byte_ranges, line_ranges): (Vec<_>, Vec<_>) = call_data
2650 let (byte_lo, byte_hi) = loc.call_expr.byte_span;
2651 let (line_lo, line_hi) = loc.call_expr.line_span;
2652 let byte_range = (byte_lo - byte_min, byte_hi - byte_min);
2653 let line_range = (line_lo - line_min, line_hi - line_min);
2654 let (line_url, line_title) = link_to_loc(call_data, loc);
2656 (byte_range, (line_range, line_url, line_title))
2660 let (_, init_url, init_title) = &line_ranges[0];
2661 let needs_expansion = line_max - line_min > NUM_VISIBLE_LINES;
2662 let locations_encoded = serde_json::to_string(&line_ranges).unwrap();
2666 "<div class=\"scraped-example {expanded_cls}\" data-locs=\"{locations}\">\
2667 <div class=\"scraped-example-title\">\
2668 {name} (<a href=\"{url}\">{title}</a>)\
2670 <div class=\"code-wrapper\">",
2671 expanded_cls = if needs_expansion { "" } else { "expanded" },
2672 name = call_data.display_name,
2675 // The locations are encoded as a data attribute, so they can be read
2676 // later by the JS for interactions.
2677 locations = Escape(&locations_encoded)
2680 if line_ranges.len() > 1 {
2681 write!(w, r#"<span class="prev">≺</span> <span class="next">≻</span>"#);
2684 if needs_expansion {
2685 write!(w, r#"<span class="expand">↕</span>"#);
2688 // Look for the example file in the source map if it exists, otherwise return a dummy span
2689 let file_span = (|| {
2690 let source_map = tcx.sess.source_map();
2691 let crate_src = tcx.sess.local_crate_source_file.as_ref()?;
2692 let abs_crate_src = crate_src.canonicalize().ok()?;
2693 let crate_root = abs_crate_src.parent()?.parent()?;
2694 let rel_path = path.strip_prefix(crate_root).ok()?;
2695 let files = source_map.files();
2696 let file = files.iter().find(|file| match &file.name {
2697 FileName::Real(RealFileName::LocalPath(other_path)) => rel_path == other_path,
2700 Some(rustc_span::Span::with_root_ctxt(
2701 file.start_pos + BytePos(byte_min),
2702 file.start_pos + BytePos(byte_max),
2705 .unwrap_or(rustc_span::DUMMY_SP);
2707 // The root path is the inverse of Context::current
2708 let root_path = vec!["../"; cx.current.len() - 1].join("");
2710 let mut decoration_info = FxHashMap::default();
2711 decoration_info.insert("highlight focus", vec![byte_ranges.remove(0)]);
2712 decoration_info.insert("highlight", byte_ranges);
2721 Some(highlight::DecorationInfo(decoration_info)),
2722 sources::SourceContext::Embedded { offset: line_min },
2724 write!(w, "</div></div>");
2729 // The call locations are output in sequence, so that sequence needs to be determined.
2730 // Ideally the most "relevant" examples would be shown first, but there's no general algorithm
2731 // for determining relevance. Instead, we prefer the smallest examples being likely the easiest to
2732 // understand at a glance.
2733 let ordered_locations = {
2734 let sort_criterion = |(_, call_data): &(_, &CallData)| {
2735 // Use the first location because that's what the user will see initially
2736 let (lo, hi) = call_data.locations[0].enclosing_item.byte_span;
2740 let mut locs = call_locations.into_iter().collect::<Vec<_>>();
2741 locs.sort_by_key(sort_criterion);
2745 let mut it = ordered_locations.into_iter().peekable();
2747 // An example may fail to write if its source can't be read for some reason, so this method
2748 // continues iterating until a write suceeds
2749 let write_and_skip_failure = |w: &mut Buffer, it: &mut Peekable<_>| {
2750 while let Some(example) = it.next() {
2751 if write_example(&mut *w, example) {
2757 // Write just one example that's visible by default in the method's description.
2758 write_and_skip_failure(w, &mut it);
2760 // Then add the remaining examples in a hidden section.
2761 if it.peek().is_some() {
2764 "<details class=\"rustdoc-toggle more-examples-toggle\">\
2765 <summary class=\"hideme\">\
2766 <span>More examples</span>\
2768 <div class=\"more-scraped-examples\">\
2769 <div class=\"toggle-line\"><div class=\"toggle-line-inner\"></div></div>\
2770 <div class=\"more-scraped-examples-inner\">"
2773 // Only generate inline code for MAX_FULL_EXAMPLES number of examples. Otherwise we could
2774 // make the page arbitrarily huge!
2775 for _ in 0..MAX_FULL_EXAMPLES {
2776 write_and_skip_failure(w, &mut it);
2779 // For the remaining examples, generate a <ul> containing links to the source files.
2780 if it.peek().is_some() {
2781 write!(w, r#"<div class="example-links">Additional examples can be found in:<br><ul>"#);
2782 it.for_each(|(_, call_data)| {
2783 let (url, _) = link_to_loc(&call_data, &call_data.locations[0]);
2786 r#"<li><a href="{url}">{name}</a></li>"#,
2788 name = call_data.display_name
2791 write!(w, "</ul></div>");
2794 write!(w, "</div></div></details>");
2797 write!(w, "</div>");