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