]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/render/mod.rs
Auto merge of #93348 - spastorino:fix-perf-overlap-mode2, r=nikomatsakis
[rust.git] / src / librustdoc / html / render / mod.rs
1 //! Rustdoc's HTML rendering module.
2 //!
3 //! This modules contains the bulk of the logic necessary for rendering a
4 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
5 //! rendering process is largely driven by the `format!` syntax extension to
6 //! perform all I/O into files and streams.
7 //!
8 //! The rendering process is largely driven by the `Context` and `Cache`
9 //! structures. The cache is pre-populated by crawling the crate in question,
10 //! and then it is shared among the various rendering threads. The cache is meant
11 //! to be a fairly large structure not implementing `Clone` (because it's shared
12 //! among threads). The context, however, should be a lightweight structure. This
13 //! is cloned per-thread and contains information about what is currently being
14 //! rendered.
15 //!
16 //! In order to speed up rendering (mostly because of markdown rendering), the
17 //! rendering process has been parallelized. This parallelization is only
18 //! exposed through the `crate` method on the context, and then also from the
19 //! fact that the shared cache is stored in TLS (and must be accessed as such).
20 //!
21 //! In addition to rendering the crate itself, this module is also responsible
22 //! for creating the corresponding search index and source file renderings.
23 //! These threads are not parallelized (they haven't been a bottleneck yet), and
24 //! both occur before the crate is rendered.
25
26 crate mod search_index;
27
28 #[cfg(test)]
29 mod tests;
30
31 mod context;
32 mod print_item;
33 mod span_map;
34 mod write_shared;
35
36 crate use self::context::*;
37 crate use self::span_map::{collect_spans_and_sources, LinkFromSrc};
38
39 use std::collections::VecDeque;
40 use std::default::Default;
41 use std::fmt;
42 use std::fs;
43 use std::iter::Peekable;
44 use std::path::PathBuf;
45 use std::str;
46 use std::string::ToString;
47
48 use rustc_ast_pretty::pprust;
49 use rustc_attr::{ConstStability, Deprecation, StabilityLevel};
50 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
51 use rustc_hir as hir;
52 use rustc_hir::def::CtorKind;
53 use rustc_hir::def_id::DefId;
54 use rustc_hir::Mutability;
55 use rustc_middle::middle::stability;
56 use rustc_middle::ty;
57 use rustc_middle::ty::TyCtxt;
58 use rustc_span::{
59     symbol::{kw, sym, Symbol},
60     BytePos, FileName, RealFileName,
61 };
62 use serde::ser::SerializeSeq;
63 use serde::{Serialize, Serializer};
64
65 use crate::clean::{self, ItemId, RenderedLink, SelfTy};
66 use crate::error::Error;
67 use crate::formats::cache::Cache;
68 use crate::formats::item_type::ItemType;
69 use crate::formats::{AssocItemRender, Impl, RenderMode};
70 use crate::html::escape::Escape;
71 use crate::html::format::{
72     href, join_with_double_colon, print_abi_with_space, print_constness_with_space,
73     print_default_space, print_generic_bounds, print_where_clause, Buffer, HrefError,
74     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     crate 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=\"{}\">source</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              </h1>",
316         );
317         // Note: print_entries does not escape the title, because we know the current set of titles
318         // doesn't require escaping.
319         print_entries(f, &self.structs, "Structs", "structs");
320         print_entries(f, &self.enums, "Enums", "enums");
321         print_entries(f, &self.unions, "Unions", "unions");
322         print_entries(f, &self.primitives, "Primitives", "primitives");
323         print_entries(f, &self.traits, "Traits", "traits");
324         print_entries(f, &self.macros, "Macros", "macros");
325         print_entries(f, &self.attributes, "Attribute Macros", "attributes");
326         print_entries(f, &self.derives, "Derive Macros", "derives");
327         print_entries(f, &self.functions, "Functions", "functions");
328         print_entries(f, &self.typedefs, "Typedefs", "typedefs");
329         print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
330         print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
331         print_entries(f, &self.statics, "Statics", "statics");
332         print_entries(f, &self.constants, "Constants", "constants")
333     }
334 }
335
336 #[derive(Debug)]
337 enum Setting {
338     Section {
339         description: &'static str,
340         sub_settings: Vec<Setting>,
341     },
342     Toggle {
343         js_data_name: &'static str,
344         description: &'static str,
345         default_value: bool,
346     },
347     Select {
348         js_data_name: &'static str,
349         description: &'static str,
350         default_value: &'static str,
351         options: Vec<String>,
352     },
353 }
354
355 impl Setting {
356     fn display(&self, root_path: &str, suffix: &str) -> String {
357         match *self {
358             Setting::Section { description, ref sub_settings } => format!(
359                 "<div class=\"setting-line\">\
360                      <div class=\"title\">{}</div>\
361                      <div class=\"sub-settings\">{}</div>
362                  </div>",
363                 description,
364                 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
365             ),
366             Setting::Toggle { js_data_name, description, default_value } => format!(
367                 "<div class=\"setting-line\">\
368                      <label class=\"toggle\">\
369                      <input type=\"checkbox\" id=\"{}\" {}>\
370                      <span class=\"slider\"></span>\
371                      </label>\
372                      <div>{}</div>\
373                  </div>",
374                 js_data_name,
375                 if default_value { " checked" } else { "" },
376                 description,
377             ),
378             Setting::Select { js_data_name, description, default_value, ref options } => format!(
379                 "<div class=\"setting-line\"><div class=\"radio-line\" id=\"{}\"><span class=\"setting-name\">{}</span>{}</div></div>",
380                 js_data_name,
381                 description,
382                 options
383                     .iter()
384                     .map(|opt| format!(
385                         "<label for=\"{js_data_name}-{name}\" class=\"choice\">
386                            <input type=\"radio\" name=\"{js_data_name}\" id=\"{js_data_name}-{name}\" value=\"{name}\" {checked}>\
387                            {name}\
388                          </label>",
389                         js_data_name = js_data_name,
390                         name = opt,
391                         checked = if opt == default_value { "checked" } else { "" },
392                     ))
393                     .collect::<String>(),
394             ),
395         }
396     }
397 }
398
399 impl From<(&'static str, &'static str, bool)> for Setting {
400     fn from(values: (&'static str, &'static str, bool)) -> Setting {
401         Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
402     }
403 }
404
405 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
406     fn from(values: (&'static str, Vec<T>)) -> Setting {
407         Setting::Section {
408             description: values.0,
409             sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
410         }
411     }
412 }
413
414 fn settings(root_path: &str, suffix: &str, theme_names: Vec<String>) -> Result<String, Error> {
415     // (id, explanation, default value)
416     let settings: &[Setting] = &[
417         Setting::from(("use-system-theme", "Use system theme", true)),
418         Setting::Select {
419             js_data_name: "theme",
420             description: "Theme",
421             default_value: "light",
422             options: theme_names.clone(),
423         },
424         Setting::Select {
425             js_data_name: "preferred-light-theme",
426             description: "Preferred light theme",
427             default_value: "light",
428             options: theme_names.clone(),
429         },
430         Setting::Select {
431             js_data_name: "preferred-dark-theme",
432             description: "Preferred dark theme",
433             default_value: "dark",
434             options: theme_names,
435         },
436         ("auto-hide-large-items", "Auto-hide item contents for large items.", true).into(),
437         ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
438         ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", false)
439             .into(),
440         ("go-to-only-result", "Directly go to item in search if there is only one result", false)
441             .into(),
442         ("line-numbers", "Show line numbers on code examples", false).into(),
443         ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
444     ];
445
446     Ok(format!(
447         "<div class=\"main-heading\">
448             <h1 class=\"fqn\">\
449                 <span class=\"in-band\">Rustdoc settings</span>\
450             </h1>\
451             <span class=\"out-of-band\">\
452             <a id=\"back\" href=\"javascript:void(0)\">Back</a>\
453             </span>\
454         </div>\
455         <div class=\"settings\">{}</div>\
456         <link rel=\"stylesheet\" href=\"{root_path}settings{suffix}.css\">\
457         <script src=\"{root_path}settings{suffix}.js\"></script>",
458         settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
459         root_path = root_path,
460         suffix = suffix
461     ))
462 }
463
464 fn document(
465     w: &mut Buffer,
466     cx: &Context<'_>,
467     item: &clean::Item,
468     parent: Option<&clean::Item>,
469     heading_offset: HeadingOffset,
470 ) {
471     if let Some(ref name) = item.name {
472         info!("Documenting {}", name);
473     }
474     document_item_info(w, cx, item, parent);
475     if parent.is_none() {
476         document_full_collapsible(w, item, cx, heading_offset);
477     } else {
478         document_full(w, item, cx, heading_offset);
479     }
480 }
481
482 /// Render md_text as markdown.
483 fn render_markdown(
484     w: &mut Buffer,
485     cx: &Context<'_>,
486     md_text: &str,
487     links: Vec<RenderedLink>,
488     heading_offset: HeadingOffset,
489 ) {
490     let mut ids = cx.id_map.borrow_mut();
491     write!(
492         w,
493         "<div class=\"docblock\">{}</div>",
494         Markdown {
495             content: md_text,
496             links: &links,
497             ids: &mut ids,
498             error_codes: cx.shared.codes,
499             edition: cx.shared.edition(),
500             playground: &cx.shared.playground,
501             heading_offset,
502         }
503         .into_string()
504     )
505 }
506
507 /// Writes a documentation block containing only the first paragraph of the documentation. If the
508 /// docs are longer, a "Read more" link is appended to the end.
509 fn document_short(
510     w: &mut Buffer,
511     item: &clean::Item,
512     cx: &Context<'_>,
513     link: AssocItemLink<'_>,
514     parent: &clean::Item,
515     show_def_docs: bool,
516 ) {
517     document_item_info(w, cx, item, Some(parent));
518     if !show_def_docs {
519         return;
520     }
521     if let Some(s) = item.doc_value() {
522         let mut summary_html = MarkdownSummaryLine(&s, &item.links(cx)).into_string();
523
524         if s.contains('\n') {
525             let link = format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link, cx));
526
527             if let Some(idx) = summary_html.rfind("</p>") {
528                 summary_html.insert_str(idx, &link);
529             } else {
530                 summary_html.push_str(&link);
531             }
532         }
533
534         write!(w, "<div class='docblock'>{}</div>", summary_html,);
535     }
536 }
537
538 fn document_full_collapsible(
539     w: &mut Buffer,
540     item: &clean::Item,
541     cx: &Context<'_>,
542     heading_offset: HeadingOffset,
543 ) {
544     document_full_inner(w, item, cx, true, heading_offset);
545 }
546
547 fn document_full(
548     w: &mut Buffer,
549     item: &clean::Item,
550     cx: &Context<'_>,
551     heading_offset: HeadingOffset,
552 ) {
553     document_full_inner(w, item, cx, false, heading_offset);
554 }
555
556 fn document_full_inner(
557     w: &mut Buffer,
558     item: &clean::Item,
559     cx: &Context<'_>,
560     is_collapsible: bool,
561     heading_offset: HeadingOffset,
562 ) {
563     if let Some(s) = item.collapsed_doc_value() {
564         debug!("Doc block: =====\n{}\n=====", s);
565         if is_collapsible {
566             w.write_str(
567                 "<details class=\"rustdoc-toggle top-doc\" open>\
568                 <summary class=\"hideme\">\
569                      <span>Expand description</span>\
570                 </summary>",
571             );
572             render_markdown(w, cx, &s, item.links(cx), heading_offset);
573             w.write_str("</details>");
574         } else {
575             render_markdown(w, cx, &s, item.links(cx), heading_offset);
576         }
577     }
578
579     let kind = match &*item.kind {
580         clean::ItemKind::StrippedItem(box kind) | kind => kind,
581     };
582
583     if let clean::ItemKind::FunctionItem(..) | clean::ItemKind::MethodItem(..) = kind {
584         render_call_locations(w, cx, item);
585     }
586 }
587
588 /// Add extra information about an item such as:
589 ///
590 /// * Stability
591 /// * Deprecated
592 /// * Required features (through the `doc_cfg` feature)
593 fn document_item_info(
594     w: &mut Buffer,
595     cx: &Context<'_>,
596     item: &clean::Item,
597     parent: Option<&clean::Item>,
598 ) {
599     let item_infos = short_item_info(item, cx, parent);
600     if !item_infos.is_empty() {
601         w.write_str("<div class=\"item-info\">");
602         for info in item_infos {
603             w.write_str(&info);
604         }
605         w.write_str("</div>");
606     }
607 }
608
609 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
610     let cfg = match (&item.cfg, parent.and_then(|p| p.cfg.as_ref())) {
611         (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
612         (cfg, _) => cfg.as_deref().cloned(),
613     };
614
615     debug!("Portability {:?} - {:?} = {:?}", item.cfg, parent.and_then(|p| p.cfg.as_ref()), cfg);
616
617     Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
618 }
619
620 /// Render the stability, deprecation and portability information that is displayed at the top of
621 /// the item's documentation.
622 fn short_item_info(
623     item: &clean::Item,
624     cx: &Context<'_>,
625     parent: Option<&clean::Item>,
626 ) -> Vec<String> {
627     let mut extra_info = vec![];
628     let error_codes = cx.shared.codes;
629
630     if let Some(depr @ Deprecation { note, since, is_since_rustc_version: _, suggestion: _ }) =
631         item.deprecation(cx.tcx())
632     {
633         // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
634         // but only display the future-deprecation messages for #[rustc_deprecated].
635         let mut message = if let Some(since) = since {
636             let since = since.as_str();
637             if !stability::deprecation_in_effect(&depr) {
638                 if since == "TBD" {
639                     String::from("Deprecating in a future Rust version")
640                 } else {
641                     format!("Deprecating in {}", Escape(since))
642                 }
643             } else {
644                 format!("Deprecated since {}", Escape(since))
645             }
646         } else {
647             String::from("Deprecated")
648         };
649
650         if let Some(note) = note {
651             let note = note.as_str();
652             let mut ids = cx.id_map.borrow_mut();
653             let html = MarkdownHtml(
654                 note,
655                 &mut ids,
656                 error_codes,
657                 cx.shared.edition(),
658                 &cx.shared.playground,
659             );
660             message.push_str(&format!(": {}", html.into_string()));
661         }
662         extra_info.push(format!(
663             "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
664             message,
665         ));
666     }
667
668     // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
669     // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
670     if let Some((StabilityLevel::Unstable { reason: _, issue, .. }, feature)) = item
671         .stability(cx.tcx())
672         .as_ref()
673         .filter(|stab| stab.feature != sym::rustc_private)
674         .map(|stab| (stab.level, stab.feature))
675     {
676         let mut message =
677             "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
678
679         let mut feature = format!("<code>{}</code>", Escape(feature.as_str()));
680         if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
681             feature.push_str(&format!(
682                 "&nbsp;<a href=\"{url}{issue}\">#{issue}</a>",
683                 url = url,
684                 issue = issue
685             ));
686         }
687
688         message.push_str(&format!(" ({})", feature));
689
690         extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
691     }
692
693     if let Some(portability) = portability(item, parent) {
694         extra_info.push(portability);
695     }
696
697     extra_info
698 }
699
700 // Render the list of items inside one of the sections "Trait Implementations",
701 // "Auto Trait Implementations," "Blanket Trait Implementations" (on struct/enum pages).
702 fn render_impls(cx: &Context<'_>, w: &mut Buffer, impls: &[&&Impl], containing_item: &clean::Item) {
703     let tcx = cx.tcx();
704     let mut rendered_impls = impls
705         .iter()
706         .map(|i| {
707             let did = i.trait_did().unwrap();
708             let provided_trait_methods = i.inner_impl().provided_trait_methods(tcx);
709             let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_trait_methods);
710             let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
711             render_impl(
712                 &mut buffer,
713                 cx,
714                 i,
715                 containing_item,
716                 assoc_link,
717                 RenderMode::Normal,
718                 None,
719                 &[],
720                 ImplRenderingParameters {
721                     show_def_docs: true,
722                     is_on_foreign_type: false,
723                     show_default_items: true,
724                     show_non_assoc_items: true,
725                     toggle_open_by_default: true,
726                 },
727             );
728             buffer.into_inner()
729         })
730         .collect::<Vec<_>>();
731     rendered_impls.sort();
732     w.write_str(&rendered_impls.join(""));
733 }
734
735 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>, cx: &Context<'_>) -> String {
736     use crate::formats::item_type::ItemType::*;
737
738     let name = it.name.as_ref().unwrap();
739     let ty = match it.type_() {
740         Typedef | AssocType => AssocType,
741         s => s,
742     };
743
744     let anchor = format!("#{}.{}", ty, name);
745     match link {
746         AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
747         AssocItemLink::Anchor(None) => anchor,
748         AssocItemLink::GotoSource(did, _) => {
749             href(did.expect_def_id(), cx).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
750         }
751     }
752 }
753
754 fn assoc_const(
755     w: &mut Buffer,
756     it: &clean::Item,
757     ty: &clean::Type,
758     link: AssocItemLink<'_>,
759     extra: &str,
760     cx: &Context<'_>,
761 ) {
762     write!(
763         w,
764         "{}{}const <a href=\"{}\" class=\"constant\">{}</a>: {}",
765         extra,
766         it.visibility.print_with_space(it.def_id, cx),
767         naive_assoc_href(it, link, cx),
768         it.name.as_ref().unwrap(),
769         ty.print(cx)
770     );
771 }
772
773 fn assoc_type(
774     w: &mut Buffer,
775     it: &clean::Item,
776     bounds: &[clean::GenericBound],
777     default: Option<&clean::Type>,
778     link: AssocItemLink<'_>,
779     extra: &str,
780     cx: &Context<'_>,
781 ) {
782     write!(
783         w,
784         "{}type <a href=\"{}\" class=\"associatedtype\">{}</a>",
785         extra,
786         naive_assoc_href(it, link, cx),
787         it.name.as_ref().unwrap()
788     );
789     if !bounds.is_empty() {
790         write!(w, ": {}", print_generic_bounds(bounds, cx))
791     }
792     if let Some(default) = default {
793         write!(w, " = {}", default.print(cx))
794     }
795 }
796
797 /// Writes a span containing the versions at which an item became stable and/or const-stable. For
798 /// example, if the item became stable at 1.0.0, and const-stable at 1.45.0, this function would
799 /// write a span containing "1.0.0 (const: 1.45.0)".
800 ///
801 /// Returns `true` if a stability annotation was rendered.
802 ///
803 /// Stability and const-stability are considered separately. If the item is unstable, no version
804 /// will be written. If the item is const-unstable, "const: unstable" will be appended to the
805 /// span, with a link to the tracking issue if present. If an item's stability or const-stability
806 /// version matches the version of its enclosing item, that version will be omitted.
807 ///
808 /// Note that it is possible for an unstable function to be const-stable. In that case, the span
809 /// will include the const-stable version, but no stable version will be emitted, as a natural
810 /// consequence of the above rules.
811 fn render_stability_since_raw(
812     w: &mut Buffer,
813     ver: Option<Symbol>,
814     const_stability: Option<ConstStability>,
815     containing_ver: Option<Symbol>,
816     containing_const_ver: Option<Symbol>,
817 ) -> bool {
818     let stable_version = ver.filter(|inner| !inner.is_empty() && Some(*inner) != containing_ver);
819
820     let mut title = String::new();
821     let mut stability = String::new();
822
823     if let Some(ver) = stable_version {
824         stability.push_str(&ver.as_str());
825         title.push_str(&format!("Stable since Rust version {}", ver));
826     }
827
828     let const_title_and_stability = match const_stability {
829         Some(ConstStability { level: StabilityLevel::Stable { since }, .. })
830             if Some(since) != containing_const_ver =>
831         {
832             Some((format!("const since {}", since), format!("const: {}", since)))
833         }
834         Some(ConstStability { level: StabilityLevel::Unstable { issue, .. }, feature, .. }) => {
835             let unstable = if let Some(n) = issue {
836                 format!(
837                     r#"<a href="https://github.com/rust-lang/rust/issues/{}" title="Tracking issue for {}">unstable</a>"#,
838                     n, feature
839                 )
840             } else {
841                 String::from("unstable")
842             };
843
844             Some((String::from("const unstable"), format!("const: {}", unstable)))
845         }
846         _ => None,
847     };
848
849     if let Some((const_title, const_stability)) = const_title_and_stability {
850         if !title.is_empty() {
851             title.push_str(&format!(", {}", const_title));
852         } else {
853             title.push_str(&const_title);
854         }
855
856         if !stability.is_empty() {
857             stability.push_str(&format!(" ({})", const_stability));
858         } else {
859             stability.push_str(&const_stability);
860         }
861     }
862
863     if !stability.is_empty() {
864         write!(w, r#"<span class="since" title="{}">{}</span>"#, title, stability);
865     }
866
867     !stability.is_empty()
868 }
869
870 fn render_assoc_item(
871     w: &mut Buffer,
872     item: &clean::Item,
873     link: AssocItemLink<'_>,
874     parent: ItemType,
875     cx: &Context<'_>,
876     render_mode: RenderMode,
877 ) {
878     fn method(
879         w: &mut Buffer,
880         meth: &clean::Item,
881         header: hir::FnHeader,
882         g: &clean::Generics,
883         d: &clean::FnDecl,
884         link: AssocItemLink<'_>,
885         parent: ItemType,
886         cx: &Context<'_>,
887         render_mode: RenderMode,
888     ) {
889         let name = meth.name.as_ref().unwrap();
890         let href = match link {
891             AssocItemLink::Anchor(Some(ref id)) => Some(format!("#{}", id)),
892             AssocItemLink::Anchor(None) => Some(format!("#{}.{}", meth.type_(), name)),
893             AssocItemLink::GotoSource(did, provided_methods) => {
894                 // We're creating a link from an impl-item to the corresponding
895                 // trait-item and need to map the anchored type accordingly.
896                 let ty = if provided_methods.contains(name) {
897                     ItemType::Method
898                 } else {
899                     ItemType::TyMethod
900                 };
901
902                 match (href(did.expect_def_id(), cx), ty) {
903                     (Ok(p), ty) => Some(format!("{}#{}.{}", p.0, ty, name)),
904                     (Err(HrefError::DocumentationNotBuilt), ItemType::TyMethod) => None,
905                     (Err(_), ty) => Some(format!("#{}.{}", ty, name)),
906                 }
907             }
908         };
909         let vis = meth.visibility.print_with_space(meth.def_id, cx).to_string();
910         // FIXME: Once https://github.com/rust-lang/rust/issues/67792 is implemented, we can remove
911         // this condition.
912         let constness = match render_mode {
913             RenderMode::Normal => {
914                 print_constness_with_space(&header.constness, meth.const_stability(cx.tcx()))
915             }
916             RenderMode::ForDeref { .. } => "",
917         };
918         let asyncness = header.asyncness.print_with_space();
919         let unsafety = header.unsafety.print_with_space();
920         let defaultness = print_default_space(meth.is_default());
921         let abi = print_abi_with_space(header.abi).to_string();
922
923         // NOTE: `{:#}` does not print HTML formatting, `{}` does. So `g.print` can't be reused between the length calculation and `write!`.
924         let generics_len = format!("{:#}", g.print(cx)).len();
925         let mut header_len = "fn ".len()
926             + vis.len()
927             + constness.len()
928             + asyncness.len()
929             + unsafety.len()
930             + defaultness.len()
931             + abi.len()
932             + name.as_str().len()
933             + generics_len;
934
935         let (indent, indent_str, end_newline) = if parent == ItemType::Trait {
936             header_len += 4;
937             let indent_str = "    ";
938             render_attributes_in_pre(w, meth, indent_str);
939             (4, indent_str, false)
940         } else {
941             render_attributes_in_code(w, meth);
942             (0, "", true)
943         };
944         w.reserve(header_len + "<a href=\"\" class=\"fnname\">{".len() + "</a>".len());
945         write!(
946             w,
947             "{indent}{vis}{constness}{asyncness}{unsafety}{defaultness}{abi}fn <a {href} class=\"fnname\">{name}</a>\
948              {generics}{decl}{notable_traits}{where_clause}",
949             indent = indent_str,
950             vis = vis,
951             constness = constness,
952             asyncness = asyncness,
953             unsafety = unsafety,
954             defaultness = defaultness,
955             abi = abi,
956             // links without a href are valid - https://www.w3schools.com/tags/att_a_href.asp
957             href = href.map(|href| format!("href=\"{}\"", href)).unwrap_or_else(|| "".to_string()),
958             name = name,
959             generics = g.print(cx),
960             decl = d.full_print(header_len, indent, header.asyncness, cx),
961             notable_traits = notable_traits_decl(d, cx),
962             where_clause = print_where_clause(g, cx, indent, end_newline),
963         )
964     }
965     match *item.kind {
966         clean::StrippedItem(..) => {}
967         clean::TyMethodItem(ref m) => {
968             method(w, item, m.header, &m.generics, &m.decl, link, parent, cx, render_mode)
969         }
970         clean::MethodItem(ref m, _) => {
971             method(w, item, m.header, &m.generics, &m.decl, link, parent, cx, render_mode)
972         }
973         clean::AssocConstItem(ref ty, _) => {
974             assoc_const(w, item, ty, link, if parent == ItemType::Trait { "    " } else { "" }, cx)
975         }
976         clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
977             w,
978             item,
979             bounds,
980             default.as_ref(),
981             link,
982             if parent == ItemType::Trait { "    " } else { "" },
983             cx,
984         ),
985         _ => panic!("render_assoc_item called on non-associated-item"),
986     }
987 }
988
989 const ALLOWED_ATTRIBUTES: &[Symbol] =
990     &[sym::export_name, sym::link_section, sym::no_mangle, sym::repr, sym::non_exhaustive];
991
992 fn attributes(it: &clean::Item) -> Vec<String> {
993     it.attrs
994         .other_attrs
995         .iter()
996         .filter_map(|attr| {
997             if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
998                 Some(pprust::attribute_to_string(attr).replace('\n', "").replace("  ", " "))
999             } else {
1000                 None
1001             }
1002         })
1003         .collect()
1004 }
1005
1006 // When an attribute is rendered inside a `<pre>` tag, it is formatted using
1007 // a whitespace prefix and newline.
1008 fn render_attributes_in_pre(w: &mut Buffer, it: &clean::Item, prefix: &str) {
1009     for a in attributes(it) {
1010         writeln!(w, "{}{}", prefix, a);
1011     }
1012 }
1013
1014 // When an attribute is rendered inside a <code> tag, it is formatted using
1015 // a div to produce a newline after it.
1016 fn render_attributes_in_code(w: &mut Buffer, it: &clean::Item) {
1017     for a in attributes(it) {
1018         write!(w, "<div class=\"code-attribute\">{}</div>", a);
1019     }
1020 }
1021
1022 #[derive(Copy, Clone)]
1023 enum AssocItemLink<'a> {
1024     Anchor(Option<&'a str>),
1025     GotoSource(ItemId, &'a FxHashSet<Symbol>),
1026 }
1027
1028 impl<'a> AssocItemLink<'a> {
1029     fn anchor(&self, id: &'a str) -> Self {
1030         match *self {
1031             AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(id)),
1032             ref other => *other,
1033         }
1034     }
1035 }
1036
1037 fn render_assoc_items(
1038     w: &mut Buffer,
1039     cx: &Context<'_>,
1040     containing_item: &clean::Item,
1041     it: DefId,
1042     what: AssocItemRender<'_>,
1043 ) {
1044     let mut derefs = FxHashSet::default();
1045     derefs.insert(it);
1046     render_assoc_items_inner(w, cx, containing_item, it, what, &mut derefs)
1047 }
1048
1049 fn render_assoc_items_inner(
1050     w: &mut Buffer,
1051     cx: &Context<'_>,
1052     containing_item: &clean::Item,
1053     it: DefId,
1054     what: AssocItemRender<'_>,
1055     derefs: &mut FxHashSet<DefId>,
1056 ) {
1057     info!("Documenting associated items of {:?}", containing_item.name);
1058     let cache = cx.cache();
1059     let v = match cache.impls.get(&it) {
1060         Some(v) => v,
1061         None => return,
1062     };
1063     let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
1064     if !non_trait.is_empty() {
1065         let mut tmp_buf = Buffer::empty_from(w);
1066         let render_mode = match what {
1067             AssocItemRender::All => {
1068                 tmp_buf.write_str(
1069                     "<h2 id=\"implementations\" class=\"small-section-header\">\
1070                          Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
1071                     </h2>",
1072                 );
1073                 RenderMode::Normal
1074             }
1075             AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
1076                 let id =
1077                     cx.derive_id(small_url_encode(format!("deref-methods-{:#}", type_.print(cx))));
1078                 if let Some(def_id) = type_.def_id(cx.cache()) {
1079                     cx.deref_id_map.borrow_mut().insert(def_id, id.clone());
1080                 }
1081                 write!(
1082                     tmp_buf,
1083                     "<h2 id=\"{id}\" class=\"small-section-header\">\
1084                          <span>Methods from {trait_}&lt;Target = {type_}&gt;</span>\
1085                          <a href=\"#{id}\" class=\"anchor\"></a>\
1086                      </h2>",
1087                     id = id,
1088                     trait_ = trait_.print(cx),
1089                     type_ = type_.print(cx),
1090                 );
1091                 RenderMode::ForDeref { mut_: deref_mut_ }
1092             }
1093         };
1094         let mut impls_buf = Buffer::empty_from(w);
1095         for i in &non_trait {
1096             render_impl(
1097                 &mut impls_buf,
1098                 cx,
1099                 i,
1100                 containing_item,
1101                 AssocItemLink::Anchor(None),
1102                 render_mode,
1103                 None,
1104                 &[],
1105                 ImplRenderingParameters {
1106                     show_def_docs: true,
1107                     is_on_foreign_type: false,
1108                     show_default_items: true,
1109                     show_non_assoc_items: true,
1110                     toggle_open_by_default: true,
1111                 },
1112             );
1113         }
1114         if !impls_buf.is_empty() {
1115             w.push_buffer(tmp_buf);
1116             w.push_buffer(impls_buf);
1117         }
1118     }
1119
1120     if !traits.is_empty() {
1121         let deref_impl =
1122             traits.iter().find(|t| t.trait_did() == cx.tcx().lang_items().deref_trait());
1123         if let Some(impl_) = deref_impl {
1124             let has_deref_mut =
1125                 traits.iter().any(|t| t.trait_did() == cx.tcx().lang_items().deref_mut_trait());
1126             render_deref_methods(w, cx, impl_, containing_item, has_deref_mut, derefs);
1127         }
1128
1129         // If we were already one level into rendering deref methods, we don't want to render
1130         // anything after recursing into any further deref methods above.
1131         if let AssocItemRender::DerefFor { .. } = what {
1132             return;
1133         }
1134
1135         let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
1136             traits.iter().partition(|t| t.inner_impl().kind.is_auto());
1137         let (blanket_impl, concrete): (Vec<&&Impl>, _) =
1138             concrete.into_iter().partition(|t| t.inner_impl().kind.is_blanket());
1139
1140         let mut impls = Buffer::empty_from(w);
1141         render_impls(cx, &mut impls, &concrete, containing_item);
1142         let impls = impls.into_inner();
1143         if !impls.is_empty() {
1144             write!(
1145                 w,
1146                 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
1147                      Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
1148                  </h2>\
1149                  <div id=\"trait-implementations-list\">{}</div>",
1150                 impls
1151             );
1152         }
1153
1154         if !synthetic.is_empty() {
1155             w.write_str(
1156                 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
1157                      Auto Trait Implementations\
1158                      <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
1159                  </h2>\
1160                  <div id=\"synthetic-implementations-list\">",
1161             );
1162             render_impls(cx, w, &synthetic, containing_item);
1163             w.write_str("</div>");
1164         }
1165
1166         if !blanket_impl.is_empty() {
1167             w.write_str(
1168                 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
1169                      Blanket Implementations\
1170                      <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
1171                  </h2>\
1172                  <div id=\"blanket-implementations-list\">",
1173             );
1174             render_impls(cx, w, &blanket_impl, containing_item);
1175             w.write_str("</div>");
1176         }
1177     }
1178 }
1179
1180 fn render_deref_methods(
1181     w: &mut Buffer,
1182     cx: &Context<'_>,
1183     impl_: &Impl,
1184     container_item: &clean::Item,
1185     deref_mut: bool,
1186     derefs: &mut FxHashSet<DefId>,
1187 ) {
1188     let cache = cx.cache();
1189     let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
1190     let (target, real_target) = impl_
1191         .inner_impl()
1192         .items
1193         .iter()
1194         .find_map(|item| match *item.kind {
1195             clean::TypedefItem(ref t, true) => Some(match *t {
1196                 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
1197                 _ => (&t.type_, &t.type_),
1198             }),
1199             _ => None,
1200         })
1201         .expect("Expected associated type binding");
1202     debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target);
1203     let what =
1204         AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
1205     if let Some(did) = target.def_id(cache) {
1206         if let Some(type_did) = impl_.inner_impl().for_.def_id(cache) {
1207             // `impl Deref<Target = S> for S`
1208             if did == type_did || !derefs.insert(did) {
1209                 // Avoid infinite cycles
1210                 return;
1211             }
1212         }
1213         render_assoc_items_inner(w, cx, container_item, did, what, derefs);
1214     } else if let Some(prim) = target.primitive_type() {
1215         if let Some(&did) = cache.primitive_locations.get(&prim) {
1216             render_assoc_items_inner(w, cx, container_item, did, what, derefs);
1217         }
1218     }
1219 }
1220
1221 fn should_render_item(item: &clean::Item, deref_mut_: bool, tcx: TyCtxt<'_>) -> bool {
1222     let self_type_opt = match *item.kind {
1223         clean::MethodItem(ref method, _) => method.decl.self_type(),
1224         clean::TyMethodItem(ref method) => method.decl.self_type(),
1225         _ => None,
1226     };
1227
1228     if let Some(self_ty) = self_type_opt {
1229         let (by_mut_ref, by_box, by_value) = match self_ty {
1230             SelfTy::SelfBorrowed(_, mutability)
1231             | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
1232                 (mutability == Mutability::Mut, false, false)
1233             }
1234             SelfTy::SelfExplicit(clean::Type::Path { path }) => {
1235                 (false, Some(path.def_id()) == tcx.lang_items().owned_box(), false)
1236             }
1237             SelfTy::SelfValue => (false, false, true),
1238             _ => (false, false, false),
1239         };
1240
1241         (deref_mut_ || !by_mut_ref) && !by_box && !by_value
1242     } else {
1243         false
1244     }
1245 }
1246
1247 fn notable_traits_decl(decl: &clean::FnDecl, cx: &Context<'_>) -> String {
1248     let mut out = Buffer::html();
1249
1250     if let Some((did, ty)) = decl.output.as_return().and_then(|t| Some((t.def_id(cx.cache())?, t)))
1251     {
1252         if let Some(impls) = cx.cache().impls.get(&did) {
1253             for i in impls {
1254                 let impl_ = i.inner_impl();
1255                 if !impl_.for_.without_borrowed_ref().is_same(ty.without_borrowed_ref(), cx.cache())
1256                 {
1257                     // Two different types might have the same did,
1258                     // without actually being the same.
1259                     continue;
1260                 }
1261                 if let Some(trait_) = &impl_.trait_ {
1262                     let trait_did = trait_.def_id();
1263
1264                     if cx.cache().traits.get(&trait_did).map_or(false, |t| t.is_notable) {
1265                         if out.is_empty() {
1266                             write!(
1267                                 &mut out,
1268                                 "<div class=\"notable\">Notable traits for {}</div>\
1269                              <code class=\"content\">",
1270                                 impl_.for_.print(cx)
1271                             );
1272                         }
1273
1274                         //use the "where" class here to make it small
1275                         write!(
1276                             &mut out,
1277                             "<span class=\"where fmt-newline\">{}</span>",
1278                             impl_.print(false, cx)
1279                         );
1280                         for it in &impl_.items {
1281                             if let clean::TypedefItem(ref tydef, _) = *it.kind {
1282                                 out.push_str("<span class=\"where fmt-newline\">    ");
1283                                 let empty_set = FxHashSet::default();
1284                                 let src_link =
1285                                     AssocItemLink::GotoSource(trait_did.into(), &empty_set);
1286                                 assoc_type(&mut out, it, &[], Some(&tydef.type_), src_link, "", cx);
1287                                 out.push_str(";</span>");
1288                             }
1289                         }
1290                     }
1291                 }
1292             }
1293         }
1294     }
1295
1296     if !out.is_empty() {
1297         out.insert_str(
1298             0,
1299             "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
1300             <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
1301         );
1302         out.push_str("</code></span></div></span></span>");
1303     }
1304
1305     out.into_inner()
1306 }
1307
1308 #[derive(Clone, Copy, Debug)]
1309 struct ImplRenderingParameters {
1310     show_def_docs: bool,
1311     is_on_foreign_type: bool,
1312     show_default_items: bool,
1313     /// Whether or not to show methods.
1314     show_non_assoc_items: bool,
1315     toggle_open_by_default: bool,
1316 }
1317
1318 fn render_impl(
1319     w: &mut Buffer,
1320     cx: &Context<'_>,
1321     i: &Impl,
1322     parent: &clean::Item,
1323     link: AssocItemLink<'_>,
1324     render_mode: RenderMode,
1325     use_absolute: Option<bool>,
1326     aliases: &[String],
1327     rendering_params: ImplRenderingParameters,
1328 ) {
1329     let cache = cx.cache();
1330     let traits = &cache.traits;
1331     let trait_ = i.trait_did().map(|did| &traits[&did]);
1332     let mut close_tags = String::new();
1333
1334     // For trait implementations, the `interesting` output contains all methods that have doc
1335     // comments, and the `boring` output contains all methods that do not. The distinction is
1336     // used to allow hiding the boring methods.
1337     // `containing_item` is used for rendering stability info. If the parent is a trait impl,
1338     // `containing_item` will the grandparent, since trait impls can't have stability attached.
1339     fn doc_impl_item(
1340         boring: &mut Buffer,
1341         interesting: &mut Buffer,
1342         cx: &Context<'_>,
1343         item: &clean::Item,
1344         parent: &clean::Item,
1345         containing_item: &clean::Item,
1346         link: AssocItemLink<'_>,
1347         render_mode: RenderMode,
1348         is_default_item: bool,
1349         trait_: Option<&clean::Trait>,
1350         rendering_params: ImplRenderingParameters,
1351     ) {
1352         let item_type = item.type_();
1353         let name = item.name.as_ref().unwrap();
1354
1355         let render_method_item = rendering_params.show_non_assoc_items
1356             && match render_mode {
1357                 RenderMode::Normal => true,
1358                 RenderMode::ForDeref { mut_: deref_mut_ } => {
1359                     should_render_item(item, deref_mut_, cx.tcx())
1360                 }
1361             };
1362
1363         let in_trait_class = if trait_.is_some() { " trait-impl" } else { "" };
1364
1365         let mut doc_buffer = Buffer::empty_from(boring);
1366         let mut info_buffer = Buffer::empty_from(boring);
1367         let mut short_documented = true;
1368
1369         if render_method_item {
1370             if !is_default_item {
1371                 if let Some(t) = trait_ {
1372                     // The trait item may have been stripped so we might not
1373                     // find any documentation or stability for it.
1374                     if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
1375                         // We need the stability of the item from the trait
1376                         // because impls can't have a stability.
1377                         if item.doc_value().is_some() {
1378                             document_item_info(&mut info_buffer, cx, it, Some(parent));
1379                             document_full(&mut doc_buffer, item, cx, HeadingOffset::H5);
1380                             short_documented = false;
1381                         } else {
1382                             // In case the item isn't documented,
1383                             // provide short documentation from the trait.
1384                             document_short(
1385                                 &mut doc_buffer,
1386                                 it,
1387                                 cx,
1388                                 link,
1389                                 parent,
1390                                 rendering_params.show_def_docs,
1391                             );
1392                         }
1393                     }
1394                 } else {
1395                     document_item_info(&mut info_buffer, cx, item, Some(parent));
1396                     if rendering_params.show_def_docs {
1397                         document_full(&mut doc_buffer, item, cx, HeadingOffset::H5);
1398                         short_documented = false;
1399                     }
1400                 }
1401             } else {
1402                 document_short(
1403                     &mut doc_buffer,
1404                     item,
1405                     cx,
1406                     link,
1407                     parent,
1408                     rendering_params.show_def_docs,
1409                 );
1410             }
1411         }
1412         let w = if short_documented && trait_.is_some() { interesting } else { boring };
1413
1414         let toggled = !doc_buffer.is_empty();
1415         if toggled {
1416             let method_toggle_class =
1417                 if item_type == ItemType::Method { " method-toggle" } else { "" };
1418             write!(w, "<details class=\"rustdoc-toggle{}\" open><summary>", method_toggle_class);
1419         }
1420         match *item.kind {
1421             clean::MethodItem(..) | clean::TyMethodItem(_) => {
1422                 // Only render when the method is not static or we allow static methods
1423                 if render_method_item {
1424                     let id = cx.derive_id(format!("{}.{}", item_type, name));
1425                     let source_id = trait_
1426                         .and_then(|trait_| {
1427                             trait_.items.iter().find(|item| {
1428                                 item.name.map(|n| n.as_str().eq(name.as_str())).unwrap_or(false)
1429                             })
1430                         })
1431                         .map(|item| format!("{}.{}", item.type_(), name));
1432                     write!(
1433                         w,
1434                         "<div id=\"{}\" class=\"{}{} has-srclink\">",
1435                         id, item_type, in_trait_class,
1436                     );
1437                     render_rightside(w, cx, item, containing_item, render_mode);
1438                     write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1439                     w.write_str("<h4 class=\"code-header\">");
1440                     render_assoc_item(
1441                         w,
1442                         item,
1443                         link.anchor(source_id.as_ref().unwrap_or(&id)),
1444                         ItemType::Impl,
1445                         cx,
1446                         render_mode,
1447                     );
1448                     w.write_str("</h4>");
1449                     w.write_str("</div>");
1450                 }
1451             }
1452             clean::TypedefItem(ref tydef, _) => {
1453                 let source_id = format!("{}.{}", ItemType::AssocType, name);
1454                 let id = cx.derive_id(source_id.clone());
1455                 write!(
1456                     w,
1457                     "<div id=\"{}\" class=\"{}{} has-srclink\">",
1458                     id, item_type, in_trait_class
1459                 );
1460                 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1461                 w.write_str("<h4 class=\"code-header\">");
1462                 assoc_type(
1463                     w,
1464                     item,
1465                     &Vec::new(),
1466                     Some(&tydef.type_),
1467                     link.anchor(if trait_.is_some() { &source_id } else { &id }),
1468                     "",
1469                     cx,
1470                 );
1471                 w.write_str("</h4>");
1472                 w.write_str("</div>");
1473             }
1474             clean::AssocConstItem(ref ty, _) => {
1475                 let source_id = format!("{}.{}", item_type, name);
1476                 let id = cx.derive_id(source_id.clone());
1477                 write!(
1478                     w,
1479                     "<div id=\"{}\" class=\"{}{} has-srclink\">",
1480                     id, item_type, in_trait_class
1481                 );
1482                 render_rightside(w, cx, item, containing_item, render_mode);
1483                 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1484                 w.write_str("<h4 class=\"code-header\">");
1485                 assoc_const(
1486                     w,
1487                     item,
1488                     ty,
1489                     link.anchor(if trait_.is_some() { &source_id } else { &id }),
1490                     "",
1491                     cx,
1492                 );
1493                 w.write_str("</h4>");
1494                 w.write_str("</div>");
1495             }
1496             clean::AssocTypeItem(ref bounds, ref default) => {
1497                 let source_id = format!("{}.{}", item_type, name);
1498                 let id = cx.derive_id(source_id.clone());
1499                 write!(w, "<div id=\"{}\" class=\"{}{}\">", id, item_type, in_trait_class,);
1500                 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1501                 w.write_str("<h4 class=\"code-header\">");
1502                 assoc_type(
1503                     w,
1504                     item,
1505                     bounds,
1506                     default.as_ref(),
1507                     link.anchor(if trait_.is_some() { &source_id } else { &id }),
1508                     "",
1509                     cx,
1510                 );
1511                 w.write_str("</h4>");
1512                 w.write_str("</div>");
1513             }
1514             clean::StrippedItem(..) => return,
1515             _ => panic!("can't make docs for trait item with name {:?}", item.name),
1516         }
1517
1518         w.push_buffer(info_buffer);
1519         if toggled {
1520             w.write_str("</summary>");
1521             w.push_buffer(doc_buffer);
1522             w.push_str("</details>");
1523         }
1524     }
1525
1526     let mut impl_items = Buffer::empty_from(w);
1527     let mut default_impl_items = Buffer::empty_from(w);
1528
1529     for trait_item in &i.inner_impl().items {
1530         doc_impl_item(
1531             &mut default_impl_items,
1532             &mut impl_items,
1533             cx,
1534             trait_item,
1535             if trait_.is_some() { &i.impl_item } else { parent },
1536             parent,
1537             link,
1538             render_mode,
1539             false,
1540             trait_.map(|t| &t.trait_),
1541             rendering_params,
1542         );
1543     }
1544
1545     fn render_default_items(
1546         boring: &mut Buffer,
1547         interesting: &mut Buffer,
1548         cx: &Context<'_>,
1549         t: &clean::Trait,
1550         i: &clean::Impl,
1551         parent: &clean::Item,
1552         containing_item: &clean::Item,
1553         render_mode: RenderMode,
1554         rendering_params: ImplRenderingParameters,
1555     ) {
1556         for trait_item in &t.items {
1557             let n = trait_item.name;
1558             if i.items.iter().any(|m| m.name == n) {
1559                 continue;
1560             }
1561             let did = i.trait_.as_ref().unwrap().def_id();
1562             let provided_methods = i.provided_trait_methods(cx.tcx());
1563             let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_methods);
1564
1565             doc_impl_item(
1566                 boring,
1567                 interesting,
1568                 cx,
1569                 trait_item,
1570                 parent,
1571                 containing_item,
1572                 assoc_link,
1573                 render_mode,
1574                 true,
1575                 Some(t),
1576                 rendering_params,
1577             );
1578         }
1579     }
1580
1581     // If we've implemented a trait, then also emit documentation for all
1582     // default items which weren't overridden in the implementation block.
1583     // We don't emit documentation for default items if they appear in the
1584     // Implementations on Foreign Types or Implementors sections.
1585     if rendering_params.show_default_items {
1586         if let Some(t) = trait_ {
1587             render_default_items(
1588                 &mut default_impl_items,
1589                 &mut impl_items,
1590                 cx,
1591                 &t.trait_,
1592                 i.inner_impl(),
1593                 &i.impl_item,
1594                 parent,
1595                 render_mode,
1596                 rendering_params,
1597             );
1598         }
1599     }
1600     if render_mode == RenderMode::Normal {
1601         let toggled = !(impl_items.is_empty() && default_impl_items.is_empty());
1602         if toggled {
1603             close_tags.insert_str(0, "</details>");
1604             write!(
1605                 w,
1606                 "<details class=\"rustdoc-toggle implementors-toggle\"{}>",
1607                 if rendering_params.toggle_open_by_default { " open" } else { "" }
1608             );
1609             write!(w, "<summary>")
1610         }
1611         render_impl_summary(
1612             w,
1613             cx,
1614             i,
1615             parent,
1616             parent,
1617             rendering_params.show_def_docs,
1618             use_absolute,
1619             rendering_params.is_on_foreign_type,
1620             aliases,
1621         );
1622         if toggled {
1623             write!(w, "</summary>")
1624         }
1625
1626         if let Some(ref dox) = i.impl_item.collapsed_doc_value() {
1627             let mut ids = cx.id_map.borrow_mut();
1628             write!(
1629                 w,
1630                 "<div class=\"docblock\">{}</div>",
1631                 Markdown {
1632                     content: &*dox,
1633                     links: &i.impl_item.links(cx),
1634                     ids: &mut ids,
1635                     error_codes: cx.shared.codes,
1636                     edition: cx.shared.edition(),
1637                     playground: &cx.shared.playground,
1638                     heading_offset: HeadingOffset::H4
1639                 }
1640                 .into_string()
1641             );
1642         }
1643     }
1644     if !default_impl_items.is_empty() || !impl_items.is_empty() {
1645         w.write_str("<div class=\"impl-items\">");
1646         w.push_buffer(default_impl_items);
1647         w.push_buffer(impl_items);
1648         close_tags.insert_str(0, "</div>");
1649     }
1650     w.write_str(&close_tags);
1651 }
1652
1653 // Render the items that appear on the right side of methods, impls, and
1654 // associated types. For example "1.0.0 (const: 1.39.0) Â· source".
1655 fn render_rightside(
1656     w: &mut Buffer,
1657     cx: &Context<'_>,
1658     item: &clean::Item,
1659     containing_item: &clean::Item,
1660     render_mode: RenderMode,
1661 ) {
1662     let tcx = cx.tcx();
1663
1664     // FIXME: Once https://github.com/rust-lang/rust/issues/67792 is implemented, we can remove
1665     // this condition.
1666     let (const_stability, const_stable_since) = match render_mode {
1667         RenderMode::Normal => (item.const_stability(tcx), containing_item.const_stable_since(tcx)),
1668         RenderMode::ForDeref { .. } => (None, None),
1669     };
1670
1671     write!(w, "<div class=\"rightside\">");
1672     let has_stability = render_stability_since_raw(
1673         w,
1674         item.stable_since(tcx),
1675         const_stability,
1676         containing_item.stable_since(tcx),
1677         const_stable_since,
1678     );
1679     let mut tmp_buf = Buffer::empty_from(w);
1680     write_srclink(cx, item, &mut tmp_buf);
1681     if has_stability && !tmp_buf.is_empty() {
1682         w.write_str(" Â· ");
1683     }
1684     w.push_buffer(tmp_buf);
1685     w.write_str("</div>");
1686 }
1687
1688 pub(crate) fn render_impl_summary(
1689     w: &mut Buffer,
1690     cx: &Context<'_>,
1691     i: &Impl,
1692     parent: &clean::Item,
1693     containing_item: &clean::Item,
1694     show_def_docs: bool,
1695     use_absolute: Option<bool>,
1696     is_on_foreign_type: bool,
1697     // This argument is used to reference same type with different paths to avoid duplication
1698     // in documentation pages for trait with automatic implementations like "Send" and "Sync".
1699     aliases: &[String],
1700 ) {
1701     let id = cx.derive_id(match i.inner_impl().trait_ {
1702         Some(ref t) => {
1703             if is_on_foreign_type {
1704                 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t, cx)
1705             } else {
1706                 format!("impl-{}", small_url_encode(format!("{:#}", t.print(cx))))
1707             }
1708         }
1709         None => "impl".to_string(),
1710     });
1711     let aliases = if aliases.is_empty() {
1712         String::new()
1713     } else {
1714         format!(" data-aliases=\"{}\"", aliases.join(","))
1715     };
1716     write!(w, "<div id=\"{}\" class=\"impl has-srclink\"{}>", id, aliases);
1717     render_rightside(w, cx, &i.impl_item, containing_item, RenderMode::Normal);
1718     write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1719     write!(w, "<h3 class=\"code-header in-band\">");
1720
1721     if let Some(use_absolute) = use_absolute {
1722         write!(w, "{}", i.inner_impl().print(use_absolute, cx));
1723         if show_def_docs {
1724             for it in &i.inner_impl().items {
1725                 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1726                     w.write_str("<span class=\"where fmt-newline\">  ");
1727                     assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "", cx);
1728                     w.write_str(";</span>");
1729                 }
1730             }
1731         }
1732     } else {
1733         write!(w, "{}", i.inner_impl().print(false, cx));
1734     }
1735     write!(w, "</h3>");
1736
1737     let is_trait = i.inner_impl().trait_.is_some();
1738     if is_trait {
1739         if let Some(portability) = portability(&i.impl_item, Some(parent)) {
1740             write!(w, "<div class=\"item-info\">{}</div>", portability);
1741         }
1742     }
1743
1744     w.write_str("</div>");
1745 }
1746
1747 fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) {
1748     let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
1749
1750     if it.is_struct()
1751         || it.is_trait()
1752         || it.is_primitive()
1753         || it.is_union()
1754         || it.is_enum()
1755         || it.is_mod()
1756         || it.is_typedef()
1757     {
1758         write!(
1759             buffer,
1760             "<h2 class=\"location\"><a href=\"#\">{}{}</a></h2>",
1761             match *it.kind {
1762                 clean::ModuleItem(..) =>
1763                     if it.is_crate() {
1764                         "Crate "
1765                     } else {
1766                         "Module "
1767                     },
1768                 _ => "",
1769             },
1770             it.name.as_ref().unwrap()
1771         );
1772     }
1773
1774     buffer.write_str("<div class=\"sidebar-elems\">");
1775     if it.is_crate() {
1776         write!(buffer, "<div class=\"block\"><ul>");
1777         if let Some(ref version) = cx.cache().crate_version {
1778             write!(buffer, "<li class=\"version\">Version {}</li>", Escape(version));
1779         }
1780         write!(buffer, "<li><a id=\"all-types\" href=\"all.html\">All Items</a></li>");
1781         buffer.write_str("</div></ul>");
1782     }
1783
1784     match *it.kind {
1785         clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s),
1786         clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t),
1787         clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it),
1788         clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u),
1789         clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e),
1790         clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it),
1791         clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
1792         clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, it),
1793         _ => {}
1794     }
1795
1796     // The sidebar is designed to display sibling functions, modules and
1797     // other miscellaneous information. since there are lots of sibling
1798     // items (and that causes quadratic growth in large modules),
1799     // we refactor common parts into a shared JavaScript file per module.
1800     // still, we don't move everything into JS because we want to preserve
1801     // as much HTML as possible in order to allow non-JS-enabled browsers
1802     // to navigate the documentation (though slightly inefficiently).
1803
1804     if !it.is_mod() {
1805         buffer.write_str("<h2 class=\"location\">In ");
1806         for (i, name) in cx.current.iter().take(parentlen).enumerate() {
1807             if i > 0 {
1808                 buffer.write_str("::<wbr>");
1809             }
1810             write!(
1811                 buffer,
1812                 "<a href=\"{}index.html\">{}</a>",
1813                 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
1814                 *name
1815             );
1816         }
1817         buffer.write_str("</h2>");
1818     }
1819
1820     // Sidebar refers to the enclosing module, not this module.
1821     let relpath = if it.is_mod() && parentlen != 0 { "./" } else { "" };
1822     write!(
1823         buffer,
1824         "<div id=\"sidebar-vars\" data-name=\"{name}\" data-ty=\"{ty}\" data-relpath=\"{path}\">\
1825         </div>",
1826         name = it.name.unwrap_or(kw::Empty),
1827         ty = it.type_(),
1828         path = relpath
1829     );
1830     write!(
1831         buffer,
1832         "<script defer src=\"{}sidebar-items{}.js\"></script>",
1833         relpath, cx.shared.resource_suffix
1834     );
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(join_with_double_colon(&path));
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 }