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