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