]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/render/mod.rs
Merge branch 'master' into feature/incorporate-tracing
[rust.git] / src / librustdoc / html / render / mod.rs
1 // ignore-tidy-filelength
2
3 //! Rustdoc's HTML rendering module.
4 //!
5 //! This modules contains the bulk of the logic necessary for rendering a
6 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
7 //! rendering process is largely driven by the `format!` syntax extension to
8 //! perform all I/O into files and streams.
9 //!
10 //! The rendering process is largely driven by the `Context` and `Cache`
11 //! structures. The cache is pre-populated by crawling the crate in question,
12 //! and then it is shared among the various rendering threads. The cache is meant
13 //! to be a fairly large structure not implementing `Clone` (because it's shared
14 //! among threads). The context, however, should be a lightweight structure. This
15 //! is cloned per-thread and contains information about what is currently being
16 //! rendered.
17 //!
18 //! In order to speed up rendering (mostly because of markdown rendering), the
19 //! rendering process has been parallelized. This parallelization is only
20 //! exposed through the `crate` method on the context, and then also from the
21 //! fact that the shared cache is stored in TLS (and must be accessed as such).
22 //!
23 //! In addition to rendering the crate itself, this module is also responsible
24 //! for creating the corresponding search index and source file renderings.
25 //! These threads are not parallelized (they haven't been a bottleneck yet), and
26 //! both occur before the crate is rendered.
27
28 pub mod cache;
29
30 #[cfg(test)]
31 mod tests;
32
33 use std::borrow::Cow;
34 use std::cell::{Cell, RefCell};
35 use std::cmp::Ordering;
36 use std::collections::{BTreeMap, VecDeque};
37 use std::default::Default;
38 use std::ffi::OsStr;
39 use std::fmt::{self, Write};
40 use std::fs::{self, File};
41 use std::io::prelude::*;
42 use std::io::{self, BufReader};
43 use std::path::{Component, Path, PathBuf};
44 use std::rc::Rc;
45 use std::str;
46 use std::string::ToString;
47 use std::sync::mpsc::{channel, Receiver};
48 use std::sync::Arc;
49
50 use itertools::Itertools;
51 use rustc_ast_pretty::pprust;
52 use rustc_data_structures::flock;
53 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
54 use rustc_feature::UnstableFeatures;
55 use rustc_hir as hir;
56 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
57 use rustc_hir::Mutability;
58 use rustc_middle::middle::stability;
59 use rustc_span::edition::Edition;
60 use rustc_span::hygiene::MacroKind;
61 use rustc_span::source_map::FileName;
62 use rustc_span::symbol::{sym, Symbol};
63 use serde::ser::SerializeSeq;
64 use serde::{Serialize, Serializer};
65
66 use crate::clean::{self, AttributesExt, Deprecation, GetDefId, SelfTy, TypeKind};
67 use crate::config::RenderInfo;
68 use crate::config::RenderOptions;
69 use crate::docfs::{DocFS, PathError};
70 use crate::doctree;
71 use crate::error::Error;
72 use crate::formats::cache::{cache, Cache};
73 use crate::formats::item_type::ItemType;
74 use crate::formats::{AssocItemRender, FormatRenderer, Impl, RenderMode};
75 use crate::html::escape::Escape;
76 use crate::html::format::fmt_impl_for_trait_page;
77 use crate::html::format::Function;
78 use crate::html::format::{href, print_default_space, print_generic_bounds, WhereClause};
79 use crate::html::format::{print_abi_with_space, Buffer, PrintWithSpace};
80 use crate::html::markdown::{self, ErrorCodes, IdMap, Markdown, MarkdownHtml, MarkdownSummaryLine};
81 use crate::html::sources;
82 use crate::html::{highlight, layout, static_files};
83 use cache::{build_index, ExternalLocation};
84
85 /// A pair of name and its optional document.
86 pub type NameDoc = (String, Option<String>);
87
88 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
89     crate::html::format::display_fn(move |f| {
90         if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { write!(f, "{}", v) }
91     })
92 }
93
94 /// Major driving force in all rustdoc rendering. This contains information
95 /// about where in the tree-like hierarchy rendering is occurring and controls
96 /// how the current page is being rendered.
97 ///
98 /// It is intended that this context is a lightweight object which can be fairly
99 /// easily cloned because it is cloned per work-job (about once per item in the
100 /// rustdoc tree).
101 #[derive(Clone)]
102 crate struct Context {
103     /// Current hierarchy of components leading down to what's currently being
104     /// rendered
105     pub current: Vec<String>,
106     /// The current destination folder of where HTML artifacts should be placed.
107     /// This changes as the context descends into the module hierarchy.
108     pub dst: PathBuf,
109     /// A flag, which when `true`, will render pages which redirect to the
110     /// real location of an item. This is used to allow external links to
111     /// publicly reused items to redirect to the right location.
112     pub render_redirect_pages: bool,
113     /// The map used to ensure all generated 'id=' attributes are unique.
114     id_map: Rc<RefCell<IdMap>>,
115     pub shared: Arc<SharedContext>,
116     all: Rc<RefCell<AllTypes>>,
117     /// Storage for the errors produced while generating documentation so they
118     /// can be printed together at the end.
119     pub errors: Rc<Receiver<String>>,
120 }
121
122 crate struct SharedContext {
123     /// The path to the crate root source minus the file name.
124     /// Used for simplifying paths to the highlighted source code files.
125     pub src_root: PathBuf,
126     /// This describes the layout of each page, and is not modified after
127     /// creation of the context (contains info like the favicon and added html).
128     pub layout: layout::Layout,
129     /// This flag indicates whether `[src]` links should be generated or not. If
130     /// the source files are present in the html rendering, then this will be
131     /// `true`.
132     pub include_sources: bool,
133     /// The local file sources we've emitted and their respective url-paths.
134     pub local_sources: FxHashMap<PathBuf, String>,
135     /// Whether the collapsed pass ran
136     pub collapsed: bool,
137     /// The base-URL of the issue tracker for when an item has been tagged with
138     /// an issue number.
139     pub issue_tracker_base_url: Option<String>,
140     /// The directories that have already been created in this doc run. Used to reduce the number
141     /// of spurious `create_dir_all` calls.
142     pub created_dirs: RefCell<FxHashSet<PathBuf>>,
143     /// This flag indicates whether listings of modules (in the side bar and documentation itself)
144     /// should be ordered alphabetically or in order of appearance (in the source code).
145     pub sort_modules_alphabetically: bool,
146     /// Additional CSS files to be added to the generated docs.
147     pub style_files: Vec<StylePath>,
148     /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
149     /// "light-v2.css").
150     pub resource_suffix: String,
151     /// Optional path string to be used to load static files on output pages. If not set, uses
152     /// combinations of `../` to reach the documentation root.
153     pub static_root_path: Option<String>,
154     /// The fs handle we are working with.
155     pub fs: DocFS,
156     /// The default edition used to parse doctests.
157     pub edition: Edition,
158     pub codes: ErrorCodes,
159     playground: Option<markdown::Playground>,
160 }
161
162 impl Context {
163     fn path(&self, filename: &str) -> PathBuf {
164         // We use splitn vs Path::extension here because we might get a filename
165         // like `style.min.css` and we want to process that into
166         // `style-suffix.min.css`.  Path::extension would just return `css`
167         // which would result in `style.min-suffix.css` which isn't what we
168         // want.
169         let mut iter = filename.splitn(2, '.');
170         let base = iter.next().unwrap();
171         let ext = iter.next().unwrap();
172         let filename = format!("{}{}.{}", base, self.shared.resource_suffix, ext,);
173         self.dst.join(&filename)
174     }
175 }
176
177 impl SharedContext {
178     crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
179         let mut dirs = self.created_dirs.borrow_mut();
180         if !dirs.contains(dst) {
181             try_err!(self.fs.create_dir_all(dst), dst);
182             dirs.insert(dst.to_path_buf());
183         }
184
185         Ok(())
186     }
187
188     /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
189     /// `collapsed_doc_value` of the given item.
190     pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
191         if self.collapsed {
192             item.collapsed_doc_value().map(|s| s.into())
193         } else {
194             item.doc_value().map(|s| s.into())
195         }
196     }
197 }
198
199 // Helper structs for rendering items/sidebars and carrying along contextual
200 // information
201
202 /// Struct representing one entry in the JS search index. These are all emitted
203 /// by hand to a large JS file at the end of cache-creation.
204 #[derive(Debug)]
205 pub struct IndexItem {
206     pub ty: ItemType,
207     pub name: String,
208     pub path: String,
209     pub desc: String,
210     pub parent: Option<DefId>,
211     pub parent_idx: Option<usize>,
212     pub search_type: Option<IndexItemFunctionType>,
213 }
214
215 impl Serialize for IndexItem {
216     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
217     where
218         S: Serializer,
219     {
220         assert_eq!(
221             self.parent.is_some(),
222             self.parent_idx.is_some(),
223             "`{}` is missing idx",
224             self.name
225         );
226
227         (self.ty, &self.name, &self.path, &self.desc, self.parent_idx, &self.search_type)
228             .serialize(serializer)
229     }
230 }
231
232 /// A type used for the search index.
233 #[derive(Debug)]
234 crate struct RenderType {
235     ty: Option<DefId>,
236     idx: Option<usize>,
237     name: Option<String>,
238     generics: Option<Vec<Generic>>,
239 }
240
241 impl Serialize for RenderType {
242     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
243     where
244         S: Serializer,
245     {
246         if let Some(name) = &self.name {
247             let mut seq = serializer.serialize_seq(None)?;
248             if let Some(id) = self.idx {
249                 seq.serialize_element(&id)?;
250             } else {
251                 seq.serialize_element(&name)?;
252             }
253             if let Some(generics) = &self.generics {
254                 seq.serialize_element(&generics)?;
255             }
256             seq.end()
257         } else {
258             serializer.serialize_none()
259         }
260     }
261 }
262
263 /// A type used for the search index.
264 #[derive(Debug)]
265 crate struct Generic {
266     name: String,
267     defid: Option<DefId>,
268     idx: Option<usize>,
269 }
270
271 impl Serialize for Generic {
272     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
273     where
274         S: Serializer,
275     {
276         if let Some(id) = self.idx {
277             serializer.serialize_some(&id)
278         } else {
279             serializer.serialize_some(&self.name)
280         }
281     }
282 }
283
284 /// Full type of functions/methods in the search index.
285 #[derive(Debug)]
286 pub struct IndexItemFunctionType {
287     inputs: Vec<TypeWithKind>,
288     output: Option<Vec<TypeWithKind>>,
289 }
290
291 impl Serialize for IndexItemFunctionType {
292     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
293     where
294         S: Serializer,
295     {
296         // If we couldn't figure out a type, just write `null`.
297         let mut iter = self.inputs.iter();
298         if match self.output {
299             Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
300             None => iter.any(|ref i| i.ty.name.is_none()),
301         } {
302             serializer.serialize_none()
303         } else {
304             let mut seq = serializer.serialize_seq(None)?;
305             seq.serialize_element(&self.inputs)?;
306             if let Some(output) = &self.output {
307                 if output.len() > 1 {
308                     seq.serialize_element(&output)?;
309                 } else {
310                     seq.serialize_element(&output[0])?;
311                 }
312             }
313             seq.end()
314         }
315     }
316 }
317
318 #[derive(Debug)]
319 crate struct TypeWithKind {
320     ty: RenderType,
321     kind: TypeKind,
322 }
323
324 impl From<(RenderType, TypeKind)> for TypeWithKind {
325     fn from(x: (RenderType, TypeKind)) -> TypeWithKind {
326         TypeWithKind { ty: x.0, kind: x.1 }
327     }
328 }
329
330 impl Serialize for TypeWithKind {
331     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
332     where
333         S: Serializer,
334     {
335         let mut seq = serializer.serialize_seq(None)?;
336         seq.serialize_element(&self.ty.name)?;
337         let x: ItemType = self.kind.into();
338         seq.serialize_element(&x)?;
339         seq.end()
340     }
341 }
342
343 #[derive(Debug, Clone)]
344 pub struct StylePath {
345     /// The path to the theme
346     pub path: PathBuf,
347     /// What the `disabled` attribute should be set to in the HTML tag
348     pub disabled: bool,
349 }
350
351 thread_local!(pub static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
352
353 pub fn initial_ids() -> Vec<String> {
354     [
355         "main",
356         "search",
357         "help",
358         "TOC",
359         "render-detail",
360         "associated-types",
361         "associated-const",
362         "required-methods",
363         "provided-methods",
364         "implementors",
365         "synthetic-implementors",
366         "implementors-list",
367         "synthetic-implementors-list",
368         "methods",
369         "deref-methods",
370         "implementations",
371     ]
372     .iter()
373     .map(|id| (String::from(*id)))
374     .collect()
375 }
376
377 /// Generates the documentation for `crate` into the directory `dst`
378 impl FormatRenderer for Context {
379     fn init(
380         mut krate: clean::Crate,
381         options: RenderOptions,
382         _render_info: RenderInfo,
383         edition: Edition,
384         cache: &mut Cache,
385     ) -> Result<(Context, clean::Crate), Error> {
386         // need to save a copy of the options for rendering the index page
387         let md_opts = options.clone();
388         let RenderOptions {
389             output,
390             external_html,
391             id_map,
392             playground_url,
393             sort_modules_alphabetically,
394             themes: style_files,
395             extension_css,
396             resource_suffix,
397             static_root_path,
398             generate_search_filter,
399             ..
400         } = options;
401
402         let src_root = match krate.src {
403             FileName::Real(ref p) => match p.local_path().parent() {
404                 Some(p) => p.to_path_buf(),
405                 None => PathBuf::new(),
406             },
407             _ => PathBuf::new(),
408         };
409         // If user passed in `--playground-url` arg, we fill in crate name here
410         let mut playground = None;
411         if let Some(url) = playground_url {
412             playground = Some(markdown::Playground { crate_name: Some(krate.name.clone()), url });
413         }
414         let mut layout = layout::Layout {
415             logo: String::new(),
416             favicon: String::new(),
417             external_html,
418             krate: krate.name.clone(),
419             css_file_extension: extension_css,
420             generate_search_filter,
421         };
422         let mut issue_tracker_base_url = None;
423         let mut include_sources = true;
424
425         // Crawl the crate attributes looking for attributes which control how we're
426         // going to emit HTML
427         if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
428             for attr in attrs.lists(sym::doc) {
429                 match (attr.name_or_empty(), attr.value_str()) {
430                     (sym::html_favicon_url, Some(s)) => {
431                         layout.favicon = s.to_string();
432                     }
433                     (sym::html_logo_url, Some(s)) => {
434                         layout.logo = s.to_string();
435                     }
436                     (sym::html_playground_url, Some(s)) => {
437                         playground = Some(markdown::Playground {
438                             crate_name: Some(krate.name.clone()),
439                             url: s.to_string(),
440                         });
441                     }
442                     (sym::issue_tracker_base_url, Some(s)) => {
443                         issue_tracker_base_url = Some(s.to_string());
444                     }
445                     (sym::html_no_source, None) if attr.is_word() => {
446                         include_sources = false;
447                     }
448                     _ => {}
449                 }
450             }
451         }
452         let (sender, receiver) = channel();
453         let mut scx = SharedContext {
454             collapsed: krate.collapsed,
455             src_root,
456             include_sources,
457             local_sources: Default::default(),
458             issue_tracker_base_url,
459             layout,
460             created_dirs: Default::default(),
461             sort_modules_alphabetically,
462             style_files,
463             resource_suffix,
464             static_root_path,
465             fs: DocFS::new(sender),
466             edition,
467             codes: ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build()),
468             playground,
469         };
470
471         // Add the default themes to the `Vec` of stylepaths
472         //
473         // Note that these must be added before `sources::render` is called
474         // so that the resulting source pages are styled
475         //
476         // `light.css` is not disabled because it is the stylesheet that stays loaded
477         // by the browser as the theme stylesheet. The theme system (hackily) works by
478         // changing the href to this stylesheet. All other themes are disabled to
479         // prevent rule conflicts
480         scx.style_files.push(StylePath { path: PathBuf::from("light.css"), disabled: false });
481         scx.style_files.push(StylePath { path: PathBuf::from("dark.css"), disabled: true });
482         scx.style_files.push(StylePath { path: PathBuf::from("ayu.css"), disabled: true });
483
484         let dst = output;
485         scx.ensure_dir(&dst)?;
486         krate = sources::render(&dst, &mut scx, krate)?;
487
488         // Build our search index
489         let index = build_index(&krate, cache);
490
491         let cache = Arc::new(cache);
492         let mut cx = Context {
493             current: Vec::new(),
494             dst,
495             render_redirect_pages: false,
496             id_map: Rc::new(RefCell::new(id_map)),
497             shared: Arc::new(scx),
498             all: Rc::new(RefCell::new(AllTypes::new())),
499             errors: Rc::new(receiver),
500         };
501
502         CURRENT_DEPTH.with(|s| s.set(0));
503
504         // Write shared runs within a flock; disable thread dispatching of IO temporarily.
505         Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true);
506         write_shared(&cx, &krate, index, &md_opts, &cache)?;
507         Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
508         Ok((cx, krate))
509     }
510
511     fn after_run(&mut self, diag: &rustc_errors::Handler) -> Result<(), Error> {
512         Arc::get_mut(&mut self.shared).unwrap().fs.close();
513         let nb_errors = self.errors.iter().map(|err| diag.struct_err(&err).emit()).count();
514         if nb_errors > 0 {
515             Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
516         } else {
517             Ok(())
518         }
519     }
520
521     fn after_krate(&mut self, krate: &clean::Crate, cache: &Cache) -> Result<(), Error> {
522         let final_file = self.dst.join(&krate.name).join("all.html");
523         let settings_file = self.dst.join("settings.html");
524         let crate_name = krate.name.clone();
525
526         let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
527         if !root_path.ends_with('/') {
528             root_path.push('/');
529         }
530         let mut page = layout::Page {
531             title: "List of all items in this crate",
532             css_class: "mod",
533             root_path: "../",
534             static_root_path: self.shared.static_root_path.as_deref(),
535             description: "List of all items in this crate",
536             keywords: BASIC_KEYWORDS,
537             resource_suffix: &self.shared.resource_suffix,
538             extra_scripts: &[],
539             static_extra_scripts: &[],
540         };
541         let sidebar = if let Some(ref version) = cache.crate_version {
542             format!(
543                 "<p class='location'>Crate {}</p>\
544                      <div class='block version'>\
545                          <p>Version {}</p>\
546                      </div>\
547                      <a id='all-types' href='index.html'><p>Back to index</p></a>",
548                 crate_name,
549                 Escape(version),
550             )
551         } else {
552             String::new()
553         };
554         let all = self.all.replace(AllTypes::new());
555         let v = layout::render(
556             &self.shared.layout,
557             &page,
558             sidebar,
559             |buf: &mut Buffer| all.print(buf),
560             &self.shared.style_files,
561         );
562         self.shared.fs.write(&final_file, v.as_bytes())?;
563
564         // Generating settings page.
565         page.title = "Rustdoc settings";
566         page.description = "Settings of Rustdoc";
567         page.root_path = "./";
568
569         let mut style_files = self.shared.style_files.clone();
570         let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
571         style_files.push(StylePath { path: PathBuf::from("settings.css"), disabled: false });
572         let v = layout::render(
573             &self.shared.layout,
574             &page,
575             sidebar,
576             settings(
577                 self.shared.static_root_path.as_deref().unwrap_or("./"),
578                 &self.shared.resource_suffix,
579             ),
580             &style_files,
581         );
582         self.shared.fs.write(&settings_file, v.as_bytes())?;
583         Ok(())
584     }
585
586     fn mod_item_in(
587         &mut self,
588         item: &clean::Item,
589         item_name: &str,
590         cache: &Cache,
591     ) -> Result<(), Error> {
592         // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
593         // if they contain impls for public types. These modules can also
594         // contain items such as publicly re-exported structures.
595         //
596         // External crates will provide links to these structures, so
597         // these modules are recursed into, but not rendered normally
598         // (a flag on the context).
599         if !self.render_redirect_pages {
600             self.render_redirect_pages = item.is_stripped();
601         }
602         let scx = &self.shared;
603         self.dst.push(item_name);
604         self.current.push(item_name.to_owned());
605
606         info!("Recursing into {}", self.dst.display());
607
608         let buf = self.render_item(item, false, cache);
609         // buf will be empty if the module is stripped and there is no redirect for it
610         if !buf.is_empty() {
611             self.shared.ensure_dir(&self.dst)?;
612             let joint_dst = self.dst.join("index.html");
613             scx.fs.write(&joint_dst, buf.as_bytes())?;
614         }
615
616         // Render sidebar-items.js used throughout this module.
617         if !self.render_redirect_pages {
618             let module = match item.inner {
619                 clean::StrippedItem(box clean::ModuleItem(ref m)) | clean::ModuleItem(ref m) => m,
620                 _ => unreachable!(),
621             };
622             let items = self.build_sidebar_items(module);
623             let js_dst = self.dst.join("sidebar-items.js");
624             let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap());
625             scx.fs.write(&js_dst, &v)?;
626         }
627         Ok(())
628     }
629
630     fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
631         info!("Recursed; leaving {}", self.dst.display());
632
633         // Go back to where we were at
634         self.dst.pop();
635         self.current.pop();
636         Ok(())
637     }
638
639     fn item(&mut self, item: clean::Item, cache: &Cache) -> Result<(), Error> {
640         // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
641         // if they contain impls for public types. These modules can also
642         // contain items such as publicly re-exported structures.
643         //
644         // External crates will provide links to these structures, so
645         // these modules are recursed into, but not rendered normally
646         // (a flag on the context).
647         if !self.render_redirect_pages {
648             self.render_redirect_pages = item.is_stripped();
649         }
650
651         let buf = self.render_item(&item, true, cache);
652         // buf will be empty if the item is stripped and there is no redirect for it
653         if !buf.is_empty() {
654             let name = item.name.as_ref().unwrap();
655             let item_type = item.type_();
656             let file_name = &item_path(item_type, name);
657             self.shared.ensure_dir(&self.dst)?;
658             let joint_dst = self.dst.join(file_name);
659             self.shared.fs.write(&joint_dst, buf.as_bytes())?;
660
661             if !self.render_redirect_pages {
662                 self.all.borrow_mut().append(full_path(self, &item), &item_type);
663             }
664             // If the item is a macro, redirect from the old macro URL (with !)
665             // to the new one (without).
666             if item_type == ItemType::Macro {
667                 let redir_name = format!("{}.{}!.html", item_type, name);
668                 let redir_dst = self.dst.join(redir_name);
669                 let v = layout::redirect(file_name);
670                 self.shared.fs.write(&redir_dst, v.as_bytes())?;
671             }
672         }
673         Ok(())
674     }
675 }
676
677 fn write_shared(
678     cx: &Context,
679     krate: &clean::Crate,
680     search_index: String,
681     options: &RenderOptions,
682     cache: &Cache,
683 ) -> Result<(), Error> {
684     // Write out the shared files. Note that these are shared among all rustdoc
685     // docs placed in the output directory, so this needs to be a synchronized
686     // operation with respect to all other rustdocs running around.
687     let lock_file = cx.dst.join(".lock");
688     let _lock = try_err!(flock::Lock::new(&lock_file, true, true, true), &lock_file);
689
690     // Add all the static files. These may already exist, but we just
691     // overwrite them anyway to make sure that they're fresh and up-to-date.
692
693     write_minify(
694         &cx.shared.fs,
695         cx.path("rustdoc.css"),
696         static_files::RUSTDOC_CSS,
697         options.enable_minification,
698     )?;
699     write_minify(
700         &cx.shared.fs,
701         cx.path("settings.css"),
702         static_files::SETTINGS_CSS,
703         options.enable_minification,
704     )?;
705     write_minify(
706         &cx.shared.fs,
707         cx.path("noscript.css"),
708         static_files::NOSCRIPT_CSS,
709         options.enable_minification,
710     )?;
711
712     // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
713     // then we'll run over the "official" styles.
714     let mut themes: FxHashSet<String> = FxHashSet::default();
715
716     for entry in &cx.shared.style_files {
717         let theme = try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path);
718         let extension =
719             try_none!(try_none!(entry.path.extension(), &entry.path).to_str(), &entry.path);
720
721         // Handle the official themes
722         match theme {
723             "light" => write_minify(
724                 &cx.shared.fs,
725                 cx.path("light.css"),
726                 static_files::themes::LIGHT,
727                 options.enable_minification,
728             )?,
729             "dark" => write_minify(
730                 &cx.shared.fs,
731                 cx.path("dark.css"),
732                 static_files::themes::DARK,
733                 options.enable_minification,
734             )?,
735             "ayu" => write_minify(
736                 &cx.shared.fs,
737                 cx.path("ayu.css"),
738                 static_files::themes::AYU,
739                 options.enable_minification,
740             )?,
741             _ => {
742                 // Handle added third-party themes
743                 let content = try_err!(fs::read(&entry.path), &entry.path);
744                 cx.shared
745                     .fs
746                     .write(cx.path(&format!("{}.{}", theme, extension)), content.as_slice())?;
747             }
748         };
749
750         themes.insert(theme.to_owned());
751     }
752
753     let write = |p, c| cx.shared.fs.write(p, c);
754     if (*cx.shared).layout.logo.is_empty() {
755         write(cx.path("rust-logo.png"), static_files::RUST_LOGO)?;
756     }
757     if (*cx.shared).layout.favicon.is_empty() {
758         write(cx.path("favicon.ico"), static_files::RUST_FAVICON)?;
759     }
760     write(cx.path("brush.svg"), static_files::BRUSH_SVG)?;
761     write(cx.path("wheel.svg"), static_files::WHEEL_SVG)?;
762     write(cx.path("down-arrow.svg"), static_files::DOWN_ARROW_SVG)?;
763
764     let mut themes: Vec<&String> = themes.iter().collect();
765     themes.sort();
766     // To avoid theme switch latencies as much as possible, we put everything theme related
767     // at the beginning of the html files into another js file.
768     let theme_js = format!(
769         r#"var themes = document.getElementById("theme-choices");
770 var themePicker = document.getElementById("theme-picker");
771
772 function showThemeButtonState() {{
773     themes.style.display = "block";
774     themePicker.style.borderBottomRightRadius = "0";
775     themePicker.style.borderBottomLeftRadius = "0";
776 }}
777
778 function hideThemeButtonState() {{
779     themes.style.display = "none";
780     themePicker.style.borderBottomRightRadius = "3px";
781     themePicker.style.borderBottomLeftRadius = "3px";
782 }}
783
784 function switchThemeButtonState() {{
785     if (themes.style.display === "block") {{
786         hideThemeButtonState();
787     }} else {{
788         showThemeButtonState();
789     }}
790 }};
791
792 function handleThemeButtonsBlur(e) {{
793     var active = document.activeElement;
794     var related = e.relatedTarget;
795
796     if (active.id !== "themePicker" &&
797         (!active.parentNode || active.parentNode.id !== "theme-choices") &&
798         (!related ||
799          (related.id !== "themePicker" &&
800           (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
801         hideThemeButtonState();
802     }}
803 }}
804
805 themePicker.onclick = switchThemeButtonState;
806 themePicker.onblur = handleThemeButtonsBlur;
807 {}.forEach(function(item) {{
808     var but = document.createElement('button');
809     but.textContent = item;
810     but.onclick = function(el) {{
811         switchTheme(currentTheme, mainTheme, item, true);
812     }};
813     but.onblur = handleThemeButtonsBlur;
814     themes.appendChild(but);
815 }});"#,
816         serde_json::to_string(&themes).unwrap()
817     );
818
819     write_minify(&cx.shared.fs, cx.path("theme.js"), &theme_js, options.enable_minification)?;
820     write_minify(
821         &cx.shared.fs,
822         cx.path("main.js"),
823         static_files::MAIN_JS,
824         options.enable_minification,
825     )?;
826     write_minify(
827         &cx.shared.fs,
828         cx.path("settings.js"),
829         static_files::SETTINGS_JS,
830         options.enable_minification,
831     )?;
832     if cx.shared.include_sources {
833         write_minify(
834             &cx.shared.fs,
835             cx.path("source-script.js"),
836             static_files::sidebar::SOURCE_SCRIPT,
837             options.enable_minification,
838         )?;
839     }
840
841     {
842         write_minify(
843             &cx.shared.fs,
844             cx.path("storage.js"),
845             &format!(
846                 "var resourcesSuffix = \"{}\";{}",
847                 cx.shared.resource_suffix,
848                 static_files::STORAGE_JS
849             ),
850             options.enable_minification,
851         )?;
852     }
853
854     if let Some(ref css) = cx.shared.layout.css_file_extension {
855         let out = cx.path("theme.css");
856         let buffer = try_err!(fs::read_to_string(css), css);
857         if !options.enable_minification {
858             cx.shared.fs.write(&out, &buffer)?;
859         } else {
860             write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?;
861         }
862     }
863     write_minify(
864         &cx.shared.fs,
865         cx.path("normalize.css"),
866         static_files::NORMALIZE_CSS,
867         options.enable_minification,
868     )?;
869     write(cx.dst.join("FiraSans-Regular.woff"), static_files::fira_sans::REGULAR)?;
870     write(cx.dst.join("FiraSans-Medium.woff"), static_files::fira_sans::MEDIUM)?;
871     write(cx.dst.join("FiraSans-LICENSE.txt"), static_files::fira_sans::LICENSE)?;
872     write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"), static_files::source_serif_pro::REGULAR)?;
873     write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"), static_files::source_serif_pro::BOLD)?;
874     write(cx.dst.join("SourceSerifPro-It.ttf.woff"), static_files::source_serif_pro::ITALIC)?;
875     write(cx.dst.join("SourceSerifPro-LICENSE.md"), static_files::source_serif_pro::LICENSE)?;
876     write(cx.dst.join("SourceCodePro-Regular.woff"), static_files::source_code_pro::REGULAR)?;
877     write(cx.dst.join("SourceCodePro-Semibold.woff"), static_files::source_code_pro::SEMIBOLD)?;
878     write(cx.dst.join("SourceCodePro-LICENSE.txt"), static_files::source_code_pro::LICENSE)?;
879     write(cx.dst.join("LICENSE-MIT.txt"), static_files::LICENSE_MIT)?;
880     write(cx.dst.join("LICENSE-APACHE.txt"), static_files::LICENSE_APACHE)?;
881     write(cx.dst.join("COPYRIGHT.txt"), static_files::COPYRIGHT)?;
882
883     fn collect(path: &Path, krate: &str, key: &str) -> io::Result<(Vec<String>, Vec<String>)> {
884         let mut ret = Vec::new();
885         let mut krates = Vec::new();
886
887         if path.exists() {
888             for line in BufReader::new(File::open(path)?).lines() {
889                 let line = line?;
890                 if !line.starts_with(key) {
891                     continue;
892                 }
893                 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
894                     continue;
895                 }
896                 ret.push(line.to_string());
897                 krates.push(
898                     line[key.len() + 2..]
899                         .split('"')
900                         .next()
901                         .map(|s| s.to_owned())
902                         .unwrap_or_else(String::new),
903                 );
904             }
905         }
906         Ok((ret, krates))
907     }
908
909     fn collect_json(path: &Path, krate: &str) -> io::Result<(Vec<String>, Vec<String>)> {
910         let mut ret = Vec::new();
911         let mut krates = Vec::new();
912
913         if path.exists() {
914             for line in BufReader::new(File::open(path)?).lines() {
915                 let line = line?;
916                 if !line.starts_with('"') {
917                     continue;
918                 }
919                 if line.starts_with(&format!("\"{}\"", krate)) {
920                     continue;
921                 }
922                 if line.ends_with(",\\") {
923                     ret.push(line[..line.len() - 2].to_string());
924                 } else {
925                     // Ends with "\\" (it's the case for the last added crate line)
926                     ret.push(line[..line.len() - 1].to_string());
927                 }
928                 krates.push(
929                     line.split('"')
930                         .find(|s| !s.is_empty())
931                         .map(|s| s.to_owned())
932                         .unwrap_or_else(String::new),
933                 );
934             }
935         }
936         Ok((ret, krates))
937     }
938
939     use std::ffi::OsString;
940
941     #[derive(Debug)]
942     struct Hierarchy {
943         elem: OsString,
944         children: FxHashMap<OsString, Hierarchy>,
945         elems: FxHashSet<OsString>,
946     }
947
948     impl Hierarchy {
949         fn new(elem: OsString) -> Hierarchy {
950             Hierarchy { elem, children: FxHashMap::default(), elems: FxHashSet::default() }
951         }
952
953         fn to_json_string(&self) -> String {
954             let mut subs: Vec<&Hierarchy> = self.children.values().collect();
955             subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
956             let mut files = self
957                 .elems
958                 .iter()
959                 .map(|s| format!("\"{}\"", s.to_str().expect("invalid osstring conversion")))
960                 .collect::<Vec<_>>();
961             files.sort_unstable_by(|a, b| a.cmp(b));
962             let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
963             let dirs =
964                 if subs.is_empty() { String::new() } else { format!(",\"dirs\":[{}]", subs) };
965             let files = files.join(",");
966             let files =
967                 if files.is_empty() { String::new() } else { format!(",\"files\":[{}]", files) };
968             format!(
969                 "{{\"name\":\"{name}\"{dirs}{files}}}",
970                 name = self.elem.to_str().expect("invalid osstring conversion"),
971                 dirs = dirs,
972                 files = files
973             )
974         }
975     }
976
977     if cx.shared.include_sources {
978         let mut hierarchy = Hierarchy::new(OsString::new());
979         for source in cx
980             .shared
981             .local_sources
982             .iter()
983             .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root).ok())
984         {
985             let mut h = &mut hierarchy;
986             let mut elems = source
987                 .components()
988                 .filter_map(|s| match s {
989                     Component::Normal(s) => Some(s.to_owned()),
990                     _ => None,
991                 })
992                 .peekable();
993             loop {
994                 let cur_elem = elems.next().expect("empty file path");
995                 if elems.peek().is_none() {
996                     h.elems.insert(cur_elem);
997                     break;
998                 } else {
999                     let e = cur_elem.clone();
1000                     h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
1001                     h = h.children.get_mut(&cur_elem).expect("not found child");
1002                 }
1003             }
1004         }
1005
1006         let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
1007         let (mut all_sources, _krates) = try_err!(collect(&dst, &krate.name, "sourcesIndex"), &dst);
1008         all_sources.push(format!(
1009             "sourcesIndex[\"{}\"] = {};",
1010             &krate.name,
1011             hierarchy.to_json_string()
1012         ));
1013         all_sources.sort();
1014         let v = format!(
1015             "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n",
1016             all_sources.join("\n")
1017         );
1018         cx.shared.fs.write(&dst, v.as_bytes())?;
1019     }
1020
1021     // Update the search index
1022     let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
1023     let (mut all_indexes, mut krates) = try_err!(collect_json(&dst, &krate.name), &dst);
1024     all_indexes.push(search_index);
1025
1026     // Sort the indexes by crate so the file will be generated identically even
1027     // with rustdoc running in parallel.
1028     all_indexes.sort();
1029     {
1030         let mut v = String::from("var searchIndex = JSON.parse('{\\\n");
1031         v.push_str(&all_indexes.join(",\\\n"));
1032         // "addSearchOptions" has to be called first so the crate filtering can be set before the
1033         // search might start (if it's set into the URL for example).
1034         v.push_str("\\\n}');\naddSearchOptions(searchIndex);initSearch(searchIndex);");
1035         cx.shared.fs.write(&dst, &v)?;
1036     }
1037     if options.enable_index_page {
1038         if let Some(index_page) = options.index_page.clone() {
1039             let mut md_opts = options.clone();
1040             md_opts.output = cx.dst.clone();
1041             md_opts.external_html = (*cx.shared).layout.external_html.clone();
1042
1043             crate::markdown::render(&index_page, md_opts, cx.shared.edition)
1044                 .map_err(|e| Error::new(e, &index_page))?;
1045         } else {
1046             let dst = cx.dst.join("index.html");
1047             let page = layout::Page {
1048                 title: "Index of crates",
1049                 css_class: "mod",
1050                 root_path: "./",
1051                 static_root_path: cx.shared.static_root_path.as_deref(),
1052                 description: "List of crates",
1053                 keywords: BASIC_KEYWORDS,
1054                 resource_suffix: &cx.shared.resource_suffix,
1055                 extra_scripts: &[],
1056                 static_extra_scripts: &[],
1057             };
1058             krates.push(krate.name.clone());
1059             krates.sort();
1060             krates.dedup();
1061
1062             let content = format!(
1063                 "<h1 class='fqn'>\
1064      <span class='in-band'>List of all crates</span>\
1065 </h1><ul class='mod'>{}</ul>",
1066                 krates
1067                     .iter()
1068                     .map(|s| {
1069                         format!("<li><a href=\"{}index.html\">{}</li>", ensure_trailing_slash(s), s)
1070                     })
1071                     .collect::<String>()
1072             );
1073             let v = layout::render(&cx.shared.layout, &page, "", content, &cx.shared.style_files);
1074             cx.shared.fs.write(&dst, v.as_bytes())?;
1075         }
1076     }
1077
1078     // Update the list of all implementors for traits
1079     let dst = cx.dst.join("implementors");
1080     for (&did, imps) in &cache.implementors {
1081         // Private modules can leak through to this phase of rustdoc, which
1082         // could contain implementations for otherwise private types. In some
1083         // rare cases we could find an implementation for an item which wasn't
1084         // indexed, so we just skip this step in that case.
1085         //
1086         // FIXME: this is a vague explanation for why this can't be a `get`, in
1087         //        theory it should be...
1088         let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
1089             Some(p) => p,
1090             None => match cache.external_paths.get(&did) {
1091                 Some(p) => p,
1092                 None => continue,
1093             },
1094         };
1095
1096         #[derive(Serialize)]
1097         struct Implementor {
1098             text: String,
1099             synthetic: bool,
1100             types: Vec<String>,
1101         }
1102
1103         let implementors = imps
1104             .iter()
1105             .filter_map(|imp| {
1106                 // If the trait and implementation are in the same crate, then
1107                 // there's no need to emit information about it (there's inlining
1108                 // going on). If they're in different crates then the crate defining
1109                 // the trait will be interested in our implementation.
1110                 //
1111                 // If the implementation is from another crate then that crate
1112                 // should add it.
1113                 if imp.impl_item.def_id.krate == did.krate || !imp.impl_item.def_id.is_local() {
1114                     None
1115                 } else {
1116                     Some(Implementor {
1117                         text: imp.inner_impl().print().to_string(),
1118                         synthetic: imp.inner_impl().synthetic,
1119                         types: collect_paths_for_type(imp.inner_impl().for_.clone()),
1120                     })
1121                 }
1122             })
1123             .collect::<Vec<_>>();
1124
1125         // Only create a js file if we have impls to add to it. If the trait is
1126         // documented locally though we always create the file to avoid dead
1127         // links.
1128         if implementors.is_empty() && !cache.paths.contains_key(&did) {
1129             continue;
1130         }
1131
1132         let implementors = format!(
1133             r#"implementors["{}"] = {};"#,
1134             krate.name,
1135             serde_json::to_string(&implementors).unwrap()
1136         );
1137
1138         let mut mydst = dst.clone();
1139         for part in &remote_path[..remote_path.len() - 1] {
1140             mydst.push(part);
1141         }
1142         cx.shared.ensure_dir(&mydst)?;
1143         mydst.push(&format!("{}.{}.js", remote_item_type, remote_path[remote_path.len() - 1]));
1144
1145         let (mut all_implementors, _) =
1146             try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
1147         all_implementors.push(implementors);
1148         // Sort the implementors by crate so the file will be generated
1149         // identically even with rustdoc running in parallel.
1150         all_implementors.sort();
1151
1152         let mut v = String::from("(function() {var implementors = {};\n");
1153         for implementor in &all_implementors {
1154             writeln!(v, "{}", *implementor).unwrap();
1155         }
1156         v.push_str(
1157             "if (window.register_implementors) {\
1158                  window.register_implementors(implementors);\
1159              } else {\
1160                  window.pending_implementors = implementors;\
1161              }",
1162         );
1163         v.push_str("})()");
1164         cx.shared.fs.write(&mydst, &v)?;
1165     }
1166     Ok(())
1167 }
1168
1169 fn write_minify(
1170     fs: &DocFS,
1171     dst: PathBuf,
1172     contents: &str,
1173     enable_minification: bool,
1174 ) -> Result<(), Error> {
1175     if enable_minification {
1176         if dst.extension() == Some(&OsStr::new("css")) {
1177             let res = try_none!(minifier::css::minify(contents).ok(), &dst);
1178             fs.write(dst, res.as_bytes())
1179         } else {
1180             fs.write(dst, minifier::js::minify(contents).as_bytes())
1181         }
1182     } else {
1183         fs.write(dst, contents.as_bytes())
1184     }
1185 }
1186
1187 #[derive(Debug, Eq, PartialEq, Hash)]
1188 struct ItemEntry {
1189     url: String,
1190     name: String,
1191 }
1192
1193 impl ItemEntry {
1194     fn new(mut url: String, name: String) -> ItemEntry {
1195         while url.starts_with('/') {
1196             url.remove(0);
1197         }
1198         ItemEntry { url, name }
1199     }
1200 }
1201
1202 impl ItemEntry {
1203     crate fn print(&self) -> impl fmt::Display + '_ {
1204         crate::html::format::display_fn(move |f| {
1205             write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1206         })
1207     }
1208 }
1209
1210 impl PartialOrd for ItemEntry {
1211     fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1212         Some(self.cmp(other))
1213     }
1214 }
1215
1216 impl Ord for ItemEntry {
1217     fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1218         self.name.cmp(&other.name)
1219     }
1220 }
1221
1222 #[derive(Debug)]
1223 struct AllTypes {
1224     structs: FxHashSet<ItemEntry>,
1225     enums: FxHashSet<ItemEntry>,
1226     unions: FxHashSet<ItemEntry>,
1227     primitives: FxHashSet<ItemEntry>,
1228     traits: FxHashSet<ItemEntry>,
1229     macros: FxHashSet<ItemEntry>,
1230     functions: FxHashSet<ItemEntry>,
1231     typedefs: FxHashSet<ItemEntry>,
1232     opaque_tys: FxHashSet<ItemEntry>,
1233     statics: FxHashSet<ItemEntry>,
1234     constants: FxHashSet<ItemEntry>,
1235     keywords: FxHashSet<ItemEntry>,
1236     attributes: FxHashSet<ItemEntry>,
1237     derives: FxHashSet<ItemEntry>,
1238     trait_aliases: FxHashSet<ItemEntry>,
1239 }
1240
1241 impl AllTypes {
1242     fn new() -> AllTypes {
1243         let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
1244         AllTypes {
1245             structs: new_set(100),
1246             enums: new_set(100),
1247             unions: new_set(100),
1248             primitives: new_set(26),
1249             traits: new_set(100),
1250             macros: new_set(100),
1251             functions: new_set(100),
1252             typedefs: new_set(100),
1253             opaque_tys: new_set(100),
1254             statics: new_set(100),
1255             constants: new_set(100),
1256             keywords: new_set(100),
1257             attributes: new_set(100),
1258             derives: new_set(100),
1259             trait_aliases: new_set(100),
1260         }
1261     }
1262
1263     fn append(&mut self, item_name: String, item_type: &ItemType) {
1264         let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1265         if let Some(name) = url.pop() {
1266             let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1267             url.push(name);
1268             let name = url.join("::");
1269             match *item_type {
1270                 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1271                 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1272                 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1273                 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1274                 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1275                 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1276                 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1277                 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
1278                 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
1279                 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1280                 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
1281                 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1282                 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1283                 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
1284                 _ => true,
1285             };
1286         }
1287     }
1288 }
1289
1290 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
1291     if !e.is_empty() {
1292         let mut e: Vec<&ItemEntry> = e.iter().collect();
1293         e.sort();
1294         write!(
1295             f,
1296             "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1297             title,
1298             Escape(title),
1299             class,
1300             e.iter().map(|s| format!("<li>{}</li>", s.print())).collect::<String>()
1301         );
1302     }
1303 }
1304
1305 impl AllTypes {
1306     fn print(self, f: &mut Buffer) {
1307         write!(
1308             f,
1309             "<h1 class='fqn'>\
1310         <span class='out-of-band'>\
1311             <span id='render-detail'>\
1312                 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1313                     [<span class='inner'>&#x2212;</span>]\
1314                 </a>\
1315             </span>
1316         </span>
1317         <span class='in-band'>List of all items</span>\
1318     </h1>"
1319         );
1320         print_entries(f, &self.structs, "Structs", "structs");
1321         print_entries(f, &self.enums, "Enums", "enums");
1322         print_entries(f, &self.unions, "Unions", "unions");
1323         print_entries(f, &self.primitives, "Primitives", "primitives");
1324         print_entries(f, &self.traits, "Traits", "traits");
1325         print_entries(f, &self.macros, "Macros", "macros");
1326         print_entries(f, &self.attributes, "Attribute Macros", "attributes");
1327         print_entries(f, &self.derives, "Derive Macros", "derives");
1328         print_entries(f, &self.functions, "Functions", "functions");
1329         print_entries(f, &self.typedefs, "Typedefs", "typedefs");
1330         print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
1331         print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
1332         print_entries(f, &self.statics, "Statics", "statics");
1333         print_entries(f, &self.constants, "Constants", "constants")
1334     }
1335 }
1336
1337 #[derive(Debug)]
1338 enum Setting {
1339     Section { description: &'static str, sub_settings: Vec<Setting> },
1340     Entry { js_data_name: &'static str, description: &'static str, default_value: bool },
1341 }
1342
1343 impl Setting {
1344     fn display(&self) -> String {
1345         match *self {
1346             Setting::Section { ref description, ref sub_settings } => format!(
1347                 "<div class='setting-line'>\
1348                         <div class='title'>{}</div>\
1349                         <div class='sub-settings'>{}</div>
1350                     </div>",
1351                 description,
1352                 sub_settings.iter().map(|s| s.display()).collect::<String>()
1353             ),
1354             Setting::Entry { ref js_data_name, ref description, ref default_value } => format!(
1355                 "<div class='setting-line'>\
1356                         <label class='toggle'>\
1357                         <input type='checkbox' id='{}' {}>\
1358                         <span class='slider'></span>\
1359                         </label>\
1360                         <div>{}</div>\
1361                     </div>",
1362                 js_data_name,
1363                 if *default_value { " checked" } else { "" },
1364                 description,
1365             ),
1366         }
1367     }
1368 }
1369
1370 impl From<(&'static str, &'static str, bool)> for Setting {
1371     fn from(values: (&'static str, &'static str, bool)) -> Setting {
1372         Setting::Entry { js_data_name: values.0, description: values.1, default_value: values.2 }
1373     }
1374 }
1375
1376 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
1377     fn from(values: (&'static str, Vec<T>)) -> Setting {
1378         Setting::Section {
1379             description: values.0,
1380             sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
1381         }
1382     }
1383 }
1384
1385 fn settings(root_path: &str, suffix: &str) -> String {
1386     // (id, explanation, default value)
1387     let settings: &[Setting] = &[
1388         (
1389             "Auto-hide item declarations",
1390             vec![
1391                 ("auto-hide-struct", "Auto-hide structs declaration", true),
1392                 ("auto-hide-enum", "Auto-hide enums declaration", false),
1393                 ("auto-hide-union", "Auto-hide unions declaration", true),
1394                 ("auto-hide-trait", "Auto-hide traits declaration", true),
1395                 ("auto-hide-macro", "Auto-hide macros declaration", false),
1396             ],
1397         )
1398             .into(),
1399         ("auto-hide-attributes", "Auto-hide item attributes.", true).into(),
1400         ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
1401         ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", true)
1402             .into(),
1403         ("auto-collapse-implementors", "Auto-hide implementors of a trait", true).into(),
1404         ("go-to-only-result", "Directly go to item in search if there is only one result", false)
1405             .into(),
1406         ("line-numbers", "Show line numbers on code examples", false).into(),
1407         ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
1408     ];
1409     format!(
1410         "<h1 class='fqn'>\
1411     <span class='in-band'>Rustdoc settings</span>\
1412 </h1>\
1413 <div class='settings'>{}</div>\
1414 <script src='{}settings{}.js'></script>",
1415         settings.iter().map(|s| s.display()).collect::<String>(),
1416         root_path,
1417         suffix
1418     )
1419 }
1420
1421 impl Context {
1422     fn derive_id(&self, id: String) -> String {
1423         let mut map = self.id_map.borrow_mut();
1424         map.derive(id)
1425     }
1426
1427     /// String representation of how to get back to the root path of the 'doc/'
1428     /// folder in terms of a relative URL.
1429     fn root_path(&self) -> String {
1430         "../".repeat(self.current.len())
1431     }
1432
1433     fn render_item(&self, it: &clean::Item, pushname: bool, cache: &Cache) -> String {
1434         // A little unfortunate that this is done like this, but it sure
1435         // does make formatting *a lot* nicer.
1436         CURRENT_DEPTH.with(|slot| {
1437             slot.set(self.current.len());
1438         });
1439
1440         let mut title = if it.is_primitive() || it.is_keyword() {
1441             // No need to include the namespace for primitive types and keywords
1442             String::new()
1443         } else {
1444             self.current.join("::")
1445         };
1446         if pushname {
1447             if !title.is_empty() {
1448                 title.push_str("::");
1449             }
1450             title.push_str(it.name.as_ref().unwrap());
1451         }
1452         title.push_str(" - Rust");
1453         let tyname = it.type_();
1454         let desc = if it.is_crate() {
1455             format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
1456         } else {
1457             format!(
1458                 "API documentation for the Rust `{}` {} in crate `{}`.",
1459                 it.name.as_ref().unwrap(),
1460                 tyname,
1461                 self.shared.layout.krate
1462             )
1463         };
1464         let keywords = make_item_keywords(it);
1465         let page = layout::Page {
1466             css_class: tyname.as_str(),
1467             root_path: &self.root_path(),
1468             static_root_path: self.shared.static_root_path.as_deref(),
1469             title: &title,
1470             description: &desc,
1471             keywords: &keywords,
1472             resource_suffix: &self.shared.resource_suffix,
1473             extra_scripts: &[],
1474             static_extra_scripts: &[],
1475         };
1476
1477         {
1478             self.id_map.borrow_mut().reset();
1479             self.id_map.borrow_mut().populate(initial_ids());
1480         }
1481
1482         if !self.render_redirect_pages {
1483             layout::render(
1484                 &self.shared.layout,
1485                 &page,
1486                 |buf: &mut _| print_sidebar(self, it, buf, cache),
1487                 |buf: &mut _| print_item(self, it, buf, cache),
1488                 &self.shared.style_files,
1489             )
1490         } else {
1491             let mut url = self.root_path();
1492             if let Some(&(ref names, ty)) = cache.paths.get(&it.def_id) {
1493                 for name in &names[..names.len() - 1] {
1494                     url.push_str(name);
1495                     url.push_str("/");
1496                 }
1497                 url.push_str(&item_path(ty, names.last().unwrap()));
1498                 layout::redirect(&url)
1499             } else {
1500                 String::new()
1501             }
1502         }
1503     }
1504
1505     fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1506         // BTreeMap instead of HashMap to get a sorted output
1507         let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
1508         for item in &m.items {
1509             if item.is_stripped() {
1510                 continue;
1511             }
1512
1513             let short = item.type_();
1514             let myname = match item.name {
1515                 None => continue,
1516                 Some(ref s) => s.to_string(),
1517             };
1518             let short = short.to_string();
1519             map.entry(short)
1520                 .or_default()
1521                 .push((myname, Some(plain_summary_line(item.doc_value()))));
1522         }
1523
1524         if self.shared.sort_modules_alphabetically {
1525             for items in map.values_mut() {
1526                 items.sort();
1527             }
1528         }
1529         map
1530     }
1531
1532     /// Generates a url appropriate for an `href` attribute back to the source of
1533     /// this item.
1534     ///
1535     /// The url generated, when clicked, will redirect the browser back to the
1536     /// original source code.
1537     ///
1538     /// If `None` is returned, then a source link couldn't be generated. This
1539     /// may happen, for example, with externally inlined items where the source
1540     /// of their crate documentation isn't known.
1541     fn src_href(&self, item: &clean::Item, cache: &Cache) -> Option<String> {
1542         let mut root = self.root_path();
1543
1544         let mut path = String::new();
1545
1546         // We can safely ignore synthetic `SourceFile`s.
1547         let file = match item.source.filename {
1548             FileName::Real(ref path) => path.local_path().to_path_buf(),
1549             _ => return None,
1550         };
1551         let file = &file;
1552
1553         let (krate, path) = if item.source.cnum == LOCAL_CRATE {
1554             if let Some(path) = self.shared.local_sources.get(file) {
1555                 (&self.shared.layout.krate, path)
1556             } else {
1557                 return None;
1558             }
1559         } else {
1560             let (krate, src_root) = match *cache.extern_locations.get(&item.source.cnum)? {
1561                 (ref name, ref src, ExternalLocation::Local) => (name, src),
1562                 (ref name, ref src, ExternalLocation::Remote(ref s)) => {
1563                     root = s.to_string();
1564                     (name, src)
1565                 }
1566                 (_, _, ExternalLocation::Unknown) => return None,
1567             };
1568
1569             sources::clean_path(&src_root, file, false, |component| {
1570                 path.push_str(&component.to_string_lossy());
1571                 path.push('/');
1572             });
1573             let mut fname = file.file_name().expect("source has no filename").to_os_string();
1574             fname.push(".html");
1575             path.push_str(&fname.to_string_lossy());
1576             (krate, &path)
1577         };
1578
1579         let lines = if item.source.loline == item.source.hiline {
1580             item.source.loline.to_string()
1581         } else {
1582             format!("{}-{}", item.source.loline, item.source.hiline)
1583         };
1584         Some(format!(
1585             "{root}src/{krate}/{path}#{lines}",
1586             root = Escape(&root),
1587             krate = krate,
1588             path = path,
1589             lines = lines
1590         ))
1591     }
1592 }
1593
1594 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1595 where
1596     F: FnOnce(&mut Buffer),
1597 {
1598     write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">");
1599     f(w);
1600     write!(w, "</div>")
1601 }
1602
1603 fn print_item(cx: &Context, item: &clean::Item, buf: &mut Buffer, cache: &Cache) {
1604     debug_assert!(!item.is_stripped());
1605     // Write the breadcrumb trail header for the top
1606     write!(buf, "<h1 class='fqn'><span class='out-of-band'>");
1607     if let Some(version) = item.stable_since() {
1608         write!(
1609             buf,
1610             "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1611             version
1612         );
1613     }
1614     write!(
1615         buf,
1616         "<span id='render-detail'>\
1617                 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1618                     title=\"collapse all docs\">\
1619                     [<span class='inner'>&#x2212;</span>]\
1620                 </a>\
1621             </span>"
1622     );
1623
1624     // Write `src` tag
1625     //
1626     // When this item is part of a `pub use` in a downstream crate, the
1627     // [src] link in the downstream documentation will actually come back to
1628     // this page, and this link will be auto-clicked. The `id` attribute is
1629     // used to find the link to auto-click.
1630     if cx.shared.include_sources && !item.is_primitive() {
1631         if let Some(l) = cx.src_href(item, cache) {
1632             write!(buf, "<a class='srclink' href='{}' title='{}'>[src]</a>", l, "goto source code");
1633         }
1634     }
1635
1636     write!(buf, "</span>"); // out-of-band
1637     write!(buf, "<span class='in-band'>");
1638     let name = match item.inner {
1639         clean::ModuleItem(ref m) => {
1640             if m.is_crate {
1641                 "Crate "
1642             } else {
1643                 "Module "
1644             }
1645         }
1646         clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
1647         clean::TraitItem(..) => "Trait ",
1648         clean::StructItem(..) => "Struct ",
1649         clean::UnionItem(..) => "Union ",
1650         clean::EnumItem(..) => "Enum ",
1651         clean::TypedefItem(..) => "Type Definition ",
1652         clean::MacroItem(..) => "Macro ",
1653         clean::ProcMacroItem(ref mac) => match mac.kind {
1654             MacroKind::Bang => "Macro ",
1655             MacroKind::Attr => "Attribute Macro ",
1656             MacroKind::Derive => "Derive Macro ",
1657         },
1658         clean::PrimitiveItem(..) => "Primitive Type ",
1659         clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
1660         clean::ConstantItem(..) => "Constant ",
1661         clean::ForeignTypeItem => "Foreign Type ",
1662         clean::KeywordItem(..) => "Keyword ",
1663         clean::OpaqueTyItem(..) => "Opaque Type ",
1664         clean::TraitAliasItem(..) => "Trait Alias ",
1665         _ => {
1666             // We don't generate pages for any other type.
1667             unreachable!();
1668         }
1669     };
1670     buf.write_str(name);
1671     if !item.is_primitive() && !item.is_keyword() {
1672         let cur = &cx.current;
1673         let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
1674         for (i, component) in cur.iter().enumerate().take(amt) {
1675             write!(
1676                 buf,
1677                 "<a href='{}index.html'>{}</a>::<wbr>",
1678                 "../".repeat(cur.len() - i - 1),
1679                 component
1680             );
1681         }
1682     }
1683     write!(buf, "<a class=\"{}\" href=''>{}</a>", item.type_(), item.name.as_ref().unwrap());
1684
1685     write!(buf, "</span></h1>"); // in-band
1686
1687     match item.inner {
1688         clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
1689         clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
1690             item_function(buf, cx, item, f)
1691         }
1692         clean::TraitItem(ref t) => item_trait(buf, cx, item, t, cache),
1693         clean::StructItem(ref s) => item_struct(buf, cx, item, s, cache),
1694         clean::UnionItem(ref s) => item_union(buf, cx, item, s, cache),
1695         clean::EnumItem(ref e) => item_enum(buf, cx, item, e, cache),
1696         clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t, cache),
1697         clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
1698         clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
1699         clean::PrimitiveItem(_) => item_primitive(buf, cx, item, cache),
1700         clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
1701         clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
1702         clean::ForeignTypeItem => item_foreign_type(buf, cx, item, cache),
1703         clean::KeywordItem(_) => item_keyword(buf, cx, item),
1704         clean::OpaqueTyItem(ref e, _) => item_opaque_ty(buf, cx, item, e, cache),
1705         clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta, cache),
1706         _ => {
1707             // We don't generate pages for any other type.
1708             unreachable!();
1709         }
1710     }
1711 }
1712
1713 fn item_path(ty: ItemType, name: &str) -> String {
1714     match ty {
1715         ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1716         _ => format!("{}.{}.html", ty, name),
1717     }
1718 }
1719
1720 fn full_path(cx: &Context, item: &clean::Item) -> String {
1721     let mut s = cx.current.join("::");
1722     s.push_str("::");
1723     s.push_str(item.name.as_ref().unwrap());
1724     s
1725 }
1726
1727 #[inline]
1728 crate fn plain_summary_line(s: Option<&str>) -> String {
1729     let s = s.unwrap_or("");
1730     // This essentially gets the first paragraph of text in one line.
1731     let mut line = s
1732         .lines()
1733         .skip_while(|line| line.chars().all(|c| c.is_whitespace()))
1734         .take_while(|line| line.chars().any(|c| !c.is_whitespace()))
1735         .fold(String::new(), |mut acc, line| {
1736             acc.push_str(line);
1737             acc.push(' ');
1738             acc
1739         });
1740     // remove final whitespace
1741     line.pop();
1742     markdown::plain_summary_line(&line[..])
1743 }
1744
1745 crate fn shorten(s: String) -> String {
1746     if s.chars().count() > 60 {
1747         let mut len = 0;
1748         let mut ret = s
1749             .split_whitespace()
1750             .take_while(|p| {
1751                 // + 1 for the added character after the word.
1752                 len += p.chars().count() + 1;
1753                 len < 60
1754             })
1755             .collect::<Vec<_>>()
1756             .join(" ");
1757         ret.push('…');
1758         ret
1759     } else {
1760         s
1761     }
1762 }
1763
1764 fn document(w: &mut Buffer, cx: &Context, item: &clean::Item) {
1765     if let Some(ref name) = item.name {
1766         info!("Documenting {}", name);
1767     }
1768     document_stability(w, cx, item, false);
1769     document_full(w, item, cx, "", false);
1770 }
1771
1772 /// Render md_text as markdown.
1773 fn render_markdown(
1774     w: &mut Buffer,
1775     cx: &Context,
1776     md_text: &str,
1777     links: Vec<(String, String)>,
1778     prefix: &str,
1779     is_hidden: bool,
1780 ) {
1781     let mut ids = cx.id_map.borrow_mut();
1782     write!(
1783         w,
1784         "<div class='docblock{}'>{}{}</div>",
1785         if is_hidden { " hidden" } else { "" },
1786         prefix,
1787         Markdown(
1788             md_text,
1789             &links,
1790             &mut ids,
1791             cx.shared.codes,
1792             cx.shared.edition,
1793             &cx.shared.playground
1794         )
1795         .into_string()
1796     )
1797 }
1798
1799 fn document_short(
1800     w: &mut Buffer,
1801     cx: &Context,
1802     item: &clean::Item,
1803     link: AssocItemLink<'_>,
1804     prefix: &str,
1805     is_hidden: bool,
1806 ) {
1807     if let Some(s) = item.doc_value() {
1808         let markdown = if s.contains('\n') {
1809             format!(
1810                 "{} [Read more]({})",
1811                 &plain_summary_line(Some(s)),
1812                 naive_assoc_href(item, link)
1813             )
1814         } else {
1815             plain_summary_line(Some(s))
1816         };
1817         render_markdown(w, cx, &markdown, item.links(), prefix, is_hidden);
1818     } else if !prefix.is_empty() {
1819         write!(
1820             w,
1821             "<div class='docblock{}'>{}</div>",
1822             if is_hidden { " hidden" } else { "" },
1823             prefix
1824         );
1825     }
1826 }
1827
1828 fn document_full(w: &mut Buffer, item: &clean::Item, cx: &Context, prefix: &str, is_hidden: bool) {
1829     if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1830         debug!("Doc block: =====\n{}\n=====", s);
1831         render_markdown(w, cx, &*s, item.links(), prefix, is_hidden);
1832     } else if !prefix.is_empty() {
1833         write!(
1834             w,
1835             "<div class='docblock{}'>{}</div>",
1836             if is_hidden { " hidden" } else { "" },
1837             prefix
1838         );
1839     }
1840 }
1841
1842 fn document_stability(w: &mut Buffer, cx: &Context, item: &clean::Item, is_hidden: bool) {
1843     let stabilities = short_stability(item, cx);
1844     if !stabilities.is_empty() {
1845         write!(w, "<div class='stability{}'>", if is_hidden { " hidden" } else { "" });
1846         for stability in stabilities {
1847             write!(w, "{}", stability);
1848         }
1849         write!(w, "</div>");
1850     }
1851 }
1852
1853 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1854     if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1855 }
1856
1857 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1858     if item.is_non_exhaustive() {
1859         write!(w, "<div class='docblock non-exhaustive non-exhaustive-{}'>", {
1860             if item.is_struct() {
1861                 "struct"
1862             } else if item.is_enum() {
1863                 "enum"
1864             } else if item.is_variant() {
1865                 "variant"
1866             } else {
1867                 "type"
1868             }
1869         });
1870
1871         if item.is_struct() {
1872             write!(
1873                 w,
1874                 "Non-exhaustive structs could have additional fields added in future. \
1875                        Therefore, non-exhaustive structs cannot be constructed in external crates \
1876                        using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
1877                        matched against without a wildcard <code>..</code>; and \
1878                        struct update syntax will not work."
1879             );
1880         } else if item.is_enum() {
1881             write!(
1882                 w,
1883                 "Non-exhaustive enums could have additional variants added in future. \
1884                        Therefore, when matching against variants of non-exhaustive enums, an \
1885                        extra wildcard arm must be added to account for any future variants."
1886             );
1887         } else if item.is_variant() {
1888             write!(
1889                 w,
1890                 "Non-exhaustive enum variants could have additional fields added in future. \
1891                        Therefore, non-exhaustive enum variants cannot be constructed in external \
1892                        crates and cannot be matched against."
1893             );
1894         } else {
1895             write!(
1896                 w,
1897                 "This type will require a wildcard arm in any match statements or \
1898                        constructors."
1899             );
1900         }
1901
1902         write!(w, "</div>");
1903     }
1904 }
1905
1906 fn name_key(name: &str) -> (&str, u64, usize) {
1907     let end = name.bytes().rposition(|b| b.is_ascii_digit()).map_or(name.len(), |i| i + 1);
1908
1909     // find number at end
1910     let split = name[0..end].bytes().rposition(|b| !b.is_ascii_digit()).map_or(0, |i| i + 1);
1911
1912     // count leading zeroes
1913     let after_zeroes =
1914         name[split..end].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
1915
1916     // sort leading zeroes last
1917     let num_zeroes = after_zeroes - split;
1918
1919     match name[split..end].parse() {
1920         Ok(n) => (&name[..split], n, num_zeroes),
1921         Err(_) => (name, 0, num_zeroes),
1922     }
1923 }
1924
1925 fn item_module(w: &mut Buffer, cx: &Context, item: &clean::Item, items: &[clean::Item]) {
1926     document(w, cx, item);
1927
1928     let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
1929
1930     // the order of item types in the listing
1931     fn reorder(ty: ItemType) -> u8 {
1932         match ty {
1933             ItemType::ExternCrate => 0,
1934             ItemType::Import => 1,
1935             ItemType::Primitive => 2,
1936             ItemType::Module => 3,
1937             ItemType::Macro => 4,
1938             ItemType::Struct => 5,
1939             ItemType::Enum => 6,
1940             ItemType::Constant => 7,
1941             ItemType::Static => 8,
1942             ItemType::Trait => 9,
1943             ItemType::Function => 10,
1944             ItemType::Typedef => 12,
1945             ItemType::Union => 13,
1946             _ => 14 + ty as u8,
1947         }
1948     }
1949
1950     fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1951         let ty1 = i1.type_();
1952         let ty2 = i2.type_();
1953         if ty1 != ty2 {
1954             return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
1955         }
1956         let s1 = i1.stability.as_ref().map(|s| s.level);
1957         let s2 = i2.stability.as_ref().map(|s| s.level);
1958         match (s1, s2) {
1959             (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1960             (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1961             _ => {}
1962         }
1963         let lhs = i1.name.as_ref().map_or("", |s| &**s);
1964         let rhs = i2.name.as_ref().map_or("", |s| &**s);
1965         name_key(lhs).cmp(&name_key(rhs))
1966     }
1967
1968     if cx.shared.sort_modules_alphabetically {
1969         indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1970     }
1971     // This call is to remove re-export duplicates in cases such as:
1972     //
1973     // ```
1974     // pub mod foo {
1975     //     pub mod bar {
1976     //         pub trait Double { fn foo(); }
1977     //     }
1978     // }
1979     //
1980     // pub use foo::bar::*;
1981     // pub use foo::*;
1982     // ```
1983     //
1984     // `Double` will appear twice in the generated docs.
1985     //
1986     // FIXME: This code is quite ugly and could be improved. Small issue: DefId
1987     // can be identical even if the elements are different (mostly in imports).
1988     // So in case this is an import, we keep everything by adding a "unique id"
1989     // (which is the position in the vector).
1990     indices.dedup_by_key(|i| {
1991         (
1992             items[*i].def_id,
1993             if items[*i].name.as_ref().is_some() { Some(full_path(cx, &items[*i])) } else { None },
1994             items[*i].type_(),
1995             if items[*i].is_import() { *i } else { 0 },
1996         )
1997     });
1998
1999     debug!("{:?}", indices);
2000     let mut curty = None;
2001     for &idx in &indices {
2002         let myitem = &items[idx];
2003         if myitem.is_stripped() {
2004             continue;
2005         }
2006
2007         let myty = Some(myitem.type_());
2008         if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
2009             // Put `extern crate` and `use` re-exports in the same section.
2010             curty = myty;
2011         } else if myty != curty {
2012             if curty.is_some() {
2013                 write!(w, "</table>");
2014             }
2015             curty = myty;
2016             let (short, name) = item_ty_to_strs(&myty.unwrap());
2017             write!(
2018                 w,
2019                 "<h2 id='{id}' class='section-header'>\
2020                        <a href=\"#{id}\">{name}</a></h2>\n<table>",
2021                 id = cx.derive_id(short.to_owned()),
2022                 name = name
2023             );
2024         }
2025
2026         match myitem.inner {
2027             clean::ExternCrateItem(ref name, ref src) => {
2028                 use crate::html::format::anchor;
2029
2030                 match *src {
2031                     Some(ref src) => write!(
2032                         w,
2033                         "<tr><td><code>{}extern crate {} as {};",
2034                         myitem.visibility.print_with_space(),
2035                         anchor(myitem.def_id, src),
2036                         name
2037                     ),
2038                     None => write!(
2039                         w,
2040                         "<tr><td><code>{}extern crate {};",
2041                         myitem.visibility.print_with_space(),
2042                         anchor(myitem.def_id, name)
2043                     ),
2044                 }
2045                 write!(w, "</code></td></tr>");
2046             }
2047
2048             clean::ImportItem(ref import) => {
2049                 write!(
2050                     w,
2051                     "<tr><td><code>{}{}</code></td></tr>",
2052                     myitem.visibility.print_with_space(),
2053                     import.print()
2054                 );
2055             }
2056
2057             _ => {
2058                 if myitem.name.is_none() {
2059                     continue;
2060                 }
2061
2062                 let unsafety_flag = match myitem.inner {
2063                     clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2064                         if func.header.unsafety == hir::Unsafety::Unsafe =>
2065                     {
2066                         "<a title='unsafe function' href='#'><sup>âš </sup></a>"
2067                     }
2068                     _ => "",
2069                 };
2070
2071                 let stab = myitem.stability_class();
2072                 let add = if stab.is_some() { " " } else { "" };
2073
2074                 let doc_value = myitem.doc_value().unwrap_or("");
2075                 write!(
2076                     w,
2077                     "\
2078                        <tr class='{stab}{add}module-item'>\
2079                            <td><a class=\"{class}\" href=\"{href}\" \
2080                                   title='{title}'>{name}</a>{unsafety_flag}</td>\
2081                            <td class='docblock-short'>{stab_tags}{docs}</td>\
2082                        </tr>",
2083                     name = *myitem.name.as_ref().unwrap(),
2084                     stab_tags = stability_tags(myitem),
2085                     docs = MarkdownSummaryLine(doc_value, &myitem.links()).into_string(),
2086                     class = myitem.type_(),
2087                     add = add,
2088                     stab = stab.unwrap_or_else(String::new),
2089                     unsafety_flag = unsafety_flag,
2090                     href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2091                     title = [full_path(cx, myitem), myitem.type_().to_string()]
2092                         .iter()
2093                         .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
2094                         .collect::<Vec<_>>()
2095                         .join(" "),
2096                 );
2097             }
2098         }
2099     }
2100
2101     if curty.is_some() {
2102         write!(w, "</table>");
2103     }
2104 }
2105
2106 /// Render the stability and deprecation tags that are displayed in the item's summary at the
2107 /// module level.
2108 fn stability_tags(item: &clean::Item) -> String {
2109     let mut tags = String::new();
2110
2111     fn tag_html(class: &str, contents: &str) -> String {
2112         format!(r#"<span class="stab {}">{}</span>"#, class, contents)
2113     }
2114
2115     // The trailing space after each tag is to space it properly against the rest of the docs.
2116     if let Some(depr) = &item.deprecation {
2117         let mut message = "Deprecated";
2118         if !stability::deprecation_in_effect(depr.is_since_rustc_version, depr.since.as_deref()) {
2119             message = "Deprecation planned";
2120         }
2121         tags += &tag_html("deprecated", message);
2122     }
2123
2124     // The "rustc_private" crates are permanently unstable so it makes no sense
2125     // to render "unstable" everywhere.
2126     if item
2127         .stability
2128         .as_ref()
2129         .map(|s| s.level == stability::Unstable && s.feature.as_deref() != Some("rustc_private"))
2130         == Some(true)
2131     {
2132         tags += &tag_html("unstable", "Experimental");
2133     }
2134
2135     if let Some(ref cfg) = item.attrs.cfg {
2136         tags += &tag_html("portability", &cfg.render_short_html());
2137     }
2138
2139     tags
2140 }
2141
2142 /// Render the stability and/or deprecation warning that is displayed at the top of the item's
2143 /// documentation.
2144 fn short_stability(item: &clean::Item, cx: &Context) -> Vec<String> {
2145     let mut stability = vec![];
2146     let error_codes = cx.shared.codes;
2147
2148     if let Some(Deprecation { ref note, ref since, is_since_rustc_version }) = item.deprecation {
2149         // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2150         // but only display the future-deprecation messages for #[rustc_deprecated].
2151         let mut message = if let Some(since) = since {
2152             if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
2153                 format!("Deprecating in {}", Escape(&since))
2154             } else {
2155                 format!("Deprecated since {}", Escape(&since))
2156             }
2157         } else {
2158             String::from("Deprecated")
2159         };
2160
2161         if let Some(note) = note {
2162             let mut ids = cx.id_map.borrow_mut();
2163             let html = MarkdownHtml(
2164                 &note,
2165                 &mut ids,
2166                 error_codes,
2167                 cx.shared.edition,
2168                 &cx.shared.playground,
2169             );
2170             message.push_str(&format!(": {}", html.into_string()));
2171         }
2172         stability.push(format!(
2173             "<div class='stab deprecated'><span class='emoji'>👎</span> {}</div>",
2174             message,
2175         ));
2176     }
2177
2178     // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
2179     // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
2180     if let Some(stab) = item.stability.as_ref().filter(|stab| {
2181         stab.level == stability::Unstable && stab.feature.as_deref() != Some("rustc_private")
2182     }) {
2183         let mut message =
2184             "<span class='emoji'>🔬</span> This is a nightly-only experimental API.".to_owned();
2185
2186         if let Some(feature) = stab.feature.as_deref() {
2187             let mut feature = format!("<code>{}</code>", Escape(&feature));
2188             if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, stab.issue) {
2189                 feature.push_str(&format!(
2190                     "&nbsp;<a href=\"{url}{issue}\">#{issue}</a>",
2191                     url = url,
2192                     issue = issue
2193                 ));
2194             }
2195
2196             message.push_str(&format!(" ({})", feature));
2197         }
2198
2199         if let Some(unstable_reason) = &stab.unstable_reason {
2200             let mut ids = cx.id_map.borrow_mut();
2201             message = format!(
2202                 "<details><summary>{}</summary>{}</details>",
2203                 message,
2204                 MarkdownHtml(
2205                     &unstable_reason,
2206                     &mut ids,
2207                     error_codes,
2208                     cx.shared.edition,
2209                     &cx.shared.playground,
2210                 )
2211                 .into_string()
2212             );
2213         }
2214
2215         stability.push(format!("<div class='stab unstable'>{}</div>", message));
2216     }
2217
2218     if let Some(ref cfg) = item.attrs.cfg {
2219         stability.push(format!("<div class='stab portability'>{}</div>", cfg.render_long_html()));
2220     }
2221
2222     stability
2223 }
2224
2225 fn item_constant(w: &mut Buffer, cx: &Context, it: &clean::Item, c: &clean::Constant) {
2226     write!(w, "<pre class='rust const'>");
2227     render_attributes(w, it, false);
2228
2229     write!(
2230         w,
2231         "{vis}const \
2232                {name}: {typ}",
2233         vis = it.visibility.print_with_space(),
2234         name = it.name.as_ref().unwrap(),
2235         typ = c.type_.print(),
2236     );
2237
2238     if c.value.is_some() || c.is_literal {
2239         write!(w, " = {expr};", expr = Escape(&c.expr));
2240     } else {
2241         write!(w, ";");
2242     }
2243
2244     if let Some(value) = &c.value {
2245         if !c.is_literal {
2246             let value_lowercase = value.to_lowercase();
2247             let expr_lowercase = c.expr.to_lowercase();
2248
2249             if value_lowercase != expr_lowercase
2250                 && value_lowercase.trim_end_matches("i32") != expr_lowercase
2251             {
2252                 write!(w, " // {value}", value = Escape(value));
2253             }
2254         }
2255     }
2256
2257     write!(w, "</pre>");
2258     document(w, cx, it)
2259 }
2260
2261 fn item_static(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Static) {
2262     write!(w, "<pre class='rust static'>");
2263     render_attributes(w, it, false);
2264     write!(
2265         w,
2266         "{vis}static {mutability}\
2267                {name}: {typ}</pre>",
2268         vis = it.visibility.print_with_space(),
2269         mutability = s.mutability.print_with_space(),
2270         name = it.name.as_ref().unwrap(),
2271         typ = s.type_.print()
2272     );
2273     document(w, cx, it)
2274 }
2275
2276 fn item_function(w: &mut Buffer, cx: &Context, it: &clean::Item, f: &clean::Function) {
2277     let header_len = format!(
2278         "{}{}{}{}{:#}fn {}{:#}",
2279         it.visibility.print_with_space(),
2280         f.header.constness.print_with_space(),
2281         f.header.asyncness.print_with_space(),
2282         f.header.unsafety.print_with_space(),
2283         print_abi_with_space(f.header.abi),
2284         it.name.as_ref().unwrap(),
2285         f.generics.print()
2286     )
2287     .len();
2288     write!(w, "<pre class='rust fn'>");
2289     render_attributes(w, it, false);
2290     write!(
2291         w,
2292         "{vis}{constness}{asyncness}{unsafety}{abi}fn \
2293            {name}{generics}{decl}{spotlight}{where_clause}</pre>",
2294         vis = it.visibility.print_with_space(),
2295         constness = f.header.constness.print_with_space(),
2296         asyncness = f.header.asyncness.print_with_space(),
2297         unsafety = f.header.unsafety.print_with_space(),
2298         abi = print_abi_with_space(f.header.abi),
2299         name = it.name.as_ref().unwrap(),
2300         generics = f.generics.print(),
2301         where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2302         decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness }
2303             .print(),
2304         spotlight = spotlight_decl(&f.decl),
2305     );
2306     document(w, cx, it)
2307 }
2308
2309 fn render_implementor(
2310     cx: &Context,
2311     implementor: &Impl,
2312     w: &mut Buffer,
2313     implementor_dups: &FxHashMap<&str, (DefId, bool)>,
2314     aliases: &[String],
2315     cache: &Cache,
2316 ) {
2317     // If there's already another implementor that has the same abbridged name, use the
2318     // full path, for example in `std::iter::ExactSizeIterator`
2319     let use_absolute = match implementor.inner_impl().for_ {
2320         clean::ResolvedPath { ref path, is_generic: false, .. }
2321         | clean::BorrowedRef {
2322             type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2323             ..
2324         } => implementor_dups[path.last_name()].1,
2325         _ => false,
2326     };
2327     render_impl(
2328         w,
2329         cx,
2330         implementor,
2331         AssocItemLink::Anchor(None),
2332         RenderMode::Normal,
2333         implementor.impl_item.stable_since(),
2334         false,
2335         Some(use_absolute),
2336         false,
2337         false,
2338         aliases,
2339         cache,
2340     );
2341 }
2342
2343 fn render_impls(
2344     cx: &Context,
2345     w: &mut Buffer,
2346     traits: &[&&Impl],
2347     containing_item: &clean::Item,
2348     cache: &Cache,
2349 ) {
2350     let mut impls = traits
2351         .iter()
2352         .map(|i| {
2353             let did = i.trait_did().unwrap();
2354             let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2355             let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
2356             render_impl(
2357                 &mut buffer,
2358                 cx,
2359                 i,
2360                 assoc_link,
2361                 RenderMode::Normal,
2362                 containing_item.stable_since(),
2363                 true,
2364                 None,
2365                 false,
2366                 true,
2367                 &[],
2368                 cache,
2369             );
2370             buffer.into_inner()
2371         })
2372         .collect::<Vec<_>>();
2373     impls.sort();
2374     w.write_str(&impls.join(""));
2375 }
2376
2377 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
2378     let mut bounds = String::new();
2379     if !t_bounds.is_empty() {
2380         if !trait_alias {
2381             bounds.push_str(": ");
2382         }
2383         for (i, p) in t_bounds.iter().enumerate() {
2384             if i > 0 {
2385                 bounds.push_str(" + ");
2386             }
2387             bounds.push_str(&p.print().to_string());
2388         }
2389     }
2390     bounds
2391 }
2392
2393 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
2394     let lhs = format!("{}", lhs.inner_impl().print());
2395     let rhs = format!("{}", rhs.inner_impl().print());
2396
2397     // lhs and rhs are formatted as HTML, which may be unnecessary
2398     name_key(&lhs).cmp(&name_key(&rhs))
2399 }
2400
2401 fn item_trait(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Trait, cache: &Cache) {
2402     let bounds = bounds(&t.bounds, false);
2403     let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2404     let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2405     let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2406     let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2407
2408     // Output the trait definition
2409     wrap_into_docblock(w, |w| {
2410         write!(w, "<pre class='rust trait'>");
2411         render_attributes(w, it, true);
2412         write!(
2413             w,
2414             "{}{}{}trait {}{}{}",
2415             it.visibility.print_with_space(),
2416             t.unsafety.print_with_space(),
2417             if t.is_auto { "auto " } else { "" },
2418             it.name.as_ref().unwrap(),
2419             t.generics.print(),
2420             bounds
2421         );
2422
2423         if !t.generics.where_predicates.is_empty() {
2424             write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true });
2425         } else {
2426             write!(w, " ");
2427         }
2428
2429         if t.items.is_empty() {
2430             write!(w, "{{ }}");
2431         } else {
2432             // FIXME: we should be using a derived_id for the Anchors here
2433             write!(w, "{{\n");
2434             for t in &types {
2435                 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2436                 write!(w, ";\n");
2437             }
2438             if !types.is_empty() && !consts.is_empty() {
2439                 w.write_str("\n");
2440             }
2441             for t in &consts {
2442                 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2443                 write!(w, ";\n");
2444             }
2445             if !consts.is_empty() && !required.is_empty() {
2446                 w.write_str("\n");
2447             }
2448             for (pos, m) in required.iter().enumerate() {
2449                 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2450                 write!(w, ";\n");
2451
2452                 if pos < required.len() - 1 {
2453                     write!(w, "<div class='item-spacer'></div>");
2454                 }
2455             }
2456             if !required.is_empty() && !provided.is_empty() {
2457                 w.write_str("\n");
2458             }
2459             for (pos, m) in provided.iter().enumerate() {
2460                 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2461                 match m.inner {
2462                     clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2463                         write!(w, ",\n    {{ ... }}\n");
2464                     }
2465                     _ => {
2466                         write!(w, " {{ ... }}\n");
2467                     }
2468                 }
2469                 if pos < provided.len() - 1 {
2470                     write!(w, "<div class='item-spacer'></div>");
2471                 }
2472             }
2473             write!(w, "}}");
2474         }
2475         write!(w, "</pre>")
2476     });
2477
2478     // Trait documentation
2479     document(w, cx, it);
2480
2481     fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
2482         write!(
2483             w,
2484             "
2485             <h2 id='{0}' class='small-section-header'>\
2486               {1}<a href='#{0}' class='anchor'></a>\
2487             </h2>{2}",
2488             id, title, extra_content
2489         )
2490     }
2491
2492     fn write_loading_content(w: &mut Buffer, extra_content: &str) {
2493         write!(w, "{}<span class='loading-content'>Loading content...</span>", extra_content)
2494     }
2495
2496     fn trait_item(w: &mut Buffer, cx: &Context, m: &clean::Item, t: &clean::Item) {
2497         let name = m.name.as_ref().unwrap();
2498         let item_type = m.type_();
2499         let id = cx.derive_id(format!("{}.{}", item_type, name));
2500         write!(w, "<h3 id='{id}' class='method'><code>", id = id,);
2501         render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl);
2502         write!(w, "</code>");
2503         render_stability_since(w, m, t);
2504         write!(w, "</h3>");
2505         document(w, cx, m);
2506     }
2507
2508     if !types.is_empty() {
2509         write_small_section_header(
2510             w,
2511             "associated-types",
2512             "Associated Types",
2513             "<div class='methods'>",
2514         );
2515         for t in &types {
2516             trait_item(w, cx, *t, it);
2517         }
2518         write_loading_content(w, "</div>");
2519     }
2520
2521     if !consts.is_empty() {
2522         write_small_section_header(
2523             w,
2524             "associated-const",
2525             "Associated Constants",
2526             "<div class='methods'>",
2527         );
2528         for t in &consts {
2529             trait_item(w, cx, *t, it);
2530         }
2531         write_loading_content(w, "</div>");
2532     }
2533
2534     // Output the documentation for each function individually
2535     if !required.is_empty() {
2536         write_small_section_header(
2537             w,
2538             "required-methods",
2539             "Required methods",
2540             "<div class='methods'>",
2541         );
2542         for m in &required {
2543             trait_item(w, cx, *m, it);
2544         }
2545         write_loading_content(w, "</div>");
2546     }
2547     if !provided.is_empty() {
2548         write_small_section_header(
2549             w,
2550             "provided-methods",
2551             "Provided methods",
2552             "<div class='methods'>",
2553         );
2554         for m in &provided {
2555             trait_item(w, cx, *m, it);
2556         }
2557         write_loading_content(w, "</div>");
2558     }
2559
2560     // If there are methods directly on this trait object, render them here.
2561     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache);
2562
2563     if let Some(implementors) = cache.implementors.get(&it.def_id) {
2564         // The DefId is for the first Type found with that name. The bool is
2565         // if any Types with the same name but different DefId have been found.
2566         let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
2567         for implementor in implementors {
2568             match implementor.inner_impl().for_ {
2569                 clean::ResolvedPath { ref path, did, is_generic: false, .. }
2570                 | clean::BorrowedRef {
2571                     type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2572                     ..
2573                 } => {
2574                     let &mut (prev_did, ref mut has_duplicates) =
2575                         implementor_dups.entry(path.last_name()).or_insert((did, false));
2576                     if prev_did != did {
2577                         *has_duplicates = true;
2578                     }
2579                 }
2580                 _ => {}
2581             }
2582         }
2583
2584         let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| {
2585             i.inner_impl().for_.def_id().map_or(true, |d| cache.paths.contains_key(&d))
2586         });
2587
2588         let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
2589             local.iter().partition(|i| i.inner_impl().synthetic);
2590
2591         synthetic.sort_by(compare_impl);
2592         concrete.sort_by(compare_impl);
2593
2594         if !foreign.is_empty() {
2595             write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
2596
2597             for implementor in foreign {
2598                 let assoc_link = AssocItemLink::GotoSource(
2599                     implementor.impl_item.def_id,
2600                     &implementor.inner_impl().provided_trait_methods,
2601                 );
2602                 render_impl(
2603                     w,
2604                     cx,
2605                     &implementor,
2606                     assoc_link,
2607                     RenderMode::Normal,
2608                     implementor.impl_item.stable_since(),
2609                     false,
2610                     None,
2611                     true,
2612                     false,
2613                     &[],
2614                     cache,
2615                 );
2616             }
2617             write_loading_content(w, "");
2618         }
2619
2620         write_small_section_header(
2621             w,
2622             "implementors",
2623             "Implementors",
2624             "<div class='item-list' id='implementors-list'>",
2625         );
2626         for implementor in concrete {
2627             render_implementor(cx, implementor, w, &implementor_dups, &[], cache);
2628         }
2629         write_loading_content(w, "</div>");
2630
2631         if t.auto {
2632             write_small_section_header(
2633                 w,
2634                 "synthetic-implementors",
2635                 "Auto implementors",
2636                 "<div class='item-list' id='synthetic-implementors-list'>",
2637             );
2638             for implementor in synthetic {
2639                 render_implementor(
2640                     cx,
2641                     implementor,
2642                     w,
2643                     &implementor_dups,
2644                     &collect_paths_for_type(implementor.inner_impl().for_.clone()),
2645                     cache,
2646                 );
2647             }
2648             write_loading_content(w, "</div>");
2649         }
2650     } else {
2651         // even without any implementations to write in, we still want the heading and list, so the
2652         // implementors javascript file pulled in below has somewhere to write the impls into
2653         write_small_section_header(
2654             w,
2655             "implementors",
2656             "Implementors",
2657             "<div class='item-list' id='implementors-list'>",
2658         );
2659         write_loading_content(w, "</div>");
2660
2661         if t.auto {
2662             write_small_section_header(
2663                 w,
2664                 "synthetic-implementors",
2665                 "Auto implementors",
2666                 "<div class='item-list' id='synthetic-implementors-list'>",
2667             );
2668             write_loading_content(w, "</div>");
2669         }
2670     }
2671
2672     write!(
2673         w,
2674         "<script type=\"text/javascript\" \
2675                  src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\
2676          </script>",
2677         root_path = vec![".."; cx.current.len()].join("/"),
2678         path = if it.def_id.is_local() {
2679             cx.current.join("/")
2680         } else {
2681             let (ref path, _) = cache.external_paths[&it.def_id];
2682             path[..path.len() - 1].join("/")
2683         },
2684         ty = it.type_(),
2685         name = *it.name.as_ref().unwrap()
2686     );
2687 }
2688
2689 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
2690     use crate::formats::item_type::ItemType::*;
2691
2692     let name = it.name.as_ref().unwrap();
2693     let ty = match it.type_() {
2694         Typedef | AssocType => AssocType,
2695         s => s,
2696     };
2697
2698     let anchor = format!("#{}.{}", ty, name);
2699     match link {
2700         AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2701         AssocItemLink::Anchor(None) => anchor,
2702         AssocItemLink::GotoSource(did, _) => {
2703             href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2704         }
2705     }
2706 }
2707
2708 fn assoc_const(
2709     w: &mut Buffer,
2710     it: &clean::Item,
2711     ty: &clean::Type,
2712     _default: Option<&String>,
2713     link: AssocItemLink<'_>,
2714     extra: &str,
2715 ) {
2716     write!(
2717         w,
2718         "{}{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2719         extra,
2720         it.visibility.print_with_space(),
2721         naive_assoc_href(it, link),
2722         it.name.as_ref().unwrap(),
2723         ty.print()
2724     );
2725 }
2726
2727 fn assoc_type(
2728     w: &mut Buffer,
2729     it: &clean::Item,
2730     bounds: &[clean::GenericBound],
2731     default: Option<&clean::Type>,
2732     link: AssocItemLink<'_>,
2733     extra: &str,
2734 ) {
2735     write!(
2736         w,
2737         "{}type <a href='{}' class=\"type\">{}</a>",
2738         extra,
2739         naive_assoc_href(it, link),
2740         it.name.as_ref().unwrap()
2741     );
2742     if !bounds.is_empty() {
2743         write!(w, ": {}", print_generic_bounds(bounds))
2744     }
2745     if let Some(default) = default {
2746         write!(w, " = {}", default.print())
2747     }
2748 }
2749
2750 fn render_stability_since_raw(w: &mut Buffer, ver: Option<&str>, containing_ver: Option<&str>) {
2751     if let Some(v) = ver {
2752         if containing_ver != ver && !v.is_empty() {
2753             write!(w, "<span class='since' title='Stable since Rust version {0}'>{0}</span>", v)
2754         }
2755     }
2756 }
2757
2758 fn render_stability_since(w: &mut Buffer, item: &clean::Item, containing_item: &clean::Item) {
2759     render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2760 }
2761
2762 fn render_assoc_item(
2763     w: &mut Buffer,
2764     item: &clean::Item,
2765     link: AssocItemLink<'_>,
2766     parent: ItemType,
2767 ) {
2768     fn method(
2769         w: &mut Buffer,
2770         meth: &clean::Item,
2771         header: hir::FnHeader,
2772         g: &clean::Generics,
2773         d: &clean::FnDecl,
2774         link: AssocItemLink<'_>,
2775         parent: ItemType,
2776     ) {
2777         let name = meth.name.as_ref().unwrap();
2778         let anchor = format!("#{}.{}", meth.type_(), name);
2779         let href = match link {
2780             AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2781             AssocItemLink::Anchor(None) => anchor,
2782             AssocItemLink::GotoSource(did, provided_methods) => {
2783                 // We're creating a link from an impl-item to the corresponding
2784                 // trait-item and need to map the anchored type accordingly.
2785                 let ty = if provided_methods.contains(name) {
2786                     ItemType::Method
2787                 } else {
2788                     ItemType::TyMethod
2789                 };
2790
2791                 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2792             }
2793         };
2794         let mut header_len = format!(
2795             "{}{}{}{}{}{:#}fn {}{:#}",
2796             meth.visibility.print_with_space(),
2797             header.constness.print_with_space(),
2798             header.asyncness.print_with_space(),
2799             header.unsafety.print_with_space(),
2800             print_default_space(meth.is_default()),
2801             print_abi_with_space(header.abi),
2802             name,
2803             g.print()
2804         )
2805         .len();
2806         let (indent, end_newline) = if parent == ItemType::Trait {
2807             header_len += 4;
2808             (4, false)
2809         } else {
2810             (0, true)
2811         };
2812         render_attributes(w, meth, false);
2813         write!(
2814             w,
2815             "{}{}{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2816                    {generics}{decl}{spotlight}{where_clause}",
2817             if parent == ItemType::Trait { "    " } else { "" },
2818             meth.visibility.print_with_space(),
2819             header.constness.print_with_space(),
2820             header.asyncness.print_with_space(),
2821             header.unsafety.print_with_space(),
2822             print_default_space(meth.is_default()),
2823             print_abi_with_space(header.abi),
2824             href = href,
2825             name = name,
2826             generics = g.print(),
2827             decl = Function { decl: d, header_len, indent, asyncness: header.asyncness }.print(),
2828             spotlight = spotlight_decl(&d),
2829             where_clause = WhereClause { gens: g, indent, end_newline }
2830         )
2831     }
2832     match item.inner {
2833         clean::StrippedItem(..) => {}
2834         clean::TyMethodItem(ref m) => method(w, item, m.header, &m.generics, &m.decl, link, parent),
2835         clean::MethodItem(ref m) => method(w, item, m.header, &m.generics, &m.decl, link, parent),
2836         clean::AssocConstItem(ref ty, ref default) => assoc_const(
2837             w,
2838             item,
2839             ty,
2840             default.as_ref(),
2841             link,
2842             if parent == ItemType::Trait { "    " } else { "" },
2843         ),
2844         clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
2845             w,
2846             item,
2847             bounds,
2848             default.as_ref(),
2849             link,
2850             if parent == ItemType::Trait { "    " } else { "" },
2851         ),
2852         _ => panic!("render_assoc_item called on non-associated-item"),
2853     }
2854 }
2855
2856 fn item_struct(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Struct, cache: &Cache) {
2857     wrap_into_docblock(w, |w| {
2858         write!(w, "<pre class='rust struct'>");
2859         render_attributes(w, it, true);
2860         render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true);
2861         write!(w, "</pre>")
2862     });
2863
2864     document(w, cx, it);
2865     let mut fields = s
2866         .fields
2867         .iter()
2868         .filter_map(|f| match f.inner {
2869             clean::StructFieldItem(ref ty) => Some((f, ty)),
2870             _ => None,
2871         })
2872         .peekable();
2873     if let doctree::Plain = s.struct_type {
2874         if fields.peek().is_some() {
2875             write!(
2876                 w,
2877                 "<h2 id='fields' class='fields small-section-header'>
2878                        Fields{}<a href='#fields' class='anchor'></a></h2>",
2879                 document_non_exhaustive_header(it)
2880             );
2881             document_non_exhaustive(w, it);
2882             for (field, ty) in fields {
2883                 let id = cx.derive_id(format!(
2884                     "{}.{}",
2885                     ItemType::StructField,
2886                     field.name.as_ref().unwrap()
2887                 ));
2888                 write!(
2889                     w,
2890                     "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
2891                            <a href=\"#{id}\" class=\"anchor field\"></a>\
2892                            <code>{name}: {ty}</code>\
2893                            </span>",
2894                     item_type = ItemType::StructField,
2895                     id = id,
2896                     name = field.name.as_ref().unwrap(),
2897                     ty = ty.print()
2898                 );
2899                 document(w, cx, field);
2900             }
2901         }
2902     }
2903     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
2904 }
2905
2906 fn item_union(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Union, cache: &Cache) {
2907     wrap_into_docblock(w, |w| {
2908         write!(w, "<pre class='rust union'>");
2909         render_attributes(w, it, true);
2910         render_union(w, it, Some(&s.generics), &s.fields, "", true);
2911         write!(w, "</pre>")
2912     });
2913
2914     document(w, cx, it);
2915     let mut fields = s
2916         .fields
2917         .iter()
2918         .filter_map(|f| match f.inner {
2919             clean::StructFieldItem(ref ty) => Some((f, ty)),
2920             _ => None,
2921         })
2922         .peekable();
2923     if fields.peek().is_some() {
2924         write!(
2925             w,
2926             "<h2 id='fields' class='fields small-section-header'>
2927                    Fields<a href='#fields' class='anchor'></a></h2>"
2928         );
2929         for (field, ty) in fields {
2930             let name = field.name.as_ref().expect("union field name");
2931             let id = format!("{}.{}", ItemType::StructField, name);
2932             write!(
2933                 w,
2934                 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
2935                            <a href=\"#{id}\" class=\"anchor field\"></a>\
2936                            <code>{name}: {ty}</code>\
2937                        </span>",
2938                 id = id,
2939                 name = name,
2940                 shortty = ItemType::StructField,
2941                 ty = ty.print()
2942             );
2943             if let Some(stability_class) = field.stability_class() {
2944                 write!(w, "<span class='stab {stab}'></span>", stab = stability_class);
2945             }
2946             document(w, cx, field);
2947         }
2948     }
2949     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
2950 }
2951
2952 fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum, cache: &Cache) {
2953     wrap_into_docblock(w, |w| {
2954         write!(w, "<pre class='rust enum'>");
2955         render_attributes(w, it, true);
2956         write!(
2957             w,
2958             "{}enum {}{}{}",
2959             it.visibility.print_with_space(),
2960             it.name.as_ref().unwrap(),
2961             e.generics.print(),
2962             WhereClause { gens: &e.generics, indent: 0, end_newline: true }
2963         );
2964         if e.variants.is_empty() && !e.variants_stripped {
2965             write!(w, " {{}}");
2966         } else {
2967             write!(w, " {{\n");
2968             for v in &e.variants {
2969                 write!(w, "    ");
2970                 let name = v.name.as_ref().unwrap();
2971                 match v.inner {
2972                     clean::VariantItem(ref var) => match var.kind {
2973                         clean::VariantKind::CLike => write!(w, "{}", name),
2974                         clean::VariantKind::Tuple(ref tys) => {
2975                             write!(w, "{}(", name);
2976                             for (i, ty) in tys.iter().enumerate() {
2977                                 if i > 0 {
2978                                     write!(w, ",&nbsp;")
2979                                 }
2980                                 write!(w, "{}", ty.print());
2981                             }
2982                             write!(w, ")");
2983                         }
2984                         clean::VariantKind::Struct(ref s) => {
2985                             render_struct(w, v, None, s.struct_type, &s.fields, "    ", false);
2986                         }
2987                     },
2988                     _ => unreachable!(),
2989                 }
2990                 write!(w, ",\n");
2991             }
2992
2993             if e.variants_stripped {
2994                 write!(w, "    // some variants omitted\n");
2995             }
2996             write!(w, "}}");
2997         }
2998         write!(w, "</pre>")
2999     });
3000
3001     document(w, cx, it);
3002     if !e.variants.is_empty() {
3003         write!(
3004             w,
3005             "<h2 id='variants' class='variants small-section-header'>
3006                    Variants{}<a href='#variants' class='anchor'></a></h2>\n",
3007             document_non_exhaustive_header(it)
3008         );
3009         document_non_exhaustive(w, it);
3010         for variant in &e.variants {
3011             let id =
3012                 cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap()));
3013             write!(
3014                 w,
3015                 "<div id=\"{id}\" class=\"variant small-section-header\">\
3016                     <a href=\"#{id}\" class=\"anchor field\"></a>\
3017                     <code>{name}",
3018                 id = id,
3019                 name = variant.name.as_ref().unwrap()
3020             );
3021             if let clean::VariantItem(ref var) = variant.inner {
3022                 if let clean::VariantKind::Tuple(ref tys) = var.kind {
3023                     write!(w, "(");
3024                     for (i, ty) in tys.iter().enumerate() {
3025                         if i > 0 {
3026                             write!(w, ",&nbsp;");
3027                         }
3028                         write!(w, "{}", ty.print());
3029                     }
3030                     write!(w, ")");
3031                 }
3032             }
3033             write!(w, "</code></div>");
3034             document(w, cx, variant);
3035             document_non_exhaustive(w, variant);
3036
3037             use crate::clean::{Variant, VariantKind};
3038             if let clean::VariantItem(Variant { kind: VariantKind::Struct(ref s) }) = variant.inner
3039             {
3040                 let variant_id = cx.derive_id(format!(
3041                     "{}.{}.fields",
3042                     ItemType::Variant,
3043                     variant.name.as_ref().unwrap()
3044                 ));
3045                 write!(w, "<div class='autohide sub-variant' id='{id}'>", id = variant_id);
3046                 write!(
3047                     w,
3048                     "<h3>Fields of <b>{name}</b></h3><div>",
3049                     name = variant.name.as_ref().unwrap()
3050                 );
3051                 for field in &s.fields {
3052                     use crate::clean::StructFieldItem;
3053                     if let StructFieldItem(ref ty) = field.inner {
3054                         let id = cx.derive_id(format!(
3055                             "variant.{}.field.{}",
3056                             variant.name.as_ref().unwrap(),
3057                             field.name.as_ref().unwrap()
3058                         ));
3059                         write!(
3060                             w,
3061                             "<span id=\"{id}\" class=\"variant small-section-header\">\
3062                                    <a href=\"#{id}\" class=\"anchor field\"></a>\
3063                                    <code>{f}:&nbsp;{t}\
3064                                    </code></span>",
3065                             id = id,
3066                             f = field.name.as_ref().unwrap(),
3067                             t = ty.print()
3068                         );
3069                         document(w, cx, field);
3070                     }
3071                 }
3072                 write!(w, "</div></div>");
3073             }
3074             render_stability_since(w, variant, it);
3075         }
3076     }
3077     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3078 }
3079
3080 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
3081     sym::export_name,
3082     sym::lang,
3083     sym::link_section,
3084     sym::must_use,
3085     sym::no_mangle,
3086     sym::repr,
3087     sym::non_exhaustive,
3088 ];
3089
3090 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
3091 // left padding. For example:
3092 //
3093 // #[foo] <----- "top" attribute
3094 // struct Foo {
3095 //     #[bar] <---- not "top" attribute
3096 //     bar: usize,
3097 // }
3098 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
3099     let attrs = it
3100         .attrs
3101         .other_attrs
3102         .iter()
3103         .filter_map(|attr| {
3104             if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
3105                 Some(pprust::attribute_to_string(&attr))
3106             } else {
3107                 None
3108             }
3109         })
3110         .join("\n");
3111
3112     if !attrs.is_empty() {
3113         write!(
3114             w,
3115             "<span class=\"docblock attributes{}\">{}</span>",
3116             if top { " top-attr" } else { "" },
3117             &attrs
3118         );
3119     }
3120 }
3121
3122 fn render_struct(
3123     w: &mut Buffer,
3124     it: &clean::Item,
3125     g: Option<&clean::Generics>,
3126     ty: doctree::StructType,
3127     fields: &[clean::Item],
3128     tab: &str,
3129     structhead: bool,
3130 ) {
3131     write!(
3132         w,
3133         "{}{}{}",
3134         it.visibility.print_with_space(),
3135         if structhead { "struct " } else { "" },
3136         it.name.as_ref().unwrap()
3137     );
3138     if let Some(g) = g {
3139         write!(w, "{}", g.print())
3140     }
3141     match ty {
3142         doctree::Plain => {
3143             if let Some(g) = g {
3144                 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })
3145             }
3146             let mut has_visible_fields = false;
3147             write!(w, " {{");
3148             for field in fields {
3149                 if let clean::StructFieldItem(ref ty) = field.inner {
3150                     write!(
3151                         w,
3152                         "\n{}    {}{}: {},",
3153                         tab,
3154                         field.visibility.print_with_space(),
3155                         field.name.as_ref().unwrap(),
3156                         ty.print()
3157                     );
3158                     has_visible_fields = true;
3159                 }
3160             }
3161
3162             if has_visible_fields {
3163                 if it.has_stripped_fields().unwrap() {
3164                     write!(w, "\n{}    // some fields omitted", tab);
3165                 }
3166                 write!(w, "\n{}", tab);
3167             } else if it.has_stripped_fields().unwrap() {
3168                 // If there are no visible fields we can just display
3169                 // `{ /* fields omitted */ }` to save space.
3170                 write!(w, " /* fields omitted */ ");
3171             }
3172             write!(w, "}}");
3173         }
3174         doctree::Tuple => {
3175             write!(w, "(");
3176             for (i, field) in fields.iter().enumerate() {
3177                 if i > 0 {
3178                     write!(w, ", ");
3179                 }
3180                 match field.inner {
3181                     clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
3182                     clean::StructFieldItem(ref ty) => {
3183                         write!(w, "{}{}", field.visibility.print_with_space(), ty.print())
3184                     }
3185                     _ => unreachable!(),
3186                 }
3187             }
3188             write!(w, ")");
3189             if let Some(g) = g {
3190                 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3191             }
3192             write!(w, ";");
3193         }
3194         doctree::Unit => {
3195             // Needed for PhantomData.
3196             if let Some(g) = g {
3197                 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
3198             }
3199             write!(w, ";");
3200         }
3201     }
3202 }
3203
3204 fn render_union(
3205     w: &mut Buffer,
3206     it: &clean::Item,
3207     g: Option<&clean::Generics>,
3208     fields: &[clean::Item],
3209     tab: &str,
3210     structhead: bool,
3211 ) {
3212     write!(
3213         w,
3214         "{}{}{}",
3215         it.visibility.print_with_space(),
3216         if structhead { "union " } else { "" },
3217         it.name.as_ref().unwrap()
3218     );
3219     if let Some(g) = g {
3220         write!(w, "{}", g.print());
3221         write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true });
3222     }
3223
3224     write!(w, " {{\n{}", tab);
3225     for field in fields {
3226         if let clean::StructFieldItem(ref ty) = field.inner {
3227             write!(
3228                 w,
3229                 "    {}{}: {},\n{}",
3230                 field.visibility.print_with_space(),
3231                 field.name.as_ref().unwrap(),
3232                 ty.print(),
3233                 tab
3234             );
3235         }
3236     }
3237
3238     if it.has_stripped_fields().unwrap() {
3239         write!(w, "    // some fields omitted\n{}", tab);
3240     }
3241     write!(w, "}}");
3242 }
3243
3244 #[derive(Copy, Clone)]
3245 enum AssocItemLink<'a> {
3246     Anchor(Option<&'a str>),
3247     GotoSource(DefId, &'a FxHashSet<String>),
3248 }
3249
3250 impl<'a> AssocItemLink<'a> {
3251     fn anchor(&self, id: &'a String) -> Self {
3252         match *self {
3253             AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
3254             ref other => *other,
3255         }
3256     }
3257 }
3258
3259 fn render_assoc_items(
3260     w: &mut Buffer,
3261     cx: &Context,
3262     containing_item: &clean::Item,
3263     it: DefId,
3264     what: AssocItemRender<'_>,
3265     cache: &Cache,
3266 ) {
3267     let v = match cache.impls.get(&it) {
3268         Some(v) => v,
3269         None => return,
3270     };
3271     let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
3272     if !non_trait.is_empty() {
3273         let render_mode = match what {
3274             AssocItemRender::All => {
3275                 write!(
3276                     w,
3277                     "\
3278                     <h2 id='implementations' class='small-section-header'>\
3279                       Implementations<a href='#implementations' class='anchor'></a>\
3280                     </h2>\
3281                 "
3282                 );
3283                 RenderMode::Normal
3284             }
3285             AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3286                 write!(
3287                     w,
3288                     "\
3289                     <h2 id='deref-methods' class='small-section-header'>\
3290                       Methods from {}&lt;Target = {}&gt;\
3291                       <a href='#deref-methods' class='anchor'></a>\
3292                     </h2>\
3293                 ",
3294                     trait_.print(),
3295                     type_.print()
3296                 );
3297                 RenderMode::ForDeref { mut_: deref_mut_ }
3298             }
3299         };
3300         for i in &non_trait {
3301             render_impl(
3302                 w,
3303                 cx,
3304                 i,
3305                 AssocItemLink::Anchor(None),
3306                 render_mode,
3307                 containing_item.stable_since(),
3308                 true,
3309                 None,
3310                 false,
3311                 true,
3312                 &[],
3313                 cache,
3314             );
3315         }
3316     }
3317     if let AssocItemRender::DerefFor { .. } = what {
3318         return;
3319     }
3320     if !traits.is_empty() {
3321         let deref_impl =
3322             traits.iter().find(|t| t.inner_impl().trait_.def_id() == cache.deref_trait_did);
3323         if let Some(impl_) = deref_impl {
3324             let has_deref_mut =
3325                 traits.iter().any(|t| t.inner_impl().trait_.def_id() == cache.deref_mut_trait_did);
3326             render_deref_methods(w, cx, impl_, containing_item, has_deref_mut, cache);
3327         }
3328
3329         let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
3330             traits.iter().partition(|t| t.inner_impl().synthetic);
3331         let (blanket_impl, concrete): (Vec<&&Impl>, _) =
3332             concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
3333
3334         let mut impls = Buffer::empty_from(&w);
3335         render_impls(cx, &mut impls, &concrete, containing_item, cache);
3336         let impls = impls.into_inner();
3337         if !impls.is_empty() {
3338             write!(
3339                 w,
3340                 "\
3341                 <h2 id='trait-implementations' class='small-section-header'>\
3342                   Trait Implementations<a href='#trait-implementations' class='anchor'></a>\
3343                 </h2>\
3344                 <div id='trait-implementations-list'>{}</div>",
3345                 impls
3346             );
3347         }
3348
3349         if !synthetic.is_empty() {
3350             write!(
3351                 w,
3352                 "\
3353                 <h2 id='synthetic-implementations' class='small-section-header'>\
3354                   Auto Trait Implementations\
3355                   <a href='#synthetic-implementations' class='anchor'></a>\
3356                 </h2>\
3357                 <div id='synthetic-implementations-list'>\
3358             "
3359             );
3360             render_impls(cx, w, &synthetic, containing_item, cache);
3361             write!(w, "</div>");
3362         }
3363
3364         if !blanket_impl.is_empty() {
3365             write!(
3366                 w,
3367                 "\
3368                 <h2 id='blanket-implementations' class='small-section-header'>\
3369                   Blanket Implementations\
3370                   <a href='#blanket-implementations' class='anchor'></a>\
3371                 </h2>\
3372                 <div id='blanket-implementations-list'>\
3373             "
3374             );
3375             render_impls(cx, w, &blanket_impl, containing_item, cache);
3376             write!(w, "</div>");
3377         }
3378     }
3379 }
3380
3381 fn render_deref_methods(
3382     w: &mut Buffer,
3383     cx: &Context,
3384     impl_: &Impl,
3385     container_item: &clean::Item,
3386     deref_mut: bool,
3387     cache: &Cache,
3388 ) {
3389     let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3390     let (target, real_target) = impl_
3391         .inner_impl()
3392         .items
3393         .iter()
3394         .find_map(|item| match item.inner {
3395             clean::TypedefItem(ref t, true) => Some(match *t {
3396                 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
3397                 _ => (&t.type_, &t.type_),
3398             }),
3399             _ => None,
3400         })
3401         .expect("Expected associated type binding");
3402     let what =
3403         AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
3404     if let Some(did) = target.def_id() {
3405         render_assoc_items(w, cx, container_item, did, what, cache);
3406     } else {
3407         if let Some(prim) = target.primitive_type() {
3408             if let Some(&did) = cache.primitive_locations.get(&prim) {
3409                 render_assoc_items(w, cx, container_item, did, what, cache);
3410             }
3411         }
3412     }
3413 }
3414
3415 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3416     let self_type_opt = match item.inner {
3417         clean::MethodItem(ref method) => method.decl.self_type(),
3418         clean::TyMethodItem(ref method) => method.decl.self_type(),
3419         _ => None,
3420     };
3421
3422     if let Some(self_ty) = self_type_opt {
3423         let (by_mut_ref, by_box, by_value) = match self_ty {
3424             SelfTy::SelfBorrowed(_, mutability)
3425             | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3426                 (mutability == Mutability::Mut, false, false)
3427             }
3428             SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3429                 (false, Some(did) == cache().owned_box_did, false)
3430             }
3431             SelfTy::SelfValue => (false, false, true),
3432             _ => (false, false, false),
3433         };
3434
3435         (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3436     } else {
3437         false
3438     }
3439 }
3440
3441 fn spotlight_decl(decl: &clean::FnDecl) -> String {
3442     let mut out = Buffer::html();
3443     let mut trait_ = String::new();
3444
3445     if let Some(did) = decl.output.def_id() {
3446         let c = cache();
3447         if let Some(impls) = c.impls.get(&did) {
3448             for i in impls {
3449                 let impl_ = i.inner_impl();
3450                 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3451                     if out.is_empty() {
3452                         out.push_str(&format!(
3453                             "<h3 class=\"important\">Important traits for {}</h3>\
3454                                       <code class=\"content\">",
3455                             impl_.for_.print()
3456                         ));
3457                         trait_.push_str(&impl_.for_.print().to_string());
3458                     }
3459
3460                     //use the "where" class here to make it small
3461                     out.push_str(&format!(
3462                         "<span class=\"where fmt-newline\">{}</span>",
3463                         impl_.print()
3464                     ));
3465                     let t_did = impl_.trait_.def_id().unwrap();
3466                     for it in &impl_.items {
3467                         if let clean::TypedefItem(ref tydef, _) = it.inner {
3468                             out.push_str("<span class=\"where fmt-newline\">    ");
3469                             assoc_type(
3470                                 &mut out,
3471                                 it,
3472                                 &[],
3473                                 Some(&tydef.type_),
3474                                 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
3475                                 "",
3476                             );
3477                             out.push_str(";</span>");
3478                         }
3479                     }
3480                 }
3481             }
3482         }
3483     }
3484
3485     if !out.is_empty() {
3486         out.insert_str(
3487             0,
3488             "<span class=\"important-traits\"><span class=\"important-traits-tooltip\">ⓘ<div class='important-traits-tooltiptext'><span class=\"docblock\">"
3489
3490         );
3491         out.push_str("</code></span></div></span></span>");
3492     }
3493
3494     out.into_inner()
3495 }
3496
3497 fn render_impl(
3498     w: &mut Buffer,
3499     cx: &Context,
3500     i: &Impl,
3501     link: AssocItemLink<'_>,
3502     render_mode: RenderMode,
3503     outer_version: Option<&str>,
3504     show_def_docs: bool,
3505     use_absolute: Option<bool>,
3506     is_on_foreign_type: bool,
3507     show_default_items: bool,
3508     // This argument is used to reference same type with different paths to avoid duplication
3509     // in documentation pages for trait with automatic implementations like "Send" and "Sync".
3510     aliases: &[String],
3511     cache: &Cache,
3512 ) {
3513     if render_mode == RenderMode::Normal {
3514         let id = cx.derive_id(match i.inner_impl().trait_ {
3515             Some(ref t) => {
3516                 if is_on_foreign_type {
3517                     get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t)
3518                 } else {
3519                     format!("impl-{}", small_url_encode(&format!("{:#}", t.print())))
3520                 }
3521             }
3522             None => "impl".to_string(),
3523         });
3524         let aliases = if aliases.is_empty() {
3525             String::new()
3526         } else {
3527             format!(" aliases=\"{}\"", aliases.join(","))
3528         };
3529         if let Some(use_absolute) = use_absolute {
3530             write!(w, "<h3 id='{}' class='impl'{}><code class='in-band'>", id, aliases);
3531             fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute);
3532             if show_def_docs {
3533                 for it in &i.inner_impl().items {
3534                     if let clean::TypedefItem(ref tydef, _) = it.inner {
3535                         write!(w, "<span class=\"where fmt-newline\">  ");
3536                         assoc_type(w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "");
3537                         write!(w, ";</span>");
3538                     }
3539                 }
3540             }
3541             write!(w, "</code>");
3542         } else {
3543             write!(
3544                 w,
3545                 "<h3 id='{}' class='impl'{}><code class='in-band'>{}</code>",
3546                 id,
3547                 aliases,
3548                 i.inner_impl().print()
3549             );
3550         }
3551         write!(w, "<a href='#{}' class='anchor'></a>", id);
3552         let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3553         render_stability_since_raw(w, since, outer_version);
3554         if let Some(l) = cx.src_href(&i.impl_item, cache) {
3555             write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>", l, "goto source code");
3556         }
3557         write!(w, "</h3>");
3558         if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3559             let mut ids = cx.id_map.borrow_mut();
3560             write!(
3561                 w,
3562                 "<div class='docblock'>{}</div>",
3563                 Markdown(
3564                     &*dox,
3565                     &i.impl_item.links(),
3566                     &mut ids,
3567                     cx.shared.codes,
3568                     cx.shared.edition,
3569                     &cx.shared.playground
3570                 )
3571                 .into_string()
3572             );
3573         }
3574     }
3575
3576     fn doc_impl_item(
3577         w: &mut Buffer,
3578         cx: &Context,
3579         item: &clean::Item,
3580         link: AssocItemLink<'_>,
3581         render_mode: RenderMode,
3582         is_default_item: bool,
3583         outer_version: Option<&str>,
3584         trait_: Option<&clean::Trait>,
3585         show_def_docs: bool,
3586         cache: &Cache,
3587     ) {
3588         let item_type = item.type_();
3589         let name = item.name.as_ref().unwrap();
3590
3591         let render_method_item = match render_mode {
3592             RenderMode::Normal => true,
3593             RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3594         };
3595
3596         let (is_hidden, extra_class) =
3597             if (trait_.is_none() || item.doc_value().is_some() || item.inner.is_associated())
3598                 && !is_default_item
3599             {
3600                 (false, "")
3601             } else {
3602                 (true, " hidden")
3603             };
3604         match item.inner {
3605             clean::MethodItem(clean::Method { .. })
3606             | clean::TyMethodItem(clean::TyMethod { .. }) => {
3607                 // Only render when the method is not static or we allow static methods
3608                 if render_method_item {
3609                     let id = cx.derive_id(format!("{}.{}", item_type, name));
3610                     write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class);
3611                     write!(w, "<code>");
3612                     render_assoc_item(w, item, link.anchor(&id), ItemType::Impl);
3613                     write!(w, "</code>");
3614                     render_stability_since_raw(w, item.stable_since(), outer_version);
3615                     if let Some(l) = cx.src_href(item, cache) {
3616                         write!(
3617                             w,
3618                             "<a class='srclink' href='{}' title='{}'>[src]</a>",
3619                             l, "goto source code"
3620                         );
3621                     }
3622                     write!(w, "</h4>");
3623                 }
3624             }
3625             clean::TypedefItem(ref tydef, _) => {
3626                 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
3627                 write!(w, "<h4 id='{}' class=\"{}{}\"><code>", id, item_type, extra_class);
3628                 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "");
3629                 write!(w, "</code></h4>");
3630             }
3631             clean::AssocConstItem(ref ty, ref default) => {
3632                 let id = cx.derive_id(format!("{}.{}", item_type, name));
3633                 write!(w, "<h4 id='{}' class=\"{}{}\"><code>", id, item_type, extra_class);
3634                 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "");
3635                 write!(w, "</code>");
3636                 render_stability_since_raw(w, item.stable_since(), outer_version);
3637                 if let Some(l) = cx.src_href(item, cache) {
3638                     write!(
3639                         w,
3640                         "<a class='srclink' href='{}' title='{}'>[src]</a>",
3641                         l, "goto source code"
3642                     );
3643                 }
3644                 write!(w, "</h4>");
3645             }
3646             clean::AssocTypeItem(ref bounds, ref default) => {
3647                 let id = cx.derive_id(format!("{}.{}", item_type, name));
3648                 write!(w, "<h4 id='{}' class=\"{}{}\"><code>", id, item_type, extra_class);
3649                 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "");
3650                 write!(w, "</code></h4>");
3651             }
3652             clean::StrippedItem(..) => return,
3653             _ => panic!("can't make docs for trait item with name {:?}", item.name),
3654         }
3655
3656         if render_method_item {
3657             if !is_default_item {
3658                 if let Some(t) = trait_ {
3659                     // The trait item may have been stripped so we might not
3660                     // find any documentation or stability for it.
3661                     if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3662                         // We need the stability of the item from the trait
3663                         // because impls can't have a stability.
3664                         document_stability(w, cx, it, is_hidden);
3665                         if item.doc_value().is_some() {
3666                             document_full(w, item, cx, "", is_hidden);
3667                         } else if show_def_docs {
3668                             // In case the item isn't documented,
3669                             // provide short documentation from the trait.
3670                             document_short(w, cx, it, link, "", is_hidden);
3671                         }
3672                     }
3673                 } else {
3674                     document_stability(w, cx, item, is_hidden);
3675                     if show_def_docs {
3676                         document_full(w, item, cx, "", is_hidden);
3677                     }
3678                 }
3679             } else {
3680                 document_stability(w, cx, item, is_hidden);
3681                 if show_def_docs {
3682                     document_short(w, cx, item, link, "", is_hidden);
3683                 }
3684             }
3685         }
3686     }
3687
3688     let traits = &cache.traits;
3689     let trait_ = i.trait_did().map(|did| &traits[&did]);
3690
3691     write!(w, "<div class='impl-items'>");
3692     for trait_item in &i.inner_impl().items {
3693         doc_impl_item(
3694             w,
3695             cx,
3696             trait_item,
3697             link,
3698             render_mode,
3699             false,
3700             outer_version,
3701             trait_,
3702             show_def_docs,
3703             cache,
3704         );
3705     }
3706
3707     fn render_default_items(
3708         w: &mut Buffer,
3709         cx: &Context,
3710         t: &clean::Trait,
3711         i: &clean::Impl,
3712         render_mode: RenderMode,
3713         outer_version: Option<&str>,
3714         show_def_docs: bool,
3715         cache: &Cache,
3716     ) {
3717         for trait_item in &t.items {
3718             let n = trait_item.name.clone();
3719             if i.items.iter().any(|m| m.name == n) {
3720                 continue;
3721             }
3722             let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3723             let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3724
3725             doc_impl_item(
3726                 w,
3727                 cx,
3728                 trait_item,
3729                 assoc_link,
3730                 render_mode,
3731                 true,
3732                 outer_version,
3733                 None,
3734                 show_def_docs,
3735                 cache,
3736             );
3737         }
3738     }
3739
3740     // If we've implemented a trait, then also emit documentation for all
3741     // default items which weren't overridden in the implementation block.
3742     // We don't emit documentation for default items if they appear in the
3743     // Implementations on Foreign Types or Implementors sections.
3744     if show_default_items {
3745         if let Some(t) = trait_ {
3746             render_default_items(
3747                 w,
3748                 cx,
3749                 t,
3750                 &i.inner_impl(),
3751                 render_mode,
3752                 outer_version,
3753                 show_def_docs,
3754                 cache,
3755             );
3756         }
3757     }
3758     write!(w, "</div>");
3759 }
3760
3761 fn item_opaque_ty(
3762     w: &mut Buffer,
3763     cx: &Context,
3764     it: &clean::Item,
3765     t: &clean::OpaqueTy,
3766     cache: &Cache,
3767 ) {
3768     write!(w, "<pre class='rust opaque'>");
3769     render_attributes(w, it, false);
3770     write!(
3771         w,
3772         "type {}{}{where_clause} = impl {bounds};</pre>",
3773         it.name.as_ref().unwrap(),
3774         t.generics.print(),
3775         where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3776         bounds = bounds(&t.bounds, false)
3777     );
3778
3779     document(w, cx, it);
3780
3781     // Render any items associated directly to this alias, as otherwise they
3782     // won't be visible anywhere in the docs. It would be nice to also show
3783     // associated items from the aliased type (see discussion in #32077), but
3784     // we need #14072 to make sense of the generics.
3785     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3786 }
3787
3788 fn item_trait_alias(
3789     w: &mut Buffer,
3790     cx: &Context,
3791     it: &clean::Item,
3792     t: &clean::TraitAlias,
3793     cache: &Cache,
3794 ) {
3795     write!(w, "<pre class='rust trait-alias'>");
3796     render_attributes(w, it, false);
3797     write!(
3798         w,
3799         "trait {}{}{} = {};</pre>",
3800         it.name.as_ref().unwrap(),
3801         t.generics.print(),
3802         WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3803         bounds(&t.bounds, true)
3804     );
3805
3806     document(w, cx, it);
3807
3808     // Render any items associated directly to this alias, as otherwise they
3809     // won't be visible anywhere in the docs. It would be nice to also show
3810     // associated items from the aliased type (see discussion in #32077), but
3811     // we need #14072 to make sense of the generics.
3812     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3813 }
3814
3815 fn item_typedef(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Typedef, cache: &Cache) {
3816     write!(w, "<pre class='rust typedef'>");
3817     render_attributes(w, it, false);
3818     write!(
3819         w,
3820         "type {}{}{where_clause} = {type_};</pre>",
3821         it.name.as_ref().unwrap(),
3822         t.generics.print(),
3823         where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3824         type_ = t.type_.print()
3825     );
3826
3827     document(w, cx, it);
3828
3829     // Render any items associated directly to this alias, as otherwise they
3830     // won't be visible anywhere in the docs. It would be nice to also show
3831     // associated items from the aliased type (see discussion in #32077), but
3832     // we need #14072 to make sense of the generics.
3833     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3834 }
3835
3836 fn item_foreign_type(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
3837     writeln!(w, "<pre class='rust foreigntype'>extern {{");
3838     render_attributes(w, it, false);
3839     write!(
3840         w,
3841         "    {}type {};\n}}</pre>",
3842         it.visibility.print_with_space(),
3843         it.name.as_ref().unwrap(),
3844     );
3845
3846     document(w, cx, it);
3847
3848     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
3849 }
3850
3851 fn print_sidebar(cx: &Context, it: &clean::Item, buffer: &mut Buffer, cache: &Cache) {
3852     let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
3853
3854     if it.is_struct()
3855         || it.is_trait()
3856         || it.is_primitive()
3857         || it.is_union()
3858         || it.is_enum()
3859         || it.is_mod()
3860         || it.is_typedef()
3861     {
3862         write!(
3863             buffer,
3864             "<p class='location'>{}{}</p>",
3865             match it.inner {
3866                 clean::StructItem(..) => "Struct ",
3867                 clean::TraitItem(..) => "Trait ",
3868                 clean::PrimitiveItem(..) => "Primitive Type ",
3869                 clean::UnionItem(..) => "Union ",
3870                 clean::EnumItem(..) => "Enum ",
3871                 clean::TypedefItem(..) => "Type Definition ",
3872                 clean::ForeignTypeItem => "Foreign Type ",
3873                 clean::ModuleItem(..) =>
3874                     if it.is_crate() {
3875                         "Crate "
3876                     } else {
3877                         "Module "
3878                     },
3879                 _ => "",
3880             },
3881             it.name.as_ref().unwrap()
3882         );
3883     }
3884
3885     if it.is_crate() {
3886         if let Some(ref version) = cache.crate_version {
3887             write!(
3888                 buffer,
3889                 "<div class='block version'>\
3890                     <p>Version {}</p>\
3891                     </div>",
3892                 Escape(version)
3893             );
3894         }
3895     }
3896
3897     write!(buffer, "<div class=\"sidebar-elems\">");
3898     if it.is_crate() {
3899         write!(
3900             buffer,
3901             "<a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
3902             it.name.as_ref().expect("crates always have a name")
3903         );
3904     }
3905     match it.inner {
3906         clean::StructItem(ref s) => sidebar_struct(buffer, it, s),
3907         clean::TraitItem(ref t) => sidebar_trait(buffer, it, t),
3908         clean::PrimitiveItem(_) => sidebar_primitive(buffer, it),
3909         clean::UnionItem(ref u) => sidebar_union(buffer, it, u),
3910         clean::EnumItem(ref e) => sidebar_enum(buffer, it, e),
3911         clean::TypedefItem(_, _) => sidebar_typedef(buffer, it),
3912         clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
3913         clean::ForeignTypeItem => sidebar_foreign_type(buffer, it),
3914         _ => (),
3915     }
3916
3917     // The sidebar is designed to display sibling functions, modules and
3918     // other miscellaneous information. since there are lots of sibling
3919     // items (and that causes quadratic growth in large modules),
3920     // we refactor common parts into a shared JavaScript file per module.
3921     // still, we don't move everything into JS because we want to preserve
3922     // as much HTML as possible in order to allow non-JS-enabled browsers
3923     // to navigate the documentation (though slightly inefficiently).
3924
3925     write!(buffer, "<p class='location'>");
3926     for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3927         if i > 0 {
3928             write!(buffer, "::<wbr>");
3929         }
3930         write!(
3931             buffer,
3932             "<a href='{}index.html'>{}</a>",
3933             &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3934             *name
3935         );
3936     }
3937     write!(buffer, "</p>");
3938
3939     // Sidebar refers to the enclosing module, not this module.
3940     let relpath = if it.is_mod() { "../" } else { "" };
3941     write!(
3942         buffer,
3943         "<script>window.sidebarCurrent = {{\
3944                 name: '{name}', \
3945                 ty: '{ty}', \
3946                 relpath: '{path}'\
3947             }};</script>",
3948         name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3949         ty = it.type_(),
3950         path = relpath
3951     );
3952     if parentlen == 0 {
3953         // There is no sidebar-items.js beyond the crate root path
3954         // FIXME maybe dynamic crate loading can be merged here
3955     } else {
3956         write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
3957     }
3958     // Closes sidebar-elems div.
3959     write!(buffer, "</div>");
3960 }
3961
3962 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
3963     if used_links.insert(url.clone()) {
3964         return url;
3965     }
3966     let mut add = 1;
3967     while !used_links.insert(format!("{}-{}", url, add)) {
3968         add += 1;
3969     }
3970     format!("{}-{}", url, add)
3971 }
3972
3973 fn get_methods(
3974     i: &clean::Impl,
3975     for_deref: bool,
3976     used_links: &mut FxHashSet<String>,
3977     deref_mut: bool,
3978 ) -> Vec<String> {
3979     i.items
3980         .iter()
3981         .filter_map(|item| match item.name {
3982             Some(ref name) if !name.is_empty() && item.is_method() => {
3983                 if !for_deref || should_render_item(item, deref_mut) {
3984                     Some(format!(
3985                         "<a href=\"#{}\">{}</a>",
3986                         get_next_url(used_links, format!("method.{}", name)),
3987                         name
3988                     ))
3989                 } else {
3990                     None
3991                 }
3992             }
3993             _ => None,
3994         })
3995         .collect::<Vec<_>>()
3996 }
3997
3998 // The point is to url encode any potential character from a type with genericity.
3999 fn small_url_encode(s: &str) -> String {
4000     s.replace("<", "%3C")
4001         .replace(">", "%3E")
4002         .replace(" ", "%20")
4003         .replace("?", "%3F")
4004         .replace("'", "%27")
4005         .replace("&", "%26")
4006         .replace(",", "%2C")
4007         .replace(":", "%3A")
4008         .replace(";", "%3B")
4009         .replace("[", "%5B")
4010         .replace("]", "%5D")
4011         .replace("\"", "%22")
4012 }
4013
4014 fn sidebar_assoc_items(it: &clean::Item) -> String {
4015     let mut out = String::new();
4016     let c = cache();
4017     if let Some(v) = c.impls.get(&it.def_id) {
4018         let mut used_links = FxHashSet::default();
4019
4020         {
4021             let used_links_bor = &mut used_links;
4022             let mut ret = v
4023                 .iter()
4024                 .filter(|i| i.inner_impl().trait_.is_none())
4025                 .flat_map(move |i| get_methods(i.inner_impl(), false, used_links_bor, false))
4026                 .collect::<Vec<_>>();
4027             if !ret.is_empty() {
4028                 // We want links' order to be reproducible so we don't use unstable sort.
4029                 ret.sort();
4030                 out.push_str(&format!(
4031                     "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
4032                      <div class=\"sidebar-links\">{}</div>",
4033                     ret.join("")
4034                 ));
4035             }
4036         }
4037
4038         if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
4039             if let Some(impl_) = v
4040                 .iter()
4041                 .filter(|i| i.inner_impl().trait_.is_some())
4042                 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did)
4043             {
4044                 if let Some((target, real_target)) =
4045                     impl_.inner_impl().items.iter().find_map(|item| match item.inner {
4046                         clean::TypedefItem(ref t, true) => Some(match *t {
4047                             clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
4048                             _ => (&t.type_, &t.type_),
4049                         }),
4050                         _ => None,
4051                     })
4052                 {
4053                     let deref_mut = v
4054                         .iter()
4055                         .filter(|i| i.inner_impl().trait_.is_some())
4056                         .any(|i| i.inner_impl().trait_.def_id() == c.deref_mut_trait_did);
4057                     let inner_impl = target
4058                         .def_id()
4059                         .or(target
4060                             .primitive_type()
4061                             .and_then(|prim| c.primitive_locations.get(&prim).cloned()))
4062                         .and_then(|did| c.impls.get(&did));
4063                     if let Some(impls) = inner_impl {
4064                         out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
4065                         out.push_str(&format!(
4066                             "Methods from {}&lt;Target={}&gt;",
4067                             Escape(&format!(
4068                                 "{:#}",
4069                                 impl_.inner_impl().trait_.as_ref().unwrap().print()
4070                             )),
4071                             Escape(&format!("{:#}", real_target.print()))
4072                         ));
4073                         out.push_str("</a>");
4074                         let mut ret = impls
4075                             .iter()
4076                             .filter(|i| i.inner_impl().trait_.is_none())
4077                             .flat_map(|i| {
4078                                 get_methods(i.inner_impl(), true, &mut used_links, deref_mut)
4079                             })
4080                             .collect::<Vec<_>>();
4081                         // We want links' order to be reproducible so we don't use unstable sort.
4082                         ret.sort();
4083                         if !ret.is_empty() {
4084                             out.push_str(&format!(
4085                                 "<div class=\"sidebar-links\">{}</div>",
4086                                 ret.join("")
4087                             ));
4088                         }
4089                     }
4090                 }
4091             }
4092             let format_impls = |impls: Vec<&Impl>| {
4093                 let mut links = FxHashSet::default();
4094
4095                 let mut ret = impls
4096                     .iter()
4097                     .filter_map(|i| {
4098                         let is_negative_impl = is_negative_impl(i.inner_impl());
4099                         if let Some(ref i) = i.inner_impl().trait_ {
4100                             let i_display = format!("{:#}", i.print());
4101                             let out = Escape(&i_display);
4102                             let encoded = small_url_encode(&format!("{:#}", i.print()));
4103                             let generated = format!(
4104                                 "<a href=\"#impl-{}\">{}{}</a>",
4105                                 encoded,
4106                                 if is_negative_impl { "!" } else { "" },
4107                                 out
4108                             );
4109                             if links.insert(generated.clone()) { Some(generated) } else { None }
4110                         } else {
4111                             None
4112                         }
4113                     })
4114                     .collect::<Vec<String>>();
4115                 ret.sort();
4116                 ret.join("")
4117             };
4118
4119             let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
4120                 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
4121             let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
4122                 .into_iter()
4123                 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
4124
4125             let concrete_format = format_impls(concrete);
4126             let synthetic_format = format_impls(synthetic);
4127             let blanket_format = format_impls(blanket_impl);
4128
4129             if !concrete_format.is_empty() {
4130                 out.push_str(
4131                     "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
4132                         Trait Implementations</a>",
4133                 );
4134                 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
4135             }
4136
4137             if !synthetic_format.is_empty() {
4138                 out.push_str(
4139                     "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
4140                         Auto Trait Implementations</a>",
4141                 );
4142                 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
4143             }
4144
4145             if !blanket_format.is_empty() {
4146                 out.push_str(
4147                     "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
4148                         Blanket Implementations</a>",
4149                 );
4150                 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
4151             }
4152         }
4153     }
4154
4155     out
4156 }
4157
4158 fn sidebar_struct(buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
4159     let mut sidebar = String::new();
4160     let fields = get_struct_fields_name(&s.fields);
4161
4162     if !fields.is_empty() {
4163         if let doctree::Plain = s.struct_type {
4164             sidebar.push_str(&format!(
4165                 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4166                                        <div class=\"sidebar-links\">{}</div>",
4167                 fields
4168             ));
4169         }
4170     }
4171
4172     sidebar.push_str(&sidebar_assoc_items(it));
4173
4174     if !sidebar.is_empty() {
4175         write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4176     }
4177 }
4178
4179 fn get_id_for_impl_on_foreign_type(for_: &clean::Type, trait_: &clean::Type) -> String {
4180     small_url_encode(&format!("impl-{:#}-for-{:#}", trait_.print(), for_.print()))
4181 }
4182
4183 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
4184     match item.inner {
4185         clean::ItemEnum::ImplItem(ref i) => {
4186             if let Some(ref trait_) = i.trait_ {
4187                 Some((
4188                     format!("{:#}", i.for_.print()),
4189                     get_id_for_impl_on_foreign_type(&i.for_, trait_),
4190                 ))
4191             } else {
4192                 None
4193             }
4194         }
4195         _ => None,
4196     }
4197 }
4198
4199 fn is_negative_impl(i: &clean::Impl) -> bool {
4200     i.polarity == Some(clean::ImplPolarity::Negative)
4201 }
4202
4203 fn sidebar_trait(buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
4204     let mut sidebar = String::new();
4205
4206     let mut types = t
4207         .items
4208         .iter()
4209         .filter_map(|m| match m.name {
4210             Some(ref name) if m.is_associated_type() => {
4211                 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>", name = name))
4212             }
4213             _ => None,
4214         })
4215         .collect::<Vec<_>>();
4216     let mut consts = t
4217         .items
4218         .iter()
4219         .filter_map(|m| match m.name {
4220             Some(ref name) if m.is_associated_const() => {
4221                 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>", name = name))
4222             }
4223             _ => None,
4224         })
4225         .collect::<Vec<_>>();
4226     let mut required = t
4227         .items
4228         .iter()
4229         .filter_map(|m| match m.name {
4230             Some(ref name) if m.is_ty_method() => {
4231                 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>", name = name))
4232             }
4233             _ => None,
4234         })
4235         .collect::<Vec<String>>();
4236     let mut provided = t
4237         .items
4238         .iter()
4239         .filter_map(|m| match m.name {
4240             Some(ref name) if m.is_method() => {
4241                 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
4242             }
4243             _ => None,
4244         })
4245         .collect::<Vec<String>>();
4246
4247     if !types.is_empty() {
4248         types.sort();
4249         sidebar.push_str(&format!(
4250             "<a class=\"sidebar-title\" href=\"#associated-types\">\
4251                 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4252             types.join("")
4253         ));
4254     }
4255     if !consts.is_empty() {
4256         consts.sort();
4257         sidebar.push_str(&format!(
4258             "<a class=\"sidebar-title\" href=\"#associated-const\">\
4259                 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4260             consts.join("")
4261         ));
4262     }
4263     if !required.is_empty() {
4264         required.sort();
4265         sidebar.push_str(&format!(
4266             "<a class=\"sidebar-title\" href=\"#required-methods\">\
4267                 Required Methods</a><div class=\"sidebar-links\">{}</div>",
4268             required.join("")
4269         ));
4270     }
4271     if !provided.is_empty() {
4272         provided.sort();
4273         sidebar.push_str(&format!(
4274             "<a class=\"sidebar-title\" href=\"#provided-methods\">\
4275                 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
4276             provided.join("")
4277         ));
4278     }
4279
4280     let c = cache();
4281
4282     if let Some(implementors) = c.implementors.get(&it.def_id) {
4283         let mut res = implementors
4284             .iter()
4285             .filter(|i| i.inner_impl().for_.def_id().map_or(false, |d| !c.paths.contains_key(&d)))
4286             .filter_map(|i| extract_for_impl_name(&i.impl_item))
4287             .collect::<Vec<_>>();
4288
4289         if !res.is_empty() {
4290             res.sort();
4291             sidebar.push_str(&format!(
4292                 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4293                     Implementations on Foreign Types</a><div \
4294                     class=\"sidebar-links\">{}</div>",
4295                 res.into_iter()
4296                     .map(|(name, id)| format!("<a href=\"#{}\">{}</a>", id, Escape(&name)))
4297                     .collect::<Vec<_>>()
4298                     .join("")
4299             ));
4300         }
4301     }
4302
4303     sidebar.push_str(&sidebar_assoc_items(it));
4304
4305     sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
4306     if t.auto {
4307         sidebar.push_str(
4308             "<a class=\"sidebar-title\" \
4309                 href=\"#synthetic-implementors\">Auto Implementors</a>",
4310         );
4311     }
4312
4313     write!(buf, "<div class=\"block items\">{}</div>", sidebar)
4314 }
4315
4316 fn sidebar_primitive(buf: &mut Buffer, it: &clean::Item) {
4317     let sidebar = sidebar_assoc_items(it);
4318
4319     if !sidebar.is_empty() {
4320         write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4321     }
4322 }
4323
4324 fn sidebar_typedef(buf: &mut Buffer, it: &clean::Item) {
4325     let sidebar = sidebar_assoc_items(it);
4326
4327     if !sidebar.is_empty() {
4328         write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4329     }
4330 }
4331
4332 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4333     let mut fields = fields
4334         .iter()
4335         .filter(|f| if let clean::StructFieldItem(..) = f.inner { true } else { false })
4336         .filter_map(|f| match f.name {
4337             Some(ref name) => {
4338                 Some(format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
4339             }
4340             _ => None,
4341         })
4342         .collect::<Vec<_>>();
4343     fields.sort();
4344     fields.join("")
4345 }
4346
4347 fn sidebar_union(buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
4348     let mut sidebar = String::new();
4349     let fields = get_struct_fields_name(&u.fields);
4350
4351     if !fields.is_empty() {
4352         sidebar.push_str(&format!(
4353             "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4354              <div class=\"sidebar-links\">{}</div>",
4355             fields
4356         ));
4357     }
4358
4359     sidebar.push_str(&sidebar_assoc_items(it));
4360
4361     if !sidebar.is_empty() {
4362         write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4363     }
4364 }
4365
4366 fn sidebar_enum(buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
4367     let mut sidebar = String::new();
4368
4369     let mut variants = e
4370         .variants
4371         .iter()
4372         .filter_map(|v| match v.name {
4373             Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
4374             _ => None,
4375         })
4376         .collect::<Vec<_>>();
4377     if !variants.is_empty() {
4378         variants.sort_unstable();
4379         sidebar.push_str(&format!(
4380             "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4381              <div class=\"sidebar-links\">{}</div>",
4382             variants.join(""),
4383         ));
4384     }
4385
4386     sidebar.push_str(&sidebar_assoc_items(it));
4387
4388     if !sidebar.is_empty() {
4389         write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4390     }
4391 }
4392
4393 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4394     match *ty {
4395         ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
4396         ItemType::Module => ("modules", "Modules"),
4397         ItemType::Struct => ("structs", "Structs"),
4398         ItemType::Union => ("unions", "Unions"),
4399         ItemType::Enum => ("enums", "Enums"),
4400         ItemType::Function => ("functions", "Functions"),
4401         ItemType::Typedef => ("types", "Type Definitions"),
4402         ItemType::Static => ("statics", "Statics"),
4403         ItemType::Constant => ("constants", "Constants"),
4404         ItemType::Trait => ("traits", "Traits"),
4405         ItemType::Impl => ("impls", "Implementations"),
4406         ItemType::TyMethod => ("tymethods", "Type Methods"),
4407         ItemType::Method => ("methods", "Methods"),
4408         ItemType::StructField => ("fields", "Struct Fields"),
4409         ItemType::Variant => ("variants", "Variants"),
4410         ItemType::Macro => ("macros", "Macros"),
4411         ItemType::Primitive => ("primitives", "Primitive Types"),
4412         ItemType::AssocType => ("associated-types", "Associated Types"),
4413         ItemType::AssocConst => ("associated-consts", "Associated Constants"),
4414         ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4415         ItemType::Keyword => ("keywords", "Keywords"),
4416         ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
4417         ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4418         ItemType::ProcDerive => ("derives", "Derive Macros"),
4419         ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
4420     }
4421 }
4422
4423 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
4424     let mut sidebar = String::new();
4425
4426     if items.iter().any(|it| it.type_() == ItemType::ExternCrate || it.type_() == ItemType::Import)
4427     {
4428         sidebar.push_str(&format!(
4429             "<li><a href=\"#{id}\">{name}</a></li>",
4430             id = "reexports",
4431             name = "Re-exports"
4432         ));
4433     }
4434
4435     // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4436     // to print its headings
4437     for &myty in &[
4438         ItemType::Primitive,
4439         ItemType::Module,
4440         ItemType::Macro,
4441         ItemType::Struct,
4442         ItemType::Enum,
4443         ItemType::Constant,
4444         ItemType::Static,
4445         ItemType::Trait,
4446         ItemType::Function,
4447         ItemType::Typedef,
4448         ItemType::Union,
4449         ItemType::Impl,
4450         ItemType::TyMethod,
4451         ItemType::Method,
4452         ItemType::StructField,
4453         ItemType::Variant,
4454         ItemType::AssocType,
4455         ItemType::AssocConst,
4456         ItemType::ForeignType,
4457         ItemType::Keyword,
4458     ] {
4459         if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
4460             let (short, name) = item_ty_to_strs(&myty);
4461             sidebar.push_str(&format!(
4462                 "<li><a href=\"#{id}\">{name}</a></li>",
4463                 id = short,
4464                 name = name
4465             ));
4466         }
4467     }
4468
4469     if !sidebar.is_empty() {
4470         write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
4471     }
4472 }
4473
4474 fn sidebar_foreign_type(buf: &mut Buffer, it: &clean::Item) {
4475     let sidebar = sidebar_assoc_items(it);
4476     if !sidebar.is_empty() {
4477         write!(buf, "<div class=\"block items\">{}</div>", sidebar);
4478     }
4479 }
4480
4481 fn item_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Macro) {
4482     wrap_into_docblock(w, |w| {
4483         w.write_str(&highlight::render_with_highlighting(
4484             t.source.clone(),
4485             Some("macro"),
4486             None,
4487             None,
4488         ))
4489     });
4490     document(w, cx, it)
4491 }
4492
4493 fn item_proc_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, m: &clean::ProcMacro) {
4494     let name = it.name.as_ref().expect("proc-macros always have names");
4495     match m.kind {
4496         MacroKind::Bang => {
4497             write!(w, "<pre class='rust macro'>");
4498             write!(w, "{}!() {{ /* proc-macro */ }}", name);
4499             write!(w, "</pre>");
4500         }
4501         MacroKind::Attr => {
4502             write!(w, "<pre class='rust attr'>");
4503             write!(w, "#[{}]", name);
4504             write!(w, "</pre>");
4505         }
4506         MacroKind::Derive => {
4507             write!(w, "<pre class='rust derive'>");
4508             write!(w, "#[derive({})]", name);
4509             if !m.helpers.is_empty() {
4510                 writeln!(w, "\n{{");
4511                 writeln!(w, "    // Attributes available to this derive:");
4512                 for attr in &m.helpers {
4513                     writeln!(w, "    #[{}]", attr);
4514                 }
4515                 write!(w, "}}");
4516             }
4517             write!(w, "</pre>");
4518         }
4519     }
4520     document(w, cx, it)
4521 }
4522
4523 fn item_primitive(w: &mut Buffer, cx: &Context, it: &clean::Item, cache: &Cache) {
4524     document(w, cx, it);
4525     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All, cache)
4526 }
4527
4528 fn item_keyword(w: &mut Buffer, cx: &Context, it: &clean::Item) {
4529     document(w, cx, it)
4530 }
4531
4532 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
4533
4534 fn make_item_keywords(it: &clean::Item) -> String {
4535     format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4536 }
4537
4538 /// Returns a list of all paths used in the type.
4539 /// This is used to help deduplicate imported impls
4540 /// for reexported types. If any of the contained
4541 /// types are re-exported, we don't use the corresponding
4542 /// entry from the js file, as inlining will have already
4543 /// picked up the impl
4544 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4545     let mut out = Vec::new();
4546     let mut visited = FxHashSet::default();
4547     let mut work = VecDeque::new();
4548     let cache = cache();
4549
4550     work.push_back(first_ty);
4551
4552     while let Some(ty) = work.pop_front() {
4553         if !visited.insert(ty.clone()) {
4554             continue;
4555         }
4556
4557         match ty {
4558             clean::Type::ResolvedPath { did, .. } => {
4559                 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4560                 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4561
4562                 if let Some(path) = fqp {
4563                     out.push(path.join("::"));
4564                 }
4565             }
4566             clean::Type::Tuple(tys) => {
4567                 work.extend(tys.into_iter());
4568             }
4569             clean::Type::Slice(ty) => {
4570                 work.push_back(*ty);
4571             }
4572             clean::Type::Array(ty, _) => {
4573                 work.push_back(*ty);
4574             }
4575             clean::Type::RawPointer(_, ty) => {
4576                 work.push_back(*ty);
4577             }
4578             clean::Type::BorrowedRef { type_, .. } => {
4579                 work.push_back(*type_);
4580             }
4581             clean::Type::QPath { self_type, trait_, .. } => {
4582                 work.push_back(*self_type);
4583                 work.push_back(*trait_);
4584             }
4585             _ => {}
4586         }
4587     }
4588     out
4589 }