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