]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/render.rs
Merge branch 'bump_installer' of https://github.com/Eijebong/rust into update-cargo
[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 "main.css" becomes
133     /// "main-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 "main.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!("main{}.css", cx.shared.resource_suffix)),
765           include_bytes!("static/themes/main.css"))?;
766     themes.insert("main".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_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 impl<'a> fmt::Display for Item<'a> {
1679     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1680         debug_assert!(!self.item.is_stripped());
1681         // Write the breadcrumb trail header for the top
1682         write!(fmt, "\n<h1 class='fqn'><span class='in-band'>")?;
1683         match self.item.inner {
1684             clean::ModuleItem(ref m) => if m.is_crate {
1685                     write!(fmt, "Crate ")?;
1686                 } else {
1687                     write!(fmt, "Module ")?;
1688                 },
1689             clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
1690             clean::TraitItem(..) => write!(fmt, "Trait ")?,
1691             clean::StructItem(..) => write!(fmt, "Struct ")?,
1692             clean::UnionItem(..) => write!(fmt, "Union ")?,
1693             clean::EnumItem(..) => write!(fmt, "Enum ")?,
1694             clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
1695             clean::MacroItem(..) => write!(fmt, "Macro ")?,
1696             clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
1697             clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
1698             clean::ConstantItem(..) => write!(fmt, "Constant ")?,
1699             clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
1700             _ => {
1701                 // We don't generate pages for any other type.
1702                 unreachable!();
1703             }
1704         }
1705         if !self.item.is_primitive() {
1706             let cur = &self.cx.current;
1707             let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
1708             for (i, component) in cur.iter().enumerate().take(amt) {
1709                 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
1710                        repeat("../").take(cur.len() - i - 1)
1711                                     .collect::<String>(),
1712                        component)?;
1713             }
1714         }
1715         write!(fmt, "<a class=\"{}\" href=''>{}</a>",
1716                self.item.type_(), self.item.name.as_ref().unwrap())?;
1717
1718         write!(fmt, "</span>")?; // in-band
1719         write!(fmt, "<span class='out-of-band'>")?;
1720         if let Some(version) = self.item.stable_since() {
1721             write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1722                    version)?;
1723         }
1724         write!(fmt,
1725                r##"<span id='render-detail'>
1726                    <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
1727                        [<span class='inner'>&#x2212;</span>]
1728                    </a>
1729                </span>"##)?;
1730
1731         // Write `src` tag
1732         //
1733         // When this item is part of a `pub use` in a downstream crate, the
1734         // [src] link in the downstream documentation will actually come back to
1735         // this page, and this link will be auto-clicked. The `id` attribute is
1736         // used to find the link to auto-click.
1737         if self.cx.shared.include_sources && !self.item.is_primitive() {
1738             if let Some(l) = self.src_href() {
1739                 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
1740                        l, "goto source code")?;
1741             }
1742         }
1743
1744         write!(fmt, "</span>")?; // out-of-band
1745
1746         write!(fmt, "</h1>\n")?;
1747
1748         match self.item.inner {
1749             clean::ModuleItem(ref m) => {
1750                 item_module(fmt, self.cx, self.item, &m.items)
1751             }
1752             clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1753                 item_function(fmt, self.cx, self.item, f),
1754             clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1755             clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
1756             clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
1757             clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
1758             clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
1759             clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
1760             clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
1761             clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1762                 item_static(fmt, self.cx, self.item, i),
1763             clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
1764             clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
1765             _ => {
1766                 // We don't generate pages for any other type.
1767                 unreachable!();
1768             }
1769         }
1770     }
1771 }
1772
1773 fn item_path(ty: ItemType, name: &str) -> String {
1774     match ty {
1775         ItemType::Module => format!("{}/index.html", name),
1776         _ => format!("{}.{}.html", ty.css_class(), name),
1777     }
1778 }
1779
1780 fn full_path(cx: &Context, item: &clean::Item) -> String {
1781     let mut s = cx.current.join("::");
1782     s.push_str("::");
1783     s.push_str(item.name.as_ref().unwrap());
1784     s
1785 }
1786
1787 fn shorter<'a>(s: Option<&'a str>) -> String {
1788     match s {
1789         Some(s) => s.lines()
1790             .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
1791             .take_while(|line|{
1792             (*line).chars().any(|chr|{
1793                 !chr.is_whitespace()
1794             })
1795         }).collect::<Vec<_>>().join("\n"),
1796         None => "".to_string()
1797     }
1798 }
1799
1800 #[inline]
1801 fn plain_summary_line(s: Option<&str>) -> String {
1802     let line = shorter(s).replace("\n", " ");
1803     markdown::plain_summary_line(&line[..])
1804 }
1805
1806 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1807     if let Some(ref name) = item.name {
1808         info!("Documenting {}", name);
1809     }
1810     document_stability(w, cx, item)?;
1811     let prefix = render_assoc_const_value(item);
1812     document_full(w, item, cx, &prefix)?;
1813     Ok(())
1814 }
1815
1816 /// Render md_text as markdown.
1817 fn render_markdown(w: &mut fmt::Formatter,
1818                    md_text: &str,
1819                    links: Vec<(String, String)>,
1820                    prefix: &str,)
1821                    -> fmt::Result {
1822     write!(w, "<div class='docblock'>{}{}</div>", prefix, Markdown(md_text, &links))
1823 }
1824
1825 fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink,
1826                   prefix: &str) -> fmt::Result {
1827     if let Some(s) = item.doc_value() {
1828         let markdown = if s.contains('\n') {
1829             format!("{} [Read more]({})",
1830                     &plain_summary_line(Some(s)), naive_assoc_href(item, link))
1831         } else {
1832             format!("{}", &plain_summary_line(Some(s)))
1833         };
1834         render_markdown(w, &markdown, item.links(), prefix)?;
1835     } else if !prefix.is_empty() {
1836         write!(w, "<div class='docblock'>{}</div>", prefix)?;
1837     }
1838     Ok(())
1839 }
1840
1841 fn render_assoc_const_value(item: &clean::Item) -> String {
1842     match item.inner {
1843         clean::AssociatedConstItem(ref ty, Some(ref default)) => {
1844             highlight::render_with_highlighting(
1845                 &format!("{}: {:#} = {}", item.name.as_ref().unwrap(), ty, default),
1846                 None,
1847                 None,
1848                 None,
1849                 None,
1850             )
1851         }
1852         _ => String::new(),
1853     }
1854 }
1855
1856 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
1857                  cx: &Context, prefix: &str) -> fmt::Result {
1858     if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1859         debug!("Doc block: =====\n{}\n=====", s);
1860         render_markdown(w, &*s, item.links(), prefix)?;
1861     } else if !prefix.is_empty() {
1862         write!(w, "<div class='docblock'>{}</div>", prefix)?;
1863     }
1864     Ok(())
1865 }
1866
1867 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1868     let stabilities = short_stability(item, cx, true);
1869     if !stabilities.is_empty() {
1870         write!(w, "<div class='stability'>")?;
1871         for stability in stabilities {
1872             write!(w, "{}", stability)?;
1873         }
1874         write!(w, "</div>")?;
1875     }
1876     Ok(())
1877 }
1878
1879 fn name_key(name: &str) -> (&str, u64, usize) {
1880     // find number at end
1881     let split = name.bytes().rposition(|b| b < b'0' || b'9' < b).map_or(0, |s| s + 1);
1882
1883     // count leading zeroes
1884     let after_zeroes =
1885         name[split..].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
1886
1887     // sort leading zeroes last
1888     let num_zeroes = after_zeroes - split;
1889
1890     match name[split..].parse() {
1891         Ok(n) => (&name[..split], n, num_zeroes),
1892         Err(_) => (name, 0, num_zeroes),
1893     }
1894 }
1895
1896 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1897                item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1898     document(w, cx, item)?;
1899
1900     let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
1901
1902     // the order of item types in the listing
1903     fn reorder(ty: ItemType) -> u8 {
1904         match ty {
1905             ItemType::ExternCrate     => 0,
1906             ItemType::Import          => 1,
1907             ItemType::Primitive       => 2,
1908             ItemType::Module          => 3,
1909             ItemType::Macro           => 4,
1910             ItemType::Struct          => 5,
1911             ItemType::Enum            => 6,
1912             ItemType::Constant        => 7,
1913             ItemType::Static          => 8,
1914             ItemType::Trait           => 9,
1915             ItemType::Function        => 10,
1916             ItemType::Typedef         => 12,
1917             ItemType::Union           => 13,
1918             _                         => 14 + ty as u8,
1919         }
1920     }
1921
1922     fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1923         let ty1 = i1.type_();
1924         let ty2 = i2.type_();
1925         if ty1 != ty2 {
1926             return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1927         }
1928         let s1 = i1.stability.as_ref().map(|s| s.level);
1929         let s2 = i2.stability.as_ref().map(|s| s.level);
1930         match (s1, s2) {
1931             (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1932             (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1933             _ => {}
1934         }
1935         let lhs = i1.name.as_ref().map_or("", |s| &**s);
1936         let rhs = i2.name.as_ref().map_or("", |s| &**s);
1937         name_key(lhs).cmp(&name_key(rhs))
1938     }
1939
1940     if cx.shared.sort_modules_alphabetically {
1941         indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1942     }
1943     // This call is to remove re-export duplicates in cases such as:
1944     //
1945     // ```
1946     // pub mod foo {
1947     //     pub mod bar {
1948     //         pub trait Double { fn foo(); }
1949     //     }
1950     // }
1951     //
1952     // pub use foo::bar::*;
1953     // pub use foo::*;
1954     // ```
1955     //
1956     // `Double` will appear twice in the generated docs.
1957     //
1958     // FIXME: This code is quite ugly and could be improved. Small issue: DefId
1959     // can be identical even if the elements are different (mostly in imports).
1960     // So in case this is an import, we keep everything by adding a "unique id"
1961     // (which is the position in the vector).
1962     indices.dedup_by_key(|i| (items[*i].def_id,
1963                               if items[*i].name.as_ref().is_some() {
1964                                   Some(full_path(cx, &items[*i]).clone())
1965                               } else {
1966                                   None
1967                               },
1968                               items[*i].type_(),
1969                               if items[*i].is_import() {
1970                                   *i
1971                               } else {
1972                                   0
1973                               }));
1974
1975     debug!("{:?}", indices);
1976     let mut curty = None;
1977     for &idx in &indices {
1978         let myitem = &items[idx];
1979         if myitem.is_stripped() {
1980             continue;
1981         }
1982
1983         let myty = Some(myitem.type_());
1984         if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
1985             // Put `extern crate` and `use` re-exports in the same section.
1986             curty = myty;
1987         } else if myty != curty {
1988             if curty.is_some() {
1989                 write!(w, "</table>")?;
1990             }
1991             curty = myty;
1992             let (short, name) = match myty.unwrap() {
1993                 ItemType::ExternCrate |
1994                 ItemType::Import          => ("reexports", "Re-exports"),
1995                 ItemType::Module          => ("modules", "Modules"),
1996                 ItemType::Struct          => ("structs", "Structs"),
1997                 ItemType::Union           => ("unions", "Unions"),
1998                 ItemType::Enum            => ("enums", "Enums"),
1999                 ItemType::Function        => ("functions", "Functions"),
2000                 ItemType::Typedef         => ("types", "Type Definitions"),
2001                 ItemType::Static          => ("statics", "Statics"),
2002                 ItemType::Constant        => ("constants", "Constants"),
2003                 ItemType::Trait           => ("traits", "Traits"),
2004                 ItemType::Impl            => ("impls", "Implementations"),
2005                 ItemType::TyMethod        => ("tymethods", "Type Methods"),
2006                 ItemType::Method          => ("methods", "Methods"),
2007                 ItemType::StructField     => ("fields", "Struct Fields"),
2008                 ItemType::Variant         => ("variants", "Variants"),
2009                 ItemType::Macro           => ("macros", "Macros"),
2010                 ItemType::Primitive       => ("primitives", "Primitive Types"),
2011                 ItemType::AssociatedType  => ("associated-types", "Associated Types"),
2012                 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
2013                 ItemType::ForeignType     => ("foreign-types", "Foreign Types"),
2014             };
2015             write!(w, "<h2 id='{id}' class='section-header'>\
2016                        <a href=\"#{id}\">{name}</a></h2>\n<table>",
2017                    id = derive_id(short.to_owned()), name = name)?;
2018         }
2019
2020         match myitem.inner {
2021             clean::ExternCrateItem(ref name, ref src) => {
2022                 use html::format::HRef;
2023
2024                 match *src {
2025                     Some(ref src) => {
2026                         write!(w, "<tr><td><code>{}extern crate {} as {};",
2027                                VisSpace(&myitem.visibility),
2028                                HRef::new(myitem.def_id, src),
2029                                name)?
2030                     }
2031                     None => {
2032                         write!(w, "<tr><td><code>{}extern crate {};",
2033                                VisSpace(&myitem.visibility),
2034                                HRef::new(myitem.def_id, name))?
2035                     }
2036                 }
2037                 write!(w, "</code></td></tr>")?;
2038             }
2039
2040             clean::ImportItem(ref import) => {
2041                 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2042                        VisSpace(&myitem.visibility), *import)?;
2043             }
2044
2045             _ => {
2046                 if myitem.name.is_none() { continue }
2047
2048                 let stabilities = short_stability(myitem, cx, false);
2049
2050                 let stab_docs = if !stabilities.is_empty() {
2051                     stabilities.iter()
2052                                .map(|s| format!("[{}]", s))
2053                                .collect::<Vec<_>>()
2054                                .as_slice()
2055                                .join(" ")
2056                 } else {
2057                     String::new()
2058                 };
2059
2060                 let unsafety_flag = match myitem.inner {
2061                     clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2062                     if func.unsafety == hir::Unsafety::Unsafe => {
2063                         "<a title='unsafe function' href='#'><sup>âš </sup></a>"
2064                     }
2065                     _ => "",
2066                 };
2067
2068                 let doc_value = myitem.doc_value().unwrap_or("");
2069                 write!(w, "
2070                        <tr class='{stab} module-item'>
2071                            <td><a class=\"{class}\" href=\"{href}\"
2072                                   title='{title_type} {title}'>{name}</a>{unsafety_flag}</td>
2073                            <td class='docblock-short'>
2074                                {stab_docs} {docs}
2075                            </td>
2076                        </tr>",
2077                        name = *myitem.name.as_ref().unwrap(),
2078                        stab_docs = stab_docs,
2079                        docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2080                        class = myitem.type_(),
2081                        stab = myitem.stability_class().unwrap_or("".to_string()),
2082                        unsafety_flag = unsafety_flag,
2083                        href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2084                        title_type = myitem.type_(),
2085                        title = full_path(cx, myitem))?;
2086             }
2087         }
2088     }
2089
2090     if curty.is_some() {
2091         write!(w, "</table>")?;
2092     }
2093     Ok(())
2094 }
2095
2096 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
2097     let mut stability = vec![];
2098
2099     if let Some(stab) = item.stability.as_ref() {
2100         let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
2101             format!(": {}", stab.deprecated_reason)
2102         } else {
2103             String::new()
2104         };
2105         if !stab.deprecated_since.is_empty() {
2106             let since = if show_reason {
2107                 format!(" since {}", Escape(&stab.deprecated_since))
2108             } else {
2109                 String::new()
2110             };
2111             let text = format!("Deprecated{}{}",
2112                                since,
2113                                MarkdownHtml(&deprecated_reason));
2114             stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2115         };
2116
2117         if stab.level == stability::Unstable {
2118             if show_reason {
2119                 let unstable_extra = match (!stab.feature.is_empty(),
2120                                             &cx.shared.issue_tracker_base_url,
2121                                             stab.issue) {
2122                     (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2123                         format!(" (<code>{} </code><a href=\"{}{}\">#{}</a>)",
2124                                 Escape(&stab.feature), tracker_url, issue_no, issue_no),
2125                     (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2126                         format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
2127                                 issue_no),
2128                     (true, ..) =>
2129                         format!(" (<code>{}</code>)", Escape(&stab.feature)),
2130                     _ => String::new(),
2131                 };
2132                 if stab.unstable_reason.is_empty() {
2133                     stability.push(format!("<div class='stab unstable'>\
2134                                             <span class=microscope>🔬</span> \
2135                                             This is a nightly-only experimental API. {}\
2136                                             </div>",
2137                                            unstable_extra));
2138                 } else {
2139                     let text = format!("<summary><span class=microscope>🔬</span> \
2140                                         This is a nightly-only experimental API. {}\
2141                                         </summary>{}",
2142                                        unstable_extra,
2143                                        MarkdownHtml(&stab.unstable_reason));
2144                     stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
2145                                    text));
2146                 }
2147             } else {
2148                 stability.push(format!("<div class='stab unstable'>Experimental</div>"))
2149             }
2150         };
2151     } else if let Some(depr) = item.deprecation.as_ref() {
2152         let note = if show_reason && !depr.note.is_empty() {
2153             format!(": {}", depr.note)
2154         } else {
2155             String::new()
2156         };
2157         let since = if show_reason && !depr.since.is_empty() {
2158             format!(" since {}", Escape(&depr.since))
2159         } else {
2160             String::new()
2161         };
2162
2163         let text = format!("Deprecated{}{}", since, MarkdownHtml(&note));
2164         stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2165     }
2166
2167     if let Some(ref cfg) = item.attrs.cfg {
2168         stability.push(format!("<div class='stab portability'>{}</div>", if show_reason {
2169             cfg.render_long_html()
2170         } else {
2171             cfg.render_short_html()
2172         }));
2173     }
2174
2175     stability
2176 }
2177
2178 struct Initializer<'a>(&'a str);
2179
2180 impl<'a> fmt::Display for Initializer<'a> {
2181     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2182         let Initializer(s) = *self;
2183         if s.is_empty() { return Ok(()); }
2184         write!(f, "<code> = </code>")?;
2185         write!(f, "<code>{}</code>", Escape(s))
2186     }
2187 }
2188
2189 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2190                  c: &clean::Constant) -> fmt::Result {
2191     write!(w, "<pre class='rust const'>")?;
2192     render_attributes(w, it)?;
2193     write!(w, "{vis}const \
2194                {name}: {typ}{init}</pre>",
2195            vis = VisSpace(&it.visibility),
2196            name = it.name.as_ref().unwrap(),
2197            typ = c.type_,
2198            init = Initializer(&c.expr))?;
2199     document(w, cx, it)
2200 }
2201
2202 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2203                s: &clean::Static) -> fmt::Result {
2204     write!(w, "<pre class='rust static'>")?;
2205     render_attributes(w, it)?;
2206     write!(w, "{vis}static {mutability}\
2207                {name}: {typ}{init}</pre>",
2208            vis = VisSpace(&it.visibility),
2209            mutability = MutableSpace(s.mutability),
2210            name = it.name.as_ref().unwrap(),
2211            typ = s.type_,
2212            init = Initializer(&s.expr))?;
2213     document(w, cx, it)
2214 }
2215
2216 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2217                  f: &clean::Function) -> fmt::Result {
2218     let name_len = format!("{}{}{}{:#}fn {}{:#}",
2219                            VisSpace(&it.visibility),
2220                            ConstnessSpace(f.constness),
2221                            UnsafetySpace(f.unsafety),
2222                            AbiSpace(f.abi),
2223                            it.name.as_ref().unwrap(),
2224                            f.generics).len();
2225     write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
2226     render_attributes(w, it)?;
2227     write!(w,
2228            "{vis}{constness}{unsafety}{abi}fn {name}{generics}{decl}{where_clause}</pre>",
2229            vis = VisSpace(&it.visibility),
2230            constness = ConstnessSpace(f.constness),
2231            unsafety = UnsafetySpace(f.unsafety),
2232            abi = AbiSpace(f.abi),
2233            name = it.name.as_ref().unwrap(),
2234            generics = f.generics,
2235            where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2236            decl = Method {
2237               decl: &f.decl,
2238               name_len,
2239               indent: 0,
2240            })?;
2241     document(w, cx, it)
2242 }
2243
2244 fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter,
2245                       implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> Result<(), fmt::Error> {
2246     write!(w, "<li>")?;
2247     if let Some(l) = (Item { cx, item: &implementor.impl_item }).src_href() {
2248         write!(w, "<div class='out-of-band'>")?;
2249         write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2250                     l, "goto source code")?;
2251         write!(w, "</div>")?;
2252     }
2253     write!(w, "<code>")?;
2254     // If there's already another implementor that has the same abbridged name, use the
2255     // full path, for example in `std::iter::ExactSizeIterator`
2256     let use_absolute = match implementor.inner_impl().for_ {
2257         clean::ResolvedPath { ref path, is_generic: false, .. } |
2258         clean::BorrowedRef {
2259             type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2260             ..
2261         } => implementor_dups[path.last_name()].1,
2262         _ => false,
2263     };
2264     fmt_impl_for_trait_page(&implementor.inner_impl(), w, use_absolute)?;
2265     for it in &implementor.inner_impl().items {
2266         if let clean::TypedefItem(ref tydef, _) = it.inner {
2267             write!(w, "<span class=\"where fmt-newline\">  ")?;
2268             assoc_type(w, it, &vec![], Some(&tydef.type_), AssocItemLink::Anchor(None))?;
2269             write!(w, ";</span>")?;
2270         }
2271     }
2272     writeln!(w, "</code></li>")?;
2273     Ok(())
2274 }
2275
2276 fn render_impls(cx: &Context, w: &mut fmt::Formatter,
2277                 traits: Vec<&&Impl>,
2278                 containing_item: &clean::Item) -> Result<(), fmt::Error> {
2279     for i in &traits {
2280         let did = i.trait_did().unwrap();
2281         let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2282         render_impl(w, cx, i, assoc_link,
2283                     RenderMode::Normal, containing_item.stable_since(), true)?;
2284     }
2285     Ok(())
2286 }
2287
2288 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2289               t: &clean::Trait) -> fmt::Result {
2290     let mut bounds = String::new();
2291     let mut bounds_plain = String::new();
2292     if !t.bounds.is_empty() {
2293         if !bounds.is_empty() {
2294             bounds.push(' ');
2295             bounds_plain.push(' ');
2296         }
2297         bounds.push_str(": ");
2298         bounds_plain.push_str(": ");
2299         for (i, p) in t.bounds.iter().enumerate() {
2300             if i > 0 {
2301                 bounds.push_str(" + ");
2302                 bounds_plain.push_str(" + ");
2303             }
2304             bounds.push_str(&format!("{}", *p));
2305             bounds_plain.push_str(&format!("{:#}", *p));
2306         }
2307     }
2308
2309     // Output the trait definition
2310     write!(w, "<pre class='rust trait'>")?;
2311     render_attributes(w, it)?;
2312     write!(w, "{}{}{}trait {}{}{}",
2313            VisSpace(&it.visibility),
2314            UnsafetySpace(t.unsafety),
2315            if t.is_auto { "auto " } else { "" },
2316            it.name.as_ref().unwrap(),
2317            t.generics,
2318            bounds)?;
2319
2320     if !t.generics.where_predicates.is_empty() {
2321         write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
2322     } else {
2323         write!(w, " ")?;
2324     }
2325
2326     let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2327     let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2328     let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2329     let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2330
2331     if t.items.is_empty() {
2332         write!(w, "{{ }}")?;
2333     } else {
2334         // FIXME: we should be using a derived_id for the Anchors here
2335         write!(w, "{{\n")?;
2336         for t in &types {
2337             write!(w, "    ")?;
2338             render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2339             write!(w, ";\n")?;
2340         }
2341         if !types.is_empty() && !consts.is_empty() {
2342             w.write_str("\n")?;
2343         }
2344         for t in &consts {
2345             write!(w, "    ")?;
2346             render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2347             write!(w, ";\n")?;
2348         }
2349         if !consts.is_empty() && !required.is_empty() {
2350             w.write_str("\n")?;
2351         }
2352         for (pos, m) in required.iter().enumerate() {
2353             write!(w, "    ")?;
2354             render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2355             write!(w, ";\n")?;
2356
2357             if pos < required.len() - 1 {
2358                write!(w, "<div class='item-spacer'></div>")?;
2359             }
2360         }
2361         if !required.is_empty() && !provided.is_empty() {
2362             w.write_str("\n")?;
2363         }
2364         for (pos, m) in provided.iter().enumerate() {
2365             write!(w, "    ")?;
2366             render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2367             match m.inner {
2368                 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2369                     write!(w, ",\n    {{ ... }}\n")?;
2370                 },
2371                 _ => {
2372                     write!(w, " {{ ... }}\n")?;
2373                 },
2374             }
2375             if pos < provided.len() - 1 {
2376                write!(w, "<div class='item-spacer'></div>")?;
2377             }
2378         }
2379         write!(w, "}}")?;
2380     }
2381     write!(w, "</pre>")?;
2382
2383     // Trait documentation
2384     document(w, cx, it)?;
2385
2386     fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
2387                   -> fmt::Result {
2388         let name = m.name.as_ref().unwrap();
2389         let item_type = m.type_();
2390         let id = derive_id(format!("{}.{}", item_type, name));
2391         let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2392         write!(w, "{extra}<h3 id='{id}' class='method'>\
2393                    <span id='{ns_id}' class='invisible'><code>",
2394                extra = render_spotlight_traits(m)?,
2395                id = id,
2396                ns_id = ns_id)?;
2397         render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
2398         write!(w, "</code>")?;
2399         render_stability_since(w, m, t)?;
2400         write!(w, "</span></h3>")?;
2401         document(w, cx, m)?;
2402         Ok(())
2403     }
2404
2405     if !types.is_empty() {
2406         write!(w, "
2407             <h2 id='associated-types' class='small-section-header'>
2408               Associated Types<a href='#associated-types' class='anchor'></a>
2409             </h2>
2410             <div class='methods'>
2411         ")?;
2412         for t in &types {
2413             trait_item(w, cx, *t, it)?;
2414         }
2415         write!(w, "</div>")?;
2416     }
2417
2418     if !consts.is_empty() {
2419         write!(w, "
2420             <h2 id='associated-const' class='small-section-header'>
2421               Associated Constants<a href='#associated-const' class='anchor'></a>
2422             </h2>
2423             <div class='methods'>
2424         ")?;
2425         for t in &consts {
2426             trait_item(w, cx, *t, it)?;
2427         }
2428         write!(w, "</div>")?;
2429     }
2430
2431     // Output the documentation for each function individually
2432     if !required.is_empty() {
2433         write!(w, "
2434             <h2 id='required-methods' class='small-section-header'>
2435               Required Methods<a href='#required-methods' class='anchor'></a>
2436             </h2>
2437             <div class='methods'>
2438         ")?;
2439         for m in &required {
2440             trait_item(w, cx, *m, it)?;
2441         }
2442         write!(w, "</div>")?;
2443     }
2444     if !provided.is_empty() {
2445         write!(w, "
2446             <h2 id='provided-methods' class='small-section-header'>
2447               Provided Methods<a href='#provided-methods' class='anchor'></a>
2448             </h2>
2449             <div class='methods'>
2450         ")?;
2451         for m in &provided {
2452             trait_item(w, cx, *m, it)?;
2453         }
2454         write!(w, "</div>")?;
2455     }
2456
2457     // If there are methods directly on this trait object, render them here.
2458     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2459
2460     let cache = cache();
2461     let impl_header = "
2462         <h2 id='implementors' class='small-section-header'>
2463           Implementors<a href='#implementors' class='anchor'></a>
2464         </h2>
2465         <ul class='item-list' id='implementors-list'>
2466     ";
2467
2468     let synthetic_impl_header = "
2469         <h2 id='synthetic-implementors' class='small-section-header'>
2470           Auto implementors<a href='#synthetic-implementors' class='anchor'></a>
2471         </h2>
2472         <ul class='item-list' id='synthetic-implementors-list'>
2473     ";
2474
2475     let mut synthetic_types = Vec::new();
2476
2477     if let Some(implementors) = cache.implementors.get(&it.def_id) {
2478         // The DefId is for the first Type found with that name. The bool is
2479         // if any Types with the same name but different DefId have been found.
2480         let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap();
2481         for implementor in implementors {
2482             match implementor.inner_impl().for_ {
2483                 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2484                 clean::BorrowedRef {
2485                     type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2486                     ..
2487                 } => {
2488                     let &mut (prev_did, ref mut has_duplicates) =
2489                         implementor_dups.entry(path.last_name()).or_insert((did, false));
2490                     if prev_did != did {
2491                         *has_duplicates = true;
2492                     }
2493                 }
2494                 _ => {}
2495             }
2496         }
2497
2498         let (local, foreign) = implementors.iter()
2499             .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
2500                                          .map_or(true, |d| cache.paths.contains_key(&d)));
2501
2502
2503         let (synthetic, concrete) = local.iter()
2504             .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
2505
2506
2507         if !foreign.is_empty() {
2508             write!(w, "
2509                 <h2 id='foreign-impls' class='small-section-header'>
2510                   Implementations on Foreign Types<a href='#foreign-impls' class='anchor'></a>
2511                 </h2>
2512             ")?;
2513
2514             for implementor in foreign {
2515                 let assoc_link = AssocItemLink::GotoSource(
2516                     implementor.impl_item.def_id, &implementor.inner_impl().provided_trait_methods
2517                 );
2518                 render_impl(w, cx, &implementor, assoc_link,
2519                             RenderMode::Normal, implementor.impl_item.stable_since(), false)?;
2520             }
2521         }
2522
2523         write!(w, "{}", impl_header)?;
2524         for implementor in concrete {
2525             render_implementor(cx, implementor, w, &implementor_dups)?;
2526         }
2527         write!(w, "</ul>")?;
2528
2529         if t.auto {
2530             write!(w, "{}", synthetic_impl_header)?;
2531             for implementor in synthetic {
2532                 synthetic_types.extend(
2533                     collect_paths_for_type(implementor.inner_impl().for_.clone())
2534                 );
2535                 render_implementor(cx, implementor, w, &implementor_dups)?;
2536             }
2537             write!(w, "</ul>")?;
2538         }
2539     } else {
2540         // even without any implementations to write in, we still want the heading and list, so the
2541         // implementors javascript file pulled in below has somewhere to write the impls into
2542         write!(w, "{}", impl_header)?;
2543         write!(w, "</ul>")?;
2544
2545         if t.auto {
2546             write!(w, "{}", synthetic_impl_header)?;
2547             write!(w, "</ul>")?;
2548         }
2549     }
2550     write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
2551            as_json(&synthetic_types))?;
2552
2553     write!(w, r#"<script type="text/javascript" async
2554                          src="{root_path}/implementors/{path}/{ty}.{name}.js">
2555                  </script>"#,
2556            root_path = vec![".."; cx.current.len()].join("/"),
2557            path = if it.def_id.is_local() {
2558                cx.current.join("/")
2559            } else {
2560                let (ref path, _) = cache.external_paths[&it.def_id];
2561                path[..path.len() - 1].join("/")
2562            },
2563            ty = it.type_().css_class(),
2564            name = *it.name.as_ref().unwrap())?;
2565     Ok(())
2566 }
2567
2568 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2569     use html::item_type::ItemType::*;
2570
2571     let name = it.name.as_ref().unwrap();
2572     let ty = match it.type_() {
2573         Typedef | AssociatedType => AssociatedType,
2574         s@_ => s,
2575     };
2576
2577     let anchor = format!("#{}.{}", ty, name);
2578     match link {
2579         AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2580         AssocItemLink::Anchor(None) => anchor,
2581         AssocItemLink::GotoSource(did, _) => {
2582             href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2583         }
2584     }
2585 }
2586
2587 fn assoc_const(w: &mut fmt::Formatter,
2588                it: &clean::Item,
2589                ty: &clean::Type,
2590                _default: Option<&String>,
2591                link: AssocItemLink) -> fmt::Result {
2592     write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2593            VisSpace(&it.visibility),
2594            naive_assoc_href(it, link),
2595            it.name.as_ref().unwrap(),
2596            ty)?;
2597     Ok(())
2598 }
2599
2600 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
2601                              bounds: &Vec<clean::TyParamBound>,
2602                              default: Option<&clean::Type>,
2603                              link: AssocItemLink) -> fmt::Result {
2604     write!(w, "type <a href='{}' class=\"type\">{}</a>",
2605            naive_assoc_href(it, link),
2606            it.name.as_ref().unwrap())?;
2607     if !bounds.is_empty() {
2608         write!(w, ": {}", TyParamBounds(bounds))?
2609     }
2610     if let Some(default) = default {
2611         write!(w, " = {}", default)?;
2612     }
2613     Ok(())
2614 }
2615
2616 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
2617                                   ver: Option<&'a str>,
2618                                   containing_ver: Option<&'a str>) -> fmt::Result {
2619     if let Some(v) = ver {
2620         if containing_ver != ver && v.len() > 0 {
2621             write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
2622                    v)?
2623         }
2624     }
2625     Ok(())
2626 }
2627
2628 fn render_stability_since(w: &mut fmt::Formatter,
2629                           item: &clean::Item,
2630                           containing_item: &clean::Item) -> fmt::Result {
2631     render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2632 }
2633
2634 fn render_assoc_item(w: &mut fmt::Formatter,
2635                      item: &clean::Item,
2636                      link: AssocItemLink,
2637                      parent: ItemType) -> fmt::Result {
2638     fn method(w: &mut fmt::Formatter,
2639               meth: &clean::Item,
2640               unsafety: hir::Unsafety,
2641               constness: hir::Constness,
2642               abi: abi::Abi,
2643               g: &clean::Generics,
2644               d: &clean::FnDecl,
2645               link: AssocItemLink,
2646               parent: ItemType)
2647               -> fmt::Result {
2648         let name = meth.name.as_ref().unwrap();
2649         let anchor = format!("#{}.{}", meth.type_(), name);
2650         let href = match link {
2651             AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2652             AssocItemLink::Anchor(None) => anchor,
2653             AssocItemLink::GotoSource(did, provided_methods) => {
2654                 // We're creating a link from an impl-item to the corresponding
2655                 // trait-item and need to map the anchored type accordingly.
2656                 let ty = if provided_methods.contains(name) {
2657                     ItemType::Method
2658                 } else {
2659                     ItemType::TyMethod
2660                 };
2661
2662                 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2663             }
2664         };
2665         let mut head_len = format!("{}{}{}{:#}fn {}{:#}",
2666                                    VisSpace(&meth.visibility),
2667                                    ConstnessSpace(constness),
2668                                    UnsafetySpace(unsafety),
2669                                    AbiSpace(abi),
2670                                    name,
2671                                    *g).len();
2672         let (indent, end_newline) = if parent == ItemType::Trait {
2673             head_len += 4;
2674             (4, false)
2675         } else {
2676             (0, true)
2677         };
2678         write!(w, "{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2679                    {generics}{decl}{where_clause}",
2680                VisSpace(&meth.visibility),
2681                ConstnessSpace(constness),
2682                UnsafetySpace(unsafety),
2683                AbiSpace(abi),
2684                href = href,
2685                name = name,
2686                generics = *g,
2687                decl = Method {
2688                    decl: d,
2689                    name_len: head_len,
2690                    indent,
2691                },
2692                where_clause = WhereClause {
2693                    gens: g,
2694                    indent,
2695                    end_newline,
2696                })
2697     }
2698     match item.inner {
2699         clean::StrippedItem(..) => Ok(()),
2700         clean::TyMethodItem(ref m) => {
2701             method(w, item, m.unsafety, hir::Constness::NotConst,
2702                    m.abi, &m.generics, &m.decl, link, parent)
2703         }
2704         clean::MethodItem(ref m) => {
2705             method(w, item, m.unsafety, m.constness,
2706                    m.abi, &m.generics, &m.decl, link, parent)
2707         }
2708         clean::AssociatedConstItem(ref ty, ref default) => {
2709             assoc_const(w, item, ty, default.as_ref(), link)
2710         }
2711         clean::AssociatedTypeItem(ref bounds, ref default) => {
2712             assoc_type(w, item, bounds, default.as_ref(), link)
2713         }
2714         _ => panic!("render_assoc_item called on non-associated-item")
2715     }
2716 }
2717
2718 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2719                s: &clean::Struct) -> fmt::Result {
2720     write!(w, "<pre class='rust struct'>")?;
2721     render_attributes(w, it)?;
2722     render_struct(w,
2723                   it,
2724                   Some(&s.generics),
2725                   s.struct_type,
2726                   &s.fields,
2727                   "",
2728                   true)?;
2729     write!(w, "</pre>")?;
2730
2731     document(w, cx, it)?;
2732     let mut fields = s.fields.iter().filter_map(|f| {
2733         match f.inner {
2734             clean::StructFieldItem(ref ty) => Some((f, ty)),
2735             _ => None,
2736         }
2737     }).peekable();
2738     if let doctree::Plain = s.struct_type {
2739         if fields.peek().is_some() {
2740             write!(w, "<h2 id='fields' class='fields small-section-header'>
2741                        Fields<a href='#fields' class='anchor'></a></h2>")?;
2742             for (field, ty) in fields {
2743                 let id = derive_id(format!("{}.{}",
2744                                            ItemType::StructField,
2745                                            field.name.as_ref().unwrap()));
2746                 let ns_id = derive_id(format!("{}.{}",
2747                                               field.name.as_ref().unwrap(),
2748                                               ItemType::StructField.name_space()));
2749                 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">
2750                            <a href=\"#{id}\" class=\"anchor field\"></a>
2751                            <span id=\"{ns_id}\" class='invisible'>
2752                            <code>{name}: {ty}</code>
2753                            </span></span>",
2754                        item_type = ItemType::StructField,
2755                        id = id,
2756                        ns_id = ns_id,
2757                        name = field.name.as_ref().unwrap(),
2758                        ty = ty)?;
2759                 if let Some(stability_class) = field.stability_class() {
2760                     write!(w, "<span class='stab {stab}'></span>",
2761                         stab = stability_class)?;
2762                 }
2763                 document(w, cx, field)?;
2764             }
2765         }
2766     }
2767     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2768 }
2769
2770 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2771                s: &clean::Union) -> fmt::Result {
2772     write!(w, "<pre class='rust union'>")?;
2773     render_attributes(w, it)?;
2774     render_union(w,
2775                  it,
2776                  Some(&s.generics),
2777                  &s.fields,
2778                  "",
2779                  true)?;
2780     write!(w, "</pre>")?;
2781
2782     document(w, cx, it)?;
2783     let mut fields = s.fields.iter().filter_map(|f| {
2784         match f.inner {
2785             clean::StructFieldItem(ref ty) => Some((f, ty)),
2786             _ => None,
2787         }
2788     }).peekable();
2789     if fields.peek().is_some() {
2790         write!(w, "<h2 id='fields' class='fields small-section-header'>
2791                    Fields<a href='#fields' class='anchor'></a></h2>")?;
2792         for (field, ty) in fields {
2793             write!(w, "<span id='{shortty}.{name}' class=\"{shortty}\"><code>{name}: {ty}</code>
2794                        </span>",
2795                    shortty = ItemType::StructField,
2796                    name = field.name.as_ref().unwrap(),
2797                    ty = ty)?;
2798             if let Some(stability_class) = field.stability_class() {
2799                 write!(w, "<span class='stab {stab}'></span>",
2800                     stab = stability_class)?;
2801             }
2802             document(w, cx, field)?;
2803         }
2804     }
2805     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2806 }
2807
2808 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2809              e: &clean::Enum) -> fmt::Result {
2810     write!(w, "<pre class='rust enum'>")?;
2811     render_attributes(w, it)?;
2812     write!(w, "{}enum {}{}{}",
2813            VisSpace(&it.visibility),
2814            it.name.as_ref().unwrap(),
2815            e.generics,
2816            WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
2817     if e.variants.is_empty() && !e.variants_stripped {
2818         write!(w, " {{}}")?;
2819     } else {
2820         write!(w, " {{\n")?;
2821         for v in &e.variants {
2822             write!(w, "    ")?;
2823             let name = v.name.as_ref().unwrap();
2824             match v.inner {
2825                 clean::VariantItem(ref var) => {
2826                     match var.kind {
2827                         clean::VariantKind::CLike => write!(w, "{}", name)?,
2828                         clean::VariantKind::Tuple(ref tys) => {
2829                             write!(w, "{}(", name)?;
2830                             for (i, ty) in tys.iter().enumerate() {
2831                                 if i > 0 {
2832                                     write!(w, ",&nbsp;")?
2833                                 }
2834                                 write!(w, "{}", *ty)?;
2835                             }
2836                             write!(w, ")")?;
2837                         }
2838                         clean::VariantKind::Struct(ref s) => {
2839                             render_struct(w,
2840                                           v,
2841                                           None,
2842                                           s.struct_type,
2843                                           &s.fields,
2844                                           "    ",
2845                                           false)?;
2846                         }
2847                     }
2848                 }
2849                 _ => unreachable!()
2850             }
2851             write!(w, ",\n")?;
2852         }
2853
2854         if e.variants_stripped {
2855             write!(w, "    // some variants omitted\n")?;
2856         }
2857         write!(w, "}}")?;
2858     }
2859     write!(w, "</pre>")?;
2860
2861     document(w, cx, it)?;
2862     if !e.variants.is_empty() {
2863         write!(w, "<h2 id='variants' class='variants small-section-header'>
2864                    Variants<a href='#variants' class='anchor'></a></h2>\n")?;
2865         for variant in &e.variants {
2866             let id = derive_id(format!("{}.{}",
2867                                        ItemType::Variant,
2868                                        variant.name.as_ref().unwrap()));
2869             let ns_id = derive_id(format!("{}.{}",
2870                                           variant.name.as_ref().unwrap(),
2871                                           ItemType::Variant.name_space()));
2872             write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
2873                        <a href=\"#{id}\" class=\"anchor field\"></a>\
2874                        <span id='{ns_id}' class='invisible'><code>{name}",
2875                    id = id,
2876                    ns_id = ns_id,
2877                    name = variant.name.as_ref().unwrap())?;
2878             if let clean::VariantItem(ref var) = variant.inner {
2879                 if let clean::VariantKind::Tuple(ref tys) = var.kind {
2880                     write!(w, "(")?;
2881                     for (i, ty) in tys.iter().enumerate() {
2882                         if i > 0 {
2883                             write!(w, ",&nbsp;")?;
2884                         }
2885                         write!(w, "{}", *ty)?;
2886                     }
2887                     write!(w, ")")?;
2888                 }
2889             }
2890             write!(w, "</code></span></span>")?;
2891             document(w, cx, variant)?;
2892
2893             use clean::{Variant, VariantKind};
2894             if let clean::VariantItem(Variant {
2895                 kind: VariantKind::Struct(ref s)
2896             }) = variant.inner {
2897                 let variant_id = derive_id(format!("{}.{}.fields",
2898                                                    ItemType::Variant,
2899                                                    variant.name.as_ref().unwrap()));
2900                 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
2901                        id = variant_id)?;
2902                 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
2903                            <table>", name = variant.name.as_ref().unwrap())?;
2904                 for field in &s.fields {
2905                     use clean::StructFieldItem;
2906                     if let StructFieldItem(ref ty) = field.inner {
2907                         let id = derive_id(format!("variant.{}.field.{}",
2908                                                    variant.name.as_ref().unwrap(),
2909                                                    field.name.as_ref().unwrap()));
2910                         let ns_id = derive_id(format!("{}.{}.{}.{}",
2911                                                       variant.name.as_ref().unwrap(),
2912                                                       ItemType::Variant.name_space(),
2913                                                       field.name.as_ref().unwrap(),
2914                                                       ItemType::StructField.name_space()));
2915                         write!(w, "<tr><td \
2916                                    id='{id}'>\
2917                                    <span id='{ns_id}' class='invisible'>\
2918                                    <code>{f}:&nbsp;{t}</code></span></td><td>",
2919                                id = id,
2920                                ns_id = ns_id,
2921                                f = field.name.as_ref().unwrap(),
2922                                t = *ty)?;
2923                         document(w, cx, field)?;
2924                         write!(w, "</td></tr>")?;
2925                     }
2926                 }
2927                 write!(w, "</table></span>")?;
2928             }
2929             render_stability_since(w, variant, it)?;
2930         }
2931     }
2932     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2933     Ok(())
2934 }
2935
2936 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
2937     let name = attr.name();
2938
2939     if attr.is_word() {
2940         Some(format!("{}", name))
2941     } else if let Some(v) = attr.value_str() {
2942         Some(format!("{} = {:?}", name, v.as_str()))
2943     } else if let Some(values) = attr.meta_item_list() {
2944         let display: Vec<_> = values.iter().filter_map(|attr| {
2945             attr.meta_item().and_then(|mi| render_attribute(mi))
2946         }).collect();
2947
2948         if display.len() > 0 {
2949             Some(format!("{}({})", name, display.join(", ")))
2950         } else {
2951             None
2952         }
2953     } else {
2954         None
2955     }
2956 }
2957
2958 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
2959     "export_name",
2960     "lang",
2961     "link_section",
2962     "must_use",
2963     "no_mangle",
2964     "repr",
2965     "unsafe_destructor_blind_to_params"
2966 ];
2967
2968 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
2969     let mut attrs = String::new();
2970
2971     for attr in &it.attrs.other_attrs {
2972         let name = attr.name().unwrap();
2973         if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
2974             continue;
2975         }
2976         if let Some(s) = render_attribute(&attr.meta().unwrap()) {
2977             attrs.push_str(&format!("#[{}]\n", s));
2978         }
2979     }
2980     if attrs.len() > 0 {
2981         write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
2982     }
2983     Ok(())
2984 }
2985
2986 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
2987                  g: Option<&clean::Generics>,
2988                  ty: doctree::StructType,
2989                  fields: &[clean::Item],
2990                  tab: &str,
2991                  structhead: bool) -> fmt::Result {
2992     write!(w, "{}{}{}",
2993            VisSpace(&it.visibility),
2994            if structhead {"struct "} else {""},
2995            it.name.as_ref().unwrap())?;
2996     if let Some(g) = g {
2997         write!(w, "{}", g)?
2998     }
2999     match ty {
3000         doctree::Plain => {
3001             if let Some(g) = g {
3002                 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
3003             }
3004             let mut has_visible_fields = false;
3005             write!(w, " {{")?;
3006             for field in fields {
3007                 if let clean::StructFieldItem(ref ty) = field.inner {
3008                     write!(w, "\n{}    {}{}: {},",
3009                            tab,
3010                            VisSpace(&field.visibility),
3011                            field.name.as_ref().unwrap(),
3012                            *ty)?;
3013                     has_visible_fields = true;
3014                 }
3015             }
3016
3017             if has_visible_fields {
3018                 if it.has_stripped_fields().unwrap() {
3019                     write!(w, "\n{}    // some fields omitted", tab)?;
3020                 }
3021                 write!(w, "\n{}", tab)?;
3022             } else if it.has_stripped_fields().unwrap() {
3023                 // If there are no visible fields we can just display
3024                 // `{ /* fields omitted */ }` to save space.
3025                 write!(w, " /* fields omitted */ ")?;
3026             }
3027             write!(w, "}}")?;
3028         }
3029         doctree::Tuple => {
3030             write!(w, "(")?;
3031             for (i, field) in fields.iter().enumerate() {
3032                 if i > 0 {
3033                     write!(w, ", ")?;
3034                 }
3035                 match field.inner {
3036                     clean::StrippedItem(box clean::StructFieldItem(..)) => {
3037                         write!(w, "_")?
3038                     }
3039                     clean::StructFieldItem(ref ty) => {
3040                         write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3041                     }
3042                     _ => unreachable!()
3043                 }
3044             }
3045             write!(w, ")")?;
3046             if let Some(g) = g {
3047                 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3048             }
3049             write!(w, ";")?;
3050         }
3051         doctree::Unit => {
3052             // Needed for PhantomData.
3053             if let Some(g) = g {
3054                 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3055             }
3056             write!(w, ";")?;
3057         }
3058     }
3059     Ok(())
3060 }
3061
3062 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
3063                 g: Option<&clean::Generics>,
3064                 fields: &[clean::Item],
3065                 tab: &str,
3066                 structhead: bool) -> fmt::Result {
3067     write!(w, "{}{}{}",
3068            VisSpace(&it.visibility),
3069            if structhead {"union "} else {""},
3070            it.name.as_ref().unwrap())?;
3071     if let Some(g) = g {
3072         write!(w, "{}", g)?;
3073         write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3074     }
3075
3076     write!(w, " {{\n{}", tab)?;
3077     for field in fields {
3078         if let clean::StructFieldItem(ref ty) = field.inner {
3079             write!(w, "    {}{}: {},\n{}",
3080                    VisSpace(&field.visibility),
3081                    field.name.as_ref().unwrap(),
3082                    *ty,
3083                    tab)?;
3084         }
3085     }
3086
3087     if it.has_stripped_fields().unwrap() {
3088         write!(w, "    // some fields omitted\n{}", tab)?;
3089     }
3090     write!(w, "}}")?;
3091     Ok(())
3092 }
3093
3094 #[derive(Copy, Clone)]
3095 enum AssocItemLink<'a> {
3096     Anchor(Option<&'a str>),
3097     GotoSource(DefId, &'a FxHashSet<String>),
3098 }
3099
3100 impl<'a> AssocItemLink<'a> {
3101     fn anchor(&self, id: &'a String) -> Self {
3102         match *self {
3103             AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3104             ref other => *other,
3105         }
3106     }
3107 }
3108
3109 enum AssocItemRender<'a> {
3110     All,
3111     DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3112 }
3113
3114 #[derive(Copy, Clone, PartialEq)]
3115 enum RenderMode {
3116     Normal,
3117     ForDeref { mut_: bool },
3118 }
3119
3120 fn render_assoc_items(w: &mut fmt::Formatter,
3121                       cx: &Context,
3122                       containing_item: &clean::Item,
3123                       it: DefId,
3124                       what: AssocItemRender) -> fmt::Result {
3125     let c = cache();
3126     let v = match c.impls.get(&it) {
3127         Some(v) => v,
3128         None => return Ok(()),
3129     };
3130     let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3131         i.inner_impl().trait_.is_none()
3132     });
3133     if !non_trait.is_empty() {
3134         let render_mode = match what {
3135             AssocItemRender::All => {
3136                 write!(w, "
3137                     <h2 id='methods' class='small-section-header'>
3138                       Methods<a href='#methods' class='anchor'></a>
3139                     </h2>
3140                 ")?;
3141                 RenderMode::Normal
3142             }
3143             AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3144                 write!(w, "
3145                     <h2 id='deref-methods' class='small-section-header'>
3146                       Methods from {}&lt;Target = {}&gt;<a href='#deref-methods' class='anchor'></a>
3147                     </h2>
3148                 ", trait_, type_)?;
3149                 RenderMode::ForDeref { mut_: deref_mut_ }
3150             }
3151         };
3152         for i in &non_trait {
3153             render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3154                         containing_item.stable_since(), true)?;
3155         }
3156     }
3157     if let AssocItemRender::DerefFor { .. } = what {
3158         return Ok(());
3159     }
3160     if !traits.is_empty() {
3161         let deref_impl = traits.iter().find(|t| {
3162             t.inner_impl().trait_.def_id() == c.deref_trait_did
3163         });
3164         if let Some(impl_) = deref_impl {
3165             let has_deref_mut = traits.iter().find(|t| {
3166                 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3167             }).is_some();
3168             render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3169         }
3170
3171         let (synthetic, concrete) = traits
3172             .iter()
3173             .partition::<Vec<_>, _>(|t| t.inner_impl().synthetic);
3174
3175         write!(w, "
3176             <h2 id='implementations' class='small-section-header'>
3177               Trait Implementations<a href='#implementations' class='anchor'></a>
3178             </h2>
3179             <div id='implementations-list'>
3180         ")?;
3181         render_impls(cx, w, concrete, containing_item)?;
3182         write!(w, "</div>")?;
3183
3184         write!(w, "
3185             <h2 id='synthetic-implementations' class='small-section-header'>
3186               Auto Trait Implementations<a href='#synthetic-implementations' class='anchor'></a>
3187             </h2>
3188             <div id='synthetic-implementations-list'>
3189         ")?;
3190         render_impls(cx, w, synthetic, containing_item)?;
3191         write!(w, "</div>")?;
3192     }
3193     Ok(())
3194 }
3195
3196 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3197                         container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3198     let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3199     let target = impl_.inner_impl().items.iter().filter_map(|item| {
3200         match item.inner {
3201             clean::TypedefItem(ref t, true) => Some(&t.type_),
3202             _ => None,
3203         }
3204     }).next().expect("Expected associated type binding");
3205     let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3206                                            deref_mut_: deref_mut };
3207     if let Some(did) = target.def_id() {
3208         render_assoc_items(w, cx, container_item, did, what)
3209     } else {
3210         if let Some(prim) = target.primitive_type() {
3211             if let Some(&did) = cache().primitive_locations.get(&prim) {
3212                 render_assoc_items(w, cx, container_item, did, what)?;
3213             }
3214         }
3215         Ok(())
3216     }
3217 }
3218
3219 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3220     let self_type_opt = match item.inner {
3221         clean::MethodItem(ref method) => method.decl.self_type(),
3222         clean::TyMethodItem(ref method) => method.decl.self_type(),
3223         _ => None
3224     };
3225
3226     if let Some(self_ty) = self_type_opt {
3227         let (by_mut_ref, by_box, by_value) = match self_ty {
3228             SelfTy::SelfBorrowed(_, mutability) |
3229             SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3230                 (mutability == Mutability::Mutable, false, false)
3231             },
3232             SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3233                 (false, Some(did) == cache().owned_box_did, false)
3234             },
3235             SelfTy::SelfValue => (false, false, true),
3236             _ => (false, false, false),
3237         };
3238
3239         (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3240     } else {
3241         false
3242     }
3243 }
3244
3245 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
3246     let mut out = String::new();
3247
3248     match item.inner {
3249         clean::FunctionItem(clean::Function { ref decl, .. }) |
3250         clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3251         clean::MethodItem(clean::Method { ref decl, .. }) |
3252         clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
3253             out = spotlight_decl(decl)?;
3254         }
3255         _ => {}
3256     }
3257
3258     Ok(out)
3259 }
3260
3261 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
3262     let mut out = String::new();
3263     let mut trait_ = String::new();
3264
3265     if let Some(did) = decl.output.def_id() {
3266         let c = cache();
3267         if let Some(impls) = c.impls.get(&did) {
3268             for i in impls {
3269                 let impl_ = i.inner_impl();
3270                 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3271                     if out.is_empty() {
3272                         out.push_str(
3273                             &format!("<h3 class=\"important\">Important traits for {}</h3>\
3274                                       <code class=\"content\">",
3275                                      impl_.for_));
3276                         trait_.push_str(&format!("{}", impl_.for_));
3277                     }
3278
3279                     //use the "where" class here to make it small
3280                     out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
3281                     let t_did = impl_.trait_.def_id().unwrap();
3282                     for it in &impl_.items {
3283                         if let clean::TypedefItem(ref tydef, _) = it.inner {
3284                             out.push_str("<span class=\"where fmt-newline\">    ");
3285                             assoc_type(&mut out, it, &vec![],
3286                                        Some(&tydef.type_),
3287                                        AssocItemLink::GotoSource(t_did, &FxHashSet()))?;
3288                             out.push_str(";</span>");
3289                         }
3290                     }
3291                 }
3292             }
3293         }
3294     }
3295
3296     if !out.is_empty() {
3297         out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3298                                     <span class='tooltiptext'>Important traits for {}</span></div>\
3299                                     <div class=\"content hidden\">",
3300                                    trait_));
3301         out.push_str("</code></div></div>");
3302     }
3303
3304     Ok(out)
3305 }
3306
3307 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
3308                render_mode: RenderMode, outer_version: Option<&str>,
3309                show_def_docs: bool) -> fmt::Result {
3310     if render_mode == RenderMode::Normal {
3311         let id = derive_id(match i.inner_impl().trait_ {
3312             Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
3313             None => "impl".to_string(),
3314         });
3315         write!(w, "<h3 id='{}' class='impl'><span class='in-band'><code>{}</code>",
3316                id, i.inner_impl())?;
3317         write!(w, "<a href='#{}' class='anchor'></a>", id)?;
3318         write!(w, "</span><span class='out-of-band'>")?;
3319         let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3320         if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
3321             write!(w, "<div class='ghost'></div>")?;
3322             render_stability_since_raw(w, since, outer_version)?;
3323             write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3324                    l, "goto source code")?;
3325         } else {
3326             render_stability_since_raw(w, since, outer_version)?;
3327         }
3328         write!(w, "</span>")?;
3329         write!(w, "</h3>\n")?;
3330         if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3331             write!(w, "<div class='docblock'>{}</div>",
3332                    Markdown(&*dox, &i.impl_item.links()))?;
3333         }
3334     }
3335
3336     fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
3337                      link: AssocItemLink, render_mode: RenderMode,
3338                      is_default_item: bool, outer_version: Option<&str>,
3339                      trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
3340         let item_type = item.type_();
3341         let name = item.name.as_ref().unwrap();
3342
3343         let render_method_item: bool = match render_mode {
3344             RenderMode::Normal => true,
3345             RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3346         };
3347
3348         match item.inner {
3349             clean::MethodItem(clean::Method { ref decl, .. }) |
3350             clean::TyMethodItem(clean::TyMethod{ ref decl, .. }) => {
3351                 // Only render when the method is not static or we allow static methods
3352                 if render_method_item {
3353                     let id = derive_id(format!("{}.{}", item_type, name));
3354                     let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3355                     write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3356                     write!(w, "{}", spotlight_decl(decl)?)?;
3357                     write!(w, "<span id='{}' class='invisible'>", ns_id)?;
3358                     write!(w, "<code>")?;
3359                     render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
3360                     write!(w, "</code>")?;
3361                     if let Some(l) = (Item { cx, item }).src_href() {
3362                         write!(w, "</span><span class='out-of-band'>")?;
3363                         write!(w, "<div class='ghost'></div>")?;
3364                         render_stability_since_raw(w, item.stable_since(), outer_version)?;
3365                         write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3366                                l, "goto source code")?;
3367                     } else {
3368                         render_stability_since_raw(w, item.stable_since(), outer_version)?;
3369                     }
3370                     write!(w, "</span></h4>\n")?;
3371                 }
3372             }
3373             clean::TypedefItem(ref tydef, _) => {
3374                 let id = derive_id(format!("{}.{}", ItemType::AssociatedType, name));
3375                 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3376                 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3377                 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3378                 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
3379                 write!(w, "</code></span></h4>\n")?;
3380             }
3381             clean::AssociatedConstItem(ref ty, ref default) => {
3382                 let id = derive_id(format!("{}.{}", item_type, name));
3383                 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3384                 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3385                 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3386                 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
3387                 write!(w, "</code></span></h4>\n")?;
3388             }
3389             clean::AssociatedTypeItem(ref bounds, ref default) => {
3390                 let id = derive_id(format!("{}.{}", item_type, name));
3391                 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3392                 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3393                 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3394                 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
3395                 write!(w, "</code></span></h4>\n")?;
3396             }
3397             clean::StrippedItem(..) => return Ok(()),
3398             _ => panic!("can't make docs for trait item with name {:?}", item.name)
3399         }
3400
3401         if render_method_item || render_mode == RenderMode::Normal {
3402             let prefix = render_assoc_const_value(item);
3403
3404             if !is_default_item {
3405                 if let Some(t) = trait_ {
3406                     // The trait item may have been stripped so we might not
3407                     // find any documentation or stability for it.
3408                     if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3409                         // We need the stability of the item from the trait
3410                         // because impls can't have a stability.
3411                         document_stability(w, cx, it)?;
3412                         if item.doc_value().is_some() {
3413                             document_full(w, item, cx, &prefix)?;
3414                         } else if show_def_docs {
3415                             // In case the item isn't documented,
3416                             // provide short documentation from the trait.
3417                             document_short(w, it, link, &prefix)?;
3418                         }
3419                     }
3420                 } else {
3421                     document_stability(w, cx, item)?;
3422                     if show_def_docs {
3423                         document_full(w, item, cx, &prefix)?;
3424                     }
3425                 }
3426             } else {
3427                 document_stability(w, cx, item)?;
3428                 if show_def_docs {
3429                     document_short(w, item, link, &prefix)?;
3430                 }
3431             }
3432         }
3433         Ok(())
3434     }
3435
3436     let traits = &cache().traits;
3437     let trait_ = i.trait_did().map(|did| &traits[&did]);
3438
3439     if !show_def_docs {
3440         write!(w, "<span class='docblock autohide'>")?;
3441     }
3442
3443     write!(w, "<div class='impl-items'>")?;
3444     for trait_item in &i.inner_impl().items {
3445         doc_impl_item(w, cx, trait_item, link, render_mode,
3446                       false, outer_version, trait_, show_def_docs)?;
3447     }
3448
3449     fn render_default_items(w: &mut fmt::Formatter,
3450                             cx: &Context,
3451                             t: &clean::Trait,
3452                             i: &clean::Impl,
3453                             render_mode: RenderMode,
3454                             outer_version: Option<&str>,
3455                             show_def_docs: bool) -> fmt::Result {
3456         for trait_item in &t.items {
3457             let n = trait_item.name.clone();
3458             if i.items.iter().find(|m| m.name == n).is_some() {
3459                 continue;
3460             }
3461             let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3462             let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3463
3464             doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3465                           outer_version, None, show_def_docs)?;
3466         }
3467         Ok(())
3468     }
3469
3470     // If we've implemented a trait, then also emit documentation for all
3471     // default items which weren't overridden in the implementation block.
3472     if let Some(t) = trait_ {
3473         render_default_items(w, cx, t, &i.inner_impl(),
3474                              render_mode, outer_version, show_def_docs)?;
3475     }
3476     write!(w, "</div>")?;
3477
3478     if !show_def_docs {
3479         write!(w, "</span>")?;
3480     }
3481
3482     Ok(())
3483 }
3484
3485 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3486                 t: &clean::Typedef) -> fmt::Result {
3487     write!(w, "<pre class='rust typedef'>")?;
3488     render_attributes(w, it)?;
3489     write!(w, "type {}{}{where_clause} = {type_};</pre>",
3490            it.name.as_ref().unwrap(),
3491            t.generics,
3492            where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3493            type_ = t.type_)?;
3494
3495     document(w, cx, it)?;
3496
3497     // Render any items associated directly to this alias, as otherwise they
3498     // won't be visible anywhere in the docs. It would be nice to also show
3499     // associated items from the aliased type (see discussion in #32077), but
3500     // we need #14072 to make sense of the generics.
3501     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3502 }
3503
3504 fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
3505     writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
3506     render_attributes(w, it)?;
3507     write!(
3508         w,
3509         "    {}type {};\n}}</pre>",
3510         VisSpace(&it.visibility),
3511         it.name.as_ref().unwrap(),
3512     )?;
3513
3514     document(w, cx, it)?;
3515
3516     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3517 }
3518
3519 impl<'a> fmt::Display for Sidebar<'a> {
3520     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3521         let cx = self.cx;
3522         let it = self.item;
3523         let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3524         let mut should_close = false;
3525
3526         if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3527             || it.is_enum() || it.is_mod() || it.is_typedef()
3528         {
3529             write!(fmt, "<p class='location'>")?;
3530             match it.inner {
3531                 clean::StructItem(..) => write!(fmt, "Struct ")?,
3532                 clean::TraitItem(..) => write!(fmt, "Trait ")?,
3533                 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
3534                 clean::UnionItem(..) => write!(fmt, "Union ")?,
3535                 clean::EnumItem(..) => write!(fmt, "Enum ")?,
3536                 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
3537                 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
3538                 clean::ModuleItem(..) => if it.is_crate() {
3539                     write!(fmt, "Crate ")?;
3540                 } else {
3541                     write!(fmt, "Module ")?;
3542                 },
3543                 _ => (),
3544             }
3545             write!(fmt, "{}", it.name.as_ref().unwrap())?;
3546             write!(fmt, "</p>")?;
3547
3548             if it.is_crate() {
3549                 if let Some(ref version) = cache().crate_version {
3550                     write!(fmt,
3551                            "<div class='block version'>\
3552                             <p>Version {}</p>\
3553                             </div>",
3554                            version)?;
3555                 }
3556             }
3557
3558             write!(fmt, "<div class=\"sidebar-elems\">")?;
3559             should_close = true;
3560             match it.inner {
3561                 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
3562                 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
3563                 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
3564                 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
3565                 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
3566                 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
3567                 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
3568                 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
3569                 _ => (),
3570             }
3571         }
3572
3573         // The sidebar is designed to display sibling functions, modules and
3574         // other miscellaneous information. since there are lots of sibling
3575         // items (and that causes quadratic growth in large modules),
3576         // we refactor common parts into a shared JavaScript file per module.
3577         // still, we don't move everything into JS because we want to preserve
3578         // as much HTML as possible in order to allow non-JS-enabled browsers
3579         // to navigate the documentation (though slightly inefficiently).
3580
3581         write!(fmt, "<p class='location'>")?;
3582         for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3583             if i > 0 {
3584                 write!(fmt, "::<wbr>")?;
3585             }
3586             write!(fmt, "<a href='{}index.html'>{}</a>",
3587                    &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3588                    *name)?;
3589         }
3590         write!(fmt, "</p>")?;
3591
3592         // Sidebar refers to the enclosing module, not this module.
3593         let relpath = if it.is_mod() { "../" } else { "" };
3594         write!(fmt,
3595                "<script>window.sidebarCurrent = {{\
3596                    name: '{name}', \
3597                    ty: '{ty}', \
3598                    relpath: '{path}'\
3599                 }};</script>",
3600                name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3601                ty = it.type_().css_class(),
3602                path = relpath)?;
3603         if parentlen == 0 {
3604             // There is no sidebar-items.js beyond the crate root path
3605             // FIXME maybe dynamic crate loading can be merged here
3606         } else {
3607             write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
3608                    path = relpath)?;
3609         }
3610         if should_close {
3611             // Closes sidebar-elems div.
3612             write!(fmt, "</div>")?;
3613         }
3614
3615         Ok(())
3616     }
3617 }
3618
3619 fn get_methods(i: &clean::Impl, for_deref: bool) -> Vec<String> {
3620     i.items.iter().filter_map(|item| {
3621         match item.name {
3622             // Maybe check with clean::Visibility::Public as well?
3623             Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
3624                 if !for_deref || should_render_item(item, false) {
3625                     Some(format!("<a href=\"#method.{name}\">{name}</a>", name = name))
3626                 } else {
3627                     None
3628                 }
3629             }
3630             _ => None,
3631         }
3632     }).collect::<Vec<_>>()
3633 }
3634
3635 // The point is to url encode any potential character from a type with genericity.
3636 fn small_url_encode(s: &str) -> String {
3637     s.replace("<", "%3C")
3638      .replace(">", "%3E")
3639      .replace(" ", "%20")
3640      .replace("?", "%3F")
3641      .replace("'", "%27")
3642      .replace("&", "%26")
3643      .replace(",", "%2C")
3644      .replace(":", "%3A")
3645      .replace(";", "%3B")
3646      .replace("[", "%5B")
3647      .replace("]", "%5D")
3648      .replace("\"", "%22")
3649 }
3650
3651 fn sidebar_assoc_items(it: &clean::Item) -> String {
3652     let mut out = String::new();
3653     let c = cache();
3654     if let Some(v) = c.impls.get(&it.def_id) {
3655         let ret = v.iter()
3656                    .filter(|i| i.inner_impl().trait_.is_none())
3657                    .flat_map(|i| get_methods(i.inner_impl(), false))
3658                    .collect::<String>();
3659         if !ret.is_empty() {
3660             out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
3661                                    </a><div class=\"sidebar-links\">{}</div>", ret));
3662         }
3663
3664         if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
3665             if let Some(impl_) = v.iter()
3666                                   .filter(|i| i.inner_impl().trait_.is_some())
3667                                   .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
3668                 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
3669                     match item.inner {
3670                         clean::TypedefItem(ref t, true) => Some(&t.type_),
3671                         _ => None,
3672                     }
3673                 }).next() {
3674                     let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
3675                         c.primitive_locations.get(&prim).cloned()
3676                     })).and_then(|did| c.impls.get(&did));
3677                     if let Some(impls) = inner_impl {
3678                         out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
3679                         out.push_str(&format!("Methods from {}&lt;Target={}&gt;",
3680                                               Escape(&format!("{:#}",
3681                                                      impl_.inner_impl().trait_.as_ref().unwrap())),
3682                                               Escape(&format!("{:#}", target))));
3683                         out.push_str("</a>");
3684                         let ret = impls.iter()
3685                                        .filter(|i| i.inner_impl().trait_.is_none())
3686                                        .flat_map(|i| get_methods(i.inner_impl(), true))
3687                                        .collect::<String>();
3688                         out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
3689                     }
3690                 }
3691             }
3692             let format_impls = |impls: Vec<&Impl>| {
3693                 let mut links = HashSet::new();
3694                 impls.iter()
3695                            .filter_map(|i| {
3696                                let is_negative_impl = is_negative_impl(i.inner_impl());
3697                                if let Some(ref i) = i.inner_impl().trait_ {
3698                                    let i_display = format!("{:#}", i);
3699                                    let out = Escape(&i_display);
3700                                    let encoded = small_url_encode(&format!("{:#}", i));
3701                                    let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
3702                                                            encoded,
3703                                                            if is_negative_impl { "!" } else { "" },
3704                                                            out);
3705                                    if links.insert(generated.clone()) {
3706                                        Some(generated)
3707                                    } else {
3708                                        None
3709                                    }
3710                                } else {
3711                                    None
3712                                }
3713                            })
3714                            .collect::<String>()
3715             };
3716
3717             let (synthetic, concrete) = v
3718                 .iter()
3719                 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
3720
3721             let concrete_format = format_impls(concrete);
3722             let synthetic_format = format_impls(synthetic);
3723
3724             if !concrete_format.is_empty() {
3725                 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
3726                               Trait Implementations</a>");
3727                 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
3728             }
3729
3730             if !synthetic_format.is_empty() {
3731                 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
3732                               Auto Trait Implementations</a>");
3733                 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
3734             }
3735         }
3736     }
3737
3738     out
3739 }
3740
3741 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
3742                   s: &clean::Struct) -> fmt::Result {
3743     let mut sidebar = String::new();
3744     let fields = get_struct_fields_name(&s.fields);
3745
3746     if !fields.is_empty() {
3747         if let doctree::Plain = s.struct_type {
3748             sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3749                                        <div class=\"sidebar-links\">{}</div>", fields));
3750         }
3751     }
3752
3753     sidebar.push_str(&sidebar_assoc_items(it));
3754
3755     if !sidebar.is_empty() {
3756         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3757     }
3758     Ok(())
3759 }
3760
3761 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
3762     match item.inner {
3763         clean::ItemEnum::ImplItem(ref i) => {
3764             if let Some(ref trait_) = i.trait_ {
3765                 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
3766             } else {
3767                 None
3768             }
3769         },
3770         _ => None,
3771     }
3772 }
3773
3774 fn is_negative_impl(i: &clean::Impl) -> bool {
3775     i.polarity == Some(clean::ImplPolarity::Negative)
3776 }
3777
3778 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
3779                  t: &clean::Trait) -> fmt::Result {
3780     let mut sidebar = String::new();
3781
3782     let types = t.items
3783                  .iter()
3784                  .filter_map(|m| {
3785                      match m.name {
3786                          Some(ref name) if m.is_associated_type() => {
3787                              Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
3788                                           name=name))
3789                          }
3790                          _ => None,
3791                      }
3792                  })
3793                  .collect::<String>();
3794     let consts = t.items
3795                   .iter()
3796                   .filter_map(|m| {
3797                       match m.name {
3798                           Some(ref name) if m.is_associated_const() => {
3799                               Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
3800                                            name=name))
3801                           }
3802                           _ => None,
3803                       }
3804                   })
3805                   .collect::<String>();
3806     let required = t.items
3807                     .iter()
3808                     .filter_map(|m| {
3809                         match m.name {
3810                             Some(ref name) if m.is_ty_method() => {
3811                                 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
3812                                              name=name))
3813                             }
3814                             _ => None,
3815                         }
3816                     })
3817                     .collect::<String>();
3818     let provided = t.items
3819                     .iter()
3820                     .filter_map(|m| {
3821                         match m.name {
3822                             Some(ref name) if m.is_method() => {
3823                                 Some(format!("<a href=\"#method.{name}\">{name}</a>", name=name))
3824                             }
3825                             _ => None,
3826                         }
3827                     })
3828                     .collect::<String>();
3829
3830     if !types.is_empty() {
3831         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
3832                                    Associated Types</a><div class=\"sidebar-links\">{}</div>",
3833                                   types));
3834     }
3835     if !consts.is_empty() {
3836         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
3837                                    Associated Constants</a><div class=\"sidebar-links\">{}</div>",
3838                                   consts));
3839     }
3840     if !required.is_empty() {
3841         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
3842                                    Required Methods</a><div class=\"sidebar-links\">{}</div>",
3843                                   required));
3844     }
3845     if !provided.is_empty() {
3846         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
3847                                    Provided Methods</a><div class=\"sidebar-links\">{}</div>",
3848                                   provided));
3849     }
3850
3851     let c = cache();
3852
3853     if let Some(implementors) = c.implementors.get(&it.def_id) {
3854         let res = implementors.iter()
3855                               .filter(|i| i.inner_impl().for_.def_id()
3856                               .map_or(false, |d| !c.paths.contains_key(&d)))
3857                               .filter_map(|i| {
3858                                   match extract_for_impl_name(&i.impl_item) {
3859                                       Some((ref name, ref url)) => {
3860                                           Some(format!("<a href=\"#impl-{}\">{}</a>",
3861                                                       small_url_encode(url),
3862                                                       Escape(name)))
3863                                       }
3864                                       _ => None,
3865                                   }
3866                               })
3867                               .collect::<String>();
3868         if !res.is_empty() {
3869             sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
3870                                        Implementations on Foreign Types</a><div \
3871                                        class=\"sidebar-links\">{}</div>",
3872                                       res));
3873         }
3874     }
3875
3876     sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
3877     if t.auto {
3878         sidebar.push_str("<a class=\"sidebar-title\" \
3879                           href=\"#synthetic-implementors\">Auto Implementors</a>");
3880     }
3881
3882     sidebar.push_str(&sidebar_assoc_items(it));
3883
3884     write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
3885 }
3886
3887 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
3888                      _p: &clean::PrimitiveType) -> fmt::Result {
3889     let sidebar = sidebar_assoc_items(it);
3890
3891     if !sidebar.is_empty() {
3892         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3893     }
3894     Ok(())
3895 }
3896
3897 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
3898                    _t: &clean::Typedef) -> fmt::Result {
3899     let sidebar = sidebar_assoc_items(it);
3900
3901     if !sidebar.is_empty() {
3902         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3903     }
3904     Ok(())
3905 }
3906
3907 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
3908     fields.iter()
3909           .filter(|f| if let clean::StructFieldItem(..) = f.inner {
3910               true
3911           } else {
3912               false
3913           })
3914           .filter_map(|f| match f.name {
3915               Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
3916                                               {name}</a>", name=name)),
3917               _ => None,
3918           })
3919           .collect()
3920 }
3921
3922 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
3923                  u: &clean::Union) -> fmt::Result {
3924     let mut sidebar = String::new();
3925     let fields = get_struct_fields_name(&u.fields);
3926
3927     if !fields.is_empty() {
3928         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3929                                    <div class=\"sidebar-links\">{}</div>", fields));
3930     }
3931
3932     sidebar.push_str(&sidebar_assoc_items(it));
3933
3934     if !sidebar.is_empty() {
3935         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3936     }
3937     Ok(())
3938 }
3939
3940 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
3941                 e: &clean::Enum) -> fmt::Result {
3942     let mut sidebar = String::new();
3943
3944     let variants = e.variants.iter()
3945                              .filter_map(|v| match v.name {
3946                                  Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
3947                                                                  </a>", name = name)),
3948                                  _ => None,
3949                              })
3950                              .collect::<String>();
3951     if !variants.is_empty() {
3952         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
3953                                    <div class=\"sidebar-links\">{}</div>", variants));
3954     }
3955
3956     sidebar.push_str(&sidebar_assoc_items(it));
3957
3958     if !sidebar.is_empty() {
3959         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3960     }
3961     Ok(())
3962 }
3963
3964 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
3965                   items: &[clean::Item]) -> fmt::Result {
3966     let mut sidebar = String::new();
3967
3968     if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
3969                              it.type_() == ItemType::Import) {
3970         sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
3971                                   id = "reexports",
3972                                   name = "Re-exports"));
3973     }
3974
3975     // ordering taken from item_module, reorder, where it prioritized elements in a certain order
3976     // to print its headings
3977     for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
3978                    ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
3979                    ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
3980                    ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
3981                    ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
3982         if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
3983             let (short, name) = match myty {
3984                 ItemType::ExternCrate |
3985                 ItemType::Import          => ("reexports", "Re-exports"),
3986                 ItemType::Module          => ("modules", "Modules"),
3987                 ItemType::Struct          => ("structs", "Structs"),
3988                 ItemType::Union           => ("unions", "Unions"),
3989                 ItemType::Enum            => ("enums", "Enums"),
3990                 ItemType::Function        => ("functions", "Functions"),
3991                 ItemType::Typedef         => ("types", "Type Definitions"),
3992                 ItemType::Static          => ("statics", "Statics"),
3993                 ItemType::Constant        => ("constants", "Constants"),
3994                 ItemType::Trait           => ("traits", "Traits"),
3995                 ItemType::Impl            => ("impls", "Implementations"),
3996                 ItemType::TyMethod        => ("tymethods", "Type Methods"),
3997                 ItemType::Method          => ("methods", "Methods"),
3998                 ItemType::StructField     => ("fields", "Struct Fields"),
3999                 ItemType::Variant         => ("variants", "Variants"),
4000                 ItemType::Macro           => ("macros", "Macros"),
4001                 ItemType::Primitive       => ("primitives", "Primitive Types"),
4002                 ItemType::AssociatedType  => ("associated-types", "Associated Types"),
4003                 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
4004                 ItemType::ForeignType     => ("foreign-types", "Foreign Types"),
4005             };
4006             sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4007                                       id = short,
4008                                       name = name));
4009         }
4010     }
4011
4012     if !sidebar.is_empty() {
4013         write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
4014     }
4015     Ok(())
4016 }
4017
4018 fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
4019     let sidebar = sidebar_assoc_items(it);
4020     if !sidebar.is_empty() {
4021         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4022     }
4023     Ok(())
4024 }
4025
4026 impl<'a> fmt::Display for Source<'a> {
4027     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4028         let Source(s) = *self;
4029         let lines = s.lines().count();
4030         let mut cols = 0;
4031         let mut tmp = lines;
4032         while tmp > 0 {
4033             cols += 1;
4034             tmp /= 10;
4035         }
4036         write!(fmt, "<pre class=\"line-numbers\">")?;
4037         for i in 1..lines + 1 {
4038             write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4039         }
4040         write!(fmt, "</pre>")?;
4041         write!(fmt, "{}",
4042                highlight::render_with_highlighting(s, None, None, None, None))?;
4043         Ok(())
4044     }
4045 }
4046
4047 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4048               t: &clean::Macro) -> fmt::Result {
4049     w.write_str(&highlight::render_with_highlighting(&t.source,
4050                                                      Some("macro"),
4051                                                      None,
4052                                                      None,
4053                                                      None))?;
4054     document(w, cx, it)
4055 }
4056
4057 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
4058                   it: &clean::Item,
4059                   _p: &clean::PrimitiveType) -> fmt::Result {
4060     document(w, cx, it)?;
4061     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4062 }
4063
4064 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4065
4066 fn make_item_keywords(it: &clean::Item) -> String {
4067     format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4068 }
4069
4070 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
4071     let decl = match item.inner {
4072         clean::FunctionItem(ref f) => &f.decl,
4073         clean::MethodItem(ref m) => &m.decl,
4074         clean::TyMethodItem(ref m) => &m.decl,
4075         _ => return None
4076     };
4077
4078     let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
4079     let output = match decl.output {
4080         clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
4081         _ => None
4082     };
4083
4084     Some(IndexItemFunctionType { inputs: inputs, output: output })
4085 }
4086
4087 fn get_index_type(clean_type: &clean::Type) -> Type {
4088     let t = Type {
4089         name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
4090         generics: get_generics(clean_type),
4091     };
4092     t
4093 }
4094
4095 /// Returns a list of all paths used in the type.
4096 /// This is used to help deduplicate imported impls
4097 /// for reexported types. If any of the contained
4098 /// types are re-exported, we don't use the corresponding
4099 /// entry from the js file, as inlining will have already
4100 /// picked up the impl
4101 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4102     let mut out = Vec::new();
4103     let mut visited = FxHashSet();
4104     let mut work = VecDeque::new();
4105     let cache = cache();
4106
4107     work.push_back(first_ty);
4108
4109     while let Some(ty) = work.pop_front() {
4110         if !visited.insert(ty.clone()) {
4111             continue;
4112         }
4113
4114         match ty {
4115             clean::Type::ResolvedPath { did, .. } => {
4116                 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4117                 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4118
4119                 match fqp {
4120                     Some(path) => {
4121                         out.push(path.join("::"));
4122                     },
4123                     _ => {}
4124                 };
4125
4126             },
4127             clean::Type::Tuple(tys) => {
4128                 work.extend(tys.into_iter());
4129             },
4130             clean::Type::Slice(ty) => {
4131                 work.push_back(*ty);
4132             }
4133             clean::Type::Array(ty, _) => {
4134                 work.push_back(*ty);
4135             },
4136             clean::Type::Unique(ty) => {
4137                 work.push_back(*ty);
4138             },
4139             clean::Type::RawPointer(_, ty) => {
4140                 work.push_back(*ty);
4141             },
4142             clean::Type::BorrowedRef { type_, .. } => {
4143                 work.push_back(*type_);
4144             },
4145             clean::Type::QPath { self_type, trait_, .. } => {
4146                 work.push_back(*self_type);
4147                 work.push_back(*trait_);
4148             },
4149             _ => {}
4150         }
4151     };
4152     out
4153 }
4154
4155 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
4156     match *clean_type {
4157         clean::ResolvedPath { ref path, .. } => {
4158             let segments = &path.segments;
4159             let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
4160                 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
4161                 clean_type, accept_generic
4162             ));
4163             Some(path_segment.name.clone())
4164         }
4165         clean::Generic(ref s) if accept_generic => Some(s.clone()),
4166         clean::Primitive(ref p) => Some(format!("{:?}", p)),
4167         clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
4168         // FIXME: add all from clean::Type.
4169         _ => None
4170     }
4171 }
4172
4173 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
4174     clean_type.generics()
4175               .and_then(|types| {
4176                   let r = types.iter()
4177                                .filter_map(|t| get_index_type_name(t, false))
4178                                .map(|s| s.to_ascii_lowercase())
4179                                .collect::<Vec<_>>();
4180                   if r.is_empty() {
4181                       None
4182                   } else {
4183                       Some(r)
4184                   }
4185               })
4186 }
4187
4188 pub fn cache() -> Arc<Cache> {
4189     CACHE_KEY.with(|c| c.borrow().clone())
4190 }
4191
4192 #[cfg(test)]
4193 #[test]
4194 fn test_unique_id() {
4195     let input = ["foo", "examples", "examples", "method.into_iter","examples",
4196                  "method.into_iter", "foo", "main", "search", "methods",
4197                  "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
4198     let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
4199                     "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
4200                     "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
4201
4202     let test = || {
4203         let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
4204         assert_eq!(&actual[..], expected);
4205     };
4206     test();
4207     reset_ids(true);
4208     test();
4209 }
4210
4211 #[cfg(test)]
4212 #[test]
4213 fn test_name_key() {
4214     assert_eq!(name_key("0"), ("", 0, 1));
4215     assert_eq!(name_key("123"), ("", 123, 0));
4216     assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
4217     assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
4218     assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
4219     assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
4220     assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
4221     assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
4222 }
4223
4224 #[cfg(test)]
4225 #[test]
4226 fn test_name_sorting() {
4227     let names = ["Apple",
4228                  "Banana",
4229                  "Fruit", "Fruit0", "Fruit00",
4230                  "Fruit1", "Fruit01",
4231                  "Fruit2", "Fruit02",
4232                  "Fruit20",
4233                  "Fruit100",
4234                  "Pear"];
4235     let mut sorted = names.to_owned();
4236     sorted.sort_by_key(|&s| name_key(s));
4237     assert_eq!(names, sorted);
4238 }