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