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