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