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