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