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