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