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