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