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