]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/render/mod.rs
Rollup merge of #91141 - jhpratt:int_roundings, r=joshtriplett
[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     link: AssocItemLink<'_>,
766     extra: &str,
767     cx: &Context<'_>,
768 ) {
769     write!(
770         w,
771         "{}{}const <a href=\"{}\" class=\"constant\">{}</a>: {}",
772         extra,
773         it.visibility.print_with_space(it.def_id, cx),
774         naive_assoc_href(it, link, cx),
775         it.name.as_ref().unwrap(),
776         ty.print(cx)
777     );
778 }
779
780 fn assoc_type(
781     w: &mut Buffer,
782     it: &clean::Item,
783     bounds: &[clean::GenericBound],
784     default: Option<&clean::Type>,
785     link: AssocItemLink<'_>,
786     extra: &str,
787     cx: &Context<'_>,
788 ) {
789     write!(
790         w,
791         "{}type <a href=\"{}\" class=\"type\">{}</a>",
792         extra,
793         naive_assoc_href(it, link, cx),
794         it.name.as_ref().unwrap()
795     );
796     if !bounds.is_empty() {
797         write!(w, ": {}", print_generic_bounds(bounds, cx))
798     }
799     if let Some(default) = default {
800         write!(w, " = {}", default.print(cx))
801     }
802 }
803
804 fn render_stability_since_raw(
805     w: &mut Buffer,
806     ver: Option<Symbol>,
807     const_stability: Option<ConstStability>,
808     containing_ver: Option<Symbol>,
809     containing_const_ver: Option<Symbol>,
810 ) {
811     let ver = ver.filter(|inner| !inner.is_empty());
812
813     match (ver, const_stability) {
814         // stable and const stable
815         (Some(v), Some(ConstStability { level: StabilityLevel::Stable { since }, .. }))
816             if Some(since) != containing_const_ver =>
817         {
818             write!(
819                 w,
820                 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
821                 v, since
822             );
823         }
824         // stable and const unstable
825         (
826             Some(v),
827             Some(ConstStability { level: StabilityLevel::Unstable { issue, .. }, feature, .. }),
828         ) => {
829             write!(
830                 w,
831                 "<span class=\"since\" title=\"Stable since Rust version {0}, const unstable\">{0} (const: ",
832                 v
833             );
834             if let Some(n) = issue {
835                 write!(
836                     w,
837                     "<a href=\"https://github.com/rust-lang/rust/issues/{}\" title=\"Tracking issue for {}\">unstable</a>",
838                     n, feature
839                 );
840             } else {
841                 write!(w, "unstable");
842             }
843             write!(w, ")</span>");
844         }
845         // stable
846         (Some(v), _) if ver != containing_ver => {
847             write!(
848                 w,
849                 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
850                 v
851             );
852         }
853         _ => {}
854     }
855 }
856
857 fn render_assoc_item(
858     w: &mut Buffer,
859     item: &clean::Item,
860     link: AssocItemLink<'_>,
861     parent: ItemType,
862     cx: &Context<'_>,
863     render_mode: RenderMode,
864 ) {
865     fn method(
866         w: &mut Buffer,
867         meth: &clean::Item,
868         header: hir::FnHeader,
869         g: &clean::Generics,
870         d: &clean::FnDecl,
871         link: AssocItemLink<'_>,
872         parent: ItemType,
873         cx: &Context<'_>,
874         render_mode: RenderMode,
875     ) {
876         let name = meth.name.as_ref().unwrap();
877         let href = match link {
878             AssocItemLink::Anchor(Some(ref id)) => Some(format!("#{}", id)),
879             AssocItemLink::Anchor(None) => Some(format!("#{}.{}", meth.type_(), name)),
880             AssocItemLink::GotoSource(did, provided_methods) => {
881                 // We're creating a link from an impl-item to the corresponding
882                 // trait-item and need to map the anchored type accordingly.
883                 let ty = if provided_methods.contains(name) {
884                     ItemType::Method
885                 } else {
886                     ItemType::TyMethod
887                 };
888
889                 match (href(did.expect_def_id(), cx), ty) {
890                     (Ok(p), ty) => Some(format!("{}#{}.{}", p.0, ty, name)),
891                     (Err(HrefError::DocumentationNotBuilt), ItemType::TyMethod) => None,
892                     (Err(_), ty) => Some(format!("#{}.{}", ty, name)),
893                 }
894             }
895         };
896         let vis = meth.visibility.print_with_space(meth.def_id, cx).to_string();
897         // FIXME: Once https://github.com/rust-lang/rust/issues/67792 is implemented, we can remove
898         // this condition.
899         let constness = match render_mode {
900             RenderMode::Normal => {
901                 print_constness_with_space(&header.constness, meth.const_stability(cx.tcx()))
902             }
903             RenderMode::ForDeref { .. } => "",
904         };
905         let asyncness = header.asyncness.print_with_space();
906         let unsafety = header.unsafety.print_with_space();
907         let defaultness = print_default_space(meth.is_default());
908         let abi = print_abi_with_space(header.abi).to_string();
909
910         // NOTE: `{:#}` does not print HTML formatting, `{}` does. So `g.print` can't be reused between the length calculation and `write!`.
911         let generics_len = format!("{:#}", g.print(cx)).len();
912         let mut header_len = "fn ".len()
913             + vis.len()
914             + constness.len()
915             + asyncness.len()
916             + unsafety.len()
917             + defaultness.len()
918             + abi.len()
919             + name.as_str().len()
920             + generics_len;
921
922         let (indent, indent_str, end_newline) = if parent == ItemType::Trait {
923             header_len += 4;
924             let indent_str = "    ";
925             render_attributes_in_pre(w, meth, indent_str);
926             (4, indent_str, false)
927         } else {
928             render_attributes_in_code(w, meth);
929             (0, "", true)
930         };
931         w.reserve(header_len + "<a href=\"\" class=\"fnname\">{".len() + "</a>".len());
932         write!(
933             w,
934             "{indent}{vis}{constness}{asyncness}{unsafety}{defaultness}{abi}fn <a {href} class=\"fnname\">{name}</a>\
935              {generics}{decl}{notable_traits}{where_clause}",
936             indent = indent_str,
937             vis = vis,
938             constness = constness,
939             asyncness = asyncness,
940             unsafety = unsafety,
941             defaultness = defaultness,
942             abi = abi,
943             // links without a href are valid - https://www.w3schools.com/tags/att_a_href.asp
944             href = href.map(|href| format!("href=\"{}\"", href)).unwrap_or_else(|| "".to_string()),
945             name = name,
946             generics = g.print(cx),
947             decl = d.full_print(header_len, indent, header.asyncness, cx),
948             notable_traits = notable_traits_decl(d, cx),
949             where_clause = print_where_clause(g, cx, indent, end_newline),
950         )
951     }
952     match *item.kind {
953         clean::StrippedItem(..) => {}
954         clean::TyMethodItem(ref m) => {
955             method(w, item, m.header, &m.generics, &m.decl, link, parent, cx, render_mode)
956         }
957         clean::MethodItem(ref m, _) => {
958             method(w, item, m.header, &m.generics, &m.decl, link, parent, cx, render_mode)
959         }
960         clean::AssocConstItem(ref ty, _) => {
961             assoc_const(w, item, ty, link, if parent == ItemType::Trait { "    " } else { "" }, cx)
962         }
963         clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
964             w,
965             item,
966             bounds,
967             default.as_ref(),
968             link,
969             if parent == ItemType::Trait { "    " } else { "" },
970             cx,
971         ),
972         _ => panic!("render_assoc_item called on non-associated-item"),
973     }
974 }
975
976 const ALLOWED_ATTRIBUTES: &[Symbol] =
977     &[sym::export_name, sym::link_section, sym::no_mangle, sym::repr, sym::non_exhaustive];
978
979 fn attributes(it: &clean::Item) -> Vec<String> {
980     it.attrs
981         .other_attrs
982         .iter()
983         .filter_map(|attr| {
984             if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
985                 Some(pprust::attribute_to_string(attr).replace('\n', "").replace("  ", " "))
986             } else {
987                 None
988             }
989         })
990         .collect()
991 }
992
993 // When an attribute is rendered inside a `<pre>` tag, it is formatted using
994 // a whitespace prefix and newline.
995 fn render_attributes_in_pre(w: &mut Buffer, it: &clean::Item, prefix: &str) {
996     for a in attributes(it) {
997         writeln!(w, "{}{}", prefix, a);
998     }
999 }
1000
1001 // When an attribute is rendered inside a <code> tag, it is formatted using
1002 // a div to produce a newline after it.
1003 fn render_attributes_in_code(w: &mut Buffer, it: &clean::Item) {
1004     for a in attributes(it) {
1005         write!(w, "<div class=\"code-attribute\">{}</div>", a);
1006     }
1007 }
1008
1009 #[derive(Copy, Clone)]
1010 enum AssocItemLink<'a> {
1011     Anchor(Option<&'a str>),
1012     GotoSource(ItemId, &'a FxHashSet<Symbol>),
1013 }
1014
1015 impl<'a> AssocItemLink<'a> {
1016     fn anchor(&self, id: &'a str) -> Self {
1017         match *self {
1018             AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(id)),
1019             ref other => *other,
1020         }
1021     }
1022 }
1023
1024 fn render_assoc_items(
1025     w: &mut Buffer,
1026     cx: &Context<'_>,
1027     containing_item: &clean::Item,
1028     it: DefId,
1029     what: AssocItemRender<'_>,
1030 ) {
1031     let mut derefs = FxHashSet::default();
1032     derefs.insert(it);
1033     render_assoc_items_inner(w, cx, containing_item, it, what, &mut derefs)
1034 }
1035
1036 fn render_assoc_items_inner(
1037     w: &mut Buffer,
1038     cx: &Context<'_>,
1039     containing_item: &clean::Item,
1040     it: DefId,
1041     what: AssocItemRender<'_>,
1042     derefs: &mut FxHashSet<DefId>,
1043 ) {
1044     info!("Documenting associated items of {:?}", containing_item.name);
1045     let cache = cx.cache();
1046     let v = match cache.impls.get(&it) {
1047         Some(v) => v,
1048         None => return,
1049     };
1050     let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
1051     if !non_trait.is_empty() {
1052         let mut tmp_buf = Buffer::empty_from(w);
1053         let render_mode = match what {
1054             AssocItemRender::All => {
1055                 tmp_buf.write_str(
1056                     "<h2 id=\"implementations\" class=\"small-section-header\">\
1057                          Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
1058                     </h2>",
1059                 );
1060                 RenderMode::Normal
1061             }
1062             AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
1063                 let id =
1064                     cx.derive_id(small_url_encode(format!("deref-methods-{:#}", type_.print(cx))));
1065                 if let Some(def_id) = type_.def_id(cx.cache()) {
1066                     cx.deref_id_map.borrow_mut().insert(def_id, id.clone());
1067                 }
1068                 write!(
1069                     tmp_buf,
1070                     "<h2 id=\"{id}\" class=\"small-section-header\">\
1071                          <span>Methods from {trait_}&lt;Target = {type_}&gt;</span>\
1072                          <a href=\"#{id}\" class=\"anchor\"></a>\
1073                      </h2>",
1074                     id = id,
1075                     trait_ = trait_.print(cx),
1076                     type_ = type_.print(cx),
1077                 );
1078                 RenderMode::ForDeref { mut_: deref_mut_ }
1079             }
1080         };
1081         let mut impls_buf = Buffer::empty_from(w);
1082         for i in &non_trait {
1083             render_impl(
1084                 &mut impls_buf,
1085                 cx,
1086                 i,
1087                 containing_item,
1088                 AssocItemLink::Anchor(None),
1089                 render_mode,
1090                 None,
1091                 &[],
1092                 ImplRenderingParameters {
1093                     show_def_docs: true,
1094                     is_on_foreign_type: false,
1095                     show_default_items: true,
1096                     show_non_assoc_items: true,
1097                     toggle_open_by_default: true,
1098                 },
1099             );
1100         }
1101         if !impls_buf.is_empty() {
1102             w.push_buffer(tmp_buf);
1103             w.push_buffer(impls_buf);
1104         }
1105     }
1106
1107     if !traits.is_empty() {
1108         let deref_impl =
1109             traits.iter().find(|t| t.trait_did() == cx.tcx().lang_items().deref_trait());
1110         if let Some(impl_) = deref_impl {
1111             let has_deref_mut =
1112                 traits.iter().any(|t| t.trait_did() == cx.tcx().lang_items().deref_mut_trait());
1113             render_deref_methods(w, cx, impl_, containing_item, has_deref_mut, derefs);
1114         }
1115
1116         // If we were already one level into rendering deref methods, we don't want to render
1117         // anything after recursing into any further deref methods above.
1118         if let AssocItemRender::DerefFor { .. } = what {
1119             return;
1120         }
1121
1122         let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
1123             traits.iter().partition(|t| t.inner_impl().kind.is_auto());
1124         let (blanket_impl, concrete): (Vec<&&Impl>, _) =
1125             concrete.into_iter().partition(|t| t.inner_impl().kind.is_blanket());
1126
1127         let mut impls = Buffer::empty_from(w);
1128         render_impls(cx, &mut impls, &concrete, containing_item);
1129         let impls = impls.into_inner();
1130         if !impls.is_empty() {
1131             write!(
1132                 w,
1133                 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
1134                      Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
1135                  </h2>\
1136                  <div id=\"trait-implementations-list\">{}</div>",
1137                 impls
1138             );
1139         }
1140
1141         if !synthetic.is_empty() {
1142             w.write_str(
1143                 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
1144                      Auto Trait Implementations\
1145                      <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
1146                  </h2>\
1147                  <div id=\"synthetic-implementations-list\">",
1148             );
1149             render_impls(cx, w, &synthetic, containing_item);
1150             w.write_str("</div>");
1151         }
1152
1153         if !blanket_impl.is_empty() {
1154             w.write_str(
1155                 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
1156                      Blanket Implementations\
1157                      <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
1158                  </h2>\
1159                  <div id=\"blanket-implementations-list\">",
1160             );
1161             render_impls(cx, w, &blanket_impl, containing_item);
1162             w.write_str("</div>");
1163         }
1164     }
1165 }
1166
1167 fn render_deref_methods(
1168     w: &mut Buffer,
1169     cx: &Context<'_>,
1170     impl_: &Impl,
1171     container_item: &clean::Item,
1172     deref_mut: bool,
1173     derefs: &mut FxHashSet<DefId>,
1174 ) {
1175     let cache = cx.cache();
1176     let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
1177     let (target, real_target) = impl_
1178         .inner_impl()
1179         .items
1180         .iter()
1181         .find_map(|item| match *item.kind {
1182             clean::TypedefItem(ref t, true) => Some(match *t {
1183                 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
1184                 _ => (&t.type_, &t.type_),
1185             }),
1186             _ => None,
1187         })
1188         .expect("Expected associated type binding");
1189     debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target);
1190     let what =
1191         AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
1192     if let Some(did) = target.def_id(cache) {
1193         if let Some(type_did) = impl_.inner_impl().for_.def_id(cache) {
1194             // `impl Deref<Target = S> for S`
1195             if did == type_did || !derefs.insert(did) {
1196                 // Avoid infinite cycles
1197                 return;
1198             }
1199         }
1200         render_assoc_items_inner(w, cx, container_item, did, what, derefs);
1201     } else {
1202         if let Some(prim) = target.primitive_type() {
1203             if let Some(&did) = cache.primitive_locations.get(&prim) {
1204                 render_assoc_items_inner(w, cx, container_item, did, what, derefs);
1205             }
1206         }
1207     }
1208 }
1209
1210 fn should_render_item(item: &clean::Item, deref_mut_: bool, tcx: TyCtxt<'_>) -> bool {
1211     let self_type_opt = match *item.kind {
1212         clean::MethodItem(ref method, _) => method.decl.self_type(),
1213         clean::TyMethodItem(ref method) => method.decl.self_type(),
1214         _ => None,
1215     };
1216
1217     if let Some(self_ty) = self_type_opt {
1218         let (by_mut_ref, by_box, by_value) = match self_ty {
1219             SelfTy::SelfBorrowed(_, mutability)
1220             | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
1221                 (mutability == Mutability::Mut, false, false)
1222             }
1223             SelfTy::SelfExplicit(clean::Type::Path { path }) => {
1224                 (false, Some(path.def_id()) == tcx.lang_items().owned_box(), false)
1225             }
1226             SelfTy::SelfValue => (false, false, true),
1227             _ => (false, false, false),
1228         };
1229
1230         (deref_mut_ || !by_mut_ref) && !by_box && !by_value
1231     } else {
1232         false
1233     }
1234 }
1235
1236 fn notable_traits_decl(decl: &clean::FnDecl, cx: &Context<'_>) -> String {
1237     let mut out = Buffer::html();
1238
1239     if let Some((did, ty)) = decl.output.as_return().and_then(|t| Some((t.def_id(cx.cache())?, t)))
1240     {
1241         if let Some(impls) = cx.cache().impls.get(&did) {
1242             for i in impls {
1243                 let impl_ = i.inner_impl();
1244                 if !impl_.for_.without_borrowed_ref().is_same(ty.without_borrowed_ref(), cx.cache())
1245                 {
1246                     // Two different types might have the same did,
1247                     // without actually being the same.
1248                     continue;
1249                 }
1250                 if let Some(trait_) = &impl_.trait_ {
1251                     let trait_did = trait_.def_id();
1252
1253                     if cx.cache().traits.get(&trait_did).map_or(false, |t| t.is_notable) {
1254                         if out.is_empty() {
1255                             write!(
1256                                 &mut out,
1257                                 "<div class=\"notable\">Notable traits for {}</div>\
1258                              <code class=\"content\">",
1259                                 impl_.for_.print(cx)
1260                             );
1261                         }
1262
1263                         //use the "where" class here to make it small
1264                         write!(
1265                             &mut out,
1266                             "<span class=\"where fmt-newline\">{}</span>",
1267                             impl_.print(false, cx)
1268                         );
1269                         for it in &impl_.items {
1270                             if let clean::TypedefItem(ref tydef, _) = *it.kind {
1271                                 out.push_str("<span class=\"where fmt-newline\">    ");
1272                                 let empty_set = FxHashSet::default();
1273                                 let src_link =
1274                                     AssocItemLink::GotoSource(trait_did.into(), &empty_set);
1275                                 assoc_type(&mut out, it, &[], Some(&tydef.type_), src_link, "", cx);
1276                                 out.push_str(";</span>");
1277                             }
1278                         }
1279                     }
1280                 }
1281             }
1282         }
1283     }
1284
1285     if !out.is_empty() {
1286         out.insert_str(
1287             0,
1288             "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
1289             <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
1290         );
1291         out.push_str("</code></span></div></span></span>");
1292     }
1293
1294     out.into_inner()
1295 }
1296
1297 #[derive(Clone, Copy, Debug)]
1298 struct ImplRenderingParameters {
1299     show_def_docs: bool,
1300     is_on_foreign_type: bool,
1301     show_default_items: bool,
1302     /// Whether or not to show methods.
1303     show_non_assoc_items: bool,
1304     toggle_open_by_default: bool,
1305 }
1306
1307 fn render_impl(
1308     w: &mut Buffer,
1309     cx: &Context<'_>,
1310     i: &Impl,
1311     parent: &clean::Item,
1312     link: AssocItemLink<'_>,
1313     render_mode: RenderMode,
1314     use_absolute: Option<bool>,
1315     aliases: &[String],
1316     rendering_params: ImplRenderingParameters,
1317 ) {
1318     let cache = cx.cache();
1319     let traits = &cache.traits;
1320     let trait_ = i.trait_did().map(|did| &traits[&did]);
1321     let mut close_tags = String::new();
1322
1323     // For trait implementations, the `interesting` output contains all methods that have doc
1324     // comments, and the `boring` output contains all methods that do not. The distinction is
1325     // used to allow hiding the boring methods.
1326     // `containing_item` is used for rendering stability info. If the parent is a trait impl,
1327     // `containing_item` will the grandparent, since trait impls can't have stability attached.
1328     fn doc_impl_item(
1329         boring: &mut Buffer,
1330         interesting: &mut Buffer,
1331         cx: &Context<'_>,
1332         item: &clean::Item,
1333         parent: &clean::Item,
1334         containing_item: &clean::Item,
1335         link: AssocItemLink<'_>,
1336         render_mode: RenderMode,
1337         is_default_item: bool,
1338         trait_: Option<&clean::Trait>,
1339         rendering_params: ImplRenderingParameters,
1340     ) {
1341         let item_type = item.type_();
1342         let name = item.name.as_ref().unwrap();
1343
1344         let render_method_item = rendering_params.show_non_assoc_items
1345             && match render_mode {
1346                 RenderMode::Normal => true,
1347                 RenderMode::ForDeref { mut_: deref_mut_ } => {
1348                     should_render_item(item, deref_mut_, cx.tcx())
1349                 }
1350             };
1351
1352         let in_trait_class = if trait_.is_some() { " trait-impl" } else { "" };
1353
1354         let mut doc_buffer = Buffer::empty_from(boring);
1355         let mut info_buffer = Buffer::empty_from(boring);
1356         let mut short_documented = true;
1357
1358         if render_method_item {
1359             if !is_default_item {
1360                 if let Some(t) = trait_ {
1361                     // The trait item may have been stripped so we might not
1362                     // find any documentation or stability for it.
1363                     if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
1364                         // We need the stability of the item from the trait
1365                         // because impls can't have a stability.
1366                         if item.doc_value().is_some() {
1367                             document_item_info(&mut info_buffer, cx, it, Some(parent));
1368                             document_full(&mut doc_buffer, item, cx, HeadingOffset::H5);
1369                             short_documented = false;
1370                         } else {
1371                             // In case the item isn't documented,
1372                             // provide short documentation from the trait.
1373                             document_short(
1374                                 &mut doc_buffer,
1375                                 it,
1376                                 cx,
1377                                 link,
1378                                 parent,
1379                                 rendering_params.show_def_docs,
1380                             );
1381                         }
1382                     }
1383                 } else {
1384                     document_item_info(&mut info_buffer, cx, item, Some(parent));
1385                     if rendering_params.show_def_docs {
1386                         document_full(&mut doc_buffer, item, cx, HeadingOffset::H5);
1387                         short_documented = false;
1388                     }
1389                 }
1390             } else {
1391                 document_short(
1392                     &mut doc_buffer,
1393                     item,
1394                     cx,
1395                     link,
1396                     parent,
1397                     rendering_params.show_def_docs,
1398                 );
1399             }
1400         }
1401         let w = if short_documented && trait_.is_some() { interesting } else { boring };
1402
1403         let toggled = !doc_buffer.is_empty();
1404         if toggled {
1405             let method_toggle_class =
1406                 if item_type == ItemType::Method { " method-toggle" } else { "" };
1407             write!(w, "<details class=\"rustdoc-toggle{}\" open><summary>", method_toggle_class);
1408         }
1409         match *item.kind {
1410             clean::MethodItem(..) | clean::TyMethodItem(_) => {
1411                 // Only render when the method is not static or we allow static methods
1412                 if render_method_item {
1413                     let id = cx.derive_id(format!("{}.{}", item_type, name));
1414                     let source_id = trait_
1415                         .and_then(|trait_| {
1416                             trait_.items.iter().find(|item| {
1417                                 item.name.map(|n| n.as_str().eq(&name.as_str())).unwrap_or(false)
1418                             })
1419                         })
1420                         .map(|item| format!("{}.{}", item.type_(), name));
1421                     write!(
1422                         w,
1423                         "<div id=\"{}\" class=\"{}{} has-srclink\">",
1424                         id, item_type, in_trait_class,
1425                     );
1426                     render_rightside(w, cx, item, containing_item, render_mode);
1427                     write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1428                     w.write_str("<h4 class=\"code-header\">");
1429                     render_assoc_item(
1430                         w,
1431                         item,
1432                         link.anchor(source_id.as_ref().unwrap_or(&id)),
1433                         ItemType::Impl,
1434                         cx,
1435                         render_mode,
1436                     );
1437                     w.write_str("</h4>");
1438                     w.write_str("</div>");
1439                 }
1440             }
1441             clean::TypedefItem(ref tydef, _) => {
1442                 let source_id = format!("{}.{}", ItemType::AssocType, name);
1443                 let id = cx.derive_id(source_id.clone());
1444                 write!(
1445                     w,
1446                     "<div id=\"{}\" class=\"{}{} has-srclink\">",
1447                     id, item_type, in_trait_class
1448                 );
1449                 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1450                 w.write_str("<h4 class=\"code-header\">");
1451                 assoc_type(
1452                     w,
1453                     item,
1454                     &Vec::new(),
1455                     Some(&tydef.type_),
1456                     link.anchor(if trait_.is_some() { &source_id } else { &id }),
1457                     "",
1458                     cx,
1459                 );
1460                 w.write_str("</h4>");
1461                 w.write_str("</div>");
1462             }
1463             clean::AssocConstItem(ref ty, _) => {
1464                 let source_id = format!("{}.{}", item_type, name);
1465                 let id = cx.derive_id(source_id.clone());
1466                 write!(
1467                     w,
1468                     "<div id=\"{}\" class=\"{}{} has-srclink\">",
1469                     id, item_type, in_trait_class
1470                 );
1471                 render_rightside(w, cx, item, containing_item, render_mode);
1472                 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1473                 w.write_str("<h4 class=\"code-header\">");
1474                 assoc_const(
1475                     w,
1476                     item,
1477                     ty,
1478                     link.anchor(if trait_.is_some() { &source_id } else { &id }),
1479                     "",
1480                     cx,
1481                 );
1482                 w.write_str("</h4>");
1483                 w.write_str("</div>");
1484             }
1485             clean::AssocTypeItem(ref bounds, ref default) => {
1486                 let source_id = format!("{}.{}", item_type, name);
1487                 let id = cx.derive_id(source_id.clone());
1488                 write!(w, "<div id=\"{}\" class=\"{}{}\">", id, item_type, in_trait_class,);
1489                 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1490                 w.write_str("<h4 class=\"code-header\">");
1491                 assoc_type(
1492                     w,
1493                     item,
1494                     bounds,
1495                     default.as_ref(),
1496                     link.anchor(if trait_.is_some() { &source_id } else { &id }),
1497                     "",
1498                     cx,
1499                 );
1500                 w.write_str("</h4>");
1501                 w.write_str("</div>");
1502             }
1503             clean::StrippedItem(..) => return,
1504             _ => panic!("can't make docs for trait item with name {:?}", item.name),
1505         }
1506
1507         w.push_buffer(info_buffer);
1508         if toggled {
1509             w.write_str("</summary>");
1510             w.push_buffer(doc_buffer);
1511             w.push_str("</details>");
1512         }
1513     }
1514
1515     let mut impl_items = Buffer::empty_from(w);
1516     let mut default_impl_items = Buffer::empty_from(w);
1517
1518     for trait_item in &i.inner_impl().items {
1519         doc_impl_item(
1520             &mut default_impl_items,
1521             &mut impl_items,
1522             cx,
1523             trait_item,
1524             if trait_.is_some() { &i.impl_item } else { parent },
1525             parent,
1526             link,
1527             render_mode,
1528             false,
1529             trait_.map(|t| &t.trait_),
1530             rendering_params,
1531         );
1532     }
1533
1534     fn render_default_items(
1535         boring: &mut Buffer,
1536         interesting: &mut Buffer,
1537         cx: &Context<'_>,
1538         t: &clean::Trait,
1539         i: &clean::Impl,
1540         parent: &clean::Item,
1541         containing_item: &clean::Item,
1542         render_mode: RenderMode,
1543         rendering_params: ImplRenderingParameters,
1544     ) {
1545         for trait_item in &t.items {
1546             let n = trait_item.name;
1547             if i.items.iter().any(|m| m.name == n) {
1548                 continue;
1549             }
1550             let did = i.trait_.as_ref().unwrap().def_id();
1551             let provided_methods = i.provided_trait_methods(cx.tcx());
1552             let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_methods);
1553
1554             doc_impl_item(
1555                 boring,
1556                 interesting,
1557                 cx,
1558                 trait_item,
1559                 parent,
1560                 containing_item,
1561                 assoc_link,
1562                 render_mode,
1563                 true,
1564                 Some(t),
1565                 rendering_params,
1566             );
1567         }
1568     }
1569
1570     // If we've implemented a trait, then also emit documentation for all
1571     // default items which weren't overridden in the implementation block.
1572     // We don't emit documentation for default items if they appear in the
1573     // Implementations on Foreign Types or Implementors sections.
1574     if rendering_params.show_default_items {
1575         if let Some(t) = trait_ {
1576             render_default_items(
1577                 &mut default_impl_items,
1578                 &mut impl_items,
1579                 cx,
1580                 &t.trait_,
1581                 i.inner_impl(),
1582                 &i.impl_item,
1583                 parent,
1584                 render_mode,
1585                 rendering_params,
1586             );
1587         }
1588     }
1589     if render_mode == RenderMode::Normal {
1590         let toggled = !(impl_items.is_empty() && default_impl_items.is_empty());
1591         if toggled {
1592             close_tags.insert_str(0, "</details>");
1593             write!(
1594                 w,
1595                 "<details class=\"rustdoc-toggle implementors-toggle\"{}>",
1596                 if rendering_params.toggle_open_by_default { " open" } else { "" }
1597             );
1598             write!(w, "<summary>")
1599         }
1600         render_impl_summary(
1601             w,
1602             cx,
1603             i,
1604             parent,
1605             parent,
1606             rendering_params.show_def_docs,
1607             use_absolute,
1608             rendering_params.is_on_foreign_type,
1609             aliases,
1610         );
1611         if toggled {
1612             write!(w, "</summary>")
1613         }
1614
1615         if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
1616             let mut ids = cx.id_map.borrow_mut();
1617             write!(
1618                 w,
1619                 "<div class=\"docblock\">{}</div>",
1620                 Markdown {
1621                     content: &*dox,
1622                     links: &i.impl_item.links(cx),
1623                     ids: &mut ids,
1624                     error_codes: cx.shared.codes,
1625                     edition: cx.shared.edition(),
1626                     playground: &cx.shared.playground,
1627                     heading_offset: HeadingOffset::H4
1628                 }
1629                 .into_string()
1630             );
1631         }
1632     }
1633     if !default_impl_items.is_empty() || !impl_items.is_empty() {
1634         w.write_str("<div class=\"impl-items\">");
1635         w.push_buffer(default_impl_items);
1636         w.push_buffer(impl_items);
1637         close_tags.insert_str(0, "</div>");
1638     }
1639     w.write_str(&close_tags);
1640 }
1641
1642 // Render the items that appear on the right side of methods, impls, and
1643 // associated types. For example "1.0.0 (const: 1.39.0) [src]".
1644 fn render_rightside(
1645     w: &mut Buffer,
1646     cx: &Context<'_>,
1647     item: &clean::Item,
1648     containing_item: &clean::Item,
1649     render_mode: RenderMode,
1650 ) {
1651     let tcx = cx.tcx();
1652
1653     // FIXME: Once https://github.com/rust-lang/rust/issues/67792 is implemented, we can remove
1654     // this condition.
1655     let (const_stability, const_stable_since) = match render_mode {
1656         RenderMode::Normal => (item.const_stability(tcx), containing_item.const_stable_since(tcx)),
1657         RenderMode::ForDeref { .. } => (None, None),
1658     };
1659
1660     write!(w, "<div class=\"rightside\">");
1661     render_stability_since_raw(
1662         w,
1663         item.stable_since(tcx),
1664         const_stability,
1665         containing_item.stable_since(tcx),
1666         const_stable_since,
1667     );
1668
1669     write_srclink(cx, item, w);
1670     w.write_str("</div>");
1671 }
1672
1673 pub(crate) fn render_impl_summary(
1674     w: &mut Buffer,
1675     cx: &Context<'_>,
1676     i: &Impl,
1677     parent: &clean::Item,
1678     containing_item: &clean::Item,
1679     show_def_docs: bool,
1680     use_absolute: Option<bool>,
1681     is_on_foreign_type: bool,
1682     // This argument is used to reference same type with different paths to avoid duplication
1683     // in documentation pages for trait with automatic implementations like "Send" and "Sync".
1684     aliases: &[String],
1685 ) {
1686     let id = cx.derive_id(match i.inner_impl().trait_ {
1687         Some(ref t) => {
1688             if is_on_foreign_type {
1689                 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t, cx)
1690             } else {
1691                 format!("impl-{}", small_url_encode(format!("{:#}", t.print(cx))))
1692             }
1693         }
1694         None => "impl".to_string(),
1695     });
1696     let aliases = if aliases.is_empty() {
1697         String::new()
1698     } else {
1699         format!(" data-aliases=\"{}\"", aliases.join(","))
1700     };
1701     write!(w, "<div id=\"{}\" class=\"impl has-srclink\"{}>", id, aliases);
1702     render_rightside(w, cx, &i.impl_item, containing_item, RenderMode::Normal);
1703     write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1704     write!(w, "<h3 class=\"code-header in-band\">");
1705
1706     if let Some(use_absolute) = use_absolute {
1707         write!(w, "{}", i.inner_impl().print(use_absolute, cx));
1708         if show_def_docs {
1709             for it in &i.inner_impl().items {
1710                 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1711                     w.write_str("<span class=\"where fmt-newline\">  ");
1712                     assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "", cx);
1713                     w.write_str(";</span>");
1714                 }
1715             }
1716         }
1717     } else {
1718         write!(w, "{}", i.inner_impl().print(false, cx));
1719     }
1720     write!(w, "</h3>");
1721
1722     let is_trait = i.inner_impl().trait_.is_some();
1723     if is_trait {
1724         if let Some(portability) = portability(&i.impl_item, Some(parent)) {
1725             write!(w, "<div class=\"item-info\">{}</div>", portability);
1726         }
1727     }
1728
1729     w.write_str("</div>");
1730 }
1731
1732 fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) {
1733     let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
1734
1735     if it.is_struct()
1736         || it.is_trait()
1737         || it.is_primitive()
1738         || it.is_union()
1739         || it.is_enum()
1740         || it.is_mod()
1741         || it.is_typedef()
1742     {
1743         write!(
1744             buffer,
1745             "<h2 class=\"location\">{}{}</h2>",
1746             match *it.kind {
1747                 clean::StructItem(..) => "Struct ",
1748                 clean::TraitItem(..) => "Trait ",
1749                 clean::PrimitiveItem(..) => "Primitive Type ",
1750                 clean::UnionItem(..) => "Union ",
1751                 clean::EnumItem(..) => "Enum ",
1752                 clean::TypedefItem(..) => "Type Definition ",
1753                 clean::ForeignTypeItem => "Foreign Type ",
1754                 clean::ModuleItem(..) =>
1755                     if it.is_crate() {
1756                         "Crate "
1757                     } else {
1758                         "Module "
1759                     },
1760                 _ => "",
1761             },
1762             it.name.as_ref().unwrap()
1763         );
1764     }
1765
1766     if it.is_crate() {
1767         if let Some(ref version) = cx.cache().crate_version {
1768             write!(
1769                 buffer,
1770                 "<div class=\"block version\">\
1771                      <div class=\"narrow-helper\"></div>\
1772                      <p>Version {}</p>\
1773                  </div>",
1774                 Escape(version),
1775             );
1776         }
1777     }
1778
1779     buffer.write_str("<div class=\"sidebar-elems\">");
1780     if it.is_crate() {
1781         write!(
1782             buffer,
1783             "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
1784             it.name.as_ref().expect("crates always have a name"),
1785         );
1786     }
1787
1788     match *it.kind {
1789         clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s),
1790         clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t),
1791         clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it),
1792         clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u),
1793         clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e),
1794         clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it),
1795         clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
1796         clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, it),
1797         _ => {}
1798     }
1799
1800     // The sidebar is designed to display sibling functions, modules and
1801     // other miscellaneous information. since there are lots of sibling
1802     // items (and that causes quadratic growth in large modules),
1803     // we refactor common parts into a shared JavaScript file per module.
1804     // still, we don't move everything into JS because we want to preserve
1805     // as much HTML as possible in order to allow non-JS-enabled browsers
1806     // to navigate the documentation (though slightly inefficiently).
1807
1808     if !it.is_mod() {
1809         buffer.write_str("<h2 class=\"location\">Other items in<br>");
1810         for (i, name) in cx.current.iter().take(parentlen).enumerate() {
1811             if i > 0 {
1812                 buffer.write_str("::<wbr>");
1813             }
1814             write!(
1815                 buffer,
1816                 "<a href=\"{}index.html\">{}</a>",
1817                 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
1818                 *name
1819             );
1820         }
1821         buffer.write_str("</h2>");
1822     }
1823
1824     // Sidebar refers to the enclosing module, not this module.
1825     let relpath = if it.is_mod() && parentlen != 0 { "./" } else { "" };
1826     write!(
1827         buffer,
1828         "<div id=\"sidebar-vars\" data-name=\"{name}\" data-ty=\"{ty}\" data-relpath=\"{path}\">\
1829         </div>",
1830         name = it.name.unwrap_or(kw::Empty),
1831         ty = it.type_(),
1832         path = relpath
1833     );
1834     write!(buffer, "<script defer src=\"{}sidebar-items.js\"></script>", relpath);
1835     // Closes sidebar-elems div.
1836     buffer.write_str("</div>");
1837 }
1838
1839 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
1840     if used_links.insert(url.clone()) {
1841         return url;
1842     }
1843     let mut add = 1;
1844     while !used_links.insert(format!("{}-{}", url, add)) {
1845         add += 1;
1846     }
1847     format!("{}-{}", url, add)
1848 }
1849
1850 struct SidebarLink {
1851     name: Symbol,
1852     url: String,
1853 }
1854
1855 impl fmt::Display for SidebarLink {
1856     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1857         write!(f, "<a href=\"#{}\">{}</a>", self.url, self.name)
1858     }
1859 }
1860
1861 impl PartialEq for SidebarLink {
1862     fn eq(&self, other: &Self) -> bool {
1863         self.url == other.url
1864     }
1865 }
1866
1867 impl Eq for SidebarLink {}
1868
1869 impl PartialOrd for SidebarLink {
1870     fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1871         Some(self.cmp(other))
1872     }
1873 }
1874
1875 impl Ord for SidebarLink {
1876     fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1877         self.url.cmp(&other.url)
1878     }
1879 }
1880
1881 fn get_methods(
1882     i: &clean::Impl,
1883     for_deref: bool,
1884     used_links: &mut FxHashSet<String>,
1885     deref_mut: bool,
1886     tcx: TyCtxt<'_>,
1887 ) -> Vec<SidebarLink> {
1888     i.items
1889         .iter()
1890         .filter_map(|item| match item.name {
1891             Some(name) if !name.is_empty() && item.is_method() => {
1892                 if !for_deref || should_render_item(item, deref_mut, tcx) {
1893                     Some(SidebarLink {
1894                         name,
1895                         url: get_next_url(used_links, format!("method.{}", name)),
1896                     })
1897                 } else {
1898                     None
1899                 }
1900             }
1901             _ => None,
1902         })
1903         .collect::<Vec<_>>()
1904 }
1905
1906 fn get_associated_constants(
1907     i: &clean::Impl,
1908     used_links: &mut FxHashSet<String>,
1909 ) -> Vec<SidebarLink> {
1910     i.items
1911         .iter()
1912         .filter_map(|item| match item.name {
1913             Some(name) if !name.is_empty() && item.is_associated_const() => Some(SidebarLink {
1914                 name,
1915                 url: get_next_url(used_links, format!("associatedconstant.{}", name)),
1916             }),
1917             _ => None,
1918         })
1919         .collect::<Vec<_>>()
1920 }
1921
1922 // The point is to url encode any potential character from a type with genericity.
1923 fn small_url_encode(s: String) -> String {
1924     let mut st = String::new();
1925     let mut last_match = 0;
1926     for (idx, c) in s.char_indices() {
1927         let escaped = match c {
1928             '<' => "%3C",
1929             '>' => "%3E",
1930             ' ' => "%20",
1931             '?' => "%3F",
1932             '\'' => "%27",
1933             '&' => "%26",
1934             ',' => "%2C",
1935             ':' => "%3A",
1936             ';' => "%3B",
1937             '[' => "%5B",
1938             ']' => "%5D",
1939             '"' => "%22",
1940             _ => continue,
1941         };
1942
1943         st += &s[last_match..idx];
1944         st += escaped;
1945         // NOTE: we only expect single byte characters here - which is fine as long as we
1946         // only match single byte characters
1947         last_match = idx + 1;
1948     }
1949
1950     if last_match != 0 {
1951         st += &s[last_match..];
1952         st
1953     } else {
1954         s
1955     }
1956 }
1957
1958 fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) {
1959     let did = it.def_id.expect_def_id();
1960     let cache = cx.cache();
1961     if let Some(v) = cache.impls.get(&did) {
1962         let mut used_links = FxHashSet::default();
1963
1964         {
1965             let used_links_bor = &mut used_links;
1966             let mut assoc_consts = v
1967                 .iter()
1968                 .flat_map(|i| get_associated_constants(i.inner_impl(), used_links_bor))
1969                 .collect::<Vec<_>>();
1970             if !assoc_consts.is_empty() {
1971                 // We want links' order to be reproducible so we don't use unstable sort.
1972                 assoc_consts.sort();
1973
1974                 out.push_str(
1975                     "<h3 class=\"sidebar-title\">\
1976                         <a href=\"#implementations\">Associated Constants</a>\
1977                      </h3>\
1978                      <div class=\"sidebar-links\">",
1979                 );
1980                 for line in assoc_consts {
1981                     write!(out, "{}", line);
1982                 }
1983                 out.push_str("</div>");
1984             }
1985             let mut methods = v
1986                 .iter()
1987                 .filter(|i| i.inner_impl().trait_.is_none())
1988                 .flat_map(|i| get_methods(i.inner_impl(), false, used_links_bor, false, cx.tcx()))
1989                 .collect::<Vec<_>>();
1990             if !methods.is_empty() {
1991                 // We want links' order to be reproducible so we don't use unstable sort.
1992                 methods.sort();
1993
1994                 out.push_str(
1995                     "<h3 class=\"sidebar-title\"><a href=\"#implementations\">Methods</a></h3>\
1996                      <div class=\"sidebar-links\">",
1997                 );
1998                 for line in methods {
1999                     write!(out, "{}", line);
2000                 }
2001                 out.push_str("</div>");
2002             }
2003         }
2004
2005         if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
2006             if let Some(impl_) =
2007                 v.iter().find(|i| i.trait_did() == cx.tcx().lang_items().deref_trait())
2008             {
2009                 let mut derefs = FxHashSet::default();
2010                 derefs.insert(did);
2011                 sidebar_deref_methods(cx, out, impl_, v, &mut derefs);
2012             }
2013
2014             let format_impls = |impls: Vec<&Impl>| {
2015                 let mut links = FxHashSet::default();
2016
2017                 let mut ret = impls
2018                     .iter()
2019                     .filter_map(|it| {
2020                         if let Some(ref i) = it.inner_impl().trait_ {
2021                             let i_display = format!("{:#}", i.print(cx));
2022                             let out = Escape(&i_display);
2023                             let encoded = small_url_encode(format!("{:#}", i.print(cx)));
2024                             let prefix = match it.inner_impl().polarity {
2025                                 ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => "",
2026                                 ty::ImplPolarity::Negative => "!",
2027                             };
2028                             let generated =
2029                                 format!("<a href=\"#impl-{}\">{}{}</a>", encoded, prefix, out);
2030                             if links.insert(generated.clone()) { Some(generated) } else { None }
2031                         } else {
2032                             None
2033                         }
2034                     })
2035                     .collect::<Vec<String>>();
2036                 ret.sort();
2037                 ret
2038             };
2039
2040             let write_sidebar_links = |out: &mut Buffer, links: Vec<String>| {
2041                 out.push_str("<div class=\"sidebar-links\">");
2042                 for link in links {
2043                     out.push_str(&link);
2044                 }
2045                 out.push_str("</div>");
2046             };
2047
2048             let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
2049                 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().kind.is_auto());
2050             let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) =
2051                 concrete.into_iter().partition::<Vec<_>, _>(|i| i.inner_impl().kind.is_blanket());
2052
2053             let concrete_format = format_impls(concrete);
2054             let synthetic_format = format_impls(synthetic);
2055             let blanket_format = format_impls(blanket_impl);
2056
2057             if !concrete_format.is_empty() {
2058                 out.push_str(
2059                     "<h3 class=\"sidebar-title\"><a href=\"#trait-implementations\">\
2060                         Trait Implementations</a></h3>",
2061                 );
2062                 write_sidebar_links(out, concrete_format);
2063             }
2064
2065             if !synthetic_format.is_empty() {
2066                 out.push_str(
2067                     "<h3 class=\"sidebar-title\"><a href=\"#synthetic-implementations\">\
2068                         Auto Trait Implementations</a></h3>",
2069                 );
2070                 write_sidebar_links(out, synthetic_format);
2071             }
2072
2073             if !blanket_format.is_empty() {
2074                 out.push_str(
2075                     "<h3 class=\"sidebar-title\"><a href=\"#blanket-implementations\">\
2076                         Blanket Implementations</a></h3>",
2077                 );
2078                 write_sidebar_links(out, blanket_format);
2079             }
2080         }
2081     }
2082 }
2083
2084 fn sidebar_deref_methods(
2085     cx: &Context<'_>,
2086     out: &mut Buffer,
2087     impl_: &Impl,
2088     v: &[Impl],
2089     derefs: &mut FxHashSet<DefId>,
2090 ) {
2091     let c = cx.cache();
2092
2093     debug!("found Deref: {:?}", impl_);
2094     if let Some((target, real_target)) =
2095         impl_.inner_impl().items.iter().find_map(|item| match *item.kind {
2096             clean::TypedefItem(ref t, true) => Some(match *t {
2097                 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
2098                 _ => (&t.type_, &t.type_),
2099             }),
2100             _ => None,
2101         })
2102     {
2103         debug!("found target, real_target: {:?} {:?}", target, real_target);
2104         if let Some(did) = target.def_id(c) {
2105             if let Some(type_did) = impl_.inner_impl().for_.def_id(c) {
2106                 // `impl Deref<Target = S> for S`
2107                 if did == type_did || !derefs.insert(did) {
2108                     // Avoid infinite cycles
2109                     return;
2110                 }
2111             }
2112         }
2113         let deref_mut = v.iter().any(|i| i.trait_did() == cx.tcx().lang_items().deref_mut_trait());
2114         let inner_impl = target
2115             .def_id(c)
2116             .or_else(|| {
2117                 target.primitive_type().and_then(|prim| c.primitive_locations.get(&prim).cloned())
2118             })
2119             .and_then(|did| c.impls.get(&did));
2120         if let Some(impls) = inner_impl {
2121             debug!("found inner_impl: {:?}", impls);
2122             let mut used_links = FxHashSet::default();
2123             let mut ret = impls
2124                 .iter()
2125                 .filter(|i| i.inner_impl().trait_.is_none())
2126                 .flat_map(|i| {
2127                     get_methods(i.inner_impl(), true, &mut used_links, deref_mut, cx.tcx())
2128                 })
2129                 .collect::<Vec<_>>();
2130             if !ret.is_empty() {
2131                 let map;
2132                 let id = if let Some(target_def_id) = real_target.def_id(c) {
2133                     map = cx.deref_id_map.borrow();
2134                     map.get(&target_def_id).expect("Deref section without derived id")
2135                 } else {
2136                     "deref-methods"
2137                 };
2138                 write!(
2139                     out,
2140                     "<h3 class=\"sidebar-title\"><a href=\"#{}\">Methods from {}&lt;Target={}&gt;</a></h3>",
2141                     id,
2142                     Escape(&format!("{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print(cx))),
2143                     Escape(&format!("{:#}", real_target.print(cx))),
2144                 );
2145                 // We want links' order to be reproducible so we don't use unstable sort.
2146                 ret.sort();
2147                 out.push_str("<div class=\"sidebar-links\">");
2148                 for link in ret {
2149                     write!(out, "{}", link);
2150                 }
2151                 out.push_str("</div>");
2152             }
2153         }
2154
2155         // Recurse into any further impls that might exist for `target`
2156         if let Some(target_did) = target.def_id(c) {
2157             if let Some(target_impls) = c.impls.get(&target_did) {
2158                 if let Some(target_deref_impl) = target_impls.iter().find(|i| {
2159                     i.inner_impl()
2160                         .trait_
2161                         .as_ref()
2162                         .map(|t| Some(t.def_id()) == cx.tcx().lang_items().deref_trait())
2163                         .unwrap_or(false)
2164                 }) {
2165                     sidebar_deref_methods(cx, out, target_deref_impl, target_impls, derefs);
2166                 }
2167             }
2168         }
2169     }
2170 }
2171
2172 fn sidebar_struct(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
2173     let mut sidebar = Buffer::new();
2174     let fields = get_struct_fields_name(&s.fields);
2175
2176     if !fields.is_empty() {
2177         if let CtorKind::Fictive = s.struct_type {
2178             sidebar.push_str(
2179                 "<h3 class=\"sidebar-title\"><a href=\"#fields\">Fields</a></h3>\
2180                 <div class=\"sidebar-links\">",
2181             );
2182
2183             for field in fields {
2184                 sidebar.push_str(&field);
2185             }
2186
2187             sidebar.push_str("</div>");
2188         } else if let CtorKind::Fn = s.struct_type {
2189             sidebar
2190                 .push_str("<h3 class=\"sidebar-title\"><a href=\"#fields\">Tuple Fields</a></h3>");
2191         }
2192     }
2193
2194     sidebar_assoc_items(cx, &mut sidebar, it);
2195
2196     if !sidebar.is_empty() {
2197         write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2198     }
2199 }
2200
2201 fn get_id_for_impl_on_foreign_type(
2202     for_: &clean::Type,
2203     trait_: &clean::Path,
2204     cx: &Context<'_>,
2205 ) -> String {
2206     small_url_encode(format!("impl-{:#}-for-{:#}", trait_.print(cx), for_.print(cx)))
2207 }
2208
2209 fn extract_for_impl_name(item: &clean::Item, cx: &Context<'_>) -> Option<(String, String)> {
2210     match *item.kind {
2211         clean::ItemKind::ImplItem(ref i) => {
2212             i.trait_.as_ref().map(|trait_| {
2213                 // Alternative format produces no URLs,
2214                 // so this parameter does nothing.
2215                 (
2216                     format!("{:#}", i.for_.print(cx)),
2217                     get_id_for_impl_on_foreign_type(&i.for_, trait_, cx),
2218                 )
2219             })
2220         }
2221         _ => None,
2222     }
2223 }
2224
2225 fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
2226     buf.write_str("<div class=\"block items\">");
2227
2228     fn print_sidebar_section(
2229         out: &mut Buffer,
2230         items: &[clean::Item],
2231         before: &str,
2232         filter: impl Fn(&clean::Item) -> bool,
2233         write: impl Fn(&mut Buffer, &str),
2234         after: &str,
2235     ) {
2236         let mut items = items
2237             .iter()
2238             .filter_map(|m| match m.name {
2239                 Some(ref name) if filter(m) => Some(name.as_str()),
2240                 _ => None,
2241             })
2242             .collect::<Vec<_>>();
2243
2244         if !items.is_empty() {
2245             items.sort_unstable();
2246             out.push_str(before);
2247             for item in items.into_iter() {
2248                 write(out, &item);
2249             }
2250             out.push_str(after);
2251         }
2252     }
2253
2254     print_sidebar_section(
2255         buf,
2256         &t.items,
2257         "<h3 class=\"sidebar-title\"><a href=\"#associated-types\">\
2258             Associated Types</a></h3><div class=\"sidebar-links\">",
2259         |m| m.is_associated_type(),
2260         |out, sym| write!(out, "<a href=\"#associatedtype.{0}\">{0}</a>", sym),
2261         "</div>",
2262     );
2263
2264     print_sidebar_section(
2265         buf,
2266         &t.items,
2267         "<h3 class=\"sidebar-title\"><a href=\"#associated-const\">\
2268             Associated Constants</a></h3><div class=\"sidebar-links\">",
2269         |m| m.is_associated_const(),
2270         |out, sym| write!(out, "<a href=\"#associatedconstant.{0}\">{0}</a>", sym),
2271         "</div>",
2272     );
2273
2274     print_sidebar_section(
2275         buf,
2276         &t.items,
2277         "<h3 class=\"sidebar-title\"><a href=\"#required-methods\">\
2278             Required Methods</a></h3><div class=\"sidebar-links\">",
2279         |m| m.is_ty_method(),
2280         |out, sym| write!(out, "<a href=\"#tymethod.{0}\">{0}</a>", sym),
2281         "</div>",
2282     );
2283
2284     print_sidebar_section(
2285         buf,
2286         &t.items,
2287         "<h3 class=\"sidebar-title\"><a href=\"#provided-methods\">\
2288             Provided Methods</a></h3><div class=\"sidebar-links\">",
2289         |m| m.is_method(),
2290         |out, sym| write!(out, "<a href=\"#method.{0}\">{0}</a>", sym),
2291         "</div>",
2292     );
2293
2294     let cache = cx.cache();
2295     if let Some(implementors) = cache.implementors.get(&it.def_id.expect_def_id()) {
2296         let mut res = implementors
2297             .iter()
2298             .filter(|i| {
2299                 i.inner_impl().for_.def_id(cache).map_or(false, |d| !cache.paths.contains_key(&d))
2300             })
2301             .filter_map(|i| extract_for_impl_name(&i.impl_item, cx))
2302             .collect::<Vec<_>>();
2303
2304         if !res.is_empty() {
2305             res.sort();
2306             buf.push_str(
2307                 "<h3 class=\"sidebar-title\"><a href=\"#foreign-impls\">\
2308                     Implementations on Foreign Types</a></h3>\
2309                  <div class=\"sidebar-links\">",
2310             );
2311             for (name, id) in res.into_iter() {
2312                 write!(buf, "<a href=\"#{}\">{}</a>", id, Escape(&name));
2313             }
2314             buf.push_str("</div>");
2315         }
2316     }
2317
2318     sidebar_assoc_items(cx, buf, it);
2319
2320     buf.push_str("<h3 class=\"sidebar-title\"><a href=\"#implementors\">Implementors</a></h3>");
2321     if t.is_auto {
2322         buf.push_str(
2323             "<h3 class=\"sidebar-title\"><a \
2324                 href=\"#synthetic-implementors\">Auto Implementors</a></h3>",
2325         );
2326     }
2327
2328     buf.push_str("</div>")
2329 }
2330
2331 fn sidebar_primitive(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2332     let mut sidebar = Buffer::new();
2333     sidebar_assoc_items(cx, &mut sidebar, it);
2334
2335     if !sidebar.is_empty() {
2336         write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2337     }
2338 }
2339
2340 fn sidebar_typedef(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2341     let mut sidebar = Buffer::new();
2342     sidebar_assoc_items(cx, &mut sidebar, it);
2343
2344     if !sidebar.is_empty() {
2345         write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2346     }
2347 }
2348
2349 fn get_struct_fields_name(fields: &[clean::Item]) -> Vec<String> {
2350     let mut fields = fields
2351         .iter()
2352         .filter(|f| matches!(*f.kind, clean::StructFieldItem(..)))
2353         .filter_map(|f| {
2354             f.name.map(|name| format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
2355         })
2356         .collect::<Vec<_>>();
2357     fields.sort();
2358     fields
2359 }
2360
2361 fn sidebar_union(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
2362     let mut sidebar = Buffer::new();
2363     let fields = get_struct_fields_name(&u.fields);
2364
2365     if !fields.is_empty() {
2366         sidebar.push_str(
2367             "<h3 class=\"sidebar-title\"><a href=\"#fields\">Fields</a></h3>\
2368             <div class=\"sidebar-links\">",
2369         );
2370
2371         for field in fields {
2372             sidebar.push_str(&field);
2373         }
2374
2375         sidebar.push_str("</div>");
2376     }
2377
2378     sidebar_assoc_items(cx, &mut sidebar, it);
2379
2380     if !sidebar.is_empty() {
2381         write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2382     }
2383 }
2384
2385 fn sidebar_enum(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
2386     let mut sidebar = Buffer::new();
2387
2388     let mut variants = e
2389         .variants
2390         .iter()
2391         .filter_map(|v| {
2392             v.name
2393                 .as_ref()
2394                 .map(|name| format!("<a href=\"#variant.{name}\">{name}</a>", name = name))
2395         })
2396         .collect::<Vec<_>>();
2397     if !variants.is_empty() {
2398         variants.sort_unstable();
2399         sidebar.push_str(&format!(
2400             "<h3 class=\"sidebar-title\"><a href=\"#variants\">Variants</a></h3>\
2401              <div class=\"sidebar-links\">{}</div>",
2402             variants.join(""),
2403         ));
2404     }
2405
2406     sidebar_assoc_items(cx, &mut sidebar, it);
2407
2408     if !sidebar.is_empty() {
2409         write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2410     }
2411 }
2412
2413 fn item_ty_to_strs(ty: ItemType) -> (&'static str, &'static str) {
2414     match ty {
2415         ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
2416         ItemType::Module => ("modules", "Modules"),
2417         ItemType::Struct => ("structs", "Structs"),
2418         ItemType::Union => ("unions", "Unions"),
2419         ItemType::Enum => ("enums", "Enums"),
2420         ItemType::Function => ("functions", "Functions"),
2421         ItemType::Typedef => ("types", "Type Definitions"),
2422         ItemType::Static => ("statics", "Statics"),
2423         ItemType::Constant => ("constants", "Constants"),
2424         ItemType::Trait => ("traits", "Traits"),
2425         ItemType::Impl => ("impls", "Implementations"),
2426         ItemType::TyMethod => ("tymethods", "Type Methods"),
2427         ItemType::Method => ("methods", "Methods"),
2428         ItemType::StructField => ("fields", "Struct Fields"),
2429         ItemType::Variant => ("variants", "Variants"),
2430         ItemType::Macro => ("macros", "Macros"),
2431         ItemType::Primitive => ("primitives", "Primitive Types"),
2432         ItemType::AssocType => ("associated-types", "Associated Types"),
2433         ItemType::AssocConst => ("associated-consts", "Associated Constants"),
2434         ItemType::ForeignType => ("foreign-types", "Foreign Types"),
2435         ItemType::Keyword => ("keywords", "Keywords"),
2436         ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
2437         ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
2438         ItemType::ProcDerive => ("derives", "Derive Macros"),
2439         ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
2440         ItemType::Generic => unreachable!(),
2441     }
2442 }
2443
2444 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
2445     let mut sidebar = String::new();
2446
2447     // Re-exports are handled a bit differently because they can be extern crates or imports.
2448     if items.iter().any(|it| {
2449         it.name.is_some()
2450             && (it.type_() == ItemType::ExternCrate
2451                 || (it.type_() == ItemType::Import && !it.is_stripped()))
2452     }) {
2453         let (id, name) = item_ty_to_strs(ItemType::Import);
2454         sidebar.push_str(&format!("<li><a href=\"#{}\">{}</a></li>", id, name));
2455     }
2456
2457     // ordering taken from item_module, reorder, where it prioritized elements in a certain order
2458     // to print its headings
2459     for &myty in &[
2460         ItemType::Primitive,
2461         ItemType::Module,
2462         ItemType::Macro,
2463         ItemType::Struct,
2464         ItemType::Enum,
2465         ItemType::Constant,
2466         ItemType::Static,
2467         ItemType::Trait,
2468         ItemType::Function,
2469         ItemType::Typedef,
2470         ItemType::Union,
2471         ItemType::Impl,
2472         ItemType::TyMethod,
2473         ItemType::Method,
2474         ItemType::StructField,
2475         ItemType::Variant,
2476         ItemType::AssocType,
2477         ItemType::AssocConst,
2478         ItemType::ForeignType,
2479         ItemType::Keyword,
2480     ] {
2481         if items.iter().any(|it| !it.is_stripped() && it.type_() == myty && it.name.is_some()) {
2482             let (id, name) = item_ty_to_strs(myty);
2483             sidebar.push_str(&format!("<li><a href=\"#{}\">{}</a></li>", id, name));
2484         }
2485     }
2486
2487     if !sidebar.is_empty() {
2488         write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
2489     }
2490 }
2491
2492 fn sidebar_foreign_type(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2493     let mut sidebar = Buffer::new();
2494     sidebar_assoc_items(cx, &mut sidebar, it);
2495
2496     if !sidebar.is_empty() {
2497         write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2498     }
2499 }
2500
2501 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
2502
2503 /// Returns a list of all paths used in the type.
2504 /// This is used to help deduplicate imported impls
2505 /// for reexported types. If any of the contained
2506 /// types are re-exported, we don't use the corresponding
2507 /// entry from the js file, as inlining will have already
2508 /// picked up the impl
2509 fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> {
2510     let mut out = Vec::new();
2511     let mut visited = FxHashSet::default();
2512     let mut work = VecDeque::new();
2513
2514     let mut process_path = |did: DefId| {
2515         let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
2516         let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
2517
2518         if let Some(path) = fqp {
2519             out.push(path.join("::"));
2520         }
2521     };
2522
2523     work.push_back(first_ty);
2524
2525     while let Some(ty) = work.pop_front() {
2526         if !visited.insert(ty.clone()) {
2527             continue;
2528         }
2529
2530         match ty {
2531             clean::Type::Path { path } => process_path(path.def_id()),
2532             clean::Type::Tuple(tys) => {
2533                 work.extend(tys.into_iter());
2534             }
2535             clean::Type::Slice(ty) => {
2536                 work.push_back(*ty);
2537             }
2538             clean::Type::Array(ty, _) => {
2539                 work.push_back(*ty);
2540             }
2541             clean::Type::RawPointer(_, ty) => {
2542                 work.push_back(*ty);
2543             }
2544             clean::Type::BorrowedRef { type_, .. } => {
2545                 work.push_back(*type_);
2546             }
2547             clean::Type::QPath { self_type, trait_, .. } => {
2548                 work.push_back(*self_type);
2549                 process_path(trait_.def_id());
2550             }
2551             _ => {}
2552         }
2553     }
2554     out
2555 }
2556
2557 const MAX_FULL_EXAMPLES: usize = 5;
2558 const NUM_VISIBLE_LINES: usize = 10;
2559
2560 /// Generates the HTML for example call locations generated via the --scrape-examples flag.
2561 fn render_call_locations(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item) {
2562     let tcx = cx.tcx();
2563     let def_id = item.def_id.expect_def_id();
2564     let key = tcx.def_path_hash(def_id);
2565     let call_locations = match cx.shared.call_locations.get(&key) {
2566         Some(call_locations) => call_locations,
2567         _ => {
2568             return;
2569         }
2570     };
2571
2572     // Generate a unique ID so users can link to this section for a given method
2573     let id = cx.id_map.borrow_mut().derive("scraped-examples");
2574     write!(
2575         w,
2576         "<div class=\"docblock scraped-example-list\">\
2577           <span></span>\
2578           <h5 id=\"{id}\" class=\"section-header\">\
2579              <a href=\"#{id}\">Examples found in repository</a>\
2580           </h5>",
2581         id = id
2582     );
2583
2584     // Create a URL to a particular location in a reverse-dependency's source file
2585     let link_to_loc = |call_data: &CallData, loc: &CallLocation| -> (String, String) {
2586         let (line_lo, line_hi) = loc.call_expr.line_span;
2587         let (anchor, title) = if line_lo == line_hi {
2588             ((line_lo + 1).to_string(), format!("line {}", line_lo + 1))
2589         } else {
2590             (
2591                 format!("{}-{}", line_lo + 1, line_hi + 1),
2592                 format!("lines {}-{}", line_lo + 1, line_hi + 1),
2593             )
2594         };
2595         let url = format!("{}{}#{}", cx.root_path(), call_data.url, anchor);
2596         (url, title)
2597     };
2598
2599     // Generate the HTML for a single example, being the title and code block
2600     let write_example = |w: &mut Buffer, (path, call_data): (&PathBuf, &CallData)| -> bool {
2601         let contents = match fs::read_to_string(&path) {
2602             Ok(contents) => contents,
2603             Err(err) => {
2604                 let span = item.span(tcx).inner();
2605                 tcx.sess
2606                     .span_err(span, &format!("failed to read file {}: {}", path.display(), err));
2607                 return false;
2608             }
2609         };
2610
2611         // To reduce file sizes, we only want to embed the source code needed to understand the example, not
2612         // the entire file. So we find the smallest byte range that covers all items enclosing examples.
2613         assert!(!call_data.locations.is_empty());
2614         let min_loc =
2615             call_data.locations.iter().min_by_key(|loc| loc.enclosing_item.byte_span.0).unwrap();
2616         let byte_min = min_loc.enclosing_item.byte_span.0;
2617         let line_min = min_loc.enclosing_item.line_span.0;
2618         let max_loc =
2619             call_data.locations.iter().max_by_key(|loc| loc.enclosing_item.byte_span.1).unwrap();
2620         let byte_max = max_loc.enclosing_item.byte_span.1;
2621         let line_max = max_loc.enclosing_item.line_span.1;
2622
2623         // The output code is limited to that byte range.
2624         let contents_subset = &contents[(byte_min as usize)..(byte_max as usize)];
2625
2626         // The call locations need to be updated to reflect that the size of the program has changed.
2627         // Specifically, the ranges are all subtracted by `byte_min` since that's the new zero point.
2628         let (mut byte_ranges, line_ranges): (Vec<_>, Vec<_>) = call_data
2629             .locations
2630             .iter()
2631             .map(|loc| {
2632                 let (byte_lo, byte_hi) = loc.call_expr.byte_span;
2633                 let (line_lo, line_hi) = loc.call_expr.line_span;
2634                 let byte_range = (byte_lo - byte_min, byte_hi - byte_min);
2635                 let line_range = (line_lo - line_min, line_hi - line_min);
2636                 let (line_url, line_title) = link_to_loc(call_data, loc);
2637
2638                 (byte_range, (line_range, line_url, line_title))
2639             })
2640             .unzip();
2641
2642         let (_, init_url, init_title) = &line_ranges[0];
2643         let needs_expansion = line_max - line_min > NUM_VISIBLE_LINES;
2644         let locations_encoded = serde_json::to_string(&line_ranges).unwrap();
2645
2646         write!(
2647             w,
2648             "<div class=\"scraped-example {expanded_cls}\" data-locs=\"{locations}\">\
2649                 <div class=\"scraped-example-title\">\
2650                    {name} (<a href=\"{url}\">{title}</a>)\
2651                 </div>\
2652                 <div class=\"code-wrapper\">",
2653             expanded_cls = if needs_expansion { "" } else { "expanded" },
2654             name = call_data.display_name,
2655             url = init_url,
2656             title = init_title,
2657             // The locations are encoded as a data attribute, so they can be read
2658             // later by the JS for interactions.
2659             locations = Escape(&locations_encoded)
2660         );
2661
2662         if line_ranges.len() > 1 {
2663             write!(w, r#"<span class="prev">&pr;</span> <span class="next">&sc;</span>"#);
2664         }
2665
2666         if needs_expansion {
2667             write!(w, r#"<span class="expand">&varr;</span>"#);
2668         }
2669
2670         // Look for the example file in the source map if it exists, otherwise return a dummy span
2671         let file_span = (|| {
2672             let source_map = tcx.sess.source_map();
2673             let crate_src = tcx.sess.local_crate_source_file.as_ref()?;
2674             let abs_crate_src = crate_src.canonicalize().ok()?;
2675             let crate_root = abs_crate_src.parent()?.parent()?;
2676             let rel_path = path.strip_prefix(crate_root).ok()?;
2677             let files = source_map.files();
2678             let file = files.iter().find(|file| match &file.name {
2679                 FileName::Real(RealFileName::LocalPath(other_path)) => rel_path == other_path,
2680                 _ => false,
2681             })?;
2682             Some(rustc_span::Span::with_root_ctxt(
2683                 file.start_pos + BytePos(byte_min),
2684                 file.start_pos + BytePos(byte_max),
2685             ))
2686         })()
2687         .unwrap_or(rustc_span::DUMMY_SP);
2688
2689         // The root path is the inverse of Context::current
2690         let root_path = vec!["../"; cx.current.len() - 1].join("");
2691
2692         let mut decoration_info = FxHashMap::default();
2693         decoration_info.insert("highlight focus", vec![byte_ranges.remove(0)]);
2694         decoration_info.insert("highlight", byte_ranges);
2695
2696         sources::print_src(
2697             w,
2698             contents_subset,
2699             call_data.edition,
2700             file_span,
2701             cx,
2702             &root_path,
2703             Some(highlight::DecorationInfo(decoration_info)),
2704             sources::SourceContext::Embedded { offset: line_min },
2705         );
2706         write!(w, "</div></div>");
2707
2708         true
2709     };
2710
2711     // The call locations are output in sequence, so that sequence needs to be determined.
2712     // Ideally the most "relevant" examples would be shown first, but there's no general algorithm
2713     // for determining relevance. Instead, we prefer the smallest examples being likely the easiest to
2714     // understand at a glance.
2715     let ordered_locations = {
2716         let sort_criterion = |(_, call_data): &(_, &CallData)| {
2717             // Use the first location because that's what the user will see initially
2718             let (lo, hi) = call_data.locations[0].enclosing_item.byte_span;
2719             hi - lo
2720         };
2721
2722         let mut locs = call_locations.into_iter().collect::<Vec<_>>();
2723         locs.sort_by_key(sort_criterion);
2724         locs
2725     };
2726
2727     let mut it = ordered_locations.into_iter().peekable();
2728
2729     // An example may fail to write if its source can't be read for some reason, so this method
2730     // continues iterating until a write suceeds
2731     let write_and_skip_failure = |w: &mut Buffer, it: &mut Peekable<_>| {
2732         while let Some(example) = it.next() {
2733             if write_example(&mut *w, example) {
2734                 break;
2735             }
2736         }
2737     };
2738
2739     // Write just one example that's visible by default in the method's description.
2740     write_and_skip_failure(w, &mut it);
2741
2742     // Then add the remaining examples in a hidden section.
2743     if it.peek().is_some() {
2744         write!(
2745             w,
2746             "<details class=\"rustdoc-toggle more-examples-toggle\">\
2747                   <summary class=\"hideme\">\
2748                      <span>More examples</span>\
2749                   </summary>\
2750                   <div class=\"more-scraped-examples\">\
2751                     <div class=\"toggle-line\"><div class=\"toggle-line-inner\"></div></div>\
2752                     <div class=\"more-scraped-examples-inner\">"
2753         );
2754
2755         // Only generate inline code for MAX_FULL_EXAMPLES number of examples. Otherwise we could
2756         // make the page arbitrarily huge!
2757         for _ in 0..MAX_FULL_EXAMPLES {
2758             write_and_skip_failure(w, &mut it);
2759         }
2760
2761         // For the remaining examples, generate a <ul> containing links to the source files.
2762         if it.peek().is_some() {
2763             write!(w, r#"<div class="example-links">Additional examples can be found in:<br><ul>"#);
2764             it.for_each(|(_, call_data)| {
2765                 let (url, _) = link_to_loc(&call_data, &call_data.locations[0]);
2766                 write!(
2767                     w,
2768                     r#"<li><a href="{url}">{name}</a></li>"#,
2769                     url = url,
2770                     name = call_data.display_name
2771                 );
2772             });
2773             write!(w, "</ul></div>");
2774         }
2775
2776         write!(w, "</div></div></details>");
2777     }
2778
2779     write!(w, "</div>");
2780 }