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