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