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