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