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.
36 crate use write_shared
::FILES_UNVERSIONED
;
38 use std
::cell
::{Cell, RefCell}
;
39 use std
::collections
::VecDeque
;
40 use std
::default::Default
;
42 use std
::path
::{Path, PathBuf}
;
44 use std
::string
::ToString
;
45 use std
::sync
::mpsc
::Receiver
;
47 use itertools
::Itertools
;
48 use rustc_ast_pretty
::pprust
;
49 use rustc_attr
::{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
;
56 use rustc_middle
::ty
::TyCtxt
;
57 use rustc_span
::edition
::Edition
;
58 use rustc_span
::symbol
::{kw, sym, Symbol}
;
59 use serde
::ser
::SerializeSeq
;
60 use serde
::{Serialize, Serializer}
;
62 use crate::clean
::{self, GetDefId, RenderedLink, SelfTy, TypeKind}
;
63 use crate::docfs
::{DocFS, PathError}
;
64 use crate::error
::Error
;
65 use crate::formats
::cache
::Cache
;
66 use crate::formats
::item_type
::ItemType
;
67 use crate::formats
::{AssocItemRender, FormatRenderer, Impl, RenderMode}
;
68 use crate::html
::escape
::Escape
;
69 use crate::html
::format
::{
70 href
, print_abi_with_space
, print_default_space
, print_generic_bounds
, Buffer
, Function
,
71 PrintWithSpace
, WhereClause
,
73 use crate::html
::layout
;
74 use crate::html
::markdown
::{self, ErrorCodes, Markdown, MarkdownHtml, MarkdownSummaryLine}
;
76 /// A pair of name and its optional document.
77 crate type NameDoc
= (String
, Option
<String
>);
79 crate fn ensure_trailing_slash(v
: &str) -> impl fmt
::Display
+ '_
{
80 crate::html
::format
::display_fn(move |f
| {
81 if !v
.ends_with('
/'
) && !v
.is_empty() { write!(f, "{}
/", v) } else { f.write_str(v) }
85 /// Shared mutable state used in [`Context`] and elsewhere.
86 crate struct SharedContext<'tcx> {
87 crate tcx: TyCtxt<'tcx>,
88 /// The path to the crate root source minus the file name.
89 /// Used for simplifying paths to the highlighted source code files.
90 crate src_root: PathBuf,
91 /// This describes the layout of each page, and is not modified after
92 /// creation of the context (contains info like the favicon and added html).
93 crate layout: layout::Layout,
94 /// This flag indicates whether `[src]` links should be generated or not. If
95 /// the source files are present in the html rendering, then this will be
97 crate include_sources: bool,
98 /// The local file sources we've emitted and their respective url-paths.
99 crate local_sources: FxHashMap<PathBuf, String>,
100 /// Whether the collapsed pass ran
102 /// The base-URL of the issue tracker for when an item has been tagged with
104 issue_tracker_base_url: Option<String>,
105 /// The directories that have already been created in this doc run. Used to reduce the number
106 /// of spurious `create_dir_all` calls.
107 created_dirs: RefCell<FxHashSet<PathBuf>>,
108 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
109 /// should be ordered alphabetically or in order of appearance (in the source code).
110 sort_modules_alphabetically: bool,
111 /// Additional CSS files to be added to the generated docs.
112 crate style_files: Vec<StylePath>,
113 /// Suffix to be added on resource files (if suffix is "-v2
" then "light
.css
" becomes
115 crate resource_suffix: String,
116 /// Optional path string to be used to load static files on output pages. If not set, uses
117 /// combinations of `../` to reach the documentation root.
118 crate static_root_path: Option<String>,
119 /// The fs handle we are working with.
121 /// The default edition used to parse doctests.
122 crate edition: Edition,
124 playground: Option<markdown::Playground>,
125 all: RefCell<AllTypes>,
126 /// Storage for the errors produced while generating documentation so they
127 /// can be printed together at the end.
128 errors: Receiver<String>,
129 /// `None` by default, depends on the `generate-redirect-map` option flag. If this field is set
130 /// to `Some(...)`, it'll store redirections and then generate a JSON file at the top level of
132 redirections: Option<RefCell<FxHashMap<String, String>>>,
135 impl SharedContext<'_> {
136 crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
137 let mut dirs = self.created_dirs.borrow_mut();
138 if !dirs.contains(dst) {
139 try_err!(self.fs.create_dir_all(dst), dst);
140 dirs.insert(dst.to_path_buf());
146 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
147 /// `collapsed_doc_value` of the given item.
148 crate fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<String> {
149 if self.collapsed { item.collapsed_doc_value() } else { item.doc_value() }
153 // Helper structs for rendering items/sidebars and carrying along contextual
156 /// Struct representing one entry in the JS search index. These are all emitted
157 /// by hand to a large JS file at the end of cache-creation.
159 crate struct IndexItem {
164 crate parent: Option<DefId>,
165 crate parent_idx: Option<usize>,
166 crate search_type: Option<IndexItemFunctionType>,
169 /// A type used for the search index.
171 crate struct RenderType {
174 name: Option<String>,
175 generics: Option<Vec<Generic>>,
178 impl Serialize for RenderType {
179 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
183 if let Some(name) = &self.name {
184 let mut seq = serializer.serialize_seq(None)?;
185 if let Some(id) = self.idx {
186 seq.serialize_element(&id)?;
188 seq.serialize_element(&name)?;
190 if let Some(generics) = &self.generics {
191 seq.serialize_element(&generics)?;
195 serializer.serialize_none()
200 /// A type used for the search index.
202 crate struct Generic {
204 defid: Option<DefId>,
208 impl Serialize for Generic {
209 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
213 if let Some(id) = self.idx {
214 serializer.serialize_some(&id)
216 serializer.serialize_some(&self.name)
221 /// Full type of functions/methods in the search index.
223 crate struct IndexItemFunctionType {
224 inputs: Vec<TypeWithKind>,
225 output: Option<Vec<TypeWithKind>>,
228 impl Serialize for IndexItemFunctionType {
229 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
233 // If we couldn't figure out a type, just write `null`.
234 let mut iter = self.inputs.iter();
235 if match self.output {
236 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
237 None => iter.any(|ref i| i.ty.name.is_none()),
239 serializer.serialize_none()
241 let mut seq = serializer.serialize_seq(None)?;
242 seq.serialize_element(&self.inputs)?;
243 if let Some(output) = &self.output {
244 if output.len() > 1 {
245 seq.serialize_element(&output)?;
247 seq.serialize_element(&output[0])?;
256 crate struct TypeWithKind {
261 impl From<(RenderType, TypeKind)> for TypeWithKind {
262 fn from(x: (RenderType, TypeKind)) -> TypeWithKind {
263 TypeWithKind { ty: x.0, kind: x.1 }
267 impl Serialize for TypeWithKind {
268 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
272 (&self.ty.name, ItemType::from(self.kind)).serialize(serializer)
276 #[derive(Debug, Clone)]
277 crate struct StylePath {
278 /// The path to the theme
280 /// What the `disabled` attribute should be set to in the HTML tag
281 crate disabled: bool,
284 thread_local!(crate static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
286 crate const INITIAL_IDS: [&'static str; 15] = [
297 "synthetic
-implementors
",
299 "synthetic
-implementors
-list
",
304 fn write_srclink(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) {
305 if let Some(l) = cx.src_href(item) {
306 write!(buf, "<a class
=\"srclink
\" href
=\"{}
\" title
=\"goto source code
\">[src
]</a
>", l)
310 #[derive(Debug, Eq, PartialEq, Hash)]
317 fn new(mut url: String, name: String) -> ItemEntry {
318 while url.starts_with('/') {
321 ItemEntry { url, name }
326 crate fn print(&self) -> impl fmt::Display + '_ {
327 crate::html::format::display_fn(move |f| {
328 write!(f, "<a href
=\"{}
\">{}
</a
>", self.url, Escape(&self.name))
333 impl PartialOrd for ItemEntry {
334 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
335 Some(self.cmp(other))
339 impl Ord for ItemEntry {
340 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
341 self.name.cmp(&other.name)
347 structs: FxHashSet<ItemEntry>,
348 enums: FxHashSet<ItemEntry>,
349 unions: FxHashSet<ItemEntry>,
350 primitives: FxHashSet<ItemEntry>,
351 traits: FxHashSet<ItemEntry>,
352 macros: FxHashSet<ItemEntry>,
353 functions: FxHashSet<ItemEntry>,
354 typedefs: FxHashSet<ItemEntry>,
355 opaque_tys: FxHashSet<ItemEntry>,
356 statics: FxHashSet<ItemEntry>,
357 constants: FxHashSet<ItemEntry>,
358 keywords: FxHashSet<ItemEntry>,
359 attributes: FxHashSet<ItemEntry>,
360 derives: FxHashSet<ItemEntry>,
361 trait_aliases: FxHashSet<ItemEntry>,
365 fn new() -> AllTypes {
366 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
368 structs: new_set(100),
370 unions: new_set(100),
371 primitives: new_set(26),
372 traits: new_set(100),
373 macros: new_set(100),
374 functions: new_set(100),
375 typedefs: new_set(100),
376 opaque_tys: new_set(100),
377 statics: new_set(100),
378 constants: new_set(100),
379 keywords: new_set(100),
380 attributes: new_set(100),
381 derives: new_set(100),
382 trait_aliases: new_set(100),
386 fn append(&mut self, item_name: String, item_type: &ItemType) {
387 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
388 if let Some(name) = url.pop() {
389 let new_url = format!("{}
/{}
.{}
.html
", url.join("/"), item_type, name);
391 let name = url.join("::");
393 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
394 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
395 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
396 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
397 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
398 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
399 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
400 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
401 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
402 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
403 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
404 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
405 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
406 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
414 fn print(self, f: &mut Buffer) {
415 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
417 let mut e: Vec<&ItemEntry> = e.iter().collect();
419 write!(f, "<h3 id
=\"{}
\">{}
</h3
><ul class
=\"{} docblock
\">", title, title, class);
422 write!(f, "<li
>{}
</li
>", s.print());
425 f.write_str("</ul
>");
431 <span class
=\"in-band
\">List of all items
</span
>\
432 <span class
=\"out
-of
-band
\">\
433 <span id
=\"render
-detail
\">\
434 <a id
=\"toggle
-all
-docs
\" href
=\"javascript
:void(0)\" \
435 title
=\"collapse all docs
\">\
436 [<span class
=\"inner
\">−</span>]\
442 // Note: print_entries does not escape the title, because we know the current set of titles
443 // don't require escaping.
444 print_entries(f, &self.structs, "Structs
", "structs
");
445 print_entries(f, &self.enums, "Enums
", "enums
");
446 print_entries(f, &self.unions, "Unions
", "unions
");
447 print_entries(f, &self.primitives, "Primitives
", "primitives
");
448 print_entries(f, &self.traits, "Traits
", "traits
");
449 print_entries(f, &self.macros, "Macros
", "macros
");
450 print_entries(f, &self.attributes, "Attribute Macros
", "attributes
");
451 print_entries(f, &self.derives, "Derive Macros
", "derives
");
452 print_entries(f, &self.functions, "Functions
", "functions
");
453 print_entries(f, &self.typedefs, "Typedefs
", "typedefs
");
454 print_entries(f, &self.trait_aliases, "Trait Aliases
", "trait-aliases
");
455 print_entries(f, &self.opaque_tys, "Opaque Types
", "opaque
-types
");
456 print_entries(f, &self.statics, "Statics
", "statics
");
457 print_entries(f, &self.constants, "Constants
", "constants
")
464 description: &'static str,
465 sub_settings: Vec<Setting>,
468 js_data_name: &'static str,
469 description: &'static str,
473 js_data_name: &'static str,
474 description: &'static str,
475 default_value: &'static str,
476 options: Vec<(String, String)>,
481 fn display(&self, root_path: &str, suffix: &str) -> String {
483 Setting::Section { description, ref sub_settings } => format!(
484 "<div class
=\"setting
-line
\">\
485 <div class
=\"title
\">{}
</div
>\
486 <div class
=\"sub
-settings
\">{}
</div
>
489 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
491 Setting::Toggle { js_data_name, description, default_value } => format!(
492 "<div class
=\"setting
-line
\">\
493 <label class
=\"toggle
\">\
494 <input
type=\"checkbox
\" id
=\"{}
\" {}
>\
495 <span class
=\"slider
\"></span
>\
500 if default_value { " checked" } else { "" },
503 Setting::Select { js_data_name, description, default_value, ref options } => format!(
504 "<div class
=\"setting
-line
\">\
506 <label class
=\"select
-wrapper
\">\
507 <select id
=\"{}
\" autocomplete
=\"off
\">{}
</select
>\
508 <img src
=\"{}down
-arrow{}
.svg
\" alt
=\"Select item
\">\
516 "<option value
=\"{}
\" {}
>{}
</option
>",
518 if opt.0 == default_value { "selected" } else { "" },
521 .collect::<String>(),
529 impl From<(&'static str, &'static str, bool)> for Setting {
530 fn from(values: (&'static str, &'static str, bool)) -> Setting {
531 Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
535 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
536 fn from(values: (&'static str, Vec<T>)) -> Setting {
538 description: values.0,
539 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
544 fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
545 let theme_names: Vec<(String, String)> = themes
549 try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
552 Ok((theme.clone(), theme))
554 .collect::<Result<_, Error>>()?;
556 // (id, explanation, default value)
557 let settings: &[Setting] = &[
561 Setting::from(("use-system
-theme
", "Use system theme
", true)),
563 js_data_name: "preferred
-dark
-theme
",
564 description: "Preferred dark theme
",
565 default_value: "dark
",
566 options: theme_names.clone(),
569 js_data_name: "preferred
-light
-theme
",
570 description: "Preferred light theme
",
571 default_value: "light
",
572 options: theme_names,
578 "Auto
-hide item declarations
",
580 ("auto-hide
-struct", "Auto
-hide structs declaration
", true),
581 ("auto-hide
-enum", "Auto
-hide enums declaration
", false),
582 ("auto-hide
-union", "Auto
-hide unions declaration
", true),
583 ("auto-hide
-trait", "Auto
-hide traits declaration
", true),
584 ("auto-hide
-macro", "Auto
-hide macros declaration
", false),
588 ("auto-hide
-attributes
", "Auto
-hide item attributes
.", true).into(),
589 ("auto-hide
-method
-docs
", "Auto
-hide item methods' documentation
", false).into(),
590 ("auto-hide
-trait-implementations
", "Auto
-hide
trait implementation documentation
", true)
592 ("auto-collapse
-implementors
", "Auto
-hide implementors of a
trait", true).into(),
593 ("go
-to
-only
-result
", "Directly go to item
in search
if there is only one result
", false)
595 ("line
-numbers
", "Show line numbers on code examples
", false).into(),
596 ("disable
-shortcuts
", "Disable keyboard shortcuts
", false).into(),
601 <span class
=\"in-band
\">Rustdoc settings
</span
>\
603 <div class
=\"settings
\">{}
</div
>\
604 <script src
=\"{}settings{}
.js
\"></script
>",
605 settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
611 fn document(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, parent: Option<&clean::Item>) {
612 if let Some(ref name) = item.name {
613 info!("Documenting {}
", name);
615 document_item_info(w, cx, item, false, parent);
616 document_full(w, item, cx, "", false);
619 /// Render md_text as markdown.
624 links: Vec<RenderedLink>,
628 let mut ids = cx.id_map.borrow_mut();
631 "<div class
=\"docblock{}
\">{}{}
</div
>",
632 if is_hidden { " hidden" } else { "" },
640 &cx.shared.playground
646 /// Writes a documentation block containing only the first paragraph of the documentation. If the
647 /// docs are longer, a "Read more
" link is appended to the end.
652 link: AssocItemLink<'_>,
655 parent: Option<&clean::Item>,
658 document_item_info(w, cx, item, is_hidden, parent);
662 if let Some(s) = item.doc_value() {
663 let mut summary_html = MarkdownSummaryLine(&s, &item.links(&cx.cache)).into_string();
665 if s.contains('\n') {
667 format!(r#" <a href
="{}">Read more
</a
>"#, naive_assoc_href(item, link, cx.cache()));
669 if let Some(idx) = summary_html.rfind("</p
>") {
670 summary_html.insert_str(idx, &link);
672 summary_html.push_str(&link);
678 "<div class
='docblock{}'
>{}{}
</div
>",
679 if is_hidden { " hidden" } else { "" },
683 } else if !prefix.is_empty() {
686 "<div class
=\"docblock{}
\">{}
</div
>",
687 if is_hidden { " hidden" } else { "" },
700 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
701 debug!("Doc block
: =====\n{}
\n=====", s);
702 render_markdown(w, cx, &*s, item.links(&cx.cache), prefix, is_hidden);
703 } else if !prefix.is_empty() {
705 w.write_str("<div class
=\"docblock hidden
\">");
707 w.write_str("<div class
=\"docblock
\">");
710 w.write_str("</div
>");
714 /// Add extra information about an item such as:
718 /// * Required features (through the `doc_cfg` feature)
719 fn document_item_info(
724 parent: Option<&clean::Item>,
726 let item_infos = short_item_info(item, cx, parent);
727 if !item_infos.is_empty() {
729 w.write_str("<div class
=\"item
-info hidden
\">");
731 w.write_str("<div class
=\"item
-info
\">");
733 for info in item_infos {
736 w.write_str("</div
>");
740 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
741 let cfg = match (&item.attrs.cfg, parent.and_then(|p| p.attrs.cfg.as_ref())) {
742 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
743 (cfg, _) => cfg.as_deref().cloned(),
747 "Portability {:?}
- {:?}
= {:?}
",
749 parent.and_then(|p| p.attrs.cfg.as_ref()),
753 Some(format!("<div class
=\"stab portability
\">{}
</div
>", cfg?.render_long_html()))
756 /// Render the stability, deprecation and portability information that is displayed at the top of
757 /// the item's documentation.
761 parent: Option<&clean::Item>,
763 let mut extra_info = vec![];
764 let error_codes = cx.shared.codes;
766 if let Some(Deprecation { note, since, is_since_rustc_version, suggestion: _ }) =
767 item.deprecation(cx.tcx())
769 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
770 // but only display the future-deprecation messages for #[rustc_deprecated].
771 let mut message = if let Some(since) = since {
772 let since = &since.as_str();
773 if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
775 String::from("Deprecating
in a future Rust version
")
777 format!("Deprecating
in {}
", Escape(since))
780 format!("Deprecated since {}
", Escape(since))
783 String::from("Deprecated
")
786 if let Some(note) = note {
787 let note = note.as_str();
788 let mut ids = cx.id_map.borrow_mut();
789 let html = MarkdownHtml(
794 &cx.shared.playground,
796 message.push_str(&format!(": {}
", html.into_string()));
798 extra_info.push(format!(
799 "<div class
=\"stab deprecated
\"><span class
=\"emoji
\">👎
</span
> {}
</div
>",
804 // Render unstable items. But don't render "rustc_private
" crates (internal compiler crates).
805 // Those crates are permanently unstable so it makes no sense to render "unstable
" everywhere.
806 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
809 .filter(|stab| stab.feature != sym::rustc_private)
810 .map(|stab| (stab.level, stab.feature))
813 "<span class
=\"emoji
\">🔬
</span
> This is a nightly
-only experimental API
.".to_owned();
815 let mut feature = format!("<code
>{}
</code
>", Escape(&feature.as_str()));
816 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
817 feature.push_str(&format!(
818 " 
;<a href
=\"{url}{issue}
\">#{issue}</a>",
824 message.push_str(&format!(" ({})", feature));
826 if let Some(unstable_reason) = reason {
827 let mut ids = cx.id_map.borrow_mut();
829 "<details><summary>{}</summary>{}</details>",
832 &unstable_reason.as_str(),
836 &cx.shared.playground,
842 extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
845 if let Some(portability) = portability(item, parent) {
846 extra_info.push(portability);
856 containing_item: &clean::Item,
858 let mut impls = traits
861 let did = i.trait_did_full(cx.cache()).unwrap();
862 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
863 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
871 containing_item.stable_since(cx.tcx()).as_deref(),
872 containing_item.const_stable_since(cx.tcx()).as_deref(),
881 .collect::<Vec<_>>();
883 w.write_str(&impls.join(""));
886 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>, cache: &Cache) -> String {
887 use crate::formats::item_type::ItemType::*;
889 let name = it.name.as_ref().unwrap();
890 let ty = match it.type_() {
891 Typedef | AssocType => AssocType,
895 let anchor = format!("#{}.{}", ty, name);
897 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
898 AssocItemLink::Anchor(None) => anchor,
899 AssocItemLink::GotoSource(did, _) => {
900 href(did, cache).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
909 _default: Option<&String>,
910 link: AssocItemLink<'_>,
916 "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
918 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
919 naive_assoc_href(it, link, cx.cache()),
920 it.name.as_ref().unwrap(),
928 bounds: &[clean::GenericBound],
929 default: Option<&clean::Type>,
930 link: AssocItemLink<'_>,
936 "{}type <a href=\"{}\" class=\"type\">{}</a>",
938 naive_assoc_href(it, link, cache),
939 it.name.as_ref().unwrap()
941 if !bounds.is_empty() {
942 write!(w, ": {}", print_generic_bounds(bounds, cache))
944 if let Some(default) = default {
945 write!(w, " = {}", default.print(cache))
949 fn render_stability_since_raw(
952 const_ver: Option<&str>,
953 containing_ver: Option<&str>,
954 containing_const_ver: Option<&str>,
956 let ver = ver.filter(|inner| !inner.is_empty());
957 let const_ver = const_ver.filter(|inner| !inner.is_empty());
959 match (ver, const_ver) {
960 (Some(v), Some(cv)) if const_ver != containing_const_ver => {
963 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
967 (Some(v), _) if ver != containing_ver => {
970 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
978 fn render_assoc_item(
981 link: AssocItemLink<'_>,
988 header: hir::FnHeader,
991 link: AssocItemLink<'_>,
995 let name = meth.name.as_ref().unwrap();
996 let anchor = format!("#{}.{}", meth.type_(), name);
997 let href = match link {
998 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
999 AssocItemLink::Anchor(None) => anchor,
1000 AssocItemLink::GotoSource(did, provided_methods) => {
1001 // We're creating a link from an impl-item to the corresponding
1002 // trait-item and need to map the anchored type accordingly.
1003 let ty = if provided_methods.contains(&name) {
1009 href(did, cx.cache()).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
1012 let mut header_len = format!(
1013 "{}{}{}{}{}{:#}fn {}{:#}",
1014 meth.visibility.print_with_space(cx.tcx(), meth.def_id, cx.cache()),
1015 header.constness.print_with_space(),
1016 header.asyncness.print_with_space(),
1017 header.unsafety.print_with_space(),
1018 print_default_space(meth.is_default()),
1019 print_abi_with_space(header.abi),
1024 let (indent, end_newline) = if parent == ItemType::Trait {
1030 render_attributes(w, meth, false);
1033 "{}{}{}{}{}{}{}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
1034 {generics}{decl}{spotlight}{where_clause}",
1035 if parent == ItemType::Trait { " " } else { "" },
1036 meth.visibility.print_with_space(cx.tcx(), meth.def_id, cx.cache()),
1037 header.constness.print_with_space(),
1038 header.asyncness.print_with_space(),
1039 header.unsafety.print_with_space(),
1040 print_default_space(meth.is_default()),
1041 print_abi_with_space(header.abi),
1044 generics = g.print(cx.cache()),
1045 decl = Function { decl: d, header_len, indent, asyncness: header.asyncness }
1047 spotlight = spotlight_decl(&d, cx.cache()),
1048 where_clause = WhereClause { gens: g, indent, end_newline }.print(cx.cache())
1052 clean::StrippedItem(..) => {}
1053 clean::TyMethodItem(ref m) => {
1054 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
1056 clean::MethodItem(ref m, _) => {
1057 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
1059 clean::AssocConstItem(ref ty, ref default) => assoc_const(
1065 if parent == ItemType::Trait { " " } else { "" },
1068 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
1074 if parent == ItemType::Trait { " " } else { "" },
1077 _ => panic!("render_assoc_item called on non-associated-item"),
1081 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
1088 sym::non_exhaustive,
1091 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
1092 // left padding. For example:
1094 // #[foo] <----- "top" attribute
1096 // #[bar] <---- not "top" attribute
1099 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
1104 .filter_map(|attr| {
1105 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
1106 Some(pprust::attribute_to_string(&attr))
1113 if !attrs.is_empty() {
1116 "<span class=\"docblock attributes{}\">{}</span>",
1117 if top { " top-attr" } else { "" },
1123 #[derive(Copy, Clone)]
1124 enum AssocItemLink<'a> {
1125 Anchor(Option<&'a str>),
1126 GotoSource(DefId, &'a FxHashSet<Symbol>),
1129 impl<'a> AssocItemLink<'a> {
1130 fn anchor(&self, id: &'a str) -> Self {
1132 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
1133 ref other => *other,
1138 fn render_assoc_items(
1141 containing_item: &clean::Item,
1143 what: AssocItemRender<'_>,
1145 info!("Documenting associated items of {:?}", containing_item.name);
1146 let v = match cx.cache.impls.get(&it) {
1150 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
1151 if !non_trait.is_empty() {
1152 let render_mode = match what {
1153 AssocItemRender::All => {
1155 "<h2 id=\"implementations\" class=\"small-section-header\">\
1156 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
1161 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
1162 let id = cx.derive_id(small_url_encode(format!(
1163 "deref-methods-{:#}",
1164 type_.print(cx.cache())
1166 debug!("Adding {} to deref id map", type_.print(cx.cache()));
1169 .insert(type_.def_id_full(cx.cache()).unwrap(), id.clone());
1172 "<h2 id=\"{id}\" class=\"small-section-header\">\
1173 Methods from {trait_}<Target = {type_}>\
1174 <a href=\"#{id}\" class=\"anchor\"></a>\
1177 trait_ = trait_.print(cx.cache()),
1178 type_ = type_.print(cx.cache()),
1180 RenderMode::ForDeref { mut_: deref_mut_ }
1183 for i in &non_trait {
1189 AssocItemLink::Anchor(None),
1191 containing_item.stable_since(cx.tcx()).as_deref(),
1192 containing_item.const_stable_since(cx.tcx()).as_deref(),
1201 if !traits.is_empty() {
1202 let deref_impl = traits
1204 .find(|t| t.inner_impl().trait_.def_id_full(cx.cache()) == cx.cache.deref_trait_did);
1205 if let Some(impl_) = deref_impl {
1206 let has_deref_mut = traits.iter().any(|t| {
1207 t.inner_impl().trait_.def_id_full(cx.cache()) == cx.cache.deref_mut_trait_did
1209 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut);
1212 // If we were already one level into rendering deref methods, we don't want to render
1213 // anything after recursing into any further deref methods above.
1214 if let AssocItemRender::DerefFor { .. } = what {
1218 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
1219 traits.iter().partition(|t| t.inner_impl().synthetic);
1220 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
1221 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
1223 let mut impls = Buffer::empty_from(&w);
1224 render_impls(cx, &mut impls, &concrete, containing_item);
1225 let impls = impls.into_inner();
1226 if !impls.is_empty() {
1229 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
1230 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
1232 <div id=\"trait-implementations-list\">{}</div>",
1237 if !synthetic.is_empty() {
1239 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
1240 Auto Trait Implementations\
1241 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
1243 <div id=\"synthetic-implementations-list\">",
1245 render_impls(cx, w, &synthetic, containing_item);
1246 w.write_str("</div>");
1249 if !blanket_impl.is_empty() {
1251 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
1252 Blanket Implementations\
1253 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
1255 <div id=\"blanket-implementations-list\">",
1257 render_impls(cx, w, &blanket_impl, containing_item);
1258 w.write_str("</div>");
1263 fn render_deref_methods(
1267 container_item: &clean::Item,
1270 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
1271 let (target, real_target) = impl_
1275 .find_map(|item| match *item.kind {
1276 clean::TypedefItem(ref t, true) => Some(match *t {
1277 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
1278 _ => (&t.type_, &t.type_),
1282 .expect("Expected associated type binding");
1283 debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target);
1285 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
1286 if let Some(did) = target.def_id_full(cx.cache()) {
1287 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) {
1288 // `impl Deref<Target = S> for S`
1289 if did == type_did {
1290 // Avoid infinite cycles
1294 render_assoc_items(w, cx, container_item, did, what);
1296 if let Some(prim) = target.primitive_type() {
1297 if let Some(&did) = cx.cache.primitive_locations.get(&prim) {
1298 render_assoc_items(w, cx, container_item, did, what);
1304 fn should_render_item(item: &clean::Item, deref_mut_: bool, cache: &Cache) -> bool {
1305 let self_type_opt = match *item.kind {
1306 clean::MethodItem(ref method, _) => method.decl.self_type(),
1307 clean::TyMethodItem(ref method) => method.decl.self_type(),
1311 if let Some(self_ty) = self_type_opt {
1312 let (by_mut_ref, by_box, by_value) = match self_ty {
1313 SelfTy::SelfBorrowed(_, mutability)
1314 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
1315 (mutability == Mutability::Mut, false, false)
1317 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
1318 (false, Some(did) == cache.owned_box_did, false)
1320 SelfTy::SelfValue => (false, false, true),
1321 _ => (false, false, false),
1324 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
1330 fn spotlight_decl(decl: &clean::FnDecl, cache: &Cache) -> String {
1331 let mut out = Buffer::html();
1332 let mut trait_ = String::new();
1334 if let Some(did) = decl.output.def_id_full(cache) {
1335 if let Some(impls) = cache.impls.get(&did) {
1337 let impl_ = i.inner_impl();
1338 if impl_.trait_.def_id().map_or(false, |d| {
1339 cache.traits.get(&d).map(|t| t.is_spotlight).unwrap_or(false)
1344 "<h3 class=\"notable\">Notable traits for {}</h3>\
1345 <code class=\"content\">",
1346 impl_.for_.print(cache)
1348 trait_.push_str(&impl_.for_.print(cache).to_string());
1351 //use the "where" class here to make it small
1354 "<span class=\"where fmt-newline\">{}</span>",
1355 impl_.print(cache, false)
1357 let t_did = impl_.trait_.def_id_full(cache).unwrap();
1358 for it in &impl_.items {
1359 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1360 out.push_str("<span class=\"where fmt-newline\"> ");
1366 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
1370 out.push_str(";</span>");
1378 if !out.is_empty() {
1381 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
1382 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
1384 out.push_str("</code></span></div></span></span>");
1394 parent: &clean::Item,
1395 link: AssocItemLink<'_>,
1396 render_mode: RenderMode,
1397 outer_version: Option<&str>,
1398 outer_const_version: Option<&str>,
1399 show_def_docs: bool,
1400 use_absolute: Option<bool>,
1401 is_on_foreign_type: bool,
1402 show_default_items: bool,
1403 // This argument is used to reference same type with different paths to avoid duplication
1404 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
1407 let traits = &cx.cache.traits;
1408 let trait_ = i.trait_did_full(cx.cache()).map(|did| &traits[&did]);
1410 if render_mode == RenderMode::Normal {
1411 let id = cx.derive_id(match i.inner_impl().trait_ {
1413 if is_on_foreign_type {
1414 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t, cx.cache())
1416 format!("impl-{}", small_url_encode(format!("{:#}", t.print(cx.cache()))))
1419 None => "impl".to_string(),
1421 let aliases = if aliases.is_empty() {
1424 format!(" aliases=\"{}\"", aliases.join(","))
1426 if let Some(use_absolute) = use_absolute {
1427 write!(w, "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">", id, aliases);
1428 write!(w, "{}", i.inner_impl().print(cx.cache(), use_absolute));
1430 for it in &i.inner_impl().items {
1431 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1432 w.write_str("<span class=\"where fmt-newline\"> ");
1438 AssocItemLink::Anchor(None),
1442 w.write_str(";</span>");
1446 w.write_str("</code>");
1450 "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">{}</code>",
1453 i.inner_impl().print(cx.cache(), false)
1456 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1457 render_stability_since_raw(
1459 i.impl_item.stable_since(cx.tcx()).as_deref(),
1460 i.impl_item.const_stable_since(cx.tcx()).as_deref(),
1462 outer_const_version,
1464 write_srclink(cx, &i.impl_item, w);
1465 w.write_str("</h3>");
1467 if trait_.is_some() {
1468 if let Some(portability) = portability(&i.impl_item, Some(parent)) {
1469 write!(w, "<div class=\"item-info\">{}</div>", portability);
1473 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
1474 let mut ids = cx.id_map.borrow_mut();
1477 "<div class=\"docblock\">{}</div>",
1480 &i.impl_item.links(&cx.cache),
1484 &cx.shared.playground
1495 parent: &clean::Item,
1496 link: AssocItemLink<'_>,
1497 render_mode: RenderMode,
1498 is_default_item: bool,
1499 outer_version: Option<&str>,
1500 outer_const_version: Option<&str>,
1501 trait_: Option<&clean::Trait>,
1502 show_def_docs: bool,
1504 let item_type = item.type_();
1505 let name = item.name.as_ref().unwrap();
1507 let render_method_item = match render_mode {
1508 RenderMode::Normal => true,
1509 RenderMode::ForDeref { mut_: deref_mut_ } => {
1510 should_render_item(&item, deref_mut_, &cx.cache)
1514 let (is_hidden, extra_class) =
1515 if (trait_.is_none() || item.doc_value().is_some() || item.kind.is_type_alias())
1523 clean::MethodItem(..) | clean::TyMethodItem(_) => {
1524 // Only render when the method is not static or we allow static methods
1525 if render_method_item {
1526 let id = cx.derive_id(format!("{}.{}", item_type, name));
1527 write!(w, "<h4 id=\"{}\" class=\"{}{}\">", id, item_type, extra_class);
1528 w.write_str("<code>");
1529 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl, cx);
1530 w.write_str("</code>");
1531 render_stability_since_raw(
1533 item.stable_since(cx.tcx()).as_deref(),
1534 item.const_stable_since(cx.tcx()).as_deref(),
1536 outer_const_version,
1538 write_srclink(cx, item, w);
1539 w.write_str("</h4>");
1542 clean::TypedefItem(ref tydef, _) => {
1543 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
1544 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
1554 w.write_str("</code></h4>");
1556 clean::AssocConstItem(ref ty, ref default) => {
1557 let id = cx.derive_id(format!("{}.{}", item_type, name));
1558 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
1559 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "", cx);
1560 w.write_str("</code>");
1561 render_stability_since_raw(
1563 item.stable_since(cx.tcx()).as_deref(),
1564 item.const_stable_since(cx.tcx()).as_deref(),
1566 outer_const_version,
1568 write_srclink(cx, item, w);
1569 w.write_str("</h4>");
1571 clean::AssocTypeItem(ref bounds, ref default) => {
1572 let id = cx.derive_id(format!("{}.{}", item_type, name));
1573 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
1574 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "", cx.cache());
1575 w.write_str("</code></h4>");
1577 clean::StrippedItem(..) => return,
1578 _ => panic!("can't make docs for trait item with name {:?}", item.name),
1581 if render_method_item {
1582 if !is_default_item {
1583 if let Some(t) = trait_ {
1584 // The trait item may have been stripped so we might not
1585 // find any documentation or stability for it.
1586 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
1587 // We need the stability of the item from the trait
1588 // because impls can't have a stability.
1589 if item.doc_value().is_some() {
1590 document_item_info(w, cx, it, is_hidden, Some(parent));
1591 document_full(w, item, cx, "", is_hidden);
1593 // In case the item isn't documented,
1594 // provide short documentation from the trait.
1608 document_item_info(w, cx, item, is_hidden, Some(parent));
1610 document_full(w, item, cx, "", is_hidden);
1614 document_short(w, item, cx, link, "", is_hidden, Some(parent), show_def_docs);
1619 w.write_str("<div class=\"impl-items\">");
1620 for trait_item in &i.inner_impl().items {
1625 if trait_.is_some() { &i.impl_item } else { parent },
1630 outer_const_version,
1631 trait_.map(|t| &t.trait_),
1636 fn render_default_items(
1641 parent: &clean::Item,
1642 render_mode: RenderMode,
1643 outer_version: Option<&str>,
1644 outer_const_version: Option<&str>,
1645 show_def_docs: bool,
1647 for trait_item in &t.items {
1648 let n = trait_item.name;
1649 if i.items.iter().any(|m| m.name == n) {
1652 let did = i.trait_.as_ref().unwrap().def_id_full(cx.cache()).unwrap();
1653 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
1664 outer_const_version,
1671 // If we've implemented a trait, then also emit documentation for all
1672 // default items which weren't overridden in the implementation block.
1673 // We don't emit documentation for default items if they appear in the
1674 // Implementations on Foreign Types or Implementors sections.
1675 if show_default_items {
1676 if let Some(t) = trait_ {
1677 render_default_items(
1685 outer_const_version,
1690 w.write_str("</div>");
1693 fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) {
1694 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
1698 || it.is_primitive()
1706 "<p class=\"location\">{}{}</p>",
1708 clean::StructItem(..) => "Struct ",
1709 clean::TraitItem(..) => "Trait ",
1710 clean::PrimitiveItem(..) => "Primitive Type ",
1711 clean::UnionItem(..) => "Union ",
1712 clean::EnumItem(..) => "Enum ",
1713 clean::TypedefItem(..) => "Type Definition ",
1714 clean::ForeignTypeItem => "Foreign Type ",
1715 clean::ModuleItem(..) =>
1723 it.name.as_ref().unwrap()
1728 if let Some(ref version) = cx.cache.crate_version {
1731 "<div class=\"block version\">\
1739 buffer.write_str("<div class=\"sidebar-elems\">");
1743 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
1744 it.name.as_ref().expect("crates always have a name")
1748 clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s),
1749 clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t),
1750 clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it),
1751 clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u),
1752 clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e),
1753 clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it),
1754 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
1755 clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, it),
1759 // The sidebar is designed to display sibling functions, modules and
1760 // other miscellaneous information. since there are lots of sibling
1761 // items (and that causes quadratic growth in large modules),
1762 // we refactor common parts into a shared JavaScript file per module.
1763 // still, we don't move everything into JS because we want to preserve
1764 // as much HTML as possible in order to allow non-JS-enabled browsers
1765 // to navigate the documentation (though slightly inefficiently).
1767 buffer.write_str("<p class=\"location\">");
1768 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
1770 buffer.write_str("::<wbr>");
1774 "<a href=\"{}index.html\">{}</a>",
1775 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
1779 buffer.write_str("</p>");
1781 // Sidebar refers to the enclosing module, not this module.
1782 let relpath = if it.is_mod() { "../" } else { "" };
1785 "<div id=\"sidebar-vars\" data-name=\"{name}\" data-ty=\"{ty}\" data-relpath=\"{path}\">\
1787 name = it.name.unwrap_or(kw::Empty),
1792 // There is no sidebar-items.js beyond the crate root path
1793 // FIXME maybe dynamic crate loading can be merged here
1795 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
1797 // Closes sidebar-elems div.
1798 buffer.write_str("</div>");
1801 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
1802 if used_links.insert(url.clone()) {
1806 while !used_links.insert(format!("{}-{}", url, add)) {
1809 format!("{}-{}", url, add)
1815 used_links: &mut FxHashSet<String>,
1821 .filter_map(|item| match item.name {
1822 Some(ref name) if !name.is_empty() && item.is_method() => {
1823 if !for_deref || should_render_item(item, deref_mut, cache) {
1825 "<a href=\"#{}\">{}</a>",
1826 get_next_url(used_links, format!("method.{}", name)),
1835 .collect::<Vec<_>>()
1838 // The point is to url encode any potential character from a type with genericity.
1839 fn small_url_encode(s: String) -> String {
1840 let mut st = String::new();
1841 let mut last_match = 0;
1842 for (idx, c) in s.char_indices() {
1843 let escaped = match c {
1859 st
+= &s
[last_match
..idx
];
1861 // NOTE: we only expect single byte characters here - which is fine as long as we
1862 // only match single byte characters
1863 last_match
= idx
+ 1;
1866 if last_match
!= 0 {
1867 st
+= &s
[last_match
..];
1874 fn sidebar_assoc_items(cx
: &Context
<'_
>, out
: &mut Buffer
, it
: &clean
::Item
) {
1875 if let Some(v
) = cx
.cache
.impls
.get(&it
.def_id
) {
1876 let mut used_links
= FxHashSet
::default();
1879 let used_links_bor
= &mut used_links
;
1882 .filter(|i
| i
.inner_impl().trait_
.is_none())
1883 .flat_map(move |i
| {
1884 get_methods(i
.inner_impl(), false, used_links_bor
, false, &cx
.cache
)
1886 .collect
::<Vec
<_
>>();
1887 if !ret
.is_empty() {
1888 // We want links' order to be reproducible so we don't use unstable sort.
1892 "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
1893 <div class=\"sidebar-links\">",
1896 out
.push_str(&line
);
1898 out
.push_str("</div>");
1902 if v
.iter().any(|i
| i
.inner_impl().trait_
.is_some()) {
1903 if let Some(impl_
) = v
1905 .filter(|i
| i
.inner_impl().trait_
.is_some())
1906 .find(|i
| i
.inner_impl().trait_
.def_id_full(cx
.cache()) == cx
.cache
.deref_trait_did
)
1908 sidebar_deref_methods(cx
, out
, impl_
, v
);
1910 let format_impls
= |impls
: Vec
<&Impl
>| {
1911 let mut links
= FxHashSet
::default();
1916 if let Some(ref i
) = it
.inner_impl().trait_
{
1917 let i_display
= format
!("{:#}", i
.print(cx
.cache()));
1918 let out
= Escape(&i_display
);
1919 let encoded
= small_url_encode(format
!("{:#}", i
.print(cx
.cache())));
1920 let generated
= format
!(
1921 "<a href=\"#impl-{}\">{}{}</a>",
1923 if it
.inner_impl().negative_polarity { "!" }
else { "" }
,
1926 if links
.insert(generated
.clone()) { Some(generated) }
else { None }
1931 .collect
::<Vec
<String
>>();
1936 let write_sidebar_links
= |out
: &mut Buffer
, links
: Vec
<String
>| {
1937 out
.push_str("<div class=\"sidebar-links\">");
1939 out
.push_str(&link
);
1941 out
.push_str("</div>");
1944 let (synthetic
, concrete
): (Vec
<&Impl
>, Vec
<&Impl
>) =
1945 v
.iter().partition
::<Vec
<_
>, _
>(|i
| i
.inner_impl().synthetic
);
1946 let (blanket_impl
, concrete
): (Vec
<&Impl
>, Vec
<&Impl
>) = concrete
1948 .partition
::<Vec
<_
>, _
>(|i
| i
.inner_impl().blanket_impl
.is_some());
1950 let concrete_format
= format_impls(concrete
);
1951 let synthetic_format
= format_impls(synthetic
);
1952 let blanket_format
= format_impls(blanket_impl
);
1954 if !concrete_format
.is_empty() {
1956 "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
1957 Trait Implementations</a>",
1959 write_sidebar_links(out
, concrete_format
);
1962 if !synthetic_format
.is_empty() {
1964 "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
1965 Auto Trait Implementations</a>",
1967 write_sidebar_links(out
, synthetic_format
);
1970 if !blanket_format
.is_empty() {
1972 "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
1973 Blanket Implementations</a>",
1975 write_sidebar_links(out
, blanket_format
);
1981 fn sidebar_deref_methods(cx
: &Context
<'_
>, out
: &mut Buffer
, impl_
: &Impl
, v
: &Vec
<Impl
>) {
1984 debug
!("found Deref: {:?}", impl_
);
1985 if let Some((target
, real_target
)) =
1986 impl_
.inner_impl().items
.iter().find_map(|item
| match *item
.kind
{
1987 clean
::TypedefItem(ref t
, true) => Some(match *t
{
1988 clean
::Typedef { item_type: Some(ref type_), .. }
=> (type_
, &t
.type_
),
1989 _
=> (&t
.type_
, &t
.type_
),
1994 debug
!("found target, real_target: {:?} {:?}", target
, real_target
);
1995 if let Some(did
) = target
.def_id_full(cx
.cache()) {
1996 if let Some(type_did
) = impl_
.inner_impl().for_
.def_id_full(cx
.cache()) {
1997 // `impl Deref<Target = S> for S`
1998 if did
== type_did
{
1999 // Avoid infinite cycles
2006 .filter(|i
| i
.inner_impl().trait_
.is_some())
2007 .any(|i
| i
.inner_impl().trait_
.def_id_full(cx
.cache()) == c
.deref_mut_trait_did
);
2008 let inner_impl
= target
2009 .def_id_full(cx
.cache())
2011 target
.primitive_type().and_then(|prim
| c
.primitive_locations
.get(&prim
).cloned())
2013 .and_then(|did
| c
.impls
.get(&did
));
2014 if let Some(impls
) = inner_impl
{
2015 debug
!("found inner_impl: {:?}", impls
);
2016 let mut used_links
= FxHashSet
::default();
2019 .filter(|i
| i
.inner_impl().trait_
.is_none())
2020 .flat_map(|i
| get_methods(i
.inner_impl(), true, &mut used_links
, deref_mut
, c
))
2021 .collect
::<Vec
<_
>>();
2022 if !ret
.is_empty() {
2023 let deref_id_map
= cx
.deref_id_map
.borrow();
2024 let id
= deref_id_map
2025 .get(&real_target
.def_id_full(cx
.cache()).unwrap())
2026 .expect("Deref section without derived id");
2029 "<a class=\"sidebar-title\" href=\"#{}\">Methods from {}<Target={}></a>",
2031 Escape(&format
!("{:#}", impl_
.inner_impl().trait_
.as_ref().unwrap().print(c
))),
2032 Escape(&format
!("{:#}", real_target
.print(c
))),
2034 // We want links' order to be reproducible so we don't use unstable sort.
2036 out
.push_str("<div class=\"sidebar-links\">");
2038 out
.push_str(&link
);
2040 out
.push_str("</div>");
2044 // Recurse into any further impls that might exist for `target`
2045 if let Some(target_did
) = target
.def_id_full(cx
.cache()) {
2046 if let Some(target_impls
) = c
.impls
.get(&target_did
) {
2047 if let Some(target_deref_impl
) = target_impls
2049 .filter(|i
| i
.inner_impl().trait_
.is_some())
2050 .find(|i
| i
.inner_impl().trait_
.def_id_full(cx
.cache()) == c
.deref_trait_did
)
2052 sidebar_deref_methods(cx
, out
, target_deref_impl
, target_impls
);
2059 fn sidebar_struct(cx
: &Context
<'_
>, buf
: &mut Buffer
, it
: &clean
::Item
, s
: &clean
::Struct
) {
2060 let mut sidebar
= Buffer
::new();
2061 let fields
= get_struct_fields_name(&s
.fields
);
2063 if !fields
.is_empty() {
2064 if let CtorKind
::Fictive
= s
.struct_type
{
2066 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
2067 <div class=\"sidebar-links\">",
2070 for field
in fields
{
2071 sidebar
.push_str(&field
);
2074 sidebar
.push_str("</div>");
2078 sidebar_assoc_items(cx
, &mut sidebar
, it
);
2080 if !sidebar
.is_empty() {
2081 write
!(buf
, "<div class=\"block items\">{}</div>", sidebar
.into_inner());
2085 fn get_id_for_impl_on_foreign_type(
2087 trait_
: &clean
::Type
,
2090 small_url_encode(format
!("impl-{:#}-for-{:#}", trait_
.print(cache
), for_
.print(cache
)))
2093 fn extract_for_impl_name(item
: &clean
::Item
, cache
: &Cache
) -> Option
<(String
, String
)> {
2095 clean
::ItemKind
::ImplItem(ref i
) => {
2096 if let Some(ref trait_
) = i
.trait_
{
2098 format
!("{:#}", i
.for_
.print(cache
)),
2099 get_id_for_impl_on_foreign_type(&i
.for_
, trait_
, cache
),
2109 fn sidebar_trait(cx
: &Context
<'_
>, buf
: &mut Buffer
, it
: &clean
::Item
, t
: &clean
::Trait
) {
2110 buf
.write_str("<div class=\"block items\">");
2112 fn print_sidebar_section(
2114 items
: &[clean
::Item
],
2116 filter
: impl Fn(&clean
::Item
) -> bool
,
2117 write
: impl Fn(&mut Buffer
, &Symbol
),
2120 let mut items
= items
2122 .filter_map(|m
| match m
.name
{
2123 Some(ref name
) if filter(m
) => Some(name
),
2126 .collect
::<Vec
<_
>>();
2128 if !items
.is_empty() {
2130 out
.push_str(before
);
2131 for item
in items
.into_iter() {
2134 out
.push_str(after
);
2138 print_sidebar_section(
2141 "<a class=\"sidebar-title\" href=\"#associated-types\">\
2142 Associated Types</a><div class=\"sidebar-links\">",
2143 |m
| m
.is_associated_type(),
2144 |out
, sym
| write
!(out
, "<a href=\"#associatedtype.{0}\">{0}</a>", sym
),
2148 print_sidebar_section(
2151 "<a class=\"sidebar-title\" href=\"#associated-const\">\
2152 Associated Constants</a><div class=\"sidebar-links\">",
2153 |m
| m
.is_associated_const(),
2154 |out
, sym
| write
!(out
, "<a href=\"#associatedconstant.{0}\">{0}</a>", sym
),
2158 print_sidebar_section(
2161 "<a class=\"sidebar-title\" href=\"#required-methods\">\
2162 Required Methods</a><div class=\"sidebar-links\">",
2163 |m
| m
.is_ty_method(),
2164 |out
, sym
| write
!(out
, "<a href=\"#tymethod.{0}\">{0}</a>", sym
),
2168 print_sidebar_section(
2171 "<a class=\"sidebar-title\" href=\"#provided-methods\">\
2172 Provided Methods</a><div class=\"sidebar-links\">",
2174 |out
, sym
| write
!(out
, "<a href=\"#method.{0}\">{0}</a>", sym
),
2178 if let Some(implementors
) = cx
.cache
.implementors
.get(&it
.def_id
) {
2179 let mut res
= implementors
2184 .def_id_full(cx
.cache())
2185 .map_or(false, |d
| !cx
.cache
.paths
.contains_key(&d
))
2187 .filter_map(|i
| extract_for_impl_name(&i
.impl_item
, cx
.cache()))
2188 .collect
::<Vec
<_
>>();
2190 if !res
.is_empty() {
2193 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
2194 Implementations on Foreign Types</a>\
2195 <div class=\"sidebar-links\">",
2197 for (name
, id
) in res
.into_iter() {
2198 write
!(buf
, "<a href=\"#{}\">{}</a>", id
, Escape(&name
));
2200 buf
.push_str("</div>");
2204 sidebar_assoc_items(cx
, buf
, it
);
2206 buf
.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
2209 "<a class=\"sidebar-title\" \
2210 href=\"#synthetic-implementors\">Auto Implementors</a>",
2214 buf
.push_str("</div>")
2217 fn sidebar_primitive(cx
: &Context
<'_
>, buf
: &mut Buffer
, it
: &clean
::Item
) {
2218 let mut sidebar
= Buffer
::new();
2219 sidebar_assoc_items(cx
, &mut sidebar
, it
);
2221 if !sidebar
.is_empty() {
2222 write
!(buf
, "<div class=\"block items\">{}</div>", sidebar
.into_inner());
2226 fn sidebar_typedef(cx
: &Context
<'_
>, buf
: &mut Buffer
, it
: &clean
::Item
) {
2227 let mut sidebar
= Buffer
::new();
2228 sidebar_assoc_items(cx
, &mut sidebar
, it
);
2230 if !sidebar
.is_empty() {
2231 write
!(buf
, "<div class=\"block items\">{}</div>", sidebar
.into_inner());
2235 fn get_struct_fields_name(fields
: &[clean
::Item
]) -> Vec
<String
> {
2236 let mut fields
= fields
2238 .filter(|f
| matches
!(*f
.kind
, clean
::StructFieldItem(..)))
2240 f
.name
.map(|name
| format
!("<a href=\"#structfield.{name}\">{name}</a>", name
= name
))
2242 .collect
::<Vec
<_
>>();
2247 fn sidebar_union(cx
: &Context
<'_
>, buf
: &mut Buffer
, it
: &clean
::Item
, u
: &clean
::Union
) {
2248 let mut sidebar
= Buffer
::new();
2249 let fields
= get_struct_fields_name(&u
.fields
);
2251 if !fields
.is_empty() {
2253 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
2254 <div class=\"sidebar-links\">",
2257 for field
in fields
{
2258 sidebar
.push_str(&field
);
2261 sidebar
.push_str("</div>");
2264 sidebar_assoc_items(cx
, &mut sidebar
, it
);
2266 if !sidebar
.is_empty() {
2267 write
!(buf
, "<div class=\"block items\">{}</div>", sidebar
.into_inner());
2271 fn sidebar_enum(cx
: &Context
<'_
>, buf
: &mut Buffer
, it
: &clean
::Item
, e
: &clean
::Enum
) {
2272 let mut sidebar
= Buffer
::new();
2274 let mut variants
= e
2277 .filter_map(|v
| match v
.name
{
2278 Some(ref name
) => Some(format
!("<a href=\"#variant.{name}\">{name}</a>", name
= name
)),
2281 .collect
::<Vec
<_
>>();
2282 if !variants
.is_empty() {
2283 variants
.sort_unstable();
2284 sidebar
.push_str(&format
!(
2285 "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
2286 <div class=\"sidebar-links\">{}</div>",
2291 sidebar_assoc_items(cx
, &mut sidebar
, it
);
2293 if !sidebar
.is_empty() {
2294 write
!(buf
, "<div class=\"block items\">{}</div>", sidebar
.into_inner());
2298 fn item_ty_to_strs(ty
: &ItemType
) -> (&'
static str, &'
static str) {
2300 ItemType
::ExternCrate
| ItemType
::Import
=> ("reexports", "Re-exports"),
2301 ItemType
::Module
=> ("modules", "Modules"),
2302 ItemType
::Struct
=> ("structs", "Structs"),
2303 ItemType
::Union
=> ("unions", "Unions"),
2304 ItemType
::Enum
=> ("enums", "Enums"),
2305 ItemType
::Function
=> ("functions", "Functions"),
2306 ItemType
::Typedef
=> ("types", "Type Definitions"),
2307 ItemType
::Static
=> ("statics", "Statics"),
2308 ItemType
::Constant
=> ("constants", "Constants"),
2309 ItemType
::Trait
=> ("traits", "Traits"),
2310 ItemType
::Impl
=> ("impls", "Implementations"),
2311 ItemType
::TyMethod
=> ("tymethods", "Type Methods"),
2312 ItemType
::Method
=> ("methods", "Methods"),
2313 ItemType
::StructField
=> ("fields", "Struct Fields"),
2314 ItemType
::Variant
=> ("variants", "Variants"),
2315 ItemType
::Macro
=> ("macros", "Macros"),
2316 ItemType
::Primitive
=> ("primitives", "Primitive Types"),
2317 ItemType
::AssocType
=> ("associated-types", "Associated Types"),
2318 ItemType
::AssocConst
=> ("associated-consts", "Associated Constants"),
2319 ItemType
::ForeignType
=> ("foreign-types", "Foreign Types"),
2320 ItemType
::Keyword
=> ("keywords", "Keywords"),
2321 ItemType
::OpaqueTy
=> ("opaque-types", "Opaque Types"),
2322 ItemType
::ProcAttribute
=> ("attributes", "Attribute Macros"),
2323 ItemType
::ProcDerive
=> ("derives", "Derive Macros"),
2324 ItemType
::TraitAlias
=> ("trait-aliases", "Trait aliases"),
2328 fn sidebar_module(buf
: &mut Buffer
, items
: &[clean
::Item
]) {
2329 let mut sidebar
= String
::new();
2331 if items
.iter().any(|it
| {
2332 it
.type_() == ItemType
::ExternCrate
|| (it
.type_() == ItemType
::Import
&& !it
.is_stripped())
2334 sidebar
.push_str("<li><a href=\"#reexports\">Re-exports</a></li>");
2337 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
2338 // to print its headings
2340 ItemType
::Primitive
,
2354 ItemType
::StructField
,
2356 ItemType
::AssocType
,
2357 ItemType
::AssocConst
,
2358 ItemType
::ForeignType
,
2361 if items
.iter().any(|it
| !it
.is_stripped() && it
.type_() == myty
) {
2362 let (short
, name
) = item_ty_to_strs(&myty
);
2363 sidebar
.push_str(&format
!(
2364 "<li><a href=\"#{id}\">{name}</a></li>",
2371 if !sidebar
.is_empty() {
2372 write
!(buf
, "<div class=\"block items\"><ul>{}</ul></div>", sidebar
);
2376 fn sidebar_foreign_type(cx
: &Context
<'_
>, buf
: &mut Buffer
, it
: &clean
::Item
) {
2377 let mut sidebar
= Buffer
::new();
2378 sidebar_assoc_items(cx
, &mut sidebar
, it
);
2380 if !sidebar
.is_empty() {
2381 write
!(buf
, "<div class=\"block items\">{}</div>", sidebar
.into_inner());
2385 crate const BASIC_KEYWORDS
: &str = "rust, rustlang, rust-lang";
2387 /// Returns a list of all paths used in the type.
2388 /// This is used to help deduplicate imported impls
2389 /// for reexported types. If any of the contained
2390 /// types are re-exported, we don't use the corresponding
2391 /// entry from the js file, as inlining will have already
2392 /// picked up the impl
2393 fn collect_paths_for_type(first_ty
: clean
::Type
, cache
: &Cache
) -> Vec
<String
> {
2394 let mut out
= Vec
::new();
2395 let mut visited
= FxHashSet
::default();
2396 let mut work
= VecDeque
::new();
2398 work
.push_back(first_ty
);
2400 while let Some(ty
) = work
.pop_front() {
2401 if !visited
.insert(ty
.clone()) {
2406 clean
::Type
::ResolvedPath { did, .. }
=> {
2407 let get_extern
= || cache
.external_paths
.get(&did
).map(|s
| s
.0.clone());
2408 let fqp
= cache
.exact_paths
.get(&did
).cloned().or_else(get_extern
);
2410 if let Some(path
) = fqp
{
2411 out
.push(path
.join("::"));
2414 clean
::Type
::Tuple(tys
) => {
2415 work
.extend(tys
.into_iter());
2417 clean
::Type
::Slice(ty
) => {
2418 work
.push_back(*ty
);
2420 clean
::Type
::Array(ty
, _
) => {
2421 work
.push_back(*ty
);
2423 clean
::Type
::RawPointer(_
, ty
) => {
2424 work
.push_back(*ty
);
2426 clean
::Type
::BorrowedRef { type_, .. }
=> {
2427 work
.push_back(*type_
);
2429 clean
::Type
::QPath { self_type, trait_, .. }
=> {
2430 work
.push_back(*self_type
);
2431 work
.push_back(*trait_
);