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