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