]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/render.rs
Rollup merge of #48106 - QuietMisdreavus:teleporting-crates, r=GuillaumeGomez
[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     let mut synthetic_types = Vec::new();
2455
2456     if let Some(implementors) = cache.implementors.get(&it.def_id) {
2457         // The DefId is for the first Type found with that name. The bool is
2458         // if any Types with the same name but different DefId have been found.
2459         let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap();
2460         for implementor in implementors {
2461             match implementor.inner_impl().for_ {
2462                 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2463                 clean::BorrowedRef {
2464                     type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2465                     ..
2466                 } => {
2467                     let &mut (prev_did, ref mut has_duplicates) =
2468                         implementor_dups.entry(path.last_name()).or_insert((did, false));
2469                     if prev_did != did {
2470                         *has_duplicates = true;
2471                     }
2472                 }
2473                 _ => {}
2474             }
2475         }
2476
2477         let (local, foreign) = implementors.iter()
2478             .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
2479                                          .map_or(true, |d| cache.paths.contains_key(&d)));
2480
2481
2482         let (synthetic, concrete) = local.iter()
2483             .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
2484
2485
2486         if !foreign.is_empty() {
2487             write!(w, "
2488                 <h2 id='foreign-impls' class='small-section-header'>
2489                   Implementations on Foreign Types<a href='#foreign-impls' class='anchor'></a>
2490                 </h2>
2491             ")?;
2492
2493             for implementor in foreign {
2494                 let assoc_link = AssocItemLink::GotoSource(
2495                     implementor.impl_item.def_id, &implementor.inner_impl().provided_trait_methods
2496                 );
2497                 render_impl(w, cx, &implementor, assoc_link,
2498                             RenderMode::Normal, implementor.impl_item.stable_since(), false)?;
2499             }
2500         }
2501
2502         write!(w, "{}", impl_header)?;
2503         for implementor in concrete {
2504             render_implementor(cx, implementor, w, &implementor_dups)?;
2505         }
2506         write!(w, "</ul>")?;
2507
2508         if t.auto {
2509             write!(w, "{}", synthetic_impl_header)?;
2510             for implementor in synthetic {
2511                 synthetic_types.extend(
2512                     collect_paths_for_type(implementor.inner_impl().for_.clone())
2513                 );
2514                 render_implementor(cx, implementor, w, &implementor_dups)?;
2515             }
2516             write!(w, "</ul>")?;
2517         }
2518     } else {
2519         // even without any implementations to write in, we still want the heading and list, so the
2520         // implementors javascript file pulled in below has somewhere to write the impls into
2521         write!(w, "{}", impl_header)?;
2522         write!(w, "</ul>")?;
2523
2524         if t.auto {
2525             write!(w, "{}", synthetic_impl_header)?;
2526             write!(w, "</ul>")?;
2527         }
2528     }
2529     write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
2530            as_json(&synthetic_types))?;
2531
2532     write!(w, r#"<script type="text/javascript" async
2533                          src="{root_path}/implementors/{path}/{ty}.{name}.js">
2534                  </script>"#,
2535            root_path = vec![".."; cx.current.len()].join("/"),
2536            path = if it.def_id.is_local() {
2537                cx.current.join("/")
2538            } else {
2539                let (ref path, _) = cache.external_paths[&it.def_id];
2540                path[..path.len() - 1].join("/")
2541            },
2542            ty = it.type_().css_class(),
2543            name = *it.name.as_ref().unwrap())?;
2544     Ok(())
2545 }
2546
2547 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2548     use html::item_type::ItemType::*;
2549
2550     let name = it.name.as_ref().unwrap();
2551     let ty = match it.type_() {
2552         Typedef | AssociatedType => AssociatedType,
2553         s@_ => s,
2554     };
2555
2556     let anchor = format!("#{}.{}", ty, name);
2557     match link {
2558         AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2559         AssocItemLink::Anchor(None) => anchor,
2560         AssocItemLink::GotoSource(did, _) => {
2561             href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2562         }
2563     }
2564 }
2565
2566 fn assoc_const(w: &mut fmt::Formatter,
2567                it: &clean::Item,
2568                ty: &clean::Type,
2569                _default: Option<&String>,
2570                link: AssocItemLink) -> fmt::Result {
2571     write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2572            VisSpace(&it.visibility),
2573            naive_assoc_href(it, link),
2574            it.name.as_ref().unwrap(),
2575            ty)?;
2576     Ok(())
2577 }
2578
2579 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
2580                              bounds: &Vec<clean::TyParamBound>,
2581                              default: Option<&clean::Type>,
2582                              link: AssocItemLink) -> fmt::Result {
2583     write!(w, "type <a href='{}' class=\"type\">{}</a>",
2584            naive_assoc_href(it, link),
2585            it.name.as_ref().unwrap())?;
2586     if !bounds.is_empty() {
2587         write!(w, ": {}", TyParamBounds(bounds))?
2588     }
2589     if let Some(default) = default {
2590         write!(w, " = {}", default)?;
2591     }
2592     Ok(())
2593 }
2594
2595 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
2596                                   ver: Option<&'a str>,
2597                                   containing_ver: Option<&'a str>) -> fmt::Result {
2598     if let Some(v) = ver {
2599         if containing_ver != ver && v.len() > 0 {
2600             write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
2601                    v)?
2602         }
2603     }
2604     Ok(())
2605 }
2606
2607 fn render_stability_since(w: &mut fmt::Formatter,
2608                           item: &clean::Item,
2609                           containing_item: &clean::Item) -> fmt::Result {
2610     render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2611 }
2612
2613 fn render_assoc_item(w: &mut fmt::Formatter,
2614                      item: &clean::Item,
2615                      link: AssocItemLink,
2616                      parent: ItemType) -> fmt::Result {
2617     fn method(w: &mut fmt::Formatter,
2618               meth: &clean::Item,
2619               unsafety: hir::Unsafety,
2620               constness: hir::Constness,
2621               abi: abi::Abi,
2622               g: &clean::Generics,
2623               d: &clean::FnDecl,
2624               link: AssocItemLink,
2625               parent: ItemType)
2626               -> fmt::Result {
2627         let name = meth.name.as_ref().unwrap();
2628         let anchor = format!("#{}.{}", meth.type_(), name);
2629         let href = match link {
2630             AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2631             AssocItemLink::Anchor(None) => anchor,
2632             AssocItemLink::GotoSource(did, provided_methods) => {
2633                 // We're creating a link from an impl-item to the corresponding
2634                 // trait-item and need to map the anchored type accordingly.
2635                 let ty = if provided_methods.contains(name) {
2636                     ItemType::Method
2637                 } else {
2638                     ItemType::TyMethod
2639                 };
2640
2641                 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2642             }
2643         };
2644         let mut head_len = format!("{}{}{}{:#}fn {}{:#}",
2645                                    VisSpace(&meth.visibility),
2646                                    ConstnessSpace(constness),
2647                                    UnsafetySpace(unsafety),
2648                                    AbiSpace(abi),
2649                                    name,
2650                                    *g).len();
2651         let (indent, end_newline) = if parent == ItemType::Trait {
2652             head_len += 4;
2653             (4, false)
2654         } else {
2655             (0, true)
2656         };
2657         write!(w, "{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2658                    {generics}{decl}{where_clause}",
2659                VisSpace(&meth.visibility),
2660                ConstnessSpace(constness),
2661                UnsafetySpace(unsafety),
2662                AbiSpace(abi),
2663                href = href,
2664                name = name,
2665                generics = *g,
2666                decl = Method {
2667                    decl: d,
2668                    name_len: head_len,
2669                    indent,
2670                },
2671                where_clause = WhereClause {
2672                    gens: g,
2673                    indent,
2674                    end_newline,
2675                })
2676     }
2677     match item.inner {
2678         clean::StrippedItem(..) => Ok(()),
2679         clean::TyMethodItem(ref m) => {
2680             method(w, item, m.unsafety, hir::Constness::NotConst,
2681                    m.abi, &m.generics, &m.decl, link, parent)
2682         }
2683         clean::MethodItem(ref m) => {
2684             method(w, item, m.unsafety, m.constness,
2685                    m.abi, &m.generics, &m.decl, link, parent)
2686         }
2687         clean::AssociatedConstItem(ref ty, ref default) => {
2688             assoc_const(w, item, ty, default.as_ref(), link)
2689         }
2690         clean::AssociatedTypeItem(ref bounds, ref default) => {
2691             assoc_type(w, item, bounds, default.as_ref(), link)
2692         }
2693         _ => panic!("render_assoc_item called on non-associated-item")
2694     }
2695 }
2696
2697 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2698                s: &clean::Struct) -> fmt::Result {
2699     write!(w, "<pre class='rust struct'>")?;
2700     render_attributes(w, it)?;
2701     render_struct(w,
2702                   it,
2703                   Some(&s.generics),
2704                   s.struct_type,
2705                   &s.fields,
2706                   "",
2707                   true)?;
2708     write!(w, "</pre>")?;
2709
2710     document(w, cx, it)?;
2711     let mut fields = s.fields.iter().filter_map(|f| {
2712         match f.inner {
2713             clean::StructFieldItem(ref ty) => Some((f, ty)),
2714             _ => None,
2715         }
2716     }).peekable();
2717     if let doctree::Plain = s.struct_type {
2718         if fields.peek().is_some() {
2719             write!(w, "<h2 id='fields' class='fields small-section-header'>
2720                        Fields<a href='#fields' class='anchor'></a></h2>")?;
2721             for (field, ty) in fields {
2722                 let id = derive_id(format!("{}.{}",
2723                                            ItemType::StructField,
2724                                            field.name.as_ref().unwrap()));
2725                 let ns_id = derive_id(format!("{}.{}",
2726                                               field.name.as_ref().unwrap(),
2727                                               ItemType::StructField.name_space()));
2728                 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">
2729                            <a href=\"#{id}\" class=\"anchor field\"></a>
2730                            <span id=\"{ns_id}\" class='invisible'>
2731                            <code>{name}: {ty}</code>
2732                            </span></span>",
2733                        item_type = ItemType::StructField,
2734                        id = id,
2735                        ns_id = ns_id,
2736                        name = field.name.as_ref().unwrap(),
2737                        ty = ty)?;
2738                 if let Some(stability_class) = field.stability_class() {
2739                     write!(w, "<span class='stab {stab}'></span>",
2740                         stab = stability_class)?;
2741                 }
2742                 document(w, cx, field)?;
2743             }
2744         }
2745     }
2746     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2747 }
2748
2749 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2750                s: &clean::Union) -> fmt::Result {
2751     write!(w, "<pre class='rust union'>")?;
2752     render_attributes(w, it)?;
2753     render_union(w,
2754                  it,
2755                  Some(&s.generics),
2756                  &s.fields,
2757                  "",
2758                  true)?;
2759     write!(w, "</pre>")?;
2760
2761     document(w, cx, it)?;
2762     let mut fields = s.fields.iter().filter_map(|f| {
2763         match f.inner {
2764             clean::StructFieldItem(ref ty) => Some((f, ty)),
2765             _ => None,
2766         }
2767     }).peekable();
2768     if fields.peek().is_some() {
2769         write!(w, "<h2 id='fields' class='fields small-section-header'>
2770                    Fields<a href='#fields' class='anchor'></a></h2>")?;
2771         for (field, ty) in fields {
2772             write!(w, "<span id='{shortty}.{name}' class=\"{shortty}\"><code>{name}: {ty}</code>
2773                        </span>",
2774                    shortty = ItemType::StructField,
2775                    name = field.name.as_ref().unwrap(),
2776                    ty = ty)?;
2777             if let Some(stability_class) = field.stability_class() {
2778                 write!(w, "<span class='stab {stab}'></span>",
2779                     stab = stability_class)?;
2780             }
2781             document(w, cx, field)?;
2782         }
2783     }
2784     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2785 }
2786
2787 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2788              e: &clean::Enum) -> fmt::Result {
2789     write!(w, "<pre class='rust enum'>")?;
2790     render_attributes(w, it)?;
2791     write!(w, "{}enum {}{}{}",
2792            VisSpace(&it.visibility),
2793            it.name.as_ref().unwrap(),
2794            e.generics,
2795            WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
2796     if e.variants.is_empty() && !e.variants_stripped {
2797         write!(w, " {{}}")?;
2798     } else {
2799         write!(w, " {{\n")?;
2800         for v in &e.variants {
2801             write!(w, "    ")?;
2802             let name = v.name.as_ref().unwrap();
2803             match v.inner {
2804                 clean::VariantItem(ref var) => {
2805                     match var.kind {
2806                         clean::VariantKind::CLike => write!(w, "{}", name)?,
2807                         clean::VariantKind::Tuple(ref tys) => {
2808                             write!(w, "{}(", name)?;
2809                             for (i, ty) in tys.iter().enumerate() {
2810                                 if i > 0 {
2811                                     write!(w, ",&nbsp;")?
2812                                 }
2813                                 write!(w, "{}", *ty)?;
2814                             }
2815                             write!(w, ")")?;
2816                         }
2817                         clean::VariantKind::Struct(ref s) => {
2818                             render_struct(w,
2819                                           v,
2820                                           None,
2821                                           s.struct_type,
2822                                           &s.fields,
2823                                           "    ",
2824                                           false)?;
2825                         }
2826                     }
2827                 }
2828                 _ => unreachable!()
2829             }
2830             write!(w, ",\n")?;
2831         }
2832
2833         if e.variants_stripped {
2834             write!(w, "    // some variants omitted\n")?;
2835         }
2836         write!(w, "}}")?;
2837     }
2838     write!(w, "</pre>")?;
2839
2840     document(w, cx, it)?;
2841     if !e.variants.is_empty() {
2842         write!(w, "<h2 id='variants' class='variants small-section-header'>
2843                    Variants<a href='#variants' class='anchor'></a></h2>\n")?;
2844         for variant in &e.variants {
2845             let id = derive_id(format!("{}.{}",
2846                                        ItemType::Variant,
2847                                        variant.name.as_ref().unwrap()));
2848             let ns_id = derive_id(format!("{}.{}",
2849                                           variant.name.as_ref().unwrap(),
2850                                           ItemType::Variant.name_space()));
2851             write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
2852                        <a href=\"#{id}\" class=\"anchor field\"></a>\
2853                        <span id='{ns_id}' class='invisible'><code>{name}",
2854                    id = id,
2855                    ns_id = ns_id,
2856                    name = variant.name.as_ref().unwrap())?;
2857             if let clean::VariantItem(ref var) = variant.inner {
2858                 if let clean::VariantKind::Tuple(ref tys) = var.kind {
2859                     write!(w, "(")?;
2860                     for (i, ty) in tys.iter().enumerate() {
2861                         if i > 0 {
2862                             write!(w, ",&nbsp;")?;
2863                         }
2864                         write!(w, "{}", *ty)?;
2865                     }
2866                     write!(w, ")")?;
2867                 }
2868             }
2869             write!(w, "</code></span></span>")?;
2870             document(w, cx, variant)?;
2871
2872             use clean::{Variant, VariantKind};
2873             if let clean::VariantItem(Variant {
2874                 kind: VariantKind::Struct(ref s)
2875             }) = variant.inner {
2876                 let variant_id = derive_id(format!("{}.{}.fields",
2877                                                    ItemType::Variant,
2878                                                    variant.name.as_ref().unwrap()));
2879                 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
2880                        id = variant_id)?;
2881                 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
2882                            <table>", name = variant.name.as_ref().unwrap())?;
2883                 for field in &s.fields {
2884                     use clean::StructFieldItem;
2885                     if let StructFieldItem(ref ty) = field.inner {
2886                         let id = derive_id(format!("variant.{}.field.{}",
2887                                                    variant.name.as_ref().unwrap(),
2888                                                    field.name.as_ref().unwrap()));
2889                         let ns_id = derive_id(format!("{}.{}.{}.{}",
2890                                                       variant.name.as_ref().unwrap(),
2891                                                       ItemType::Variant.name_space(),
2892                                                       field.name.as_ref().unwrap(),
2893                                                       ItemType::StructField.name_space()));
2894                         write!(w, "<tr><td \
2895                                    id='{id}'>\
2896                                    <span id='{ns_id}' class='invisible'>\
2897                                    <code>{f}:&nbsp;{t}</code></span></td><td>",
2898                                id = id,
2899                                ns_id = ns_id,
2900                                f = field.name.as_ref().unwrap(),
2901                                t = *ty)?;
2902                         document(w, cx, field)?;
2903                         write!(w, "</td></tr>")?;
2904                     }
2905                 }
2906                 write!(w, "</table></span>")?;
2907             }
2908             render_stability_since(w, variant, it)?;
2909         }
2910     }
2911     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2912     Ok(())
2913 }
2914
2915 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
2916     let name = attr.name();
2917
2918     if attr.is_word() {
2919         Some(format!("{}", name))
2920     } else if let Some(v) = attr.value_str() {
2921         Some(format!("{} = {:?}", name, v.as_str()))
2922     } else if let Some(values) = attr.meta_item_list() {
2923         let display: Vec<_> = values.iter().filter_map(|attr| {
2924             attr.meta_item().and_then(|mi| render_attribute(mi))
2925         }).collect();
2926
2927         if display.len() > 0 {
2928             Some(format!("{}({})", name, display.join(", ")))
2929         } else {
2930             None
2931         }
2932     } else {
2933         None
2934     }
2935 }
2936
2937 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
2938     "export_name",
2939     "lang",
2940     "link_section",
2941     "must_use",
2942     "no_mangle",
2943     "repr",
2944     "unsafe_destructor_blind_to_params"
2945 ];
2946
2947 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
2948     let mut attrs = String::new();
2949
2950     for attr in &it.attrs.other_attrs {
2951         let name = attr.name().unwrap();
2952         if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
2953             continue;
2954         }
2955         if let Some(s) = render_attribute(&attr.meta().unwrap()) {
2956             attrs.push_str(&format!("#[{}]\n", s));
2957         }
2958     }
2959     if attrs.len() > 0 {
2960         write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
2961     }
2962     Ok(())
2963 }
2964
2965 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
2966                  g: Option<&clean::Generics>,
2967                  ty: doctree::StructType,
2968                  fields: &[clean::Item],
2969                  tab: &str,
2970                  structhead: bool) -> fmt::Result {
2971     write!(w, "{}{}{}",
2972            VisSpace(&it.visibility),
2973            if structhead {"struct "} else {""},
2974            it.name.as_ref().unwrap())?;
2975     if let Some(g) = g {
2976         write!(w, "{}", g)?
2977     }
2978     match ty {
2979         doctree::Plain => {
2980             if let Some(g) = g {
2981                 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
2982             }
2983             let mut has_visible_fields = false;
2984             write!(w, " {{")?;
2985             for field in fields {
2986                 if let clean::StructFieldItem(ref ty) = field.inner {
2987                     write!(w, "\n{}    {}{}: {},",
2988                            tab,
2989                            VisSpace(&field.visibility),
2990                            field.name.as_ref().unwrap(),
2991                            *ty)?;
2992                     has_visible_fields = true;
2993                 }
2994             }
2995
2996             if has_visible_fields {
2997                 if it.has_stripped_fields().unwrap() {
2998                     write!(w, "\n{}    // some fields omitted", tab)?;
2999                 }
3000                 write!(w, "\n{}", tab)?;
3001             } else if it.has_stripped_fields().unwrap() {
3002                 // If there are no visible fields we can just display
3003                 // `{ /* fields omitted */ }` to save space.
3004                 write!(w, " /* fields omitted */ ")?;
3005             }
3006             write!(w, "}}")?;
3007         }
3008         doctree::Tuple => {
3009             write!(w, "(")?;
3010             for (i, field) in fields.iter().enumerate() {
3011                 if i > 0 {
3012                     write!(w, ", ")?;
3013                 }
3014                 match field.inner {
3015                     clean::StrippedItem(box clean::StructFieldItem(..)) => {
3016                         write!(w, "_")?
3017                     }
3018                     clean::StructFieldItem(ref ty) => {
3019                         write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
3020                     }
3021                     _ => unreachable!()
3022                 }
3023             }
3024             write!(w, ")")?;
3025             if let Some(g) = g {
3026                 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3027             }
3028             write!(w, ";")?;
3029         }
3030         doctree::Unit => {
3031             // Needed for PhantomData.
3032             if let Some(g) = g {
3033                 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
3034             }
3035             write!(w, ";")?;
3036         }
3037     }
3038     Ok(())
3039 }
3040
3041 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
3042                 g: Option<&clean::Generics>,
3043                 fields: &[clean::Item],
3044                 tab: &str,
3045                 structhead: bool) -> fmt::Result {
3046     write!(w, "{}{}{}",
3047            VisSpace(&it.visibility),
3048            if structhead {"union "} else {""},
3049            it.name.as_ref().unwrap())?;
3050     if let Some(g) = g {
3051         write!(w, "{}", g)?;
3052         write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
3053     }
3054
3055     write!(w, " {{\n{}", tab)?;
3056     for field in fields {
3057         if let clean::StructFieldItem(ref ty) = field.inner {
3058             write!(w, "    {}{}: {},\n{}",
3059                    VisSpace(&field.visibility),
3060                    field.name.as_ref().unwrap(),
3061                    *ty,
3062                    tab)?;
3063         }
3064     }
3065
3066     if it.has_stripped_fields().unwrap() {
3067         write!(w, "    // some fields omitted\n{}", tab)?;
3068     }
3069     write!(w, "}}")?;
3070     Ok(())
3071 }
3072
3073 #[derive(Copy, Clone)]
3074 enum AssocItemLink<'a> {
3075     Anchor(Option<&'a str>),
3076     GotoSource(DefId, &'a FxHashSet<String>),
3077 }
3078
3079 impl<'a> AssocItemLink<'a> {
3080     fn anchor(&self, id: &'a String) -> Self {
3081         match *self {
3082             AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3083             ref other => *other,
3084         }
3085     }
3086 }
3087
3088 enum AssocItemRender<'a> {
3089     All,
3090     DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3091 }
3092
3093 #[derive(Copy, Clone, PartialEq)]
3094 enum RenderMode {
3095     Normal,
3096     ForDeref { mut_: bool },
3097 }
3098
3099 fn render_assoc_items(w: &mut fmt::Formatter,
3100                       cx: &Context,
3101                       containing_item: &clean::Item,
3102                       it: DefId,
3103                       what: AssocItemRender) -> fmt::Result {
3104     let c = cache();
3105     let v = match c.impls.get(&it) {
3106         Some(v) => v,
3107         None => return Ok(()),
3108     };
3109     let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3110         i.inner_impl().trait_.is_none()
3111     });
3112     if !non_trait.is_empty() {
3113         let render_mode = match what {
3114             AssocItemRender::All => {
3115                 write!(w, "
3116                     <h2 id='methods' class='small-section-header'>
3117                       Methods<a href='#methods' class='anchor'></a>
3118                     </h2>
3119                 ")?;
3120                 RenderMode::Normal
3121             }
3122             AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3123                 write!(w, "
3124                     <h2 id='deref-methods' class='small-section-header'>
3125                       Methods from {}&lt;Target = {}&gt;<a href='#deref-methods' class='anchor'></a>
3126                     </h2>
3127                 ", trait_, type_)?;
3128                 RenderMode::ForDeref { mut_: deref_mut_ }
3129             }
3130         };
3131         for i in &non_trait {
3132             render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3133                         containing_item.stable_since(), true)?;
3134         }
3135     }
3136     if let AssocItemRender::DerefFor { .. } = what {
3137         return Ok(());
3138     }
3139     if !traits.is_empty() {
3140         let deref_impl = traits.iter().find(|t| {
3141             t.inner_impl().trait_.def_id() == c.deref_trait_did
3142         });
3143         if let Some(impl_) = deref_impl {
3144             let has_deref_mut = traits.iter().find(|t| {
3145                 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3146             }).is_some();
3147             render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3148         }
3149
3150         let (synthetic, concrete) = traits
3151             .iter()
3152             .partition::<Vec<_>, _>(|t| t.inner_impl().synthetic);
3153
3154         write!(w, "
3155             <h2 id='implementations' class='small-section-header'>
3156               Trait Implementations<a href='#implementations' class='anchor'></a>
3157             </h2>
3158             <div id='implementations-list'>
3159         ")?;
3160         render_impls(cx, w, concrete, containing_item)?;
3161         write!(w, "</div>")?;
3162
3163         write!(w, "
3164             <h2 id='synthetic-implementations' class='small-section-header'>
3165               Auto Trait Implementations<a href='#synthetic-implementations' class='anchor'></a>
3166             </h2>
3167             <div id='synthetic-implementations-list'>
3168         ")?;
3169         render_impls(cx, w, synthetic, containing_item)?;
3170         write!(w, "</div>")?;
3171     }
3172     Ok(())
3173 }
3174
3175 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3176                         container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3177     let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3178     let target = impl_.inner_impl().items.iter().filter_map(|item| {
3179         match item.inner {
3180             clean::TypedefItem(ref t, true) => Some(&t.type_),
3181             _ => None,
3182         }
3183     }).next().expect("Expected associated type binding");
3184     let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3185                                            deref_mut_: deref_mut };
3186     if let Some(did) = target.def_id() {
3187         render_assoc_items(w, cx, container_item, did, what)
3188     } else {
3189         if let Some(prim) = target.primitive_type() {
3190             if let Some(&did) = cache().primitive_locations.get(&prim) {
3191                 render_assoc_items(w, cx, container_item, did, what)?;
3192             }
3193         }
3194         Ok(())
3195     }
3196 }
3197
3198 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3199     let self_type_opt = match item.inner {
3200         clean::MethodItem(ref method) => method.decl.self_type(),
3201         clean::TyMethodItem(ref method) => method.decl.self_type(),
3202         _ => None
3203     };
3204
3205     if let Some(self_ty) = self_type_opt {
3206         let (by_mut_ref, by_box, by_value) = match self_ty {
3207             SelfTy::SelfBorrowed(_, mutability) |
3208             SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3209                 (mutability == Mutability::Mutable, false, false)
3210             },
3211             SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3212                 (false, Some(did) == cache().owned_box_did, false)
3213             },
3214             SelfTy::SelfValue => (false, false, true),
3215             _ => (false, false, false),
3216         };
3217
3218         (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3219     } else {
3220         false
3221     }
3222 }
3223
3224 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
3225     let mut out = String::new();
3226
3227     match item.inner {
3228         clean::FunctionItem(clean::Function { ref decl, .. }) |
3229         clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3230         clean::MethodItem(clean::Method { ref decl, .. }) |
3231         clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
3232             out = spotlight_decl(decl)?;
3233         }
3234         _ => {}
3235     }
3236
3237     Ok(out)
3238 }
3239
3240 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
3241     let mut out = String::new();
3242     let mut trait_ = String::new();
3243
3244     if let Some(did) = decl.output.def_id() {
3245         let c = cache();
3246         if let Some(impls) = c.impls.get(&did) {
3247             for i in impls {
3248                 let impl_ = i.inner_impl();
3249                 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3250                     if out.is_empty() {
3251                         out.push_str(
3252                             &format!("<h3 class=\"important\">Important traits for {}</h3>\
3253                                       <code class=\"content\">",
3254                                      impl_.for_));
3255                         trait_.push_str(&format!("{}", impl_.for_));
3256                     }
3257
3258                     //use the "where" class here to make it small
3259                     out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
3260                     let t_did = impl_.trait_.def_id().unwrap();
3261                     for it in &impl_.items {
3262                         if let clean::TypedefItem(ref tydef, _) = it.inner {
3263                             out.push_str("<span class=\"where fmt-newline\">    ");
3264                             assoc_type(&mut out, it, &vec![],
3265                                        Some(&tydef.type_),
3266                                        AssocItemLink::GotoSource(t_did, &FxHashSet()))?;
3267                             out.push_str(";</span>");
3268                         }
3269                     }
3270                 }
3271             }
3272         }
3273     }
3274
3275     if !out.is_empty() {
3276         out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3277                                     <span class='tooltiptext'>Important traits for {}</span></div>\
3278                                     <div class=\"content hidden\">",
3279                                    trait_));
3280         out.push_str("</code></div></div>");
3281     }
3282
3283     Ok(out)
3284 }
3285
3286 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
3287                render_mode: RenderMode, outer_version: Option<&str>,
3288                show_def_docs: bool) -> fmt::Result {
3289     if render_mode == RenderMode::Normal {
3290         let id = derive_id(match i.inner_impl().trait_ {
3291             Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
3292             None => "impl".to_string(),
3293         });
3294         write!(w, "<h3 id='{}' class='impl'><span class='in-band'><code>{}</code>",
3295                id, i.inner_impl())?;
3296         write!(w, "<a href='#{}' class='anchor'></a>", id)?;
3297         write!(w, "</span><span class='out-of-band'>")?;
3298         let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3299         if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
3300             write!(w, "<div class='ghost'></div>")?;
3301             render_stability_since_raw(w, since, outer_version)?;
3302             write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3303                    l, "goto source code")?;
3304         } else {
3305             render_stability_since_raw(w, since, outer_version)?;
3306         }
3307         write!(w, "</span>")?;
3308         write!(w, "</h3>\n")?;
3309         if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3310             write!(w, "<div class='docblock'>{}</div>",
3311                    Markdown(&*dox, &i.impl_item.links()))?;
3312         }
3313     }
3314
3315     fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
3316                      link: AssocItemLink, render_mode: RenderMode,
3317                      is_default_item: bool, outer_version: Option<&str>,
3318                      trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
3319         let item_type = item.type_();
3320         let name = item.name.as_ref().unwrap();
3321
3322         let render_method_item: bool = match render_mode {
3323             RenderMode::Normal => true,
3324             RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3325         };
3326
3327         match item.inner {
3328             clean::MethodItem(clean::Method { ref decl, .. }) |
3329             clean::TyMethodItem(clean::TyMethod{ ref decl, .. }) => {
3330                 // Only render when the method is not static or we allow static methods
3331                 if render_method_item {
3332                     let id = derive_id(format!("{}.{}", item_type, name));
3333                     let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3334                     write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3335                     write!(w, "{}", spotlight_decl(decl)?)?;
3336                     write!(w, "<span id='{}' class='invisible'>", ns_id)?;
3337                     write!(w, "<code>")?;
3338                     render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
3339                     write!(w, "</code>")?;
3340                     if let Some(l) = (Item { cx, item }).src_href() {
3341                         write!(w, "</span><span class='out-of-band'>")?;
3342                         write!(w, "<div class='ghost'></div>")?;
3343                         render_stability_since_raw(w, item.stable_since(), outer_version)?;
3344                         write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3345                                l, "goto source code")?;
3346                     } else {
3347                         render_stability_since_raw(w, item.stable_since(), outer_version)?;
3348                     }
3349                     write!(w, "</span></h4>\n")?;
3350                 }
3351             }
3352             clean::TypedefItem(ref tydef, _) => {
3353                 let id = derive_id(format!("{}.{}", ItemType::AssociatedType, name));
3354                 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3355                 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3356                 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3357                 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
3358                 write!(w, "</code></span></h4>\n")?;
3359             }
3360             clean::AssociatedConstItem(ref ty, ref default) => {
3361                 let id = derive_id(format!("{}.{}", item_type, name));
3362                 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3363                 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3364                 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3365                 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
3366                 write!(w, "</code></span></h4>\n")?;
3367             }
3368             clean::AssociatedTypeItem(ref bounds, ref default) => {
3369                 let id = derive_id(format!("{}.{}", item_type, name));
3370                 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3371                 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3372                 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3373                 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
3374                 write!(w, "</code></span></h4>\n")?;
3375             }
3376             clean::StrippedItem(..) => return Ok(()),
3377             _ => panic!("can't make docs for trait item with name {:?}", item.name)
3378         }
3379
3380         if render_method_item || render_mode == RenderMode::Normal {
3381             let prefix = render_assoc_const_value(item);
3382
3383             if !is_default_item {
3384                 if let Some(t) = trait_ {
3385                     // The trait item may have been stripped so we might not
3386                     // find any documentation or stability for it.
3387                     if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3388                         // We need the stability of the item from the trait
3389                         // because impls can't have a stability.
3390                         document_stability(w, cx, it)?;
3391                         if item.doc_value().is_some() {
3392                             document_full(w, item, cx, &prefix)?;
3393                         } else if show_def_docs {
3394                             // In case the item isn't documented,
3395                             // provide short documentation from the trait.
3396                             document_short(w, it, link, &prefix)?;
3397                         }
3398                     }
3399                 } else {
3400                     document_stability(w, cx, item)?;
3401                     if show_def_docs {
3402                         document_full(w, item, cx, &prefix)?;
3403                     }
3404                 }
3405             } else {
3406                 document_stability(w, cx, item)?;
3407                 if show_def_docs {
3408                     document_short(w, item, link, &prefix)?;
3409                 }
3410             }
3411         }
3412         Ok(())
3413     }
3414
3415     let traits = &cache().traits;
3416     let trait_ = i.trait_did().map(|did| &traits[&did]);
3417
3418     if !show_def_docs {
3419         write!(w, "<span class='docblock autohide'>")?;
3420     }
3421
3422     write!(w, "<div class='impl-items'>")?;
3423     for trait_item in &i.inner_impl().items {
3424         doc_impl_item(w, cx, trait_item, link, render_mode,
3425                       false, outer_version, trait_, show_def_docs)?;
3426     }
3427
3428     fn render_default_items(w: &mut fmt::Formatter,
3429                             cx: &Context,
3430                             t: &clean::Trait,
3431                             i: &clean::Impl,
3432                             render_mode: RenderMode,
3433                             outer_version: Option<&str>,
3434                             show_def_docs: bool) -> fmt::Result {
3435         for trait_item in &t.items {
3436             let n = trait_item.name.clone();
3437             if i.items.iter().find(|m| m.name == n).is_some() {
3438                 continue;
3439             }
3440             let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3441             let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3442
3443             doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3444                           outer_version, None, show_def_docs)?;
3445         }
3446         Ok(())
3447     }
3448
3449     // If we've implemented a trait, then also emit documentation for all
3450     // default items which weren't overridden in the implementation block.
3451     if let Some(t) = trait_ {
3452         render_default_items(w, cx, t, &i.inner_impl(),
3453                              render_mode, outer_version, show_def_docs)?;
3454     }
3455     write!(w, "</div>")?;
3456
3457     if !show_def_docs {
3458         write!(w, "</span>")?;
3459     }
3460
3461     Ok(())
3462 }
3463
3464 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3465                 t: &clean::Typedef) -> fmt::Result {
3466     write!(w, "<pre class='rust typedef'>")?;
3467     render_attributes(w, it)?;
3468     write!(w, "type {}{}{where_clause} = {type_};</pre>",
3469            it.name.as_ref().unwrap(),
3470            t.generics,
3471            where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3472            type_ = t.type_)?;
3473
3474     document(w, cx, it)?;
3475
3476     // Render any items associated directly to this alias, as otherwise they
3477     // won't be visible anywhere in the docs. It would be nice to also show
3478     // associated items from the aliased type (see discussion in #32077), but
3479     // we need #14072 to make sense of the generics.
3480     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3481 }
3482
3483 fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
3484     writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
3485     render_attributes(w, it)?;
3486     write!(
3487         w,
3488         "    {}type {};\n}}</pre>",
3489         VisSpace(&it.visibility),
3490         it.name.as_ref().unwrap(),
3491     )?;
3492
3493     document(w, cx, it)?;
3494
3495     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3496 }
3497
3498 impl<'a> fmt::Display for Sidebar<'a> {
3499     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3500         let cx = self.cx;
3501         let it = self.item;
3502         let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3503         let mut should_close = false;
3504
3505         if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3506             || it.is_enum() || it.is_mod() || it.is_typedef()
3507         {
3508             write!(fmt, "<p class='location'>")?;
3509             match it.inner {
3510                 clean::StructItem(..) => write!(fmt, "Struct ")?,
3511                 clean::TraitItem(..) => write!(fmt, "Trait ")?,
3512                 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
3513                 clean::UnionItem(..) => write!(fmt, "Union ")?,
3514                 clean::EnumItem(..) => write!(fmt, "Enum ")?,
3515                 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
3516                 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
3517                 clean::ModuleItem(..) => if it.is_crate() {
3518                     write!(fmt, "Crate ")?;
3519                 } else {
3520                     write!(fmt, "Module ")?;
3521                 },
3522                 _ => (),
3523             }
3524             write!(fmt, "{}", it.name.as_ref().unwrap())?;
3525             write!(fmt, "</p>")?;
3526
3527             if it.is_crate() {
3528                 if let Some(ref version) = cache().crate_version {
3529                     write!(fmt,
3530                            "<div class='block version'>\
3531                             <p>Version {}</p>\
3532                             </div>",
3533                            version)?;
3534                 }
3535             }
3536
3537             write!(fmt, "<div class=\"sidebar-elems\">")?;
3538             should_close = true;
3539             match it.inner {
3540                 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
3541                 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
3542                 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
3543                 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
3544                 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
3545                 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
3546                 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
3547                 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
3548                 _ => (),
3549             }
3550         }
3551
3552         // The sidebar is designed to display sibling functions, modules and
3553         // other miscellaneous information. since there are lots of sibling
3554         // items (and that causes quadratic growth in large modules),
3555         // we refactor common parts into a shared JavaScript file per module.
3556         // still, we don't move everything into JS because we want to preserve
3557         // as much HTML as possible in order to allow non-JS-enabled browsers
3558         // to navigate the documentation (though slightly inefficiently).
3559
3560         write!(fmt, "<p class='location'>")?;
3561         for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3562             if i > 0 {
3563                 write!(fmt, "::<wbr>")?;
3564             }
3565             write!(fmt, "<a href='{}index.html'>{}</a>",
3566                    &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3567                    *name)?;
3568         }
3569         write!(fmt, "</p>")?;
3570
3571         // Sidebar refers to the enclosing module, not this module.
3572         let relpath = if it.is_mod() { "../" } else { "" };
3573         write!(fmt,
3574                "<script>window.sidebarCurrent = {{\
3575                    name: '{name}', \
3576                    ty: '{ty}', \
3577                    relpath: '{path}'\
3578                 }};</script>",
3579                name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3580                ty = it.type_().css_class(),
3581                path = relpath)?;
3582         if parentlen == 0 {
3583             // There is no sidebar-items.js beyond the crate root path
3584             // FIXME maybe dynamic crate loading can be merged here
3585         } else {
3586             write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
3587                    path = relpath)?;
3588         }
3589         if should_close {
3590             // Closes sidebar-elems div.
3591             write!(fmt, "</div>")?;
3592         }
3593
3594         Ok(())
3595     }
3596 }
3597
3598 fn get_methods(i: &clean::Impl, for_deref: bool) -> Vec<String> {
3599     i.items.iter().filter_map(|item| {
3600         match item.name {
3601             // Maybe check with clean::Visibility::Public as well?
3602             Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
3603                 if !for_deref || should_render_item(item, false) {
3604                     Some(format!("<a href=\"#method.{name}\">{name}</a>", name = name))
3605                 } else {
3606                     None
3607                 }
3608             }
3609             _ => None,
3610         }
3611     }).collect::<Vec<_>>()
3612 }
3613
3614 // The point is to url encode any potential character from a type with genericity.
3615 fn small_url_encode(s: &str) -> String {
3616     s.replace("<", "%3C")
3617      .replace(">", "%3E")
3618      .replace(" ", "%20")
3619      .replace("?", "%3F")
3620      .replace("'", "%27")
3621      .replace("&", "%26")
3622      .replace(",", "%2C")
3623      .replace(":", "%3A")
3624      .replace(";", "%3B")
3625      .replace("[", "%5B")
3626      .replace("]", "%5D")
3627      .replace("\"", "%22")
3628 }
3629
3630 fn sidebar_assoc_items(it: &clean::Item) -> String {
3631     let mut out = String::new();
3632     let c = cache();
3633     if let Some(v) = c.impls.get(&it.def_id) {
3634         let ret = v.iter()
3635                    .filter(|i| i.inner_impl().trait_.is_none())
3636                    .flat_map(|i| get_methods(i.inner_impl(), false))
3637                    .collect::<String>();
3638         if !ret.is_empty() {
3639             out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
3640                                    </a><div class=\"sidebar-links\">{}</div>", ret));
3641         }
3642
3643         if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
3644             if let Some(impl_) = v.iter()
3645                                   .filter(|i| i.inner_impl().trait_.is_some())
3646                                   .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
3647                 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
3648                     match item.inner {
3649                         clean::TypedefItem(ref t, true) => Some(&t.type_),
3650                         _ => None,
3651                     }
3652                 }).next() {
3653                     let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
3654                         c.primitive_locations.get(&prim).cloned()
3655                     })).and_then(|did| c.impls.get(&did));
3656                     if let Some(impls) = inner_impl {
3657                         out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
3658                         out.push_str(&format!("Methods from {}&lt;Target={}&gt;",
3659                                               Escape(&format!("{:#}",
3660                                                      impl_.inner_impl().trait_.as_ref().unwrap())),
3661                                               Escape(&format!("{:#}", target))));
3662                         out.push_str("</a>");
3663                         let ret = impls.iter()
3664                                        .filter(|i| i.inner_impl().trait_.is_none())
3665                                        .flat_map(|i| get_methods(i.inner_impl(), true))
3666                                        .collect::<String>();
3667                         out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
3668                     }
3669                 }
3670             }
3671             let format_impls = |impls: Vec<&Impl>| {
3672                 let mut links = HashSet::new();
3673                 impls.iter()
3674                            .filter_map(|i| {
3675                                let is_negative_impl = is_negative_impl(i.inner_impl());
3676                                if let Some(ref i) = i.inner_impl().trait_ {
3677                                    let i_display = format!("{:#}", i);
3678                                    let out = Escape(&i_display);
3679                                    let encoded = small_url_encode(&format!("{:#}", i));
3680                                    let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
3681                                                            encoded,
3682                                                            if is_negative_impl { "!" } else { "" },
3683                                                            out);
3684                                    if links.insert(generated.clone()) {
3685                                        Some(generated)
3686                                    } else {
3687                                        None
3688                                    }
3689                                } else {
3690                                    None
3691                                }
3692                            })
3693                            .collect::<String>()
3694             };
3695
3696             let (synthetic, concrete) = v
3697                 .iter()
3698                 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
3699
3700             let concrete_format = format_impls(concrete);
3701             let synthetic_format = format_impls(synthetic);
3702
3703             if !concrete_format.is_empty() {
3704                 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
3705                               Trait Implementations</a>");
3706                 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
3707             }
3708
3709             if !synthetic_format.is_empty() {
3710                 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
3711                               Auto Trait Implementations</a>");
3712                 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
3713             }
3714         }
3715     }
3716
3717     out
3718 }
3719
3720 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
3721                   s: &clean::Struct) -> fmt::Result {
3722     let mut sidebar = String::new();
3723     let fields = get_struct_fields_name(&s.fields);
3724
3725     if !fields.is_empty() {
3726         if let doctree::Plain = s.struct_type {
3727             sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3728                                        <div class=\"sidebar-links\">{}</div>", fields));
3729         }
3730     }
3731
3732     sidebar.push_str(&sidebar_assoc_items(it));
3733
3734     if !sidebar.is_empty() {
3735         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3736     }
3737     Ok(())
3738 }
3739
3740 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
3741     match item.inner {
3742         clean::ItemEnum::ImplItem(ref i) => {
3743             if let Some(ref trait_) = i.trait_ {
3744                 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
3745             } else {
3746                 None
3747             }
3748         },
3749         _ => None,
3750     }
3751 }
3752
3753 fn is_negative_impl(i: &clean::Impl) -> bool {
3754     i.polarity == Some(clean::ImplPolarity::Negative)
3755 }
3756
3757 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
3758                  t: &clean::Trait) -> fmt::Result {
3759     let mut sidebar = String::new();
3760
3761     let types = t.items
3762                  .iter()
3763                  .filter_map(|m| {
3764                      match m.name {
3765                          Some(ref name) if m.is_associated_type() => {
3766                              Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
3767                                           name=name))
3768                          }
3769                          _ => None,
3770                      }
3771                  })
3772                  .collect::<String>();
3773     let consts = t.items
3774                   .iter()
3775                   .filter_map(|m| {
3776                       match m.name {
3777                           Some(ref name) if m.is_associated_const() => {
3778                               Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
3779                                            name=name))
3780                           }
3781                           _ => None,
3782                       }
3783                   })
3784                   .collect::<String>();
3785     let required = t.items
3786                     .iter()
3787                     .filter_map(|m| {
3788                         match m.name {
3789                             Some(ref name) if m.is_ty_method() => {
3790                                 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
3791                                              name=name))
3792                             }
3793                             _ => None,
3794                         }
3795                     })
3796                     .collect::<String>();
3797     let provided = t.items
3798                     .iter()
3799                     .filter_map(|m| {
3800                         match m.name {
3801                             Some(ref name) if m.is_method() => {
3802                                 Some(format!("<a href=\"#method.{name}\">{name}</a>", name=name))
3803                             }
3804                             _ => None,
3805                         }
3806                     })
3807                     .collect::<String>();
3808
3809     if !types.is_empty() {
3810         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
3811                                    Associated Types</a><div class=\"sidebar-links\">{}</div>",
3812                                   types));
3813     }
3814     if !consts.is_empty() {
3815         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
3816                                    Associated Constants</a><div class=\"sidebar-links\">{}</div>",
3817                                   consts));
3818     }
3819     if !required.is_empty() {
3820         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
3821                                    Required Methods</a><div class=\"sidebar-links\">{}</div>",
3822                                   required));
3823     }
3824     if !provided.is_empty() {
3825         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
3826                                    Provided Methods</a><div class=\"sidebar-links\">{}</div>",
3827                                   provided));
3828     }
3829
3830     let c = cache();
3831
3832     if let Some(implementors) = c.implementors.get(&it.def_id) {
3833         let res = implementors.iter()
3834                               .filter(|i| i.inner_impl().for_.def_id()
3835                               .map_or(false, |d| !c.paths.contains_key(&d)))
3836                               .filter_map(|i| {
3837                                   match extract_for_impl_name(&i.impl_item) {
3838                                       Some((ref name, ref url)) => {
3839                                           Some(format!("<a href=\"#impl-{}\">{}</a>",
3840                                                       small_url_encode(url),
3841                                                       Escape(name)))
3842                                       }
3843                                       _ => None,
3844                                   }
3845                               })
3846                               .collect::<String>();
3847         if !res.is_empty() {
3848             sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
3849                                        Implementations on Foreign Types</a><div \
3850                                        class=\"sidebar-links\">{}</div>",
3851                                       res));
3852         }
3853     }
3854
3855     sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
3856     if t.auto {
3857         sidebar.push_str("<a class=\"sidebar-title\" \
3858                           href=\"#synthetic-implementors\">Auto Implementors</a>");
3859     }
3860
3861     sidebar.push_str(&sidebar_assoc_items(it));
3862
3863     write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
3864 }
3865
3866 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
3867                      _p: &clean::PrimitiveType) -> fmt::Result {
3868     let sidebar = sidebar_assoc_items(it);
3869
3870     if !sidebar.is_empty() {
3871         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3872     }
3873     Ok(())
3874 }
3875
3876 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
3877                    _t: &clean::Typedef) -> fmt::Result {
3878     let sidebar = sidebar_assoc_items(it);
3879
3880     if !sidebar.is_empty() {
3881         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3882     }
3883     Ok(())
3884 }
3885
3886 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
3887     fields.iter()
3888           .filter(|f| if let clean::StructFieldItem(..) = f.inner {
3889               true
3890           } else {
3891               false
3892           })
3893           .filter_map(|f| match f.name {
3894               Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
3895                                               {name}</a>", name=name)),
3896               _ => None,
3897           })
3898           .collect()
3899 }
3900
3901 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
3902                  u: &clean::Union) -> fmt::Result {
3903     let mut sidebar = String::new();
3904     let fields = get_struct_fields_name(&u.fields);
3905
3906     if !fields.is_empty() {
3907         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3908                                    <div class=\"sidebar-links\">{}</div>", fields));
3909     }
3910
3911     sidebar.push_str(&sidebar_assoc_items(it));
3912
3913     if !sidebar.is_empty() {
3914         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3915     }
3916     Ok(())
3917 }
3918
3919 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
3920                 e: &clean::Enum) -> fmt::Result {
3921     let mut sidebar = String::new();
3922
3923     let variants = e.variants.iter()
3924                              .filter_map(|v| match v.name {
3925                                  Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
3926                                                                  </a>", name = name)),
3927                                  _ => None,
3928                              })
3929                              .collect::<String>();
3930     if !variants.is_empty() {
3931         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
3932                                    <div class=\"sidebar-links\">{}</div>", variants));
3933     }
3934
3935     sidebar.push_str(&sidebar_assoc_items(it));
3936
3937     if !sidebar.is_empty() {
3938         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3939     }
3940     Ok(())
3941 }
3942
3943 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
3944                   items: &[clean::Item]) -> fmt::Result {
3945     let mut sidebar = String::new();
3946
3947     if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
3948                              it.type_() == ItemType::Import) {
3949         sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
3950                                   id = "reexports",
3951                                   name = "Re-exports"));
3952     }
3953
3954     // ordering taken from item_module, reorder, where it prioritized elements in a certain order
3955     // to print its headings
3956     for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
3957                    ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
3958                    ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
3959                    ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
3960                    ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
3961         if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
3962             let (short, name) = match myty {
3963                 ItemType::ExternCrate |
3964                 ItemType::Import          => ("reexports", "Re-exports"),
3965                 ItemType::Module          => ("modules", "Modules"),
3966                 ItemType::Struct          => ("structs", "Structs"),
3967                 ItemType::Union           => ("unions", "Unions"),
3968                 ItemType::Enum            => ("enums", "Enums"),
3969                 ItemType::Function        => ("functions", "Functions"),
3970                 ItemType::Typedef         => ("types", "Type Definitions"),
3971                 ItemType::Static          => ("statics", "Statics"),
3972                 ItemType::Constant        => ("constants", "Constants"),
3973                 ItemType::Trait           => ("traits", "Traits"),
3974                 ItemType::Impl            => ("impls", "Implementations"),
3975                 ItemType::TyMethod        => ("tymethods", "Type Methods"),
3976                 ItemType::Method          => ("methods", "Methods"),
3977                 ItemType::StructField     => ("fields", "Struct Fields"),
3978                 ItemType::Variant         => ("variants", "Variants"),
3979                 ItemType::Macro           => ("macros", "Macros"),
3980                 ItemType::Primitive       => ("primitives", "Primitive Types"),
3981                 ItemType::AssociatedType  => ("associated-types", "Associated Types"),
3982                 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
3983                 ItemType::ForeignType     => ("foreign-types", "Foreign Types"),
3984             };
3985             sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
3986                                       id = short,
3987                                       name = name));
3988         }
3989     }
3990
3991     if !sidebar.is_empty() {
3992         write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
3993     }
3994     Ok(())
3995 }
3996
3997 fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
3998     let sidebar = sidebar_assoc_items(it);
3999     if !sidebar.is_empty() {
4000         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
4001     }
4002     Ok(())
4003 }
4004
4005 impl<'a> fmt::Display for Source<'a> {
4006     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4007         let Source(s) = *self;
4008         let lines = s.lines().count();
4009         let mut cols = 0;
4010         let mut tmp = lines;
4011         while tmp > 0 {
4012             cols += 1;
4013             tmp /= 10;
4014         }
4015         write!(fmt, "<pre class=\"line-numbers\">")?;
4016         for i in 1..lines + 1 {
4017             write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
4018         }
4019         write!(fmt, "</pre>")?;
4020         write!(fmt, "{}",
4021                highlight::render_with_highlighting(s, None, None, None, None))?;
4022         Ok(())
4023     }
4024 }
4025
4026 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4027               t: &clean::Macro) -> fmt::Result {
4028     w.write_str(&highlight::render_with_highlighting(&t.source,
4029                                                      Some("macro"),
4030                                                      None,
4031                                                      None,
4032                                                      None))?;
4033     document(w, cx, it)
4034 }
4035
4036 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
4037                   it: &clean::Item,
4038                   _p: &clean::PrimitiveType) -> fmt::Result {
4039     document(w, cx, it)?;
4040     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4041 }
4042
4043 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
4044
4045 fn make_item_keywords(it: &clean::Item) -> String {
4046     format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
4047 }
4048
4049 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
4050     let decl = match item.inner {
4051         clean::FunctionItem(ref f) => &f.decl,
4052         clean::MethodItem(ref m) => &m.decl,
4053         clean::TyMethodItem(ref m) => &m.decl,
4054         _ => return None
4055     };
4056
4057     let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
4058     let output = match decl.output {
4059         clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
4060         _ => None
4061     };
4062
4063     Some(IndexItemFunctionType { inputs: inputs, output: output })
4064 }
4065
4066 fn get_index_type(clean_type: &clean::Type) -> Type {
4067     let t = Type {
4068         name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
4069         generics: get_generics(clean_type),
4070     };
4071     t
4072 }
4073
4074 /// Returns a list of all paths used in the type.
4075 /// This is used to help deduplicate imported impls
4076 /// for reexported types. If any of the contained
4077 /// types are re-exported, we don't use the corresponding
4078 /// entry from the js file, as inlining will have already
4079 /// picked up the impl
4080 fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4081     let mut out = Vec::new();
4082     let mut visited = FxHashSet();
4083     let mut work = VecDeque::new();
4084     let cache = cache();
4085
4086     work.push_back(first_ty);
4087
4088     while let Some(ty) = work.pop_front() {
4089         if !visited.insert(ty.clone()) {
4090             continue;
4091         }
4092
4093         match ty {
4094             clean::Type::ResolvedPath { did, .. } => {
4095                 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4096                 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4097
4098                 match fqp {
4099                     Some(path) => {
4100                         out.push(path.join("::"));
4101                     },
4102                     _ => {}
4103                 };
4104
4105             },
4106             clean::Type::Tuple(tys) => {
4107                 work.extend(tys.into_iter());
4108             },
4109             clean::Type::Slice(ty) => {
4110                 work.push_back(*ty);
4111             }
4112             clean::Type::Array(ty, _) => {
4113                 work.push_back(*ty);
4114             },
4115             clean::Type::Unique(ty) => {
4116                 work.push_back(*ty);
4117             },
4118             clean::Type::RawPointer(_, ty) => {
4119                 work.push_back(*ty);
4120             },
4121             clean::Type::BorrowedRef { type_, .. } => {
4122                 work.push_back(*type_);
4123             },
4124             clean::Type::QPath { self_type, trait_, .. } => {
4125                 work.push_back(*self_type);
4126                 work.push_back(*trait_);
4127             },
4128             _ => {}
4129         }
4130     };
4131     out
4132 }
4133
4134 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
4135     match *clean_type {
4136         clean::ResolvedPath { ref path, .. } => {
4137             let segments = &path.segments;
4138             let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
4139                 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
4140                 clean_type, accept_generic
4141             ));
4142             Some(path_segment.name.clone())
4143         }
4144         clean::Generic(ref s) if accept_generic => Some(s.clone()),
4145         clean::Primitive(ref p) => Some(format!("{:?}", p)),
4146         clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
4147         // FIXME: add all from clean::Type.
4148         _ => None
4149     }
4150 }
4151
4152 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
4153     clean_type.generics()
4154               .and_then(|types| {
4155                   let r = types.iter()
4156                                .filter_map(|t| get_index_type_name(t, false))
4157                                .map(|s| s.to_ascii_lowercase())
4158                                .collect::<Vec<_>>();
4159                   if r.is_empty() {
4160                       None
4161                   } else {
4162                       Some(r)
4163                   }
4164               })
4165 }
4166
4167 pub fn cache() -> Arc<Cache> {
4168     CACHE_KEY.with(|c| c.borrow().clone())
4169 }
4170
4171 #[cfg(test)]
4172 #[test]
4173 fn test_unique_id() {
4174     let input = ["foo", "examples", "examples", "method.into_iter","examples",
4175                  "method.into_iter", "foo", "main", "search", "methods",
4176                  "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
4177     let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
4178                     "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
4179                     "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
4180
4181     let test = || {
4182         let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
4183         assert_eq!(&actual[..], expected);
4184     };
4185     test();
4186     reset_ids(true);
4187     test();
4188 }
4189
4190 #[cfg(test)]
4191 #[test]
4192 fn test_name_key() {
4193     assert_eq!(name_key("0"), ("", 0, 1));
4194     assert_eq!(name_key("123"), ("", 123, 0));
4195     assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
4196     assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
4197     assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
4198     assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
4199     assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
4200     assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
4201 }
4202
4203 #[cfg(test)]
4204 #[test]
4205 fn test_name_sorting() {
4206     let names = ["Apple",
4207                  "Banana",
4208                  "Fruit", "Fruit0", "Fruit00",
4209                  "Fruit1", "Fruit01",
4210                  "Fruit2", "Fruit02",
4211                  "Fruit20",
4212                  "Fruit100",
4213                  "Pear"];
4214     let mut sorted = names.to_owned();
4215     sorted.sort_by_key(|&s| name_key(s));
4216     assert_eq!(names, sorted);
4217 }