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