]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/render/mod.rs
Rollup merge of #83810 - benmezger:update-builtin-docs-typo, r=jonas-schievink
[rust.git] / src / librustdoc / html / render / mod.rs
1 //! Rustdoc's HTML rendering module.
2 //!
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.
7 //!
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
14 //! rendered.
15 //!
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).
20 //!
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.
25
26 crate mod cache;
27
28 #[cfg(test)]
29 mod tests;
30
31 mod context;
32 mod print_item;
33 mod write_shared;
34
35 crate use context::*;
36 crate use write_shared::FILES_UNVERSIONED;
37
38 use std::cell::{Cell, RefCell};
39 use std::collections::VecDeque;
40 use std::default::Default;
41 use std::fmt;
42 use std::path::{Path, PathBuf};
43 use std::str;
44 use std::string::ToString;
45 use std::sync::mpsc::Receiver;
46
47 use itertools::Itertools;
48 use rustc_ast_pretty::pprust;
49 use rustc_attr::{Deprecation, StabilityLevel};
50 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
51 use rustc_hir as hir;
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};
61
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, print_where_clause,
71     Buffer, PrintWithSpace,
72 };
73 use crate::html::layout;
74 use crate::html::markdown::{self, ErrorCodes, Markdown, MarkdownHtml, MarkdownSummaryLine};
75
76 /// A pair of name and its optional document.
77 crate type NameDoc = (String, Option<String>);
78
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) }
82     })
83 }
84
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
96     /// `true`.
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
101     collapsed: bool,
102     /// The base-URL of the issue tracker for when an item has been tagged with
103     /// an issue number.
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
114     /// "light-v2.css").
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.
120     crate fs: DocFS,
121     /// The default edition used to parse doctests.
122     crate edition: Edition,
123     codes: ErrorCodes,
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
131     /// the crate.
132     redirections: Option<RefCell<FxHashMap<String, String>>>,
133 }
134
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());
141         }
142
143         Ok(())
144     }
145
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() }
150     }
151 }
152
153 // Helper structs for rendering items/sidebars and carrying along contextual
154 // information
155
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.
158 #[derive(Debug)]
159 crate struct IndexItem {
160     crate ty: ItemType,
161     crate name: String,
162     crate path: String,
163     crate desc: String,
164     crate parent: Option<DefId>,
165     crate parent_idx: Option<usize>,
166     crate search_type: Option<IndexItemFunctionType>,
167 }
168
169 /// A type used for the search index.
170 #[derive(Debug)]
171 crate struct RenderType {
172     ty: Option<DefId>,
173     idx: Option<usize>,
174     name: Option<String>,
175     generics: Option<Vec<Generic>>,
176 }
177
178 impl Serialize for RenderType {
179     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
180     where
181         S: Serializer,
182     {
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)?;
187             } else {
188                 seq.serialize_element(&name)?;
189             }
190             if let Some(generics) = &self.generics {
191                 seq.serialize_element(&generics)?;
192             }
193             seq.end()
194         } else {
195             serializer.serialize_none()
196         }
197     }
198 }
199
200 /// A type used for the search index.
201 #[derive(Debug)]
202 crate struct Generic {
203     name: String,
204     defid: Option<DefId>,
205     idx: Option<usize>,
206 }
207
208 impl Serialize for Generic {
209     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
210     where
211         S: Serializer,
212     {
213         if let Some(id) = self.idx {
214             serializer.serialize_some(&id)
215         } else {
216             serializer.serialize_some(&self.name)
217         }
218     }
219 }
220
221 /// Full type of functions/methods in the search index.
222 #[derive(Debug)]
223 crate struct IndexItemFunctionType {
224     inputs: Vec<TypeWithKind>,
225     output: Option<Vec<TypeWithKind>>,
226 }
227
228 impl Serialize for IndexItemFunctionType {
229     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
230     where
231         S: Serializer,
232     {
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()),
238         } {
239             serializer.serialize_none()
240         } else {
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)?;
246                 } else {
247                     seq.serialize_element(&output[0])?;
248                 }
249             }
250             seq.end()
251         }
252     }
253 }
254
255 #[derive(Debug)]
256 crate struct TypeWithKind {
257     ty: RenderType,
258     kind: TypeKind,
259 }
260
261 impl From<(RenderType, TypeKind)> for TypeWithKind {
262     fn from(x: (RenderType, TypeKind)) -> TypeWithKind {
263         TypeWithKind { ty: x.0, kind: x.1 }
264     }
265 }
266
267 impl Serialize for TypeWithKind {
268     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
269     where
270         S: Serializer,
271     {
272         (&self.ty.name, ItemType::from(self.kind)).serialize(serializer)
273     }
274 }
275
276 #[derive(Debug, Clone)]
277 crate struct StylePath {
278     /// The path to the theme
279     crate path: PathBuf,
280     /// What the `disabled` attribute should be set to in the HTML tag
281     crate disabled: bool,
282 }
283
284 thread_local!(crate static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
285
286 crate const INITIAL_IDS: [&'static str; 15] = [
287     "main",
288     "search",
289     "help",
290     "TOC",
291     "render-detail",
292     "associated-types",
293     "associated-const",
294     "required-methods",
295     "provided-methods",
296     "implementors",
297     "synthetic-implementors",
298     "implementors-list",
299     "synthetic-implementors-list",
300     "methods",
301     "implementations",
302 ];
303
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)
307     }
308 }
309
310 #[derive(Debug, Eq, PartialEq, Hash)]
311 struct ItemEntry {
312     url: String,
313     name: String,
314 }
315
316 impl ItemEntry {
317     fn new(mut url: String, name: String) -> ItemEntry {
318         while url.starts_with('/') {
319             url.remove(0);
320         }
321         ItemEntry { url, name }
322     }
323 }
324
325 impl ItemEntry {
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))
329         })
330     }
331 }
332
333 impl PartialOrd for ItemEntry {
334     fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
335         Some(self.cmp(other))
336     }
337 }
338
339 impl Ord for ItemEntry {
340     fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
341         self.name.cmp(&other.name)
342     }
343 }
344
345 #[derive(Debug)]
346 struct AllTypes {
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>,
362 }
363
364 impl AllTypes {
365     fn new() -> AllTypes {
366         let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
367         AllTypes {
368             structs: new_set(100),
369             enums: 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),
383         }
384     }
385
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);
390             url.push(name);
391             let name = url.join("::");
392             match *item_type {
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)),
407                 _ => true,
408             };
409         }
410     }
411 }
412
413 impl AllTypes {
414     fn print(self, f: &mut Buffer) {
415         fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
416             if !e.is_empty() {
417                 let mut e: Vec<&ItemEntry> = e.iter().collect();
418                 e.sort();
419                 write!(f, "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">", title, title, class);
420
421                 for s in e.iter() {
422                     write!(f, "<li>{}</li>", s.print());
423                 }
424
425                 f.write_str("</ul>");
426             }
427         }
428
429         f.write_str(
430             "<h1 class=\"fqn\">\
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\">&#x2212;</span>]\
437                          </a>\
438                      </span>
439                  </span>
440              </h1>",
441         );
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")
458     }
459 }
460
461 #[derive(Debug)]
462 enum Setting {
463     Section {
464         description: &'static str,
465         sub_settings: Vec<Setting>,
466     },
467     Toggle {
468         js_data_name: &'static str,
469         description: &'static str,
470         default_value: bool,
471     },
472     Select {
473         js_data_name: &'static str,
474         description: &'static str,
475         default_value: &'static str,
476         options: Vec<(String, String)>,
477     },
478 }
479
480 impl Setting {
481     fn display(&self, root_path: &str, suffix: &str) -> String {
482         match *self {
483             Setting::Section { description, ref sub_settings } => format!(
484                 "<div class=\"setting-line\">\
485                      <div class=\"title\">{}</div>\
486                      <div class=\"sub-settings\">{}</div>
487                  </div>",
488                 description,
489                 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
490             ),
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>\
496                      </label>\
497                      <div>{}</div>\
498                  </div>",
499                 js_data_name,
500                 if default_value { " checked" } else { "" },
501                 description,
502             ),
503             Setting::Select { js_data_name, description, default_value, ref options } => format!(
504                 "<div class=\"setting-line\">\
505                      <div>{}</div>\
506                      <label class=\"select-wrapper\">\
507                          <select id=\"{}\" autocomplete=\"off\">{}</select>\
508                          <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
509                      </label>\
510                  </div>",
511                 description,
512                 js_data_name,
513                 options
514                     .iter()
515                     .map(|opt| format!(
516                         "<option value=\"{}\" {}>{}</option>",
517                         opt.0,
518                         if opt.0 == default_value { "selected" } else { "" },
519                         opt.1,
520                     ))
521                     .collect::<String>(),
522                 root_path,
523                 suffix,
524             ),
525         }
526     }
527 }
528
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 }
532     }
533 }
534
535 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
536     fn from(values: (&'static str, Vec<T>)) -> Setting {
537         Setting::Section {
538             description: values.0,
539             sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
540         }
541     }
542 }
543
544 fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
545     let theme_names: Vec<(String, String)> = themes
546         .iter()
547         .map(|entry| {
548             let theme =
549                 try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
550                     .to_string();
551
552             Ok((theme.clone(), theme))
553         })
554         .collect::<Result<_, Error>>()?;
555
556     // (id, explanation, default value)
557     let settings: &[Setting] = &[
558         (
559             "Theme preferences",
560             vec![
561                 Setting::from(("use-system-theme", "Use system theme", true)),
562                 Setting::Select {
563                     js_data_name: "preferred-dark-theme",
564                     description: "Preferred dark theme",
565                     default_value: "dark",
566                     options: theme_names.clone(),
567                 },
568                 Setting::Select {
569                     js_data_name: "preferred-light-theme",
570                     description: "Preferred light theme",
571                     default_value: "light",
572                     options: theme_names,
573                 },
574             ],
575         )
576             .into(),
577         (
578             "Auto-hide item declarations",
579             vec![
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),
585             ],
586         )
587             .into(),
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)
591             .into(),
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)
594             .into(),
595         ("line-numbers", "Show line numbers on code examples", false).into(),
596         ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
597     ];
598
599     Ok(format!(
600         "<h1 class=\"fqn\">\
601             <span class=\"in-band\">Rustdoc settings</span>\
602         </h1>\
603         <div class=\"settings\">{}</div>\
604         <script src=\"{}settings{}.js\"></script>",
605         settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
606         root_path,
607         suffix
608     ))
609 }
610
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);
614     }
615     document_item_info(w, cx, item, false, parent);
616     document_full(w, item, cx, "", false);
617 }
618
619 /// Render md_text as markdown.
620 fn render_markdown(
621     w: &mut Buffer,
622     cx: &Context<'_>,
623     md_text: &str,
624     links: Vec<RenderedLink>,
625     prefix: &str,
626     is_hidden: bool,
627 ) {
628     let mut ids = cx.id_map.borrow_mut();
629     write!(
630         w,
631         "<div class=\"docblock{}\">{}{}</div>",
632         if is_hidden { " hidden" } else { "" },
633         prefix,
634         Markdown(
635             md_text,
636             &links,
637             &mut ids,
638             cx.shared.codes,
639             cx.shared.edition,
640             &cx.shared.playground
641         )
642         .into_string()
643     )
644 }
645
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.
648 fn document_short(
649     w: &mut Buffer,
650     item: &clean::Item,
651     cx: &Context<'_>,
652     link: AssocItemLink<'_>,
653     prefix: &str,
654     is_hidden: bool,
655     parent: Option<&clean::Item>,
656     show_def_docs: bool,
657 ) {
658     document_item_info(w, cx, item, is_hidden, parent);
659     if !show_def_docs {
660         return;
661     }
662     if let Some(s) = item.doc_value() {
663         let mut summary_html = MarkdownSummaryLine(&s, &item.links(&cx.cache)).into_string();
664
665         if s.contains('\n') {
666             let link =
667                 format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link, cx.cache()));
668
669             if let Some(idx) = summary_html.rfind("</p>") {
670                 summary_html.insert_str(idx, &link);
671             } else {
672                 summary_html.push_str(&link);
673             }
674         }
675
676         write!(
677             w,
678             "<div class='docblock{}'>{}{}</div>",
679             if is_hidden { " hidden" } else { "" },
680             prefix,
681             summary_html,
682         );
683     } else if !prefix.is_empty() {
684         write!(
685             w,
686             "<div class=\"docblock{}\">{}</div>",
687             if is_hidden { " hidden" } else { "" },
688             prefix
689         );
690     }
691 }
692
693 fn document_full(
694     w: &mut Buffer,
695     item: &clean::Item,
696     cx: &Context<'_>,
697     prefix: &str,
698     is_hidden: bool,
699 ) {
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() {
704         if is_hidden {
705             w.write_str("<div class=\"docblock hidden\">");
706         } else {
707             w.write_str("<div class=\"docblock\">");
708         }
709         w.write_str(prefix);
710         w.write_str("</div>");
711     }
712 }
713
714 /// Add extra information about an item such as:
715 ///
716 /// * Stability
717 /// * Deprecated
718 /// * Required features (through the `doc_cfg` feature)
719 fn document_item_info(
720     w: &mut Buffer,
721     cx: &Context<'_>,
722     item: &clean::Item,
723     is_hidden: bool,
724     parent: Option<&clean::Item>,
725 ) {
726     let item_infos = short_item_info(item, cx, parent);
727     if !item_infos.is_empty() {
728         if is_hidden {
729             w.write_str("<div class=\"item-info hidden\">");
730         } else {
731             w.write_str("<div class=\"item-info\">");
732         }
733         for info in item_infos {
734             w.write_str(&info);
735         }
736         w.write_str("</div>");
737     }
738 }
739
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(),
744     };
745
746     debug!(
747         "Portability {:?} - {:?} = {:?}",
748         item.attrs.cfg,
749         parent.and_then(|p| p.attrs.cfg.as_ref()),
750         cfg
751     );
752
753     Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
754 }
755
756 /// Render the stability, deprecation and portability information that is displayed at the top of
757 /// the item's documentation.
758 fn short_item_info(
759     item: &clean::Item,
760     cx: &Context<'_>,
761     parent: Option<&clean::Item>,
762 ) -> Vec<String> {
763     let mut extra_info = vec![];
764     let error_codes = cx.shared.codes;
765
766     if let Some(Deprecation { note, since, is_since_rustc_version, suggestion: _ }) =
767         item.deprecation(cx.tcx())
768     {
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)) {
774                 if *since == "TBD" {
775                     String::from("Deprecating in a future Rust version")
776                 } else {
777                     format!("Deprecating in {}", Escape(since))
778                 }
779             } else {
780                 format!("Deprecated since {}", Escape(since))
781             }
782         } else {
783             String::from("Deprecated")
784         };
785
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(
790                 &note,
791                 &mut ids,
792                 error_codes,
793                 cx.shared.edition,
794                 &cx.shared.playground,
795             );
796             message.push_str(&format!(": {}", html.into_string()));
797         }
798         extra_info.push(format!(
799             "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
800             message,
801         ));
802     }
803
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
807         .stability(cx.tcx())
808         .as_ref()
809         .filter(|stab| stab.feature != sym::rustc_private)
810         .map(|stab| (stab.level, stab.feature))
811     {
812         let mut message =
813             "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
814
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                 "&nbsp;<a href=\"{url}{issue}\">#{issue}</a>",
819                 url = url,
820                 issue = issue
821             ));
822         }
823
824         message.push_str(&format!(" ({})", feature));
825
826         if let Some(unstable_reason) = reason {
827             let mut ids = cx.id_map.borrow_mut();
828             message = format!(
829                 "<details><summary>{}</summary>{}</details>",
830                 message,
831                 MarkdownHtml(
832                     &unstable_reason.as_str(),
833                     &mut ids,
834                     error_codes,
835                     cx.shared.edition,
836                     &cx.shared.playground,
837                 )
838                 .into_string()
839             );
840         }
841
842         extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
843     }
844
845     if let Some(portability) = portability(item, parent) {
846         extra_info.push(portability);
847     }
848
849     extra_info
850 }
851
852 fn render_impls(
853     cx: &Context<'_>,
854     w: &mut Buffer,
855     traits: &[&&Impl],
856     containing_item: &clean::Item,
857 ) {
858     let cache = cx.cache();
859     let tcx = cx.tcx();
860     let mut impls = traits
861         .iter()
862         .map(|i| {
863             let did = i.trait_did_full(cache).unwrap();
864             let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
865             let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
866             render_impl(
867                 &mut buffer,
868                 cx,
869                 i,
870                 containing_item,
871                 assoc_link,
872                 RenderMode::Normal,
873                 containing_item.stable_since(tcx).as_deref(),
874                 containing_item.const_stable_since(tcx).as_deref(),
875                 true,
876                 None,
877                 false,
878                 true,
879                 &[],
880             );
881             buffer.into_inner()
882         })
883         .collect::<Vec<_>>();
884     impls.sort();
885     w.write_str(&impls.join(""));
886 }
887
888 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>, cache: &Cache) -> String {
889     use crate::formats::item_type::ItemType::*;
890
891     let name = it.name.as_ref().unwrap();
892     let ty = match it.type_() {
893         Typedef | AssocType => AssocType,
894         s => s,
895     };
896
897     let anchor = format!("#{}.{}", ty, name);
898     match link {
899         AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
900         AssocItemLink::Anchor(None) => anchor,
901         AssocItemLink::GotoSource(did, _) => {
902             href(did, cache).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
903         }
904     }
905 }
906
907 fn assoc_const(
908     w: &mut Buffer,
909     it: &clean::Item,
910     ty: &clean::Type,
911     _default: Option<&String>,
912     link: AssocItemLink<'_>,
913     extra: &str,
914     cx: &Context<'_>,
915 ) {
916     let cache = cx.cache();
917     let tcx = cx.tcx();
918     write!(
919         w,
920         "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
921         extra,
922         it.visibility.print_with_space(tcx, it.def_id, cache),
923         naive_assoc_href(it, link, cache),
924         it.name.as_ref().unwrap(),
925         ty.print(cache, tcx)
926     );
927 }
928
929 fn assoc_type(
930     w: &mut Buffer,
931     it: &clean::Item,
932     bounds: &[clean::GenericBound],
933     default: Option<&clean::Type>,
934     link: AssocItemLink<'_>,
935     extra: &str,
936     cache: &Cache,
937     tcx: TyCtxt<'_>,
938 ) {
939     write!(
940         w,
941         "{}type <a href=\"{}\" class=\"type\">{}</a>",
942         extra,
943         naive_assoc_href(it, link, cache),
944         it.name.as_ref().unwrap()
945     );
946     if !bounds.is_empty() {
947         write!(w, ": {}", print_generic_bounds(bounds, cache, tcx))
948     }
949     if let Some(default) = default {
950         write!(w, " = {}", default.print(cache, tcx))
951     }
952 }
953
954 fn render_stability_since_raw(
955     w: &mut Buffer,
956     ver: Option<&str>,
957     const_ver: Option<&str>,
958     containing_ver: Option<&str>,
959     containing_const_ver: Option<&str>,
960 ) {
961     let ver = ver.filter(|inner| !inner.is_empty());
962     let const_ver = const_ver.filter(|inner| !inner.is_empty());
963
964     match (ver, const_ver) {
965         (Some(v), Some(cv)) if const_ver != containing_const_ver => {
966             write!(
967                 w,
968                 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
969                 v, cv
970             );
971         }
972         (Some(v), _) if ver != containing_ver => {
973             write!(
974                 w,
975                 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
976                 v
977             );
978         }
979         _ => {}
980     }
981 }
982
983 fn render_assoc_item(
984     w: &mut Buffer,
985     item: &clean::Item,
986     link: AssocItemLink<'_>,
987     parent: ItemType,
988     cx: &Context<'_>,
989 ) {
990     fn method(
991         w: &mut Buffer,
992         meth: &clean::Item,
993         header: hir::FnHeader,
994         g: &clean::Generics,
995         d: &clean::FnDecl,
996         link: AssocItemLink<'_>,
997         parent: ItemType,
998         cx: &Context<'_>,
999     ) {
1000         let cache = cx.cache();
1001         let tcx = cx.tcx();
1002         let name = meth.name.as_ref().unwrap();
1003         let anchor = format!("#{}.{}", meth.type_(), name);
1004         let href = match link {
1005             AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
1006             AssocItemLink::Anchor(None) => anchor,
1007             AssocItemLink::GotoSource(did, provided_methods) => {
1008                 // We're creating a link from an impl-item to the corresponding
1009                 // trait-item and need to map the anchored type accordingly.
1010                 let ty = if provided_methods.contains(&name) {
1011                     ItemType::Method
1012                 } else {
1013                     ItemType::TyMethod
1014                 };
1015
1016                 href(did, cache).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
1017             }
1018         };
1019         let vis = meth.visibility.print_with_space(tcx, meth.def_id, cache).to_string();
1020         let constness = header.constness.print_with_space();
1021         let asyncness = header.asyncness.print_with_space();
1022         let unsafety = header.unsafety.print_with_space();
1023         let defaultness = print_default_space(meth.is_default());
1024         let abi = print_abi_with_space(header.abi).to_string();
1025         // NOTE: `{:#}` does not print HTML formatting, `{}` does. So `g.print` can't be reused between the length calculation and `write!`.
1026         let generics_len = format!("{:#}", g.print(cache, tcx)).len();
1027         let mut header_len = "fn ".len()
1028             + vis.len()
1029             + constness.len()
1030             + asyncness.len()
1031             + unsafety.len()
1032             + defaultness.len()
1033             + abi.len()
1034             + name.as_str().len()
1035             + generics_len;
1036
1037         let (indent, end_newline) = if parent == ItemType::Trait {
1038             header_len += 4;
1039             (4, false)
1040         } else {
1041             (0, true)
1042         };
1043         render_attributes(w, meth, false);
1044         w.reserve(header_len + "<a href=\"\" class=\"fnname\">{".len() + "</a>".len());
1045         write!(
1046             w,
1047             "{}{}{}{}{}{}{}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
1048              {generics}{decl}{notable_traits}{where_clause}",
1049             if parent == ItemType::Trait { "    " } else { "" },
1050             vis,
1051             constness,
1052             asyncness,
1053             unsafety,
1054             defaultness,
1055             abi,
1056             href = href,
1057             name = name,
1058             generics = g.print(cache, tcx),
1059             decl = d.full_print(cache, tcx, header_len, indent, header.asyncness),
1060             notable_traits = notable_traits_decl(&d, cache, tcx),
1061             where_clause = print_where_clause(g, cache, tcx, indent, end_newline),
1062         )
1063     }
1064     match *item.kind {
1065         clean::StrippedItem(..) => {}
1066         clean::TyMethodItem(ref m) => {
1067             method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
1068         }
1069         clean::MethodItem(ref m, _) => {
1070             method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
1071         }
1072         clean::AssocConstItem(ref ty, ref default) => assoc_const(
1073             w,
1074             item,
1075             ty,
1076             default.as_ref(),
1077             link,
1078             if parent == ItemType::Trait { "    " } else { "" },
1079             cx,
1080         ),
1081         clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
1082             w,
1083             item,
1084             bounds,
1085             default.as_ref(),
1086             link,
1087             if parent == ItemType::Trait { "    " } else { "" },
1088             cx.cache(),
1089             cx.tcx(),
1090         ),
1091         _ => panic!("render_assoc_item called on non-associated-item"),
1092     }
1093 }
1094
1095 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
1096     sym::export_name,
1097     sym::lang,
1098     sym::link_section,
1099     sym::must_use,
1100     sym::no_mangle,
1101     sym::repr,
1102     sym::non_exhaustive,
1103 ];
1104
1105 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
1106 // left padding. For example:
1107 //
1108 // #[foo] <----- "top" attribute
1109 // struct Foo {
1110 //     #[bar] <---- not "top" attribute
1111 //     bar: usize,
1112 // }
1113 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
1114     let attrs = it
1115         .attrs
1116         .other_attrs
1117         .iter()
1118         .filter_map(|attr| {
1119             if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
1120                 Some(pprust::attribute_to_string(&attr))
1121             } else {
1122                 None
1123             }
1124         })
1125         .join("\n");
1126
1127     if !attrs.is_empty() {
1128         write!(
1129             w,
1130             "<span class=\"docblock attributes{}\">{}</span>",
1131             if top { " top-attr" } else { "" },
1132             &attrs
1133         );
1134     }
1135 }
1136
1137 #[derive(Copy, Clone)]
1138 enum AssocItemLink<'a> {
1139     Anchor(Option<&'a str>),
1140     GotoSource(DefId, &'a FxHashSet<Symbol>),
1141 }
1142
1143 impl<'a> AssocItemLink<'a> {
1144     fn anchor(&self, id: &'a str) -> Self {
1145         match *self {
1146             AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
1147             ref other => *other,
1148         }
1149     }
1150 }
1151
1152 fn render_assoc_items(
1153     w: &mut Buffer,
1154     cx: &Context<'_>,
1155     containing_item: &clean::Item,
1156     it: DefId,
1157     what: AssocItemRender<'_>,
1158 ) {
1159     info!("Documenting associated items of {:?}", containing_item.name);
1160     let v = match cx.cache.impls.get(&it) {
1161         Some(v) => v,
1162         None => return,
1163     };
1164     let tcx = cx.tcx();
1165     let cache = cx.cache();
1166     let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
1167     if !non_trait.is_empty() {
1168         let render_mode = match what {
1169             AssocItemRender::All => {
1170                 w.write_str(
1171                     "<h2 id=\"implementations\" class=\"small-section-header\">\
1172                          Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
1173                     </h2>",
1174                 );
1175                 RenderMode::Normal
1176             }
1177             AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
1178                 let id = cx.derive_id(small_url_encode(format!(
1179                     "deref-methods-{:#}",
1180                     type_.print(cache, tcx)
1181                 )));
1182                 debug!("Adding {} to deref id map", type_.print(cache, tcx));
1183                 cx.deref_id_map.borrow_mut().insert(type_.def_id_full(cache).unwrap(), id.clone());
1184                 write!(
1185                     w,
1186                     "<h2 id=\"{id}\" class=\"small-section-header\">\
1187                          Methods from {trait_}&lt;Target = {type_}&gt;\
1188                          <a href=\"#{id}\" class=\"anchor\"></a>\
1189                      </h2>",
1190                     id = id,
1191                     trait_ = trait_.print(cache, tcx),
1192                     type_ = type_.print(cache, tcx),
1193                 );
1194                 RenderMode::ForDeref { mut_: deref_mut_ }
1195             }
1196         };
1197         for i in &non_trait {
1198             render_impl(
1199                 w,
1200                 cx,
1201                 i,
1202                 containing_item,
1203                 AssocItemLink::Anchor(None),
1204                 render_mode,
1205                 containing_item.stable_since(tcx).as_deref(),
1206                 containing_item.const_stable_since(tcx).as_deref(),
1207                 true,
1208                 None,
1209                 false,
1210                 true,
1211                 &[],
1212             );
1213         }
1214     }
1215     if !traits.is_empty() {
1216         let deref_impl = traits
1217             .iter()
1218             .find(|t| t.inner_impl().trait_.def_id_full(cache) == cx.cache.deref_trait_did);
1219         if let Some(impl_) = deref_impl {
1220             let has_deref_mut = traits
1221                 .iter()
1222                 .any(|t| t.inner_impl().trait_.def_id_full(cache) == cx.cache.deref_mut_trait_did);
1223             render_deref_methods(w, cx, impl_, containing_item, has_deref_mut);
1224         }
1225
1226         // If we were already one level into rendering deref methods, we don't want to render
1227         // anything after recursing into any further deref methods above.
1228         if let AssocItemRender::DerefFor { .. } = what {
1229             return;
1230         }
1231
1232         let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
1233             traits.iter().partition(|t| t.inner_impl().synthetic);
1234         let (blanket_impl, concrete): (Vec<&&Impl>, _) =
1235             concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
1236
1237         let mut impls = Buffer::empty_from(&w);
1238         render_impls(cx, &mut impls, &concrete, containing_item);
1239         let impls = impls.into_inner();
1240         if !impls.is_empty() {
1241             write!(
1242                 w,
1243                 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
1244                      Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
1245                  </h2>\
1246                  <div id=\"trait-implementations-list\">{}</div>",
1247                 impls
1248             );
1249         }
1250
1251         if !synthetic.is_empty() {
1252             w.write_str(
1253                 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
1254                      Auto Trait Implementations\
1255                      <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
1256                  </h2>\
1257                  <div id=\"synthetic-implementations-list\">",
1258             );
1259             render_impls(cx, w, &synthetic, containing_item);
1260             w.write_str("</div>");
1261         }
1262
1263         if !blanket_impl.is_empty() {
1264             w.write_str(
1265                 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
1266                      Blanket Implementations\
1267                      <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
1268                  </h2>\
1269                  <div id=\"blanket-implementations-list\">",
1270             );
1271             render_impls(cx, w, &blanket_impl, containing_item);
1272             w.write_str("</div>");
1273         }
1274     }
1275 }
1276
1277 fn render_deref_methods(
1278     w: &mut Buffer,
1279     cx: &Context<'_>,
1280     impl_: &Impl,
1281     container_item: &clean::Item,
1282     deref_mut: bool,
1283 ) {
1284     let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
1285     let (target, real_target) = impl_
1286         .inner_impl()
1287         .items
1288         .iter()
1289         .find_map(|item| match *item.kind {
1290             clean::TypedefItem(ref t, true) => Some(match *t {
1291                 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
1292                 _ => (&t.type_, &t.type_),
1293             }),
1294             _ => None,
1295         })
1296         .expect("Expected associated type binding");
1297     debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target);
1298     let what =
1299         AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
1300     if let Some(did) = target.def_id_full(cx.cache()) {
1301         if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) {
1302             // `impl Deref<Target = S> for S`
1303             if did == type_did {
1304                 // Avoid infinite cycles
1305                 return;
1306             }
1307         }
1308         render_assoc_items(w, cx, container_item, did, what);
1309     } else {
1310         if let Some(prim) = target.primitive_type() {
1311             if let Some(&did) = cx.cache.primitive_locations.get(&prim) {
1312                 render_assoc_items(w, cx, container_item, did, what);
1313             }
1314         }
1315     }
1316 }
1317
1318 fn should_render_item(item: &clean::Item, deref_mut_: bool, cache: &Cache) -> bool {
1319     let self_type_opt = match *item.kind {
1320         clean::MethodItem(ref method, _) => method.decl.self_type(),
1321         clean::TyMethodItem(ref method) => method.decl.self_type(),
1322         _ => None,
1323     };
1324
1325     if let Some(self_ty) = self_type_opt {
1326         let (by_mut_ref, by_box, by_value) = match self_ty {
1327             SelfTy::SelfBorrowed(_, mutability)
1328             | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
1329                 (mutability == Mutability::Mut, false, false)
1330             }
1331             SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
1332                 (false, Some(did) == cache.owned_box_did, false)
1333             }
1334             SelfTy::SelfValue => (false, false, true),
1335             _ => (false, false, false),
1336         };
1337
1338         (deref_mut_ || !by_mut_ref) && !by_box && !by_value
1339     } else {
1340         false
1341     }
1342 }
1343
1344 fn notable_traits_decl(decl: &clean::FnDecl, cache: &Cache, tcx: TyCtxt<'_>) -> String {
1345     let mut out = Buffer::html();
1346     let mut trait_ = String::new();
1347
1348     if let Some(did) = decl.output.def_id_full(cache) {
1349         if let Some(impls) = cache.impls.get(&did) {
1350             for i in impls {
1351                 let impl_ = i.inner_impl();
1352                 if impl_
1353                     .trait_
1354                     .def_id()
1355                     .map_or(false, |d| cache.traits.get(&d).map(|t| t.is_notable).unwrap_or(false))
1356                 {
1357                     if out.is_empty() {
1358                         write!(
1359                             &mut out,
1360                             "<h3 class=\"notable\">Notable traits for {}</h3>\
1361                              <code class=\"content\">",
1362                             impl_.for_.print(cache, tcx)
1363                         );
1364                         trait_.push_str(&impl_.for_.print(cache, tcx).to_string());
1365                     }
1366
1367                     //use the "where" class here to make it small
1368                     write!(
1369                         &mut out,
1370                         "<span class=\"where fmt-newline\">{}</span>",
1371                         impl_.print(cache, false, tcx)
1372                     );
1373                     let t_did = impl_.trait_.def_id_full(cache).unwrap();
1374                     for it in &impl_.items {
1375                         if let clean::TypedefItem(ref tydef, _) = *it.kind {
1376                             out.push_str("<span class=\"where fmt-newline\">    ");
1377                             assoc_type(
1378                                 &mut out,
1379                                 it,
1380                                 &[],
1381                                 Some(&tydef.type_),
1382                                 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
1383                                 "",
1384                                 cache,
1385                                 tcx,
1386                             );
1387                             out.push_str(";</span>");
1388                         }
1389                     }
1390                 }
1391             }
1392         }
1393     }
1394
1395     if !out.is_empty() {
1396         out.insert_str(
1397             0,
1398             "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
1399             <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
1400         );
1401         out.push_str("</code></span></div></span></span>");
1402     }
1403
1404     out.into_inner()
1405 }
1406
1407 fn render_impl(
1408     w: &mut Buffer,
1409     cx: &Context<'_>,
1410     i: &Impl,
1411     parent: &clean::Item,
1412     link: AssocItemLink<'_>,
1413     render_mode: RenderMode,
1414     outer_version: Option<&str>,
1415     outer_const_version: Option<&str>,
1416     show_def_docs: bool,
1417     use_absolute: Option<bool>,
1418     is_on_foreign_type: bool,
1419     show_default_items: bool,
1420     // This argument is used to reference same type with different paths to avoid duplication
1421     // in documentation pages for trait with automatic implementations like "Send" and "Sync".
1422     aliases: &[String],
1423 ) {
1424     let traits = &cx.cache.traits;
1425     let tcx = cx.tcx();
1426     let cache = cx.cache();
1427     let trait_ = i.trait_did_full(cache).map(|did| &traits[&did]);
1428
1429     if render_mode == RenderMode::Normal {
1430         let id = cx.derive_id(match i.inner_impl().trait_ {
1431             Some(ref t) => {
1432                 if is_on_foreign_type {
1433                     get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t, cache, tcx)
1434                 } else {
1435                     format!("impl-{}", small_url_encode(format!("{:#}", t.print(cache, tcx))))
1436                 }
1437             }
1438             None => "impl".to_string(),
1439         });
1440         let aliases = if aliases.is_empty() {
1441             String::new()
1442         } else {
1443             format!(" aliases=\"{}\"", aliases.join(","))
1444         };
1445         if let Some(use_absolute) = use_absolute {
1446             write!(w, "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">", id, aliases);
1447             write!(w, "{}", i.inner_impl().print(cache, use_absolute, tcx));
1448             if show_def_docs {
1449                 for it in &i.inner_impl().items {
1450                     if let clean::TypedefItem(ref tydef, _) = *it.kind {
1451                         w.write_str("<span class=\"where fmt-newline\">  ");
1452                         assoc_type(
1453                             w,
1454                             it,
1455                             &[],
1456                             Some(&tydef.type_),
1457                             AssocItemLink::Anchor(None),
1458                             "",
1459                             cache,
1460                             tcx,
1461                         );
1462                         w.write_str(";</span>");
1463                     }
1464                 }
1465             }
1466             w.write_str("</code>");
1467         } else {
1468             write!(
1469                 w,
1470                 "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">{}</code>",
1471                 id,
1472                 aliases,
1473                 i.inner_impl().print(cache, false, tcx)
1474             );
1475         }
1476         write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1477         render_stability_since_raw(
1478             w,
1479             i.impl_item.stable_since(tcx).as_deref(),
1480             i.impl_item.const_stable_since(tcx).as_deref(),
1481             outer_version,
1482             outer_const_version,
1483         );
1484         write_srclink(cx, &i.impl_item, w);
1485         w.write_str("</h3>");
1486
1487         if trait_.is_some() {
1488             if let Some(portability) = portability(&i.impl_item, Some(parent)) {
1489                 write!(w, "<div class=\"item-info\">{}</div>", portability);
1490             }
1491         }
1492
1493         if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
1494             let mut ids = cx.id_map.borrow_mut();
1495             write!(
1496                 w,
1497                 "<div class=\"docblock\">{}</div>",
1498                 Markdown(
1499                     &*dox,
1500                     &i.impl_item.links(&cx.cache),
1501                     &mut ids,
1502                     cx.shared.codes,
1503                     cx.shared.edition,
1504                     &cx.shared.playground
1505                 )
1506                 .into_string()
1507             );
1508         }
1509     }
1510
1511     fn doc_impl_item(
1512         w: &mut Buffer,
1513         cx: &Context<'_>,
1514         item: &clean::Item,
1515         parent: &clean::Item,
1516         link: AssocItemLink<'_>,
1517         render_mode: RenderMode,
1518         is_default_item: bool,
1519         outer_version: Option<&str>,
1520         outer_const_version: Option<&str>,
1521         trait_: Option<&clean::Trait>,
1522         show_def_docs: bool,
1523     ) {
1524         let item_type = item.type_();
1525         let name = item.name.as_ref().unwrap();
1526         let tcx = cx.tcx();
1527
1528         let render_method_item = match render_mode {
1529             RenderMode::Normal => true,
1530             RenderMode::ForDeref { mut_: deref_mut_ } => {
1531                 should_render_item(&item, deref_mut_, &cx.cache)
1532             }
1533         };
1534
1535         let (is_hidden, extra_class) =
1536             if (trait_.is_none() || item.doc_value().is_some() || item.kind.is_type_alias())
1537                 && !is_default_item
1538             {
1539                 (false, "")
1540             } else {
1541                 (true, " hidden")
1542             };
1543         match *item.kind {
1544             clean::MethodItem(..) | clean::TyMethodItem(_) => {
1545                 // Only render when the method is not static or we allow static methods
1546                 if render_method_item {
1547                     let id = cx.derive_id(format!("{}.{}", item_type, name));
1548                     write!(w, "<h4 id=\"{}\" class=\"{}{}\">", id, item_type, extra_class);
1549                     w.write_str("<code>");
1550                     render_assoc_item(w, item, link.anchor(&id), ItemType::Impl, cx);
1551                     w.write_str("</code>");
1552                     render_stability_since_raw(
1553                         w,
1554                         item.stable_since(tcx).as_deref(),
1555                         item.const_stable_since(tcx).as_deref(),
1556                         outer_version,
1557                         outer_const_version,
1558                     );
1559                     write_srclink(cx, item, w);
1560                     w.write_str("</h4>");
1561                 }
1562             }
1563             clean::TypedefItem(ref tydef, _) => {
1564                 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
1565                 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
1566                 assoc_type(
1567                     w,
1568                     item,
1569                     &Vec::new(),
1570                     Some(&tydef.type_),
1571                     link.anchor(&id),
1572                     "",
1573                     cx.cache(),
1574                     tcx,
1575                 );
1576                 w.write_str("</code></h4>");
1577             }
1578             clean::AssocConstItem(ref ty, ref default) => {
1579                 let id = cx.derive_id(format!("{}.{}", item_type, name));
1580                 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
1581                 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "", cx);
1582                 w.write_str("</code>");
1583                 render_stability_since_raw(
1584                     w,
1585                     item.stable_since(tcx).as_deref(),
1586                     item.const_stable_since(tcx).as_deref(),
1587                     outer_version,
1588                     outer_const_version,
1589                 );
1590                 write_srclink(cx, item, w);
1591                 w.write_str("</h4>");
1592             }
1593             clean::AssocTypeItem(ref bounds, ref default) => {
1594                 let id = cx.derive_id(format!("{}.{}", item_type, name));
1595                 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
1596                 assoc_type(
1597                     w,
1598                     item,
1599                     bounds,
1600                     default.as_ref(),
1601                     link.anchor(&id),
1602                     "",
1603                     cx.cache(),
1604                     tcx,
1605                 );
1606                 w.write_str("</code></h4>");
1607             }
1608             clean::StrippedItem(..) => return,
1609             _ => panic!("can't make docs for trait item with name {:?}", item.name),
1610         }
1611
1612         if render_method_item {
1613             if !is_default_item {
1614                 if let Some(t) = trait_ {
1615                     // The trait item may have been stripped so we might not
1616                     // find any documentation or stability for it.
1617                     if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
1618                         // We need the stability of the item from the trait
1619                         // because impls can't have a stability.
1620                         if item.doc_value().is_some() {
1621                             document_item_info(w, cx, it, is_hidden, Some(parent));
1622                             document_full(w, item, cx, "", is_hidden);
1623                         } else {
1624                             // In case the item isn't documented,
1625                             // provide short documentation from the trait.
1626                             document_short(
1627                                 w,
1628                                 it,
1629                                 cx,
1630                                 link,
1631                                 "",
1632                                 is_hidden,
1633                                 Some(parent),
1634                                 show_def_docs,
1635                             );
1636                         }
1637                     }
1638                 } else {
1639                     document_item_info(w, cx, item, is_hidden, Some(parent));
1640                     if show_def_docs {
1641                         document_full(w, item, cx, "", is_hidden);
1642                     }
1643                 }
1644             } else {
1645                 document_short(w, item, cx, link, "", is_hidden, Some(parent), show_def_docs);
1646             }
1647         }
1648     }
1649
1650     w.write_str("<div class=\"impl-items\">");
1651     for trait_item in &i.inner_impl().items {
1652         doc_impl_item(
1653             w,
1654             cx,
1655             trait_item,
1656             if trait_.is_some() { &i.impl_item } else { parent },
1657             link,
1658             render_mode,
1659             false,
1660             outer_version,
1661             outer_const_version,
1662             trait_.map(|t| &t.trait_),
1663             show_def_docs,
1664         );
1665     }
1666
1667     fn render_default_items(
1668         w: &mut Buffer,
1669         cx: &Context<'_>,
1670         t: &clean::Trait,
1671         i: &clean::Impl,
1672         parent: &clean::Item,
1673         render_mode: RenderMode,
1674         outer_version: Option<&str>,
1675         outer_const_version: Option<&str>,
1676         show_def_docs: bool,
1677     ) {
1678         for trait_item in &t.items {
1679             let n = trait_item.name;
1680             if i.items.iter().any(|m| m.name == n) {
1681                 continue;
1682             }
1683             let did = i.trait_.as_ref().unwrap().def_id_full(cx.cache()).unwrap();
1684             let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
1685
1686             doc_impl_item(
1687                 w,
1688                 cx,
1689                 trait_item,
1690                 parent,
1691                 assoc_link,
1692                 render_mode,
1693                 true,
1694                 outer_version,
1695                 outer_const_version,
1696                 None,
1697                 show_def_docs,
1698             );
1699         }
1700     }
1701
1702     // If we've implemented a trait, then also emit documentation for all
1703     // default items which weren't overridden in the implementation block.
1704     // We don't emit documentation for default items if they appear in the
1705     // Implementations on Foreign Types or Implementors sections.
1706     if show_default_items {
1707         if let Some(t) = trait_ {
1708             render_default_items(
1709                 w,
1710                 cx,
1711                 &t.trait_,
1712                 &i.inner_impl(),
1713                 &i.impl_item,
1714                 render_mode,
1715                 outer_version,
1716                 outer_const_version,
1717                 show_def_docs,
1718             );
1719         }
1720     }
1721     w.write_str("</div>");
1722 }
1723
1724 fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) {
1725     let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
1726
1727     if it.is_struct()
1728         || it.is_trait()
1729         || it.is_primitive()
1730         || it.is_union()
1731         || it.is_enum()
1732         || it.is_mod()
1733         || it.is_typedef()
1734     {
1735         write!(
1736             buffer,
1737             "<p class=\"location\">{}{}</p>",
1738             match *it.kind {
1739                 clean::StructItem(..) => "Struct ",
1740                 clean::TraitItem(..) => "Trait ",
1741                 clean::PrimitiveItem(..) => "Primitive Type ",
1742                 clean::UnionItem(..) => "Union ",
1743                 clean::EnumItem(..) => "Enum ",
1744                 clean::TypedefItem(..) => "Type Definition ",
1745                 clean::ForeignTypeItem => "Foreign Type ",
1746                 clean::ModuleItem(..) =>
1747                     if it.is_crate() {
1748                         "Crate "
1749                     } else {
1750                         "Module "
1751                     },
1752                 _ => "",
1753             },
1754             it.name.as_ref().unwrap()
1755         );
1756     }
1757
1758     if it.is_crate() {
1759         if let Some(ref version) = cx.cache.crate_version {
1760             write!(
1761                 buffer,
1762                 "<div class=\"block version\">\
1763                      <p>Version {}</p>\
1764                  </div>",
1765                 Escape(version)
1766             );
1767         }
1768     }
1769
1770     buffer.write_str("<div class=\"sidebar-elems\">");
1771     if it.is_crate() {
1772         write!(
1773             buffer,
1774             "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
1775             it.name.as_ref().expect("crates always have a name")
1776         );
1777     }
1778     match *it.kind {
1779         clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s),
1780         clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t),
1781         clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it),
1782         clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u),
1783         clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e),
1784         clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it),
1785         clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
1786         clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, it),
1787         _ => (),
1788     }
1789
1790     // The sidebar is designed to display sibling functions, modules and
1791     // other miscellaneous information. since there are lots of sibling
1792     // items (and that causes quadratic growth in large modules),
1793     // we refactor common parts into a shared JavaScript file per module.
1794     // still, we don't move everything into JS because we want to preserve
1795     // as much HTML as possible in order to allow non-JS-enabled browsers
1796     // to navigate the documentation (though slightly inefficiently).
1797
1798     buffer.write_str("<p class=\"location\">");
1799     for (i, name) in cx.current.iter().take(parentlen).enumerate() {
1800         if i > 0 {
1801             buffer.write_str("::<wbr>");
1802         }
1803         write!(
1804             buffer,
1805             "<a href=\"{}index.html\">{}</a>",
1806             &cx.root_path()[..(cx.current.len() - i - 1) * 3],
1807             *name
1808         );
1809     }
1810     buffer.write_str("</p>");
1811
1812     // Sidebar refers to the enclosing module, not this module.
1813     let relpath = if it.is_mod() { "../" } else { "" };
1814     write!(
1815         buffer,
1816         "<div id=\"sidebar-vars\" data-name=\"{name}\" data-ty=\"{ty}\" data-relpath=\"{path}\">\
1817         </div>",
1818         name = it.name.unwrap_or(kw::Empty),
1819         ty = it.type_(),
1820         path = relpath
1821     );
1822     if parentlen == 0 {
1823         // There is no sidebar-items.js beyond the crate root path
1824         // FIXME maybe dynamic crate loading can be merged here
1825     } else {
1826         write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
1827     }
1828     // Closes sidebar-elems div.
1829     buffer.write_str("</div>");
1830 }
1831
1832 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
1833     if used_links.insert(url.clone()) {
1834         return url;
1835     }
1836     let mut add = 1;
1837     while !used_links.insert(format!("{}-{}", url, add)) {
1838         add += 1;
1839     }
1840     format!("{}-{}", url, add)
1841 }
1842
1843 fn get_methods(
1844     i: &clean::Impl,
1845     for_deref: bool,
1846     used_links: &mut FxHashSet<String>,
1847     deref_mut: bool,
1848     cache: &Cache,
1849 ) -> Vec<String> {
1850     i.items
1851         .iter()
1852         .filter_map(|item| match item.name {
1853             Some(ref name) if !name.is_empty() && item.is_method() => {
1854                 if !for_deref || should_render_item(item, deref_mut, cache) {
1855                     Some(format!(
1856                         "<a href=\"#{}\">{}</a>",
1857                         get_next_url(used_links, format!("method.{}", name)),
1858                         name
1859                     ))
1860                 } else {
1861                     None
1862                 }
1863             }
1864             _ => None,
1865         })
1866         .collect::<Vec<_>>()
1867 }
1868
1869 // The point is to url encode any potential character from a type with genericity.
1870 fn small_url_encode(s: String) -> String {
1871     let mut st = String::new();
1872     let mut last_match = 0;
1873     for (idx, c) in s.char_indices() {
1874         let escaped = match c {
1875             '<' => "%3C",
1876             '>' => "%3E",
1877             ' ' => "%20",
1878             '?' => "%3F",
1879             '\'' => "%27",
1880             '&' => "%26",
1881             ',' => "%2C",
1882             ':' => "%3A",
1883             ';' => "%3B",
1884             '[' => "%5B",
1885             ']' => "%5D",
1886             '"' => "%22",
1887             _ => continue,
1888         };
1889
1890         st += &s[last_match..idx];
1891         st += escaped;
1892         // NOTE: we only expect single byte characters here - which is fine as long as we
1893         // only match single byte characters
1894         last_match = idx + 1;
1895     }
1896
1897     if last_match != 0 {
1898         st += &s[last_match..];
1899         st
1900     } else {
1901         s
1902     }
1903 }
1904
1905 fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) {
1906     if let Some(v) = cx.cache.impls.get(&it.def_id) {
1907         let mut used_links = FxHashSet::default();
1908         let tcx = cx.tcx();
1909         let cache = cx.cache();
1910
1911         {
1912             let used_links_bor = &mut used_links;
1913             let mut ret = v
1914                 .iter()
1915                 .filter(|i| i.inner_impl().trait_.is_none())
1916                 .flat_map(move |i| {
1917                     get_methods(i.inner_impl(), false, used_links_bor, false, &cx.cache)
1918                 })
1919                 .collect::<Vec<_>>();
1920             if !ret.is_empty() {
1921                 // We want links' order to be reproducible so we don't use unstable sort.
1922                 ret.sort();
1923
1924                 out.push_str(
1925                     "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
1926                      <div class=\"sidebar-links\">",
1927                 );
1928                 for line in ret {
1929                     out.push_str(&line);
1930                 }
1931                 out.push_str("</div>");
1932             }
1933         }
1934
1935         if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
1936             if let Some(impl_) = v
1937                 .iter()
1938                 .filter(|i| i.inner_impl().trait_.is_some())
1939                 .find(|i| i.inner_impl().trait_.def_id_full(cache) == cx.cache.deref_trait_did)
1940             {
1941                 sidebar_deref_methods(cx, out, impl_, v);
1942             }
1943             let format_impls = |impls: Vec<&Impl>| {
1944                 let mut links = FxHashSet::default();
1945
1946                 let mut ret = impls
1947                     .iter()
1948                     .filter_map(|it| {
1949                         if let Some(ref i) = it.inner_impl().trait_ {
1950                             let i_display = format!("{:#}", i.print(cache, tcx));
1951                             let out = Escape(&i_display);
1952                             let encoded = small_url_encode(format!("{:#}", i.print(cache, tcx)));
1953                             let generated = format!(
1954                                 "<a href=\"#impl-{}\">{}{}</a>",
1955                                 encoded,
1956                                 if it.inner_impl().negative_polarity { "!" } else { "" },
1957                                 out
1958                             );
1959                             if links.insert(generated.clone()) { Some(generated) } else { None }
1960                         } else {
1961                             None
1962                         }
1963                     })
1964                     .collect::<Vec<String>>();
1965                 ret.sort();
1966                 ret
1967             };
1968
1969             let write_sidebar_links = |out: &mut Buffer, links: Vec<String>| {
1970                 out.push_str("<div class=\"sidebar-links\">");
1971                 for link in links {
1972                     out.push_str(&link);
1973                 }
1974                 out.push_str("</div>");
1975             };
1976
1977             let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
1978                 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
1979             let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
1980                 .into_iter()
1981                 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
1982
1983             let concrete_format = format_impls(concrete);
1984             let synthetic_format = format_impls(synthetic);
1985             let blanket_format = format_impls(blanket_impl);
1986
1987             if !concrete_format.is_empty() {
1988                 out.push_str(
1989                     "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
1990                         Trait Implementations</a>",
1991                 );
1992                 write_sidebar_links(out, concrete_format);
1993             }
1994
1995             if !synthetic_format.is_empty() {
1996                 out.push_str(
1997                     "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
1998                         Auto Trait Implementations</a>",
1999                 );
2000                 write_sidebar_links(out, synthetic_format);
2001             }
2002
2003             if !blanket_format.is_empty() {
2004                 out.push_str(
2005                     "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
2006                         Blanket Implementations</a>",
2007                 );
2008                 write_sidebar_links(out, blanket_format);
2009             }
2010         }
2011     }
2012 }
2013
2014 fn sidebar_deref_methods(cx: &Context<'_>, out: &mut Buffer, impl_: &Impl, v: &Vec<Impl>) {
2015     let c = cx.cache();
2016     let tcx = cx.tcx();
2017
2018     debug!("found Deref: {:?}", impl_);
2019     if let Some((target, real_target)) =
2020         impl_.inner_impl().items.iter().find_map(|item| match *item.kind {
2021             clean::TypedefItem(ref t, true) => Some(match *t {
2022                 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
2023                 _ => (&t.type_, &t.type_),
2024             }),
2025             _ => None,
2026         })
2027     {
2028         debug!("found target, real_target: {:?} {:?}", target, real_target);
2029         if let Some(did) = target.def_id_full(c) {
2030             if let Some(type_did) = impl_.inner_impl().for_.def_id_full(c) {
2031                 // `impl Deref<Target = S> for S`
2032                 if did == type_did {
2033                     // Avoid infinite cycles
2034                     return;
2035                 }
2036             }
2037         }
2038         let deref_mut = v
2039             .iter()
2040             .filter(|i| i.inner_impl().trait_.is_some())
2041             .any(|i| i.inner_impl().trait_.def_id_full(c) == c.deref_mut_trait_did);
2042         let inner_impl = target
2043             .def_id_full(c)
2044             .or_else(|| {
2045                 target.primitive_type().and_then(|prim| c.primitive_locations.get(&prim).cloned())
2046             })
2047             .and_then(|did| c.impls.get(&did));
2048         if let Some(impls) = inner_impl {
2049             debug!("found inner_impl: {:?}", impls);
2050             let mut used_links = FxHashSet::default();
2051             let mut ret = impls
2052                 .iter()
2053                 .filter(|i| i.inner_impl().trait_.is_none())
2054                 .flat_map(|i| get_methods(i.inner_impl(), true, &mut used_links, deref_mut, c))
2055                 .collect::<Vec<_>>();
2056             if !ret.is_empty() {
2057                 let deref_id_map = cx.deref_id_map.borrow();
2058                 let id = deref_id_map
2059                     .get(&real_target.def_id_full(c).unwrap())
2060                     .expect("Deref section without derived id");
2061                 write!(
2062                     out,
2063                     "<a class=\"sidebar-title\" href=\"#{}\">Methods from {}&lt;Target={}&gt;</a>",
2064                     id,
2065                     Escape(&format!(
2066                         "{:#}",
2067                         impl_.inner_impl().trait_.as_ref().unwrap().print(c, tcx)
2068                     )),
2069                     Escape(&format!("{:#}", real_target.print(c, tcx))),
2070                 );
2071                 // We want links' order to be reproducible so we don't use unstable sort.
2072                 ret.sort();
2073                 out.push_str("<div class=\"sidebar-links\">");
2074                 for link in ret {
2075                     out.push_str(&link);
2076                 }
2077                 out.push_str("</div>");
2078             }
2079         }
2080
2081         // Recurse into any further impls that might exist for `target`
2082         if let Some(target_did) = target.def_id_full(c) {
2083             if let Some(target_impls) = c.impls.get(&target_did) {
2084                 if let Some(target_deref_impl) = target_impls
2085                     .iter()
2086                     .filter(|i| i.inner_impl().trait_.is_some())
2087                     .find(|i| i.inner_impl().trait_.def_id_full(c) == c.deref_trait_did)
2088                 {
2089                     sidebar_deref_methods(cx, out, target_deref_impl, target_impls);
2090                 }
2091             }
2092         }
2093     }
2094 }
2095
2096 fn sidebar_struct(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
2097     let mut sidebar = Buffer::new();
2098     let fields = get_struct_fields_name(&s.fields);
2099
2100     if !fields.is_empty() {
2101         if let CtorKind::Fictive = s.struct_type {
2102             sidebar.push_str(
2103                 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
2104                 <div class=\"sidebar-links\">",
2105             );
2106
2107             for field in fields {
2108                 sidebar.push_str(&field);
2109             }
2110
2111             sidebar.push_str("</div>");
2112         }
2113     }
2114
2115     sidebar_assoc_items(cx, &mut sidebar, it);
2116
2117     if !sidebar.is_empty() {
2118         write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2119     }
2120 }
2121
2122 fn get_id_for_impl_on_foreign_type(
2123     for_: &clean::Type,
2124     trait_: &clean::Type,
2125     cache: &Cache,
2126     tcx: TyCtxt<'_>,
2127 ) -> String {
2128     small_url_encode(format!(
2129         "impl-{:#}-for-{:#}",
2130         trait_.print(cache, tcx),
2131         for_.print(cache, tcx)
2132     ))
2133 }
2134
2135 fn extract_for_impl_name(
2136     item: &clean::Item,
2137     cache: &Cache,
2138     tcx: TyCtxt<'_>,
2139 ) -> Option<(String, String)> {
2140     match *item.kind {
2141         clean::ItemKind::ImplItem(ref i) => {
2142             if let Some(ref trait_) = i.trait_ {
2143                 Some((
2144                     format!("{:#}", i.for_.print(cache, tcx)),
2145                     get_id_for_impl_on_foreign_type(&i.for_, trait_, cache, tcx),
2146                 ))
2147             } else {
2148                 None
2149             }
2150         }
2151         _ => None,
2152     }
2153 }
2154
2155 fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
2156     buf.write_str("<div class=\"block items\">");
2157
2158     fn print_sidebar_section(
2159         out: &mut Buffer,
2160         items: &[clean::Item],
2161         before: &str,
2162         filter: impl Fn(&clean::Item) -> bool,
2163         write: impl Fn(&mut Buffer, &str),
2164         after: &str,
2165     ) {
2166         let mut items = items
2167             .iter()
2168             .filter_map(|m| match m.name {
2169                 Some(ref name) if filter(m) => Some(name.as_str()),
2170                 _ => None,
2171             })
2172             .collect::<Vec<_>>();
2173
2174         if !items.is_empty() {
2175             items.sort_unstable();
2176             out.push_str(before);
2177             for item in items.into_iter() {
2178                 write(out, &item);
2179             }
2180             out.push_str(after);
2181         }
2182     }
2183
2184     print_sidebar_section(
2185         buf,
2186         &t.items,
2187         "<a class=\"sidebar-title\" href=\"#associated-types\">\
2188             Associated Types</a><div class=\"sidebar-links\">",
2189         |m| m.is_associated_type(),
2190         |out, sym| write!(out, "<a href=\"#associatedtype.{0}\">{0}</a>", sym),
2191         "</div>",
2192     );
2193
2194     print_sidebar_section(
2195         buf,
2196         &t.items,
2197         "<a class=\"sidebar-title\" href=\"#associated-const\">\
2198             Associated Constants</a><div class=\"sidebar-links\">",
2199         |m| m.is_associated_const(),
2200         |out, sym| write!(out, "<a href=\"#associatedconstant.{0}\">{0}</a>", sym),
2201         "</div>",
2202     );
2203
2204     print_sidebar_section(
2205         buf,
2206         &t.items,
2207         "<a class=\"sidebar-title\" href=\"#required-methods\">\
2208             Required Methods</a><div class=\"sidebar-links\">",
2209         |m| m.is_ty_method(),
2210         |out, sym| write!(out, "<a href=\"#tymethod.{0}\">{0}</a>", sym),
2211         "</div>",
2212     );
2213
2214     print_sidebar_section(
2215         buf,
2216         &t.items,
2217         "<a class=\"sidebar-title\" href=\"#provided-methods\">\
2218             Provided Methods</a><div class=\"sidebar-links\">",
2219         |m| m.is_method(),
2220         |out, sym| write!(out, "<a href=\"#method.{0}\">{0}</a>", sym),
2221         "</div>",
2222     );
2223
2224     if let Some(implementors) = cx.cache.implementors.get(&it.def_id) {
2225         let cache = cx.cache();
2226         let tcx = cx.tcx();
2227         let mut res = implementors
2228             .iter()
2229             .filter(|i| {
2230                 i.inner_impl()
2231                     .for_
2232                     .def_id_full(cache)
2233                     .map_or(false, |d| !cx.cache.paths.contains_key(&d))
2234             })
2235             .filter_map(|i| extract_for_impl_name(&i.impl_item, cache, tcx))
2236             .collect::<Vec<_>>();
2237
2238         if !res.is_empty() {
2239             res.sort();
2240             buf.push_str(
2241                 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
2242                     Implementations on Foreign Types</a>\
2243                  <div class=\"sidebar-links\">",
2244             );
2245             for (name, id) in res.into_iter() {
2246                 write!(buf, "<a href=\"#{}\">{}</a>", id, Escape(&name));
2247             }
2248             buf.push_str("</div>");
2249         }
2250     }
2251
2252     sidebar_assoc_items(cx, buf, it);
2253
2254     buf.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
2255     if t.is_auto {
2256         buf.push_str(
2257             "<a class=\"sidebar-title\" \
2258                 href=\"#synthetic-implementors\">Auto Implementors</a>",
2259         );
2260     }
2261
2262     buf.push_str("</div>")
2263 }
2264
2265 fn sidebar_primitive(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2266     let mut sidebar = Buffer::new();
2267     sidebar_assoc_items(cx, &mut sidebar, it);
2268
2269     if !sidebar.is_empty() {
2270         write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2271     }
2272 }
2273
2274 fn sidebar_typedef(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2275     let mut sidebar = Buffer::new();
2276     sidebar_assoc_items(cx, &mut sidebar, it);
2277
2278     if !sidebar.is_empty() {
2279         write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2280     }
2281 }
2282
2283 fn get_struct_fields_name(fields: &[clean::Item]) -> Vec<String> {
2284     let mut fields = fields
2285         .iter()
2286         .filter(|f| matches!(*f.kind, clean::StructFieldItem(..)))
2287         .filter_map(|f| {
2288             f.name.map(|name| format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
2289         })
2290         .collect::<Vec<_>>();
2291     fields.sort();
2292     fields
2293 }
2294
2295 fn sidebar_union(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
2296     let mut sidebar = Buffer::new();
2297     let fields = get_struct_fields_name(&u.fields);
2298
2299     if !fields.is_empty() {
2300         sidebar.push_str(
2301             "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
2302             <div class=\"sidebar-links\">",
2303         );
2304
2305         for field in fields {
2306             sidebar.push_str(&field);
2307         }
2308
2309         sidebar.push_str("</div>");
2310     }
2311
2312     sidebar_assoc_items(cx, &mut sidebar, it);
2313
2314     if !sidebar.is_empty() {
2315         write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2316     }
2317 }
2318
2319 fn sidebar_enum(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
2320     let mut sidebar = Buffer::new();
2321
2322     let mut variants = e
2323         .variants
2324         .iter()
2325         .filter_map(|v| match v.name {
2326             Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
2327             _ => None,
2328         })
2329         .collect::<Vec<_>>();
2330     if !variants.is_empty() {
2331         variants.sort_unstable();
2332         sidebar.push_str(&format!(
2333             "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
2334              <div class=\"sidebar-links\">{}</div>",
2335             variants.join(""),
2336         ));
2337     }
2338
2339     sidebar_assoc_items(cx, &mut sidebar, it);
2340
2341     if !sidebar.is_empty() {
2342         write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2343     }
2344 }
2345
2346 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
2347     match *ty {
2348         ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
2349         ItemType::Module => ("modules", "Modules"),
2350         ItemType::Struct => ("structs", "Structs"),
2351         ItemType::Union => ("unions", "Unions"),
2352         ItemType::Enum => ("enums", "Enums"),
2353         ItemType::Function => ("functions", "Functions"),
2354         ItemType::Typedef => ("types", "Type Definitions"),
2355         ItemType::Static => ("statics", "Statics"),
2356         ItemType::Constant => ("constants", "Constants"),
2357         ItemType::Trait => ("traits", "Traits"),
2358         ItemType::Impl => ("impls", "Implementations"),
2359         ItemType::TyMethod => ("tymethods", "Type Methods"),
2360         ItemType::Method => ("methods", "Methods"),
2361         ItemType::StructField => ("fields", "Struct Fields"),
2362         ItemType::Variant => ("variants", "Variants"),
2363         ItemType::Macro => ("macros", "Macros"),
2364         ItemType::Primitive => ("primitives", "Primitive Types"),
2365         ItemType::AssocType => ("associated-types", "Associated Types"),
2366         ItemType::AssocConst => ("associated-consts", "Associated Constants"),
2367         ItemType::ForeignType => ("foreign-types", "Foreign Types"),
2368         ItemType::Keyword => ("keywords", "Keywords"),
2369         ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
2370         ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
2371         ItemType::ProcDerive => ("derives", "Derive Macros"),
2372         ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
2373     }
2374 }
2375
2376 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
2377     let mut sidebar = String::new();
2378
2379     if items.iter().any(|it| {
2380         it.type_() == ItemType::ExternCrate || (it.type_() == ItemType::Import && !it.is_stripped())
2381     }) {
2382         sidebar.push_str("<li><a href=\"#reexports\">Re-exports</a></li>");
2383     }
2384
2385     // ordering taken from item_module, reorder, where it prioritized elements in a certain order
2386     // to print its headings
2387     for &myty in &[
2388         ItemType::Primitive,
2389         ItemType::Module,
2390         ItemType::Macro,
2391         ItemType::Struct,
2392         ItemType::Enum,
2393         ItemType::Constant,
2394         ItemType::Static,
2395         ItemType::Trait,
2396         ItemType::Function,
2397         ItemType::Typedef,
2398         ItemType::Union,
2399         ItemType::Impl,
2400         ItemType::TyMethod,
2401         ItemType::Method,
2402         ItemType::StructField,
2403         ItemType::Variant,
2404         ItemType::AssocType,
2405         ItemType::AssocConst,
2406         ItemType::ForeignType,
2407         ItemType::Keyword,
2408     ] {
2409         if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
2410             let (short, name) = item_ty_to_strs(&myty);
2411             sidebar.push_str(&format!(
2412                 "<li><a href=\"#{id}\">{name}</a></li>",
2413                 id = short,
2414                 name = name
2415             ));
2416         }
2417     }
2418
2419     if !sidebar.is_empty() {
2420         write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
2421     }
2422 }
2423
2424 fn sidebar_foreign_type(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2425     let mut sidebar = Buffer::new();
2426     sidebar_assoc_items(cx, &mut sidebar, it);
2427
2428     if !sidebar.is_empty() {
2429         write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2430     }
2431 }
2432
2433 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
2434
2435 /// Returns a list of all paths used in the type.
2436 /// This is used to help deduplicate imported impls
2437 /// for reexported types. If any of the contained
2438 /// types are re-exported, we don't use the corresponding
2439 /// entry from the js file, as inlining will have already
2440 /// picked up the impl
2441 fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> {
2442     let mut out = Vec::new();
2443     let mut visited = FxHashSet::default();
2444     let mut work = VecDeque::new();
2445
2446     work.push_back(first_ty);
2447
2448     while let Some(ty) = work.pop_front() {
2449         if !visited.insert(ty.clone()) {
2450             continue;
2451         }
2452
2453         match ty {
2454             clean::Type::ResolvedPath { did, .. } => {
2455                 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
2456                 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
2457
2458                 if let Some(path) = fqp {
2459                     out.push(path.join("::"));
2460                 }
2461             }
2462             clean::Type::Tuple(tys) => {
2463                 work.extend(tys.into_iter());
2464             }
2465             clean::Type::Slice(ty) => {
2466                 work.push_back(*ty);
2467             }
2468             clean::Type::Array(ty, _) => {
2469                 work.push_back(*ty);
2470             }
2471             clean::Type::RawPointer(_, ty) => {
2472                 work.push_back(*ty);
2473             }
2474             clean::Type::BorrowedRef { type_, .. } => {
2475                 work.push_back(*type_);
2476             }
2477             clean::Type::QPath { self_type, trait_, .. } => {
2478                 work.push_back(*self_type);
2479                 work.push_back(*trait_);
2480             }
2481             _ => {}
2482         }
2483     }
2484     out
2485 }