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