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