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