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