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