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