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