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