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