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