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