]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/render.rs
Rollup merge of #39604 - est31:i128_tests, r=alexcrichton
[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::ascii::AsciiExt;
38 use std::cell::RefCell;
39 use std::cmp::Ordering;
40 use std::collections::BTreeMap;
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::feature_gate::UnstableFeatures;
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};
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 }
124
125 /// Indicates where an external crate can be found.
126 pub enum ExternalLocation {
127     /// Remote URL root of the external crate
128     Remote(String),
129     /// This external crate can be found in the local doc/ folder
130     Local,
131     /// The external crate could not be found.
132     Unknown,
133 }
134
135 /// Metadata about an implementor of a trait.
136 pub struct Implementor {
137     pub def_id: DefId,
138     pub stability: Option<clean::Stability>,
139     pub impl_: clean::Impl,
140 }
141
142 /// Metadata about implementations for a type.
143 #[derive(Clone)]
144 pub struct Impl {
145     pub impl_item: clean::Item,
146 }
147
148 impl Impl {
149     fn inner_impl(&self) -> &clean::Impl {
150         match self.impl_item.inner {
151             clean::ImplItem(ref impl_) => impl_,
152             _ => panic!("non-impl item found in impl")
153         }
154     }
155
156     fn trait_did(&self) -> Option<DefId> {
157         self.inner_impl().trait_.def_id()
158     }
159 }
160
161 #[derive(Debug)]
162 pub struct Error {
163     file: PathBuf,
164     error: io::Error,
165 }
166
167 impl error::Error for Error {
168     fn description(&self) -> &str {
169         self.error.description()
170     }
171 }
172
173 impl Display for Error {
174     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
175         write!(f, "\"{}\": {}", self.file.display(), self.error)
176     }
177 }
178
179 impl Error {
180     pub fn new(e: io::Error, file: &Path) -> Error {
181         Error {
182             file: file.to_path_buf(),
183             error: e,
184         }
185     }
186 }
187
188 macro_rules! try_err {
189     ($e:expr, $file:expr) => ({
190         match $e {
191             Ok(e) => e,
192             Err(e) => return Err(Error::new(e, $file)),
193         }
194     })
195 }
196
197 /// This cache is used to store information about the `clean::Crate` being
198 /// rendered in order to provide more useful documentation. This contains
199 /// information like all implementors of a trait, all traits a type implements,
200 /// documentation for all known traits, etc.
201 ///
202 /// This structure purposefully does not implement `Clone` because it's intended
203 /// to be a fairly large and expensive structure to clone. Instead this adheres
204 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
205 /// rendering threads.
206 #[derive(Default)]
207 pub struct Cache {
208     /// Mapping of typaram ids to the name of the type parameter. This is used
209     /// when pretty-printing a type (so pretty printing doesn't have to
210     /// painfully maintain a context like this)
211     pub typarams: FxHashMap<DefId, String>,
212
213     /// Maps a type id to all known implementations for that type. This is only
214     /// recognized for intra-crate `ResolvedPath` types, and is used to print
215     /// out extra documentation on the page of an enum/struct.
216     ///
217     /// The values of the map are a list of implementations and documentation
218     /// found on that implementation.
219     pub impls: FxHashMap<DefId, Vec<Impl>>,
220
221     /// Maintains a mapping of local crate node ids to the fully qualified name
222     /// and "short type description" of that node. This is used when generating
223     /// URLs when a type is being linked to. External paths are not located in
224     /// this map because the `External` type itself has all the information
225     /// necessary.
226     pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
227
228     /// Similar to `paths`, but only holds external paths. This is only used for
229     /// generating explicit hyperlinks to other crates.
230     pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
231
232     /// This map contains information about all known traits of this crate.
233     /// Implementations of a crate should inherit the documentation of the
234     /// parent trait if no extra documentation is specified, and default methods
235     /// should show up in documentation about trait implementations.
236     pub traits: FxHashMap<DefId, clean::Trait>,
237
238     /// When rendering traits, it's often useful to be able to list all
239     /// implementors of the trait, and this mapping is exactly, that: a mapping
240     /// of trait ids to the list of known implementors of the trait
241     pub implementors: FxHashMap<DefId, Vec<Implementor>>,
242
243     /// Cache of where external crate documentation can be found.
244     pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
245
246     /// Cache of where documentation for primitives can be found.
247     pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
248
249     // Note that external items for which `doc(hidden)` applies to are shown as
250     // non-reachable while local items aren't. This is because we're reusing
251     // the access levels from crateanalysis.
252     pub access_levels: Arc<AccessLevels<DefId>>,
253
254     // Private fields only used when initially crawling a crate to build a cache
255
256     stack: Vec<String>,
257     parent_stack: Vec<DefId>,
258     parent_is_trait_impl: bool,
259     search_index: Vec<IndexItem>,
260     stripped_mod: bool,
261     deref_trait_did: Option<DefId>,
262     deref_mut_trait_did: Option<DefId>,
263
264     // In rare case where a structure is defined in one module but implemented
265     // in another, if the implementing module is parsed before defining module,
266     // then the fully qualified name of the structure isn't presented in `paths`
267     // yet when its implementation methods are being indexed. Caches such methods
268     // and their parent id here and indexes them at the end of crate parsing.
269     orphan_impl_items: Vec<(DefId, clean::Item)>,
270 }
271
272 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
273 /// Later on moved into `CACHE_KEY`.
274 #[derive(Default)]
275 pub struct RenderInfo {
276     pub inlined: FxHashSet<DefId>,
277     pub external_paths: ::core::ExternalPaths,
278     pub external_typarams: FxHashMap<DefId, String>,
279     pub deref_trait_did: Option<DefId>,
280     pub deref_mut_trait_did: Option<DefId>,
281 }
282
283 /// Helper struct to render all source code to HTML pages
284 struct SourceCollector<'a> {
285     scx: &'a mut SharedContext,
286
287     /// Root destination to place all HTML output into
288     dst: PathBuf,
289 }
290
291 /// Wrapper struct to render the source code of a file. This will do things like
292 /// adding line numbers to the left-hand side.
293 struct Source<'a>(&'a str);
294
295 // Helper structs for rendering items/sidebars and carrying along contextual
296 // information
297
298 #[derive(Copy, Clone)]
299 struct Item<'a> {
300     cx: &'a Context,
301     item: &'a clean::Item,
302 }
303
304 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
305
306 /// Struct representing one entry in the JS search index. These are all emitted
307 /// by hand to a large JS file at the end of cache-creation.
308 struct IndexItem {
309     ty: ItemType,
310     name: String,
311     path: String,
312     desc: String,
313     parent: Option<DefId>,
314     parent_idx: Option<usize>,
315     search_type: Option<IndexItemFunctionType>,
316 }
317
318 impl ToJson for IndexItem {
319     fn to_json(&self) -> Json {
320         assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
321
322         let mut data = Vec::with_capacity(6);
323         data.push((self.ty as usize).to_json());
324         data.push(self.name.to_json());
325         data.push(self.path.to_json());
326         data.push(self.desc.to_json());
327         data.push(self.parent_idx.to_json());
328         data.push(self.search_type.to_json());
329
330         Json::Array(data)
331     }
332 }
333
334 /// A type used for the search index.
335 struct Type {
336     name: Option<String>,
337 }
338
339 impl ToJson for Type {
340     fn to_json(&self) -> Json {
341         match self.name {
342             Some(ref name) => {
343                 let mut data = BTreeMap::new();
344                 data.insert("name".to_owned(), name.to_json());
345                 Json::Object(data)
346             },
347             None => Json::Null
348         }
349     }
350 }
351
352 /// Full type of functions/methods in the search index.
353 struct IndexItemFunctionType {
354     inputs: Vec<Type>,
355     output: Option<Type>
356 }
357
358 impl ToJson for IndexItemFunctionType {
359     fn to_json(&self) -> Json {
360         // If we couldn't figure out a type, just write `null`.
361         if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
362             Json::Null
363         } else {
364             let mut data = BTreeMap::new();
365             data.insert("inputs".to_owned(), self.inputs.to_json());
366             data.insert("output".to_owned(), self.output.to_json());
367             Json::Object(data)
368         }
369     }
370 }
371
372 // TLS keys used to carry information around during rendering.
373
374 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
375 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> =
376                     RefCell::new(Vec::new()));
377 thread_local!(static USED_ID_MAP: RefCell<FxHashMap<String, usize>> =
378                     RefCell::new(init_ids()));
379
380 fn init_ids() -> FxHashMap<String, usize> {
381     [
382      "main",
383      "search",
384      "help",
385      "TOC",
386      "render-detail",
387      "associated-types",
388      "associated-const",
389      "required-methods",
390      "provided-methods",
391      "implementors",
392      "implementors-list",
393      "methods",
394      "deref-methods",
395      "implementations",
396      ].into_iter().map(|id| (String::from(*id), 1)).collect()
397 }
398
399 /// This method resets the local table of used ID attributes. This is typically
400 /// used at the beginning of rendering an entire HTML page to reset from the
401 /// previous state (if any).
402 pub fn reset_ids(embedded: bool) {
403     USED_ID_MAP.with(|s| {
404         *s.borrow_mut() = if embedded {
405             init_ids()
406         } else {
407             FxHashMap()
408         };
409     });
410 }
411
412 pub fn derive_id(candidate: String) -> String {
413     USED_ID_MAP.with(|map| {
414         let id = match map.borrow_mut().get_mut(&candidate) {
415             None => candidate,
416             Some(a) => {
417                 let id = format!("{}-{}", candidate, *a);
418                 *a += 1;
419                 id
420             }
421         };
422
423         map.borrow_mut().insert(id.clone(), 1);
424         id
425     })
426 }
427
428 /// Generates the documentation for `crate` into the directory `dst`
429 pub fn run(mut krate: clean::Crate,
430            external_html: &ExternalHtml,
431            playground_url: Option<String>,
432            dst: PathBuf,
433            passes: FxHashSet<String>,
434            css_file_extension: Option<PathBuf>,
435            renderinfo: RenderInfo) -> Result<(), Error> {
436     let src_root = match krate.src.parent() {
437         Some(p) => p.to_path_buf(),
438         None => PathBuf::new(),
439     };
440     let mut scx = SharedContext {
441         src_root: src_root,
442         passes: passes,
443         include_sources: true,
444         local_sources: FxHashMap(),
445         issue_tracker_base_url: None,
446         layout: layout::Layout {
447             logo: "".to_string(),
448             favicon: "".to_string(),
449             external_html: external_html.clone(),
450             krate: krate.name.clone(),
451         },
452         css_file_extension: css_file_extension.clone(),
453     };
454
455     // If user passed in `--playground-url` arg, we fill in crate name here
456     if let Some(url) = playground_url {
457         markdown::PLAYGROUND.with(|slot| {
458             *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
459         });
460     }
461
462     // Crawl the crate attributes looking for attributes which control how we're
463     // going to emit HTML
464     if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
465         for attr in attrs.lists("doc") {
466             let name = attr.name().map(|s| s.as_str());
467             match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
468                 (Some("html_favicon_url"), Some(s)) => {
469                     scx.layout.favicon = s.to_string();
470                 }
471                 (Some("html_logo_url"), Some(s)) => {
472                     scx.layout.logo = s.to_string();
473                 }
474                 (Some("html_playground_url"), Some(s)) => {
475                     markdown::PLAYGROUND.with(|slot| {
476                         let name = krate.name.clone();
477                         *slot.borrow_mut() = Some((Some(name), s.to_string()));
478                     });
479                 }
480                 (Some("issue_tracker_base_url"), Some(s)) => {
481                     scx.issue_tracker_base_url = Some(s.to_string());
482                 }
483                 (Some("html_no_source"), None) if attr.is_word() => {
484                     scx.include_sources = false;
485                 }
486                 _ => {}
487             }
488         }
489     }
490     try_err!(mkdir(&dst), &dst);
491     krate = render_sources(&dst, &mut scx, krate)?;
492     let cx = Context {
493         current: Vec::new(),
494         dst: dst,
495         render_redirect_pages: false,
496         shared: Arc::new(scx),
497     };
498
499     // Crawl the crate to build various caches used for the output
500     let RenderInfo {
501         inlined: _,
502         external_paths,
503         external_typarams,
504         deref_trait_did,
505         deref_mut_trait_did,
506     } = renderinfo;
507
508     let external_paths = external_paths.into_iter()
509         .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
510         .collect();
511
512     let mut cache = Cache {
513         impls: FxHashMap(),
514         external_paths: external_paths,
515         paths: FxHashMap(),
516         implementors: FxHashMap(),
517         stack: Vec::new(),
518         parent_stack: Vec::new(),
519         search_index: Vec::new(),
520         parent_is_trait_impl: false,
521         extern_locations: FxHashMap(),
522         primitive_locations: FxHashMap(),
523         stripped_mod: false,
524         access_levels: krate.access_levels.clone(),
525         orphan_impl_items: Vec::new(),
526         traits: mem::replace(&mut krate.external_traits, FxHashMap()),
527         deref_trait_did: deref_trait_did,
528         deref_mut_trait_did: deref_mut_trait_did,
529         typarams: external_typarams,
530     };
531
532     // Cache where all our extern crates are located
533     for &(n, ref e) in &krate.externs {
534         let src_root = match Path::new(&e.src).parent() {
535             Some(p) => p.to_path_buf(),
536             None => PathBuf::new(),
537         };
538         cache.extern_locations.insert(n, (e.name.clone(), src_root,
539                                           extern_location(e, &cx.dst)));
540
541         let did = DefId { krate: n, index: CRATE_DEF_INDEX };
542         cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
543     }
544
545     // Cache where all known primitives have their documentation located.
546     //
547     // Favor linking to as local extern as possible, so iterate all crates in
548     // reverse topological order.
549     for &(_, ref e) in krate.externs.iter().rev() {
550         for &(def_id, prim, _) in &e.primitives {
551             cache.primitive_locations.insert(prim, def_id);
552         }
553     }
554     for &(def_id, prim, _) in &krate.primitives {
555         cache.primitive_locations.insert(prim, def_id);
556     }
557
558     cache.stack.push(krate.name.clone());
559     krate = cache.fold_crate(krate);
560
561     // Build our search index
562     let index = build_index(&krate, &mut cache);
563
564     // Freeze the cache now that the index has been built. Put an Arc into TLS
565     // for future parallelization opportunities
566     let cache = Arc::new(cache);
567     CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
568     CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
569
570     write_shared(&cx, &krate, &*cache, index)?;
571
572     // And finally render the whole crate's documentation
573     cx.krate(krate)
574 }
575
576 /// Build the search index from the collected metadata
577 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
578     let mut nodeid_to_pathid = FxHashMap();
579     let mut crate_items = Vec::with_capacity(cache.search_index.len());
580     let mut crate_paths = Vec::<Json>::new();
581
582     let Cache { ref mut search_index,
583                 ref orphan_impl_items,
584                 ref mut paths, .. } = *cache;
585
586     // Attach all orphan items to the type's definition if the type
587     // has since been learned.
588     for &(did, ref item) in orphan_impl_items {
589         if let Some(&(ref fqp, _)) = paths.get(&did) {
590             search_index.push(IndexItem {
591                 ty: item.type_(),
592                 name: item.name.clone().unwrap(),
593                 path: fqp[..fqp.len() - 1].join("::"),
594                 desc: plain_summary_line(item.doc_value()),
595                 parent: Some(did),
596                 parent_idx: None,
597                 search_type: get_index_search_type(&item),
598             });
599         }
600     }
601
602     // Reduce `NodeId` in paths into smaller sequential numbers,
603     // and prune the paths that do not appear in the index.
604     let mut lastpath = String::new();
605     let mut lastpathid = 0usize;
606
607     for item in search_index {
608         item.parent_idx = item.parent.map(|nodeid| {
609             if nodeid_to_pathid.contains_key(&nodeid) {
610                 *nodeid_to_pathid.get(&nodeid).unwrap()
611             } else {
612                 let pathid = lastpathid;
613                 nodeid_to_pathid.insert(nodeid, pathid);
614                 lastpathid += 1;
615
616                 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
617                 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
618                 pathid
619             }
620         });
621
622         // Omit the parent path if it is same to that of the prior item.
623         if lastpath == item.path {
624             item.path.clear();
625         } else {
626             lastpath = item.path.clone();
627         }
628         crate_items.push(item.to_json());
629     }
630
631     let crate_doc = krate.module.as_ref().map(|module| {
632         plain_summary_line(module.doc_value())
633     }).unwrap_or(String::new());
634
635     let mut crate_data = BTreeMap::new();
636     crate_data.insert("doc".to_owned(), Json::String(crate_doc));
637     crate_data.insert("items".to_owned(), Json::Array(crate_items));
638     crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
639
640     // Collect the index into a string
641     format!("searchIndex[{}] = {};",
642             as_json(&krate.name),
643             Json::Object(crate_data))
644 }
645
646 fn write_shared(cx: &Context,
647                 krate: &clean::Crate,
648                 cache: &Cache,
649                 search_index: String) -> Result<(), Error> {
650     // Write out the shared files. Note that these are shared among all rustdoc
651     // docs placed in the output directory, so this needs to be a synchronized
652     // operation with respect to all other rustdocs running around.
653     try_err!(mkdir(&cx.dst), &cx.dst);
654     let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
655
656     // Add all the static files. These may already exist, but we just
657     // overwrite them anyway to make sure that they're fresh and up-to-date.
658
659     write(cx.dst.join("jquery.js"),
660           include_bytes!("static/jquery-2.1.4.min.js"))?;
661     write(cx.dst.join("main.js"),
662           include_bytes!("static/main.js"))?;
663     write(cx.dst.join("rustdoc.css"),
664           include_bytes!("static/rustdoc.css"))?;
665     write(cx.dst.join("main.css"),
666           include_bytes!("static/styles/main.css"))?;
667     if let Some(ref css) = cx.shared.css_file_extension {
668         let mut content = String::new();
669         let css = css.as_path();
670         let mut f = try_err!(File::open(css), css);
671
672         try_err!(f.read_to_string(&mut content), css);
673         let css = cx.dst.join("theme.css");
674         let css = css.as_path();
675         let mut f = try_err!(File::create(css), css);
676         try_err!(write!(f, "{}", &content), css);
677     }
678     write(cx.dst.join("normalize.css"),
679           include_bytes!("static/normalize.css"))?;
680     write(cx.dst.join("FiraSans-Regular.woff"),
681           include_bytes!("static/FiraSans-Regular.woff"))?;
682     write(cx.dst.join("FiraSans-Medium.woff"),
683           include_bytes!("static/FiraSans-Medium.woff"))?;
684     write(cx.dst.join("FiraSans-LICENSE.txt"),
685           include_bytes!("static/FiraSans-LICENSE.txt"))?;
686     write(cx.dst.join("Heuristica-Italic.woff"),
687           include_bytes!("static/Heuristica-Italic.woff"))?;
688     write(cx.dst.join("Heuristica-LICENSE.txt"),
689           include_bytes!("static/Heuristica-LICENSE.txt"))?;
690     write(cx.dst.join("SourceSerifPro-Regular.woff"),
691           include_bytes!("static/SourceSerifPro-Regular.woff"))?;
692     write(cx.dst.join("SourceSerifPro-Bold.woff"),
693           include_bytes!("static/SourceSerifPro-Bold.woff"))?;
694     write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
695           include_bytes!("static/SourceSerifPro-LICENSE.txt"))?;
696     write(cx.dst.join("SourceCodePro-Regular.woff"),
697           include_bytes!("static/SourceCodePro-Regular.woff"))?;
698     write(cx.dst.join("SourceCodePro-Semibold.woff"),
699           include_bytes!("static/SourceCodePro-Semibold.woff"))?;
700     write(cx.dst.join("SourceCodePro-LICENSE.txt"),
701           include_bytes!("static/SourceCodePro-LICENSE.txt"))?;
702     write(cx.dst.join("LICENSE-MIT.txt"),
703           include_bytes!("static/LICENSE-MIT.txt"))?;
704     write(cx.dst.join("LICENSE-APACHE.txt"),
705           include_bytes!("static/LICENSE-APACHE.txt"))?;
706     write(cx.dst.join("COPYRIGHT.txt"),
707           include_bytes!("static/COPYRIGHT.txt"))?;
708
709     fn collect(path: &Path, krate: &str,
710                key: &str) -> io::Result<Vec<String>> {
711         let mut ret = Vec::new();
712         if path.exists() {
713             for line in BufReader::new(File::open(path)?).lines() {
714                 let line = line?;
715                 if !line.starts_with(key) {
716                     continue;
717                 }
718                 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
719                     continue;
720                 }
721                 ret.push(line.to_string());
722             }
723         }
724         Ok(ret)
725     }
726
727     // Update the search index
728     let dst = cx.dst.join("search-index.js");
729     let mut all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
730     all_indexes.push(search_index);
731     // Sort the indexes by crate so the file will be generated identically even
732     // with rustdoc running in parallel.
733     all_indexes.sort();
734     let mut w = try_err!(File::create(&dst), &dst);
735     try_err!(writeln!(&mut w, "var searchIndex = {{}};"), &dst);
736     for index in &all_indexes {
737         try_err!(writeln!(&mut w, "{}", *index), &dst);
738     }
739     try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
740
741     // Update the list of all implementors for traits
742     let dst = cx.dst.join("implementors");
743     for (&did, imps) in &cache.implementors {
744         // Private modules can leak through to this phase of rustdoc, which
745         // could contain implementations for otherwise private types. In some
746         // rare cases we could find an implementation for an item which wasn't
747         // indexed, so we just skip this step in that case.
748         //
749         // FIXME: this is a vague explanation for why this can't be a `get`, in
750         //        theory it should be...
751         let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
752             Some(p) => p,
753             None => match cache.external_paths.get(&did) {
754                 Some(p) => p,
755                 None => continue,
756             }
757         };
758
759         let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
760         for imp in imps {
761             // If the trait and implementation are in the same crate, then
762             // there's no need to emit information about it (there's inlining
763             // going on). If they're in different crates then the crate defining
764             // the trait will be interested in our implementation.
765             if imp.def_id.krate == did.krate { continue }
766             write!(implementors, r#""{}","#, imp.impl_).unwrap();
767         }
768         implementors.push_str("];");
769
770         let mut mydst = dst.clone();
771         for part in &remote_path[..remote_path.len() - 1] {
772             mydst.push(part);
773         }
774         try_err!(fs::create_dir_all(&mydst), &mydst);
775         mydst.push(&format!("{}.{}.js",
776                             remote_item_type.css_class(),
777                             remote_path[remote_path.len() - 1]));
778
779         let mut all_implementors = try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
780         all_implementors.push(implementors);
781         // Sort the implementors by crate so the file will be generated
782         // identically even with rustdoc running in parallel.
783         all_implementors.sort();
784
785         let mut f = try_err!(File::create(&mydst), &mydst);
786         try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
787         for implementor in &all_implementors {
788             try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
789         }
790         try_err!(writeln!(&mut f, "{}", r"
791             if (window.register_implementors) {
792                 window.register_implementors(implementors);
793             } else {
794                 window.pending_implementors = implementors;
795             }
796         "), &mydst);
797         try_err!(writeln!(&mut f, r"}})()"), &mydst);
798     }
799     Ok(())
800 }
801
802 fn render_sources(dst: &Path, scx: &mut SharedContext,
803                   krate: clean::Crate) -> Result<clean::Crate, Error> {
804     info!("emitting source files");
805     let dst = dst.join("src");
806     try_err!(mkdir(&dst), &dst);
807     let dst = dst.join(&krate.name);
808     try_err!(mkdir(&dst), &dst);
809     let mut folder = SourceCollector {
810         dst: dst,
811         scx: scx,
812     };
813     Ok(folder.fold_crate(krate))
814 }
815
816 /// Writes the entire contents of a string to a destination, not attempting to
817 /// catch any errors.
818 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
819     Ok(try_err!(try_err!(File::create(&dst), &dst).write_all(contents), &dst))
820 }
821
822 /// Makes a directory on the filesystem, failing the thread if an error occurs
823 /// and skipping if the directory already exists.
824 ///
825 /// Note that this also handles races as rustdoc is likely to be run
826 /// concurrently against another invocation.
827 fn mkdir(path: &Path) -> io::Result<()> {
828     match fs::create_dir(path) {
829         Ok(()) => Ok(()),
830         Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(()),
831         Err(e) => Err(e)
832     }
833 }
834
835 /// Takes a path to a source file and cleans the path to it. This canonicalizes
836 /// things like ".." to components which preserve the "top down" hierarchy of a
837 /// static HTML tree. Each component in the cleaned path will be passed as an
838 /// argument to `f`. The very last component of the path (ie the file name) will
839 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
840 // FIXME (#9639): The closure should deal with &[u8] instead of &str
841 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
842 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
843     F: FnMut(&str),
844 {
845     // make it relative, if possible
846     let p = p.strip_prefix(src_root).unwrap_or(p);
847
848     let mut iter = p.components().peekable();
849
850     while let Some(c) = iter.next() {
851         if !keep_filename && iter.peek().is_none() {
852             break;
853         }
854
855         match c {
856             Component::ParentDir => f("up"),
857             Component::Normal(c) => f(c.to_str().unwrap()),
858             _ => continue,
859         }
860     }
861 }
862
863 /// Attempts to find where an external crate is located, given that we're
864 /// rendering in to the specified source destination.
865 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
866     // See if there's documentation generated into the local directory
867     let local_location = dst.join(&e.name);
868     if local_location.is_dir() {
869         return Local;
870     }
871
872     // Failing that, see if there's an attribute specifying where to find this
873     // external crate
874     e.attrs.lists("doc")
875      .filter(|a| a.check_name("html_root_url"))
876      .filter_map(|a| a.value_str())
877      .map(|url| {
878         let mut url = url.to_string();
879         if !url.ends_with("/") {
880             url.push('/')
881         }
882         Remote(url)
883     }).next().unwrap_or(Unknown) // Well, at least we tried.
884 }
885
886 impl<'a> DocFolder for SourceCollector<'a> {
887     fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
888         // If we're including source files, and we haven't seen this file yet,
889         // then we need to render it out to the filesystem.
890         if self.scx.include_sources
891             // skip all invalid spans
892             && item.source.filename != ""
893             // skip non-local items
894             && item.def_id.is_local()
895             // Macros from other libraries get special filenames which we can
896             // safely ignore.
897             && !(item.source.filename.starts_with("<")
898                 && item.source.filename.ends_with("macros>")) {
899
900             // If it turns out that we couldn't read this file, then we probably
901             // can't read any of the files (generating html output from json or
902             // something like that), so just don't include sources for the
903             // entire crate. The other option is maintaining this mapping on a
904             // per-file basis, but that's probably not worth it...
905             self.scx
906                 .include_sources = match self.emit_source(&item.source.filename) {
907                 Ok(()) => true,
908                 Err(e) => {
909                     println!("warning: source code was requested to be rendered, \
910                               but processing `{}` had an error: {}",
911                              item.source.filename, e);
912                     println!("         skipping rendering of source code");
913                     false
914                 }
915             };
916         }
917         self.fold_item_recur(item)
918     }
919 }
920
921 impl<'a> SourceCollector<'a> {
922     /// Renders the given filename into its corresponding HTML source file.
923     fn emit_source(&mut self, filename: &str) -> io::Result<()> {
924         let p = PathBuf::from(filename);
925         if self.scx.local_sources.contains_key(&p) {
926             // We've already emitted this source
927             return Ok(());
928         }
929
930         let mut contents = Vec::new();
931         File::open(&p).and_then(|mut f| f.read_to_end(&mut contents))?;
932
933         let contents = str::from_utf8(&contents).unwrap();
934
935         // Remove the utf-8 BOM if any
936         let contents = if contents.starts_with("\u{feff}") {
937             &contents[3..]
938         } else {
939             contents
940         };
941
942         // Create the intermediate directories
943         let mut cur = self.dst.clone();
944         let mut root_path = String::from("../../");
945         let mut href = String::new();
946         clean_srcpath(&self.scx.src_root, &p, false, |component| {
947             cur.push(component);
948             mkdir(&cur).unwrap();
949             root_path.push_str("../");
950             href.push_str(component);
951             href.push('/');
952         });
953         let mut fname = p.file_name().expect("source has no filename")
954                          .to_os_string();
955         fname.push(".html");
956         cur.push(&fname);
957         href.push_str(&fname.to_string_lossy());
958
959         let mut w = BufWriter::new(File::create(&cur)?);
960         let title = format!("{} -- source", cur.file_name().unwrap()
961                                                .to_string_lossy());
962         let desc = format!("Source to the Rust file `{}`.", filename);
963         let page = layout::Page {
964             title: &title,
965             css_class: "source",
966             root_path: &root_path,
967             description: &desc,
968             keywords: BASIC_KEYWORDS,
969         };
970         layout::render(&mut w, &self.scx.layout,
971                        &page, &(""), &Source(contents),
972                        self.scx.css_file_extension.is_some())?;
973         w.flush()?;
974         self.scx.local_sources.insert(p, href);
975         Ok(())
976     }
977 }
978
979 impl DocFolder for Cache {
980     fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
981         // If this is a stripped module,
982         // we don't want it or its children in the search index.
983         let orig_stripped_mod = match item.inner {
984             clean::StrippedItem(box clean::ModuleItem(..)) => {
985                 mem::replace(&mut self.stripped_mod, true)
986             }
987             _ => self.stripped_mod,
988         };
989
990         // Register any generics to their corresponding string. This is used
991         // when pretty-printing types.
992         if let Some(generics) = item.inner.generics() {
993             self.generics(generics);
994         }
995
996         // Propagate a trait method's documentation to all implementors of the
997         // trait.
998         if let clean::TraitItem(ref t) = item.inner {
999             self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1000         }
1001
1002         // Collect all the implementors of traits.
1003         if let clean::ImplItem(ref i) = item.inner {
1004             if let Some(did) = i.trait_.def_id() {
1005                 self.implementors.entry(did).or_insert(vec![]).push(Implementor {
1006                     def_id: item.def_id,
1007                     stability: item.stability.clone(),
1008                     impl_: i.clone(),
1009                 });
1010             }
1011         }
1012
1013         // Index this method for searching later on.
1014         if let Some(ref s) = item.name {
1015             let (parent, is_inherent_impl_item) = match item.inner {
1016                 clean::StrippedItem(..) => ((None, None), false),
1017                 clean::AssociatedConstItem(..) |
1018                 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1019                     // skip associated items in trait impls
1020                     ((None, None), false)
1021                 }
1022                 clean::AssociatedTypeItem(..) |
1023                 clean::TyMethodItem(..) |
1024                 clean::StructFieldItem(..) |
1025                 clean::VariantItem(..) => {
1026                     ((Some(*self.parent_stack.last().unwrap()),
1027                       Some(&self.stack[..self.stack.len() - 1])),
1028                      false)
1029                 }
1030                 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1031                     if self.parent_stack.is_empty() {
1032                         ((None, None), false)
1033                     } else {
1034                         let last = self.parent_stack.last().unwrap();
1035                         let did = *last;
1036                         let path = match self.paths.get(&did) {
1037                             // The current stack not necessarily has correlation
1038                             // for where the type was defined. On the other
1039                             // hand, `paths` always has the right
1040                             // information if present.
1041                             Some(&(ref fqp, ItemType::Trait)) |
1042                             Some(&(ref fqp, ItemType::Struct)) |
1043                             Some(&(ref fqp, ItemType::Union)) |
1044                             Some(&(ref fqp, ItemType::Enum)) =>
1045                                 Some(&fqp[..fqp.len() - 1]),
1046                             Some(..) => Some(&*self.stack),
1047                             None => None
1048                         };
1049                         ((Some(*last), path), true)
1050                     }
1051                 }
1052                 _ => ((None, Some(&*self.stack)), false)
1053             };
1054
1055             match parent {
1056                 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1057                     debug_assert!(!item.is_stripped());
1058
1059                     // A crate has a module at its root, containing all items,
1060                     // which should not be indexed. The crate-item itself is
1061                     // inserted later on when serializing the search-index.
1062                     if item.def_id.index != CRATE_DEF_INDEX {
1063                         self.search_index.push(IndexItem {
1064                             ty: item.type_(),
1065                             name: s.to_string(),
1066                             path: path.join("::").to_string(),
1067                             desc: plain_summary_line(item.doc_value()),
1068                             parent: parent,
1069                             parent_idx: None,
1070                             search_type: get_index_search_type(&item),
1071                         });
1072                     }
1073                 }
1074                 (Some(parent), None) if is_inherent_impl_item => {
1075                     // We have a parent, but we don't know where they're
1076                     // defined yet. Wait for later to index this item.
1077                     self.orphan_impl_items.push((parent, item.clone()));
1078                 }
1079                 _ => {}
1080             }
1081         }
1082
1083         // Keep track of the fully qualified path for this item.
1084         let pushed = match item.name {
1085             Some(ref n) if !n.is_empty() => {
1086                 self.stack.push(n.to_string());
1087                 true
1088             }
1089             _ => false,
1090         };
1091
1092         match item.inner {
1093             clean::StructItem(..) | clean::EnumItem(..) |
1094             clean::TypedefItem(..) | clean::TraitItem(..) |
1095             clean::FunctionItem(..) | clean::ModuleItem(..) |
1096             clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1097             clean::ConstantItem(..) | clean::StaticItem(..) |
1098             clean::UnionItem(..)
1099             if !self.stripped_mod => {
1100                 // Reexported items mean that the same id can show up twice
1101                 // in the rustdoc ast that we're looking at. We know,
1102                 // however, that a reexported item doesn't show up in the
1103                 // `public_items` map, so we can skip inserting into the
1104                 // paths map if there was already an entry present and we're
1105                 // not a public item.
1106                 if
1107                     !self.paths.contains_key(&item.def_id) ||
1108                     self.access_levels.is_public(item.def_id)
1109                 {
1110                     self.paths.insert(item.def_id,
1111                                       (self.stack.clone(), item.type_()));
1112                 }
1113             }
1114             // Link variants to their parent enum because pages aren't emitted
1115             // for each variant.
1116             clean::VariantItem(..) if !self.stripped_mod => {
1117                 let mut stack = self.stack.clone();
1118                 stack.pop();
1119                 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1120             }
1121
1122             clean::PrimitiveItem(..) if item.visibility.is_some() => {
1123                 self.paths.insert(item.def_id, (self.stack.clone(),
1124                                                 item.type_()));
1125             }
1126
1127             _ => {}
1128         }
1129
1130         // Maintain the parent stack
1131         let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1132         let parent_pushed = match item.inner {
1133             clean::TraitItem(..) | clean::EnumItem(..) |
1134             clean::StructItem(..) | clean::UnionItem(..) => {
1135                 self.parent_stack.push(item.def_id);
1136                 self.parent_is_trait_impl = false;
1137                 true
1138             }
1139             clean::ImplItem(ref i) => {
1140                 self.parent_is_trait_impl = i.trait_.is_some();
1141                 match i.for_ {
1142                     clean::ResolvedPath{ did, .. } => {
1143                         self.parent_stack.push(did);
1144                         true
1145                     }
1146                     ref t => {
1147                         let prim_did = t.primitive_type().and_then(|t| {
1148                             self.primitive_locations.get(&t).cloned()
1149                         });
1150                         match prim_did {
1151                             Some(did) => {
1152                                 self.parent_stack.push(did);
1153                                 true
1154                             }
1155                             None => false,
1156                         }
1157                     }
1158                 }
1159             }
1160             _ => false
1161         };
1162
1163         // Once we've recursively found all the generics, hoard off all the
1164         // implementations elsewhere.
1165         let ret = self.fold_item_recur(item).and_then(|item| {
1166             if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1167                 // Figure out the id of this impl. This may map to a
1168                 // primitive rather than always to a struct/enum.
1169                 // Note: matching twice to restrict the lifetime of the `i` borrow.
1170                 let did = if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1171                     match i.for_ {
1172                         clean::ResolvedPath { did, .. } |
1173                         clean::BorrowedRef {
1174                             type_: box clean::ResolvedPath { did, .. }, ..
1175                         } => {
1176                             Some(did)
1177                         }
1178                         ref t => {
1179                             t.primitive_type().and_then(|t| {
1180                                 self.primitive_locations.get(&t).cloned()
1181                             })
1182                         }
1183                     }
1184                 } else {
1185                     unreachable!()
1186                 };
1187                 if let Some(did) = did {
1188                     self.impls.entry(did).or_insert(vec![]).push(Impl {
1189                         impl_item: item,
1190                     });
1191                 }
1192                 None
1193             } else {
1194                 Some(item)
1195             }
1196         });
1197
1198         if pushed { self.stack.pop().unwrap(); }
1199         if parent_pushed { self.parent_stack.pop().unwrap(); }
1200         self.stripped_mod = orig_stripped_mod;
1201         self.parent_is_trait_impl = orig_parent_is_trait_impl;
1202         ret
1203     }
1204 }
1205
1206 impl<'a> Cache {
1207     fn generics(&mut self, generics: &clean::Generics) {
1208         for typ in &generics.type_params {
1209             self.typarams.insert(typ.did, typ.name.clone());
1210         }
1211     }
1212 }
1213
1214 impl Context {
1215     /// String representation of how to get back to the root path of the 'doc/'
1216     /// folder in terms of a relative URL.
1217     fn root_path(&self) -> String {
1218         repeat("../").take(self.current.len()).collect::<String>()
1219     }
1220
1221     /// Recurse in the directory structure and change the "root path" to make
1222     /// sure it always points to the top (relatively).
1223     fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1224         F: FnOnce(&mut Context) -> T,
1225     {
1226         if s.is_empty() {
1227             panic!("Unexpected empty destination: {:?}", self.current);
1228         }
1229         let prev = self.dst.clone();
1230         self.dst.push(&s);
1231         self.current.push(s);
1232
1233         info!("Recursing into {}", self.dst.display());
1234
1235         let ret = f(self);
1236
1237         info!("Recursed; leaving {}", self.dst.display());
1238
1239         // Go back to where we were at
1240         self.dst = prev;
1241         self.current.pop().unwrap();
1242
1243         ret
1244     }
1245
1246     /// Main method for rendering a crate.
1247     ///
1248     /// This currently isn't parallelized, but it'd be pretty easy to add
1249     /// parallelization to this function.
1250     fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1251         let mut item = match krate.module.take() {
1252             Some(i) => i,
1253             None => return Ok(()),
1254         };
1255         item.name = Some(krate.name);
1256
1257         // Render the crate documentation
1258         let mut work = vec![(self, item)];
1259
1260         while let Some((mut cx, item)) = work.pop() {
1261             cx.item(item, |cx, item| {
1262                 work.push((cx.clone(), item))
1263             })?
1264         }
1265         Ok(())
1266     }
1267
1268     fn render_item(&self,
1269                    writer: &mut io::Write,
1270                    it: &clean::Item,
1271                    pushname: bool)
1272                    -> io::Result<()> {
1273         // A little unfortunate that this is done like this, but it sure
1274         // does make formatting *a lot* nicer.
1275         CURRENT_LOCATION_KEY.with(|slot| {
1276             *slot.borrow_mut() = self.current.clone();
1277         });
1278
1279         let mut title = if it.is_primitive() {
1280             // No need to include the namespace for primitive types
1281             String::new()
1282         } else {
1283             self.current.join("::")
1284         };
1285         if pushname {
1286             if !title.is_empty() {
1287                 title.push_str("::");
1288             }
1289             title.push_str(it.name.as_ref().unwrap());
1290         }
1291         title.push_str(" - Rust");
1292         let tyname = it.type_().css_class();
1293         let desc = if it.is_crate() {
1294             format!("API documentation for the Rust `{}` crate.",
1295                     self.shared.layout.krate)
1296         } else {
1297             format!("API documentation for the Rust `{}` {} in crate `{}`.",
1298                     it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1299         };
1300         let keywords = make_item_keywords(it);
1301         let page = layout::Page {
1302             css_class: tyname,
1303             root_path: &self.root_path(),
1304             title: &title,
1305             description: &desc,
1306             keywords: &keywords,
1307         };
1308
1309         reset_ids(true);
1310
1311         if !self.render_redirect_pages {
1312             layout::render(writer, &self.shared.layout, &page,
1313                            &Sidebar{ cx: self, item: it },
1314                            &Item{ cx: self, item: it },
1315                            self.shared.css_file_extension.is_some())?;
1316         } else {
1317             let mut url = self.root_path();
1318             if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
1319                 for name in &names[..names.len() - 1] {
1320                     url.push_str(name);
1321                     url.push_str("/");
1322                 }
1323                 url.push_str(&item_path(ty, names.last().unwrap()));
1324                 layout::redirect(writer, &url)?;
1325             }
1326         }
1327         Ok(())
1328     }
1329
1330     /// Non-parallelized version of rendering an item. This will take the input
1331     /// item, render its contents, and then invoke the specified closure with
1332     /// all sub-items which need to be rendered.
1333     ///
1334     /// The rendering driver uses this closure to queue up more work.
1335     fn item<F>(&mut self, item: clean::Item, mut f: F) -> Result<(), Error> where
1336         F: FnMut(&mut Context, clean::Item),
1337     {
1338         // Stripped modules survive the rustdoc passes (i.e. `strip-private`)
1339         // if they contain impls for public types. These modules can also
1340         // contain items such as publicly reexported structures.
1341         //
1342         // External crates will provide links to these structures, so
1343         // these modules are recursed into, but not rendered normally
1344         // (a flag on the context).
1345         if !self.render_redirect_pages {
1346             self.render_redirect_pages = maybe_ignore_item(&item);
1347         }
1348
1349         if item.is_mod() {
1350             // modules are special because they add a namespace. We also need to
1351             // recurse into the items of the module as well.
1352             let name = item.name.as_ref().unwrap().to_string();
1353             let mut item = Some(item);
1354             self.recurse(name, |this| {
1355                 let item = item.take().unwrap();
1356
1357                 let mut buf = Vec::new();
1358                 this.render_item(&mut buf, &item, false).unwrap();
1359                 // buf will be empty if the module is stripped and there is no redirect for it
1360                 if !buf.is_empty() {
1361                     let joint_dst = this.dst.join("index.html");
1362                     try_err!(fs::create_dir_all(&this.dst), &this.dst);
1363                     let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1364                     try_err!(dst.write_all(&buf), &joint_dst);
1365                 }
1366
1367                 let m = match item.inner {
1368                     clean::StrippedItem(box clean::ModuleItem(m)) |
1369                     clean::ModuleItem(m) => m,
1370                     _ => unreachable!()
1371                 };
1372
1373                 // Render sidebar-items.js used throughout this module.
1374                 if !this.render_redirect_pages {
1375                     let items = this.build_sidebar_items(&m);
1376                     let js_dst = this.dst.join("sidebar-items.js");
1377                     let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
1378                     try_err!(write!(&mut js_out, "initSidebarItems({});",
1379                                     as_json(&items)), &js_dst);
1380                 }
1381
1382                 for item in m.items {
1383                     f(this,item);
1384                 }
1385
1386                 Ok(())
1387             })?;
1388         } else if item.name.is_some() {
1389             let mut buf = Vec::new();
1390             self.render_item(&mut buf, &item, true).unwrap();
1391             // buf will be empty if the item is stripped and there is no redirect for it
1392             if !buf.is_empty() {
1393                 let name = item.name.as_ref().unwrap();
1394                 let item_type = item.type_();
1395                 let file_name = &item_path(item_type, name);
1396                 let joint_dst = self.dst.join(file_name);
1397                 try_err!(fs::create_dir_all(&self.dst), &self.dst);
1398                 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1399                 try_err!(dst.write_all(&buf), &joint_dst);
1400
1401                 // Redirect from a sane URL using the namespace to Rustdoc's
1402                 // URL for the page.
1403                 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1404                 let redir_dst = self.dst.join(redir_name);
1405                 if let Ok(mut redirect_out) = OpenOptions::new().create_new(true)
1406                                                                 .write(true)
1407                                                                 .open(&redir_dst) {
1408                     try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1409                 }
1410
1411                 // If the item is a macro, redirect from the old macro URL (with !)
1412                 // to the new one (without).
1413                 // FIXME(#35705) remove this redirect.
1414                 if item_type == ItemType::Macro {
1415                     let redir_name = format!("{}.{}!.html", item_type, name);
1416                     let redir_dst = self.dst.join(redir_name);
1417                     let mut redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
1418                     try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1419                 }
1420             }
1421         }
1422         Ok(())
1423     }
1424
1425     fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1426         // BTreeMap instead of HashMap to get a sorted output
1427         let mut map = BTreeMap::new();
1428         for item in &m.items {
1429             if maybe_ignore_item(item) { continue }
1430
1431             let short = item.type_().css_class();
1432             let myname = match item.name {
1433                 None => continue,
1434                 Some(ref s) => s.to_string(),
1435             };
1436             let short = short.to_string();
1437             map.entry(short).or_insert(vec![])
1438                 .push((myname, Some(plain_summary_line(item.doc_value()))));
1439         }
1440
1441         for (_, items) in &mut map {
1442             items.sort();
1443         }
1444         map
1445     }
1446 }
1447
1448 impl<'a> Item<'a> {
1449     /// Generate a url appropriate for an `href` attribute back to the source of
1450     /// this item.
1451     ///
1452     /// The url generated, when clicked, will redirect the browser back to the
1453     /// original source code.
1454     ///
1455     /// If `None` is returned, then a source link couldn't be generated. This
1456     /// may happen, for example, with externally inlined items where the source
1457     /// of their crate documentation isn't known.
1458     fn src_href(&self) -> Option<String> {
1459         let mut root = self.cx.root_path();
1460
1461         let cache = cache();
1462         let mut path = String::new();
1463         let (krate, path) = if self.item.def_id.is_local() {
1464             let path = PathBuf::from(&self.item.source.filename);
1465             if let Some(path) = self.cx.shared.local_sources.get(&path) {
1466                 (&self.cx.shared.layout.krate, path)
1467             } else {
1468                 return None;
1469             }
1470         } else {
1471             // Macros from other libraries get special filenames which we can
1472             // safely ignore.
1473             if self.item.source.filename.starts_with("<") &&
1474                self.item.source.filename.ends_with("macros>") {
1475                 return None;
1476             }
1477
1478             let (krate, src_root) = match cache.extern_locations.get(&self.item.def_id.krate) {
1479                 Some(&(ref name, ref src, Local)) => (name, src),
1480                 Some(&(ref name, ref src, Remote(ref s))) => {
1481                     root = s.to_string();
1482                     (name, src)
1483                 }
1484                 Some(&(_, _, Unknown)) | None => return None,
1485             };
1486
1487             let file = Path::new(&self.item.source.filename);
1488             clean_srcpath(&src_root, file, false, |component| {
1489                 path.push_str(component);
1490                 path.push('/');
1491             });
1492             let mut fname = file.file_name().expect("source has no filename")
1493                                 .to_os_string();
1494             fname.push(".html");
1495             path.push_str(&fname.to_string_lossy());
1496             (krate, &path)
1497         };
1498
1499         let lines = if self.item.source.loline == self.item.source.hiline {
1500             format!("{}", self.item.source.loline)
1501         } else {
1502             format!("{}-{}", self.item.source.loline, self.item.source.hiline)
1503         };
1504         Some(format!("{root}src/{krate}/{path}#{lines}",
1505                      root = root,
1506                      krate = krate,
1507                      path = path,
1508                      lines = lines))
1509     }
1510 }
1511
1512 impl<'a> fmt::Display for Item<'a> {
1513     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1514         debug_assert!(!self.item.is_stripped());
1515         // Write the breadcrumb trail header for the top
1516         write!(fmt, "\n<h1 class='fqn'><span class='in-band'>")?;
1517         match self.item.inner {
1518             clean::ModuleItem(ref m) => if m.is_crate {
1519                     write!(fmt, "Crate ")?;
1520                 } else {
1521                     write!(fmt, "Module ")?;
1522                 },
1523             clean::FunctionItem(..) | clean::ForeignFunctionItem(..) =>
1524                 write!(fmt, "Function ")?,
1525             clean::TraitItem(..) => write!(fmt, "Trait ")?,
1526             clean::StructItem(..) => write!(fmt, "Struct ")?,
1527             clean::UnionItem(..) => write!(fmt, "Union ")?,
1528             clean::EnumItem(..) => write!(fmt, "Enum ")?,
1529             clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
1530             clean::MacroItem(..) => write!(fmt, "Macro ")?,
1531             clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
1532             clean::StaticItem(..) | clean::ForeignStaticItem(..) =>
1533                 write!(fmt, "Static ")?,
1534             clean::ConstantItem(..) => write!(fmt, "Constant ")?,
1535             _ => {
1536                 // We don't generate pages for any other type.
1537                 unreachable!();
1538             }
1539         }
1540         if !self.item.is_primitive() {
1541             let cur = &self.cx.current;
1542             let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
1543             for (i, component) in cur.iter().enumerate().take(amt) {
1544                 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
1545                        repeat("../").take(cur.len() - i - 1)
1546                                     .collect::<String>(),
1547                        component)?;
1548             }
1549         }
1550         write!(fmt, "<a class='{}' href=''>{}</a>",
1551                self.item.type_(), self.item.name.as_ref().unwrap())?;
1552
1553         write!(fmt, "</span>")?; // in-band
1554         write!(fmt, "<span class='out-of-band'>")?;
1555         if let Some(version) = self.item.stable_since() {
1556             write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1557                    version)?;
1558         }
1559         write!(fmt,
1560                r##"<span id='render-detail'>
1561                    <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
1562                        [<span class='inner'>&#x2212;</span>]
1563                    </a>
1564                </span>"##)?;
1565
1566         // Write `src` tag
1567         //
1568         // When this item is part of a `pub use` in a downstream crate, the
1569         // [src] link in the downstream documentation will actually come back to
1570         // this page, and this link will be auto-clicked. The `id` attribute is
1571         // used to find the link to auto-click.
1572         if self.cx.shared.include_sources && !self.item.is_primitive() {
1573             if let Some(l) = self.src_href() {
1574                 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
1575                        l, "goto source code")?;
1576             }
1577         }
1578
1579         write!(fmt, "</span>")?; // out-of-band
1580
1581         write!(fmt, "</h1>\n")?;
1582
1583         match self.item.inner {
1584             clean::ModuleItem(ref m) => {
1585                 item_module(fmt, self.cx, self.item, &m.items)
1586             }
1587             clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1588                 item_function(fmt, self.cx, self.item, f),
1589             clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1590             clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
1591             clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
1592             clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
1593             clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
1594             clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
1595             clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
1596             clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1597                 item_static(fmt, self.cx, self.item, i),
1598             clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
1599             _ => {
1600                 // We don't generate pages for any other type.
1601                 unreachable!();
1602             }
1603         }
1604     }
1605 }
1606
1607 fn item_path(ty: ItemType, name: &str) -> String {
1608     match ty {
1609         ItemType::Module => format!("{}/index.html", name),
1610         _ => format!("{}.{}.html", ty.css_class(), name),
1611     }
1612 }
1613
1614 fn full_path(cx: &Context, item: &clean::Item) -> String {
1615     let mut s = cx.current.join("::");
1616     s.push_str("::");
1617     s.push_str(item.name.as_ref().unwrap());
1618     s
1619 }
1620
1621 fn shorter<'a>(s: Option<&'a str>) -> String {
1622     match s {
1623         Some(s) => s.lines().take_while(|line|{
1624             (*line).chars().any(|chr|{
1625                 !chr.is_whitespace()
1626             })
1627         }).collect::<Vec<_>>().join("\n"),
1628         None => "".to_string()
1629     }
1630 }
1631
1632 #[inline]
1633 fn plain_summary_line(s: Option<&str>) -> String {
1634     let line = shorter(s).replace("\n", " ");
1635     markdown::plain_summary_line(&line[..])
1636 }
1637
1638 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1639     document_stability(w, cx, item)?;
1640     document_full(w, item)?;
1641     Ok(())
1642 }
1643
1644 fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink) -> fmt::Result {
1645     if let Some(s) = item.doc_value() {
1646         let markdown = if s.contains('\n') {
1647             format!("{} [Read more]({})",
1648                     &plain_summary_line(Some(s)), naive_assoc_href(item, link))
1649         } else {
1650             format!("{}", &plain_summary_line(Some(s)))
1651         };
1652         write!(w, "<div class='docblock'>{}</div>", Markdown(&markdown))?;
1653     }
1654     Ok(())
1655 }
1656
1657 fn document_full(w: &mut fmt::Formatter, item: &clean::Item) -> fmt::Result {
1658     if let Some(s) = item.doc_value() {
1659         write!(w, "<div class='docblock'>{}</div>", Markdown(s))?;
1660     }
1661     Ok(())
1662 }
1663
1664 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1665     let stabilities = short_stability(item, cx, true);
1666     if !stabilities.is_empty() {
1667         write!(w, "<div class='stability'>")?;
1668         for stability in stabilities {
1669             write!(w, "{}", stability)?;
1670         }
1671         write!(w, "</div>")?;
1672     }
1673     Ok(())
1674 }
1675
1676 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1677                item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1678     document(w, cx, item)?;
1679
1680     let mut indices = (0..items.len()).filter(|i| {
1681         if let clean::DefaultImplItem(..) = items[*i].inner {
1682             return false;
1683         }
1684         !maybe_ignore_item(&items[*i])
1685     }).collect::<Vec<usize>>();
1686
1687     // the order of item types in the listing
1688     fn reorder(ty: ItemType) -> u8 {
1689         match ty {
1690             ItemType::ExternCrate     => 0,
1691             ItemType::Import          => 1,
1692             ItemType::Primitive       => 2,
1693             ItemType::Module          => 3,
1694             ItemType::Macro           => 4,
1695             ItemType::Struct          => 5,
1696             ItemType::Enum            => 6,
1697             ItemType::Constant        => 7,
1698             ItemType::Static          => 8,
1699             ItemType::Trait           => 9,
1700             ItemType::Function        => 10,
1701             ItemType::Typedef         => 12,
1702             ItemType::Union           => 13,
1703             _                         => 14 + ty as u8,
1704         }
1705     }
1706
1707     fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1708         let ty1 = i1.type_();
1709         let ty2 = i2.type_();
1710         if ty1 != ty2 {
1711             return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1712         }
1713         let s1 = i1.stability.as_ref().map(|s| s.level);
1714         let s2 = i2.stability.as_ref().map(|s| s.level);
1715         match (s1, s2) {
1716             (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1717             (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1718             _ => {}
1719         }
1720         i1.name.cmp(&i2.name)
1721     }
1722
1723     indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1724
1725     debug!("{:?}", indices);
1726     let mut curty = None;
1727     for &idx in &indices {
1728         let myitem = &items[idx];
1729         if myitem.is_stripped() {
1730             continue;
1731         }
1732
1733         let myty = Some(myitem.type_());
1734         if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
1735             // Put `extern crate` and `use` re-exports in the same section.
1736             curty = myty;
1737         } else if myty != curty {
1738             if curty.is_some() {
1739                 write!(w, "</table>")?;
1740             }
1741             curty = myty;
1742             let (short, name) = match myty.unwrap() {
1743                 ItemType::ExternCrate |
1744                 ItemType::Import          => ("reexports", "Reexports"),
1745                 ItemType::Module          => ("modules", "Modules"),
1746                 ItemType::Struct          => ("structs", "Structs"),
1747                 ItemType::Union           => ("unions", "Unions"),
1748                 ItemType::Enum            => ("enums", "Enums"),
1749                 ItemType::Function        => ("functions", "Functions"),
1750                 ItemType::Typedef         => ("types", "Type Definitions"),
1751                 ItemType::Static          => ("statics", "Statics"),
1752                 ItemType::Constant        => ("constants", "Constants"),
1753                 ItemType::Trait           => ("traits", "Traits"),
1754                 ItemType::Impl            => ("impls", "Implementations"),
1755                 ItemType::TyMethod        => ("tymethods", "Type Methods"),
1756                 ItemType::Method          => ("methods", "Methods"),
1757                 ItemType::StructField     => ("fields", "Struct Fields"),
1758                 ItemType::Variant         => ("variants", "Variants"),
1759                 ItemType::Macro           => ("macros", "Macros"),
1760                 ItemType::Primitive       => ("primitives", "Primitive Types"),
1761                 ItemType::AssociatedType  => ("associated-types", "Associated Types"),
1762                 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
1763             };
1764             write!(w, "<h2 id='{id}' class='section-header'>\
1765                        <a href=\"#{id}\">{name}</a></h2>\n<table>",
1766                    id = derive_id(short.to_owned()), name = name)?;
1767         }
1768
1769         match myitem.inner {
1770             clean::ExternCrateItem(ref name, ref src) => {
1771                 use html::format::HRef;
1772
1773                 match *src {
1774                     Some(ref src) => {
1775                         write!(w, "<tr><td><code>{}extern crate {} as {};",
1776                                VisSpace(&myitem.visibility),
1777                                HRef::new(myitem.def_id, src),
1778                                name)?
1779                     }
1780                     None => {
1781                         write!(w, "<tr><td><code>{}extern crate {};",
1782                                VisSpace(&myitem.visibility),
1783                                HRef::new(myitem.def_id, name))?
1784                     }
1785                 }
1786                 write!(w, "</code></td></tr>")?;
1787             }
1788
1789             clean::ImportItem(ref import) => {
1790                 write!(w, "<tr><td><code>{}{}</code></td></tr>",
1791                        VisSpace(&myitem.visibility), *import)?;
1792             }
1793
1794             _ => {
1795                 if myitem.name.is_none() { continue }
1796
1797                 let stabilities = short_stability(myitem, cx, false);
1798
1799                 let stab_docs = if !stabilities.is_empty() {
1800                     stabilities.iter()
1801                                .map(|s| format!("[{}]", s))
1802                                .collect::<Vec<_>>()
1803                                .as_slice()
1804                                .join(" ")
1805                 } else {
1806                     String::new()
1807                 };
1808
1809                 let unsafety_flag = match myitem.inner {
1810                     clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
1811                     if func.unsafety == hir::Unsafety::Unsafe => {
1812                         "<a title='unsafe function' href='#'><sup>âš </sup></a>"
1813                     }
1814                     _ => "",
1815                 };
1816
1817                 let doc_value = myitem.doc_value().unwrap_or("");
1818                 write!(w, "
1819                        <tr class='{stab} module-item'>
1820                            <td><a class='{class}' href='{href}'
1821                                   title='{title}'>{name}</a>{unsafety_flag}</td>
1822                            <td class='docblock-short'>
1823                                {stab_docs} {docs}
1824                            </td>
1825                        </tr>",
1826                        name = *myitem.name.as_ref().unwrap(),
1827                        stab_docs = stab_docs,
1828                        docs = shorter(Some(&Markdown(doc_value).to_string())),
1829                        class = myitem.type_(),
1830                        stab = myitem.stability_class(),
1831                        unsafety_flag = unsafety_flag,
1832                        href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
1833                        title = full_path(cx, myitem))?;
1834             }
1835         }
1836     }
1837
1838     if curty.is_some() {
1839         write!(w, "</table>")?;
1840     }
1841     Ok(())
1842 }
1843
1844 fn maybe_ignore_item(it: &clean::Item) -> bool {
1845     match it.inner {
1846         clean::StrippedItem(..) => true,
1847         clean::ModuleItem(ref m) => {
1848             it.doc_value().is_none() && m.items.is_empty()
1849                                      && it.visibility != Some(clean::Public)
1850         },
1851         _ => false,
1852     }
1853 }
1854
1855 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
1856     let mut stability = vec![];
1857
1858     if let Some(stab) = item.stability.as_ref() {
1859         let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
1860             format!(": {}", stab.deprecated_reason)
1861         } else {
1862             String::new()
1863         };
1864         if !stab.deprecated_since.is_empty() {
1865             let since = if show_reason {
1866                 format!(" since {}", Escape(&stab.deprecated_since))
1867             } else {
1868                 String::new()
1869             };
1870             let text = format!("Deprecated{}{}", since, MarkdownHtml(&deprecated_reason));
1871             stability.push(format!("<div class='stab deprecated'>{}</div>", text))
1872         };
1873
1874         if stab.level == stability::Unstable {
1875             if show_reason {
1876                 let unstable_extra = match (!stab.feature.is_empty(),
1877                                             &cx.shared.issue_tracker_base_url,
1878                                             stab.issue) {
1879                     (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
1880                         format!(" (<code>{}</code> <a href=\"{}{}\">#{}</a>)",
1881                                 Escape(&stab.feature), tracker_url, issue_no, issue_no),
1882                     (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
1883                         format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
1884                                 issue_no),
1885                     (true, ..) =>
1886                         format!(" (<code>{}</code>)", Escape(&stab.feature)),
1887                     _ => String::new(),
1888                 };
1889                 if stab.unstable_reason.is_empty() {
1890                     stability.push(format!("<div class='stab unstable'>\
1891                                             <span class=microscope>🔬</span> \
1892                                             This is a nightly-only experimental API. &nbsp;{}\
1893                                             </div>",
1894                                    unstable_extra));
1895                 } else {
1896                     let text = format!("<summary><span class=microscope>🔬</span> \
1897                                         This is a nightly-only experimental API. &nbsp;{}\
1898                                         </summary>{}",
1899                                        unstable_extra, MarkdownHtml(&stab.unstable_reason));
1900                     stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
1901                                    text));
1902                 }
1903             } else {
1904                 stability.push(format!("<div class='stab unstable'>Experimental</div>"))
1905             }
1906         };
1907     } else if let Some(depr) = item.deprecation.as_ref() {
1908         let note = if show_reason && !depr.note.is_empty() {
1909             format!(": {}", depr.note)
1910         } else {
1911             String::new()
1912         };
1913         let since = if show_reason && !depr.since.is_empty() {
1914             format!(" since {}", Escape(&depr.since))
1915         } else {
1916             String::new()
1917         };
1918
1919         let text = format!("Deprecated{}{}", since, MarkdownHtml(&note));
1920         stability.push(format!("<div class='stab deprecated'>{}</div>", text))
1921     }
1922
1923     stability
1924 }
1925
1926 struct Initializer<'a>(&'a str);
1927
1928 impl<'a> fmt::Display for Initializer<'a> {
1929     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1930         let Initializer(s) = *self;
1931         if s.is_empty() { return Ok(()); }
1932         write!(f, "<code> = </code>")?;
1933         write!(f, "<code>{}</code>", Escape(s))
1934     }
1935 }
1936
1937 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1938                  c: &clean::Constant) -> fmt::Result {
1939     write!(w, "<pre class='rust const'>{vis}const \
1940                {name}: {typ}{init}</pre>",
1941            vis = VisSpace(&it.visibility),
1942            name = it.name.as_ref().unwrap(),
1943            typ = c.type_,
1944            init = Initializer(&c.expr))?;
1945     document(w, cx, it)
1946 }
1947
1948 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1949                s: &clean::Static) -> fmt::Result {
1950     write!(w, "<pre class='rust static'>{vis}static {mutability}\
1951                {name}: {typ}{init}</pre>",
1952            vis = VisSpace(&it.visibility),
1953            mutability = MutableSpace(s.mutability),
1954            name = it.name.as_ref().unwrap(),
1955            typ = s.type_,
1956            init = Initializer(&s.expr))?;
1957     document(w, cx, it)
1958 }
1959
1960 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1961                  f: &clean::Function) -> fmt::Result {
1962     // FIXME(#24111): remove when `const_fn` is stabilized
1963     let vis_constness = match UnstableFeatures::from_environment() {
1964         UnstableFeatures::Allow => f.constness,
1965         _ => hir::Constness::NotConst
1966     };
1967     let indent = format!("{}{}{}{:#}fn {}{:#}",
1968                          VisSpace(&it.visibility),
1969                          ConstnessSpace(vis_constness),
1970                          UnsafetySpace(f.unsafety),
1971                          AbiSpace(f.abi),
1972                          it.name.as_ref().unwrap(),
1973                          f.generics).len();
1974     write!(w, "<pre class='rust fn'>{vis}{constness}{unsafety}{abi}fn \
1975                {name}{generics}{decl}{where_clause}</pre>",
1976            vis = VisSpace(&it.visibility),
1977            constness = ConstnessSpace(vis_constness),
1978            unsafety = UnsafetySpace(f.unsafety),
1979            abi = AbiSpace(f.abi),
1980            name = it.name.as_ref().unwrap(),
1981            generics = f.generics,
1982            where_clause = WhereClause(&f.generics, 2),
1983            decl = Method(&f.decl, indent))?;
1984     document(w, cx, it)
1985 }
1986
1987 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1988               t: &clean::Trait) -> fmt::Result {
1989     let mut bounds = String::new();
1990     let mut bounds_plain = String::new();
1991     if !t.bounds.is_empty() {
1992         if !bounds.is_empty() {
1993             bounds.push(' ');
1994             bounds_plain.push(' ');
1995         }
1996         bounds.push_str(": ");
1997         bounds_plain.push_str(": ");
1998         for (i, p) in t.bounds.iter().enumerate() {
1999             if i > 0 {
2000                 bounds.push_str(" + ");
2001                 bounds_plain.push_str(" + ");
2002             }
2003             bounds.push_str(&format!("{}", *p));
2004             bounds_plain.push_str(&format!("{:#}", *p));
2005         }
2006     }
2007
2008     // Output the trait definition
2009     write!(w, "<pre class='rust trait'>{}{}trait {}{}{}{} ",
2010            VisSpace(&it.visibility),
2011            UnsafetySpace(t.unsafety),
2012            it.name.as_ref().unwrap(),
2013            t.generics,
2014            bounds,
2015            // Where clauses in traits are indented nine spaces, per rustdoc.css
2016            WhereClause(&t.generics, 9))?;
2017
2018     let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2019     let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2020     let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2021     let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2022
2023     if t.items.is_empty() {
2024         write!(w, "{{ }}")?;
2025     } else {
2026         // FIXME: we should be using a derived_id for the Anchors here
2027         write!(w, "{{\n")?;
2028         for t in &types {
2029             write!(w, "    ")?;
2030             render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2031             write!(w, ";\n")?;
2032         }
2033         if !types.is_empty() && !consts.is_empty() {
2034             w.write_str("\n")?;
2035         }
2036         for t in &consts {
2037             write!(w, "    ")?;
2038             render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2039             write!(w, ";\n")?;
2040         }
2041         if !consts.is_empty() && !required.is_empty() {
2042             w.write_str("\n")?;
2043         }
2044         for m in &required {
2045             write!(w, "    ")?;
2046             render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2047             write!(w, ";\n")?;
2048         }
2049         if !required.is_empty() && !provided.is_empty() {
2050             w.write_str("\n")?;
2051         }
2052         for m in &provided {
2053             write!(w, "    ")?;
2054             render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2055             write!(w, " {{ ... }}\n")?;
2056         }
2057         write!(w, "}}")?;
2058     }
2059     write!(w, "</pre>")?;
2060
2061     // Trait documentation
2062     document(w, cx, it)?;
2063
2064     fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
2065                   -> fmt::Result {
2066         let name = m.name.as_ref().unwrap();
2067         let item_type = m.type_();
2068         let id = derive_id(format!("{}.{}", item_type, name));
2069         let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2070         write!(w, "<h3 id='{id}' class='method'>\
2071                    <span id='{ns_id}' class='invisible'><code>",
2072                id = id,
2073                ns_id = ns_id)?;
2074         render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
2075         write!(w, "</code>")?;
2076         render_stability_since(w, m, t)?;
2077         write!(w, "</span></h3>")?;
2078         document(w, cx, m)?;
2079         Ok(())
2080     }
2081
2082     if !types.is_empty() {
2083         write!(w, "
2084             <h2 id='associated-types'>Associated Types</h2>
2085             <div class='methods'>
2086         ")?;
2087         for t in &types {
2088             trait_item(w, cx, *t, it)?;
2089         }
2090         write!(w, "</div>")?;
2091     }
2092
2093     if !consts.is_empty() {
2094         write!(w, "
2095             <h2 id='associated-const'>Associated Constants</h2>
2096             <div class='methods'>
2097         ")?;
2098         for t in &consts {
2099             trait_item(w, cx, *t, it)?;
2100         }
2101         write!(w, "</div>")?;
2102     }
2103
2104     // Output the documentation for each function individually
2105     if !required.is_empty() {
2106         write!(w, "
2107             <h2 id='required-methods'>Required Methods</h2>
2108             <div class='methods'>
2109         ")?;
2110         for m in &required {
2111             trait_item(w, cx, *m, it)?;
2112         }
2113         write!(w, "</div>")?;
2114     }
2115     if !provided.is_empty() {
2116         write!(w, "
2117             <h2 id='provided-methods'>Provided Methods</h2>
2118             <div class='methods'>
2119         ")?;
2120         for m in &provided {
2121             trait_item(w, cx, *m, it)?;
2122         }
2123         write!(w, "</div>")?;
2124     }
2125
2126     // If there are methods directly on this trait object, render them here.
2127     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2128
2129     let cache = cache();
2130     write!(w, "
2131         <h2 id='implementors'>Implementors</h2>
2132         <ul class='item-list' id='implementors-list'>
2133     ")?;
2134     if let Some(implementors) = cache.implementors.get(&it.def_id) {
2135         // The DefId is for the first Type found with that name. The bool is
2136         // if any Types with the same name but different DefId have been found.
2137         let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap();
2138         for implementor in implementors {
2139             match implementor.impl_.for_ {
2140                 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2141                 clean::BorrowedRef {
2142                     type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2143                     ..
2144                 } => {
2145                     let &mut (prev_did, ref mut has_duplicates) =
2146                         implementor_dups.entry(path.last_name()).or_insert((did, false));
2147                     if prev_did != did {
2148                         *has_duplicates = true;
2149                     }
2150                 }
2151                 _ => {}
2152             }
2153         }
2154
2155         for implementor in implementors {
2156             write!(w, "<li><code>")?;
2157             // If there's already another implementor that has the same abbridged name, use the
2158             // full path, for example in `std::iter::ExactSizeIterator`
2159             let use_absolute = match implementor.impl_.for_ {
2160                 clean::ResolvedPath { ref path, is_generic: false, .. } |
2161                 clean::BorrowedRef {
2162                     type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2163                     ..
2164                 } => implementor_dups[path.last_name()].1,
2165                 _ => false,
2166             };
2167             fmt_impl_for_trait_page(&implementor.impl_, w, use_absolute)?;
2168             writeln!(w, "</code></li>")?;
2169         }
2170     }
2171     write!(w, "</ul>")?;
2172     write!(w, r#"<script type="text/javascript" async
2173                          src="{root_path}/implementors/{path}/{ty}.{name}.js">
2174                  </script>"#,
2175            root_path = vec![".."; cx.current.len()].join("/"),
2176            path = if it.def_id.is_local() {
2177                cx.current.join("/")
2178            } else {
2179                let (ref path, _) = cache.external_paths[&it.def_id];
2180                path[..path.len() - 1].join("/")
2181            },
2182            ty = it.type_().css_class(),
2183            name = *it.name.as_ref().unwrap())?;
2184     Ok(())
2185 }
2186
2187 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2188     use html::item_type::ItemType::*;
2189
2190     let name = it.name.as_ref().unwrap();
2191     let ty = match it.type_() {
2192         Typedef | AssociatedType => AssociatedType,
2193         s@_ => s,
2194     };
2195
2196     let anchor = format!("#{}.{}", ty, name);
2197     match link {
2198         AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2199         AssocItemLink::Anchor(None) => anchor,
2200         AssocItemLink::GotoSource(did, _) => {
2201             href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2202         }
2203     }
2204 }
2205
2206 fn assoc_const(w: &mut fmt::Formatter,
2207                it: &clean::Item,
2208                ty: &clean::Type,
2209                default: Option<&String>,
2210                link: AssocItemLink) -> fmt::Result {
2211     write!(w, "const <a href='{}' class='constant'>{}</a>",
2212            naive_assoc_href(it, link),
2213            it.name.as_ref().unwrap())?;
2214
2215     write!(w, ": {}", ty)?;
2216     if let Some(default) = default {
2217         write!(w, " = {}", Escape(default))?;
2218     }
2219     Ok(())
2220 }
2221
2222 fn assoc_type(w: &mut fmt::Formatter, it: &clean::Item,
2223               bounds: &Vec<clean::TyParamBound>,
2224               default: Option<&clean::Type>,
2225               link: AssocItemLink) -> fmt::Result {
2226     write!(w, "type <a href='{}' class='type'>{}</a>",
2227            naive_assoc_href(it, link),
2228            it.name.as_ref().unwrap())?;
2229     if !bounds.is_empty() {
2230         write!(w, ": {}", TyParamBounds(bounds))?
2231     }
2232     if let Some(default) = default {
2233         write!(w, " = {}", default)?;
2234     }
2235     Ok(())
2236 }
2237
2238 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
2239                                   ver: Option<&'a str>,
2240                                   containing_ver: Option<&'a str>) -> fmt::Result {
2241     if let Some(v) = ver {
2242         if containing_ver != ver && v.len() > 0 {
2243             write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
2244                    v)?
2245         }
2246     }
2247     Ok(())
2248 }
2249
2250 fn render_stability_since(w: &mut fmt::Formatter,
2251                           item: &clean::Item,
2252                           containing_item: &clean::Item) -> fmt::Result {
2253     render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2254 }
2255
2256 fn render_assoc_item(w: &mut fmt::Formatter,
2257                      item: &clean::Item,
2258                      link: AssocItemLink,
2259                      parent: ItemType) -> fmt::Result {
2260     fn method(w: &mut fmt::Formatter,
2261               meth: &clean::Item,
2262               unsafety: hir::Unsafety,
2263               constness: hir::Constness,
2264               abi: abi::Abi,
2265               g: &clean::Generics,
2266               d: &clean::FnDecl,
2267               link: AssocItemLink,
2268               parent: ItemType)
2269               -> fmt::Result {
2270         let name = meth.name.as_ref().unwrap();
2271         let anchor = format!("#{}.{}", meth.type_(), name);
2272         let href = match link {
2273             AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2274             AssocItemLink::Anchor(None) => anchor,
2275             AssocItemLink::GotoSource(did, provided_methods) => {
2276                 // We're creating a link from an impl-item to the corresponding
2277                 // trait-item and need to map the anchored type accordingly.
2278                 let ty = if provided_methods.contains(name) {
2279                     ItemType::Method
2280                 } else {
2281                     ItemType::TyMethod
2282                 };
2283
2284                 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2285             }
2286         };
2287         // FIXME(#24111): remove when `const_fn` is stabilized
2288         let vis_constness = match UnstableFeatures::from_environment() {
2289             UnstableFeatures::Allow => constness,
2290             _ => hir::Constness::NotConst
2291         };
2292         let prefix = format!("{}{}{:#}fn {}{:#}",
2293                              ConstnessSpace(vis_constness),
2294                              UnsafetySpace(unsafety),
2295                              AbiSpace(abi),
2296                              name,
2297                              *g);
2298         let mut indent = prefix.len();
2299         let where_indent = if parent == ItemType::Trait {
2300             indent += 4;
2301             8
2302         } else if parent == ItemType::Impl {
2303             2
2304         } else {
2305             let prefix = prefix + &format!("{:#}", Method(d, indent));
2306             prefix.lines().last().unwrap().len() + 1
2307         };
2308         write!(w, "{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2309                    {generics}{decl}{where_clause}",
2310                ConstnessSpace(vis_constness),
2311                UnsafetySpace(unsafety),
2312                AbiSpace(abi),
2313                href = href,
2314                name = name,
2315                generics = *g,
2316                decl = Method(d, indent),
2317                where_clause = WhereClause(g, where_indent))
2318     }
2319     match item.inner {
2320         clean::StrippedItem(..) => Ok(()),
2321         clean::TyMethodItem(ref m) => {
2322             method(w, item, m.unsafety, hir::Constness::NotConst,
2323                    m.abi, &m.generics, &m.decl, link, parent)
2324         }
2325         clean::MethodItem(ref m) => {
2326             method(w, item, m.unsafety, m.constness,
2327                    m.abi, &m.generics, &m.decl, link, parent)
2328         }
2329         clean::AssociatedConstItem(ref ty, ref default) => {
2330             assoc_const(w, item, ty, default.as_ref(), link)
2331         }
2332         clean::AssociatedTypeItem(ref bounds, ref default) => {
2333             assoc_type(w, item, bounds, default.as_ref(), link)
2334         }
2335         _ => panic!("render_assoc_item called on non-associated-item")
2336     }
2337 }
2338
2339 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2340                s: &clean::Struct) -> fmt::Result {
2341     write!(w, "<pre class='rust struct'>")?;
2342     render_attributes(w, it)?;
2343     render_struct(w,
2344                   it,
2345                   Some(&s.generics),
2346                   s.struct_type,
2347                   &s.fields,
2348                   "",
2349                   true)?;
2350     write!(w, "</pre>")?;
2351
2352     document(w, cx, it)?;
2353     let mut fields = s.fields.iter().filter_map(|f| {
2354         match f.inner {
2355             clean::StructFieldItem(ref ty) => Some((f, ty)),
2356             _ => None,
2357         }
2358     }).peekable();
2359     if let doctree::Plain = s.struct_type {
2360         if fields.peek().is_some() {
2361             write!(w, "<h2 class='fields'>Fields</h2>")?;
2362             for (field, ty) in fields {
2363                 let id = derive_id(format!("{}.{}",
2364                                            ItemType::StructField,
2365                                            field.name.as_ref().unwrap()));
2366                 let ns_id = derive_id(format!("{}.{}",
2367                                               field.name.as_ref().unwrap(),
2368                                               ItemType::StructField.name_space()));
2369                 write!(w, "<span id='{id}' class='{item_type}'>
2370                            <span id='{ns_id}' class='invisible'>
2371                            <code>{name}: {ty}</code>
2372                            </span></span><span class='stab {stab}'></span>",
2373                        item_type = ItemType::StructField,
2374                        id = id,
2375                        ns_id = ns_id,
2376                        stab = field.stability_class(),
2377                        name = field.name.as_ref().unwrap(),
2378                        ty = ty)?;
2379                 document(w, cx, field)?;
2380             }
2381         }
2382     }
2383     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2384 }
2385
2386 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2387                s: &clean::Union) -> fmt::Result {
2388     write!(w, "<pre class='rust union'>")?;
2389     render_attributes(w, it)?;
2390     render_union(w,
2391                  it,
2392                  Some(&s.generics),
2393                  &s.fields,
2394                  "",
2395                  true)?;
2396     write!(w, "</pre>")?;
2397
2398     document(w, cx, it)?;
2399     let mut fields = s.fields.iter().filter_map(|f| {
2400         match f.inner {
2401             clean::StructFieldItem(ref ty) => Some((f, ty)),
2402             _ => None,
2403         }
2404     }).peekable();
2405     if fields.peek().is_some() {
2406         write!(w, "<h2 class='fields'>Fields</h2>")?;
2407         for (field, ty) in fields {
2408             write!(w, "<span id='{shortty}.{name}' class='{shortty}'><code>{name}: {ty}</code>
2409                        </span><span class='stab {stab}'></span>",
2410                    shortty = ItemType::StructField,
2411                    stab = field.stability_class(),
2412                    name = field.name.as_ref().unwrap(),
2413                    ty = ty)?;
2414             document(w, cx, field)?;
2415         }
2416     }
2417     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2418 }
2419
2420 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2421              e: &clean::Enum) -> fmt::Result {
2422     write!(w, "<pre class='rust enum'>")?;
2423     render_attributes(w, it)?;
2424     let padding = format!("{}enum {}{:#} ",
2425                           VisSpace(&it.visibility),
2426                           it.name.as_ref().unwrap(),
2427                           e.generics).len();
2428     write!(w, "{}enum {}{}{}",
2429            VisSpace(&it.visibility),
2430            it.name.as_ref().unwrap(),
2431            e.generics,
2432            WhereClause(&e.generics, padding))?;
2433     if e.variants.is_empty() && !e.variants_stripped {
2434         write!(w, " {{}}")?;
2435     } else {
2436         write!(w, " {{\n")?;
2437         for v in &e.variants {
2438             write!(w, "    ")?;
2439             let name = v.name.as_ref().unwrap();
2440             match v.inner {
2441                 clean::VariantItem(ref var) => {
2442                     match var.kind {
2443                         clean::VariantKind::CLike => write!(w, "{}", name)?,
2444                         clean::VariantKind::Tuple(ref tys) => {
2445                             write!(w, "{}(", name)?;
2446                             for (i, ty) in tys.iter().enumerate() {
2447                                 if i > 0 {
2448                                     write!(w, ",&nbsp;")?
2449                                 }
2450                                 write!(w, "{}", *ty)?;
2451                             }
2452                             write!(w, ")")?;
2453                         }
2454                         clean::VariantKind::Struct(ref s) => {
2455                             render_struct(w,
2456                                           v,
2457                                           None,
2458                                           s.struct_type,
2459                                           &s.fields,
2460                                           "    ",
2461                                           false)?;
2462                         }
2463                     }
2464                 }
2465                 _ => unreachable!()
2466             }
2467             write!(w, ",\n")?;
2468         }
2469
2470         if e.variants_stripped {
2471             write!(w, "    // some variants omitted\n")?;
2472         }
2473         write!(w, "}}")?;
2474     }
2475     write!(w, "</pre>")?;
2476
2477     document(w, cx, it)?;
2478     if !e.variants.is_empty() {
2479         write!(w, "<h2 class='variants'>Variants</h2>\n")?;
2480         for variant in &e.variants {
2481             let id = derive_id(format!("{}.{}",
2482                                        ItemType::Variant,
2483                                        variant.name.as_ref().unwrap()));
2484             let ns_id = derive_id(format!("{}.{}",
2485                                           variant.name.as_ref().unwrap(),
2486                                           ItemType::Variant.name_space()));
2487             write!(w, "<span id='{id}' class='variant'>\
2488                        <span id='{ns_id}' class='invisible'><code>{name}",
2489                    id = id,
2490                    ns_id = ns_id,
2491                    name = variant.name.as_ref().unwrap())?;
2492             if let clean::VariantItem(ref var) = variant.inner {
2493                 if let clean::VariantKind::Tuple(ref tys) = var.kind {
2494                     write!(w, "(")?;
2495                     for (i, ty) in tys.iter().enumerate() {
2496                         if i > 0 {
2497                             write!(w, ",&nbsp;")?;
2498                         }
2499                         write!(w, "{}", *ty)?;
2500                     }
2501                     write!(w, ")")?;
2502                 }
2503             }
2504             write!(w, "</code></span></span>")?;
2505             document(w, cx, variant)?;
2506
2507             use clean::{Variant, VariantKind};
2508             if let clean::VariantItem(Variant {
2509                 kind: VariantKind::Struct(ref s)
2510             }) = variant.inner {
2511                 let variant_id = derive_id(format!("{}.{}.fields",
2512                                                    ItemType::Variant,
2513                                                    variant.name.as_ref().unwrap()));
2514                 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
2515                        id = variant_id)?;
2516                 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
2517                            <table>", name = variant.name.as_ref().unwrap())?;
2518                 for field in &s.fields {
2519                     use clean::StructFieldItem;
2520                     if let StructFieldItem(ref ty) = field.inner {
2521                         let id = derive_id(format!("variant.{}.field.{}",
2522                                                    variant.name.as_ref().unwrap(),
2523                                                    field.name.as_ref().unwrap()));
2524                         let ns_id = derive_id(format!("{}.{}.{}.{}",
2525                                                       variant.name.as_ref().unwrap(),
2526                                                       ItemType::Variant.name_space(),
2527                                                       field.name.as_ref().unwrap(),
2528                                                       ItemType::StructField.name_space()));
2529                         write!(w, "<tr><td \
2530                                    id='{id}'>\
2531                                    <span id='{ns_id}' class='invisible'>\
2532                                    <code>{f}:&nbsp;{t}</code></span></td><td>",
2533                                id = id,
2534                                ns_id = ns_id,
2535                                f = field.name.as_ref().unwrap(),
2536                                t = *ty)?;
2537                         document(w, cx, field)?;
2538                         write!(w, "</td></tr>")?;
2539                     }
2540                 }
2541                 write!(w, "</table></span>")?;
2542             }
2543             render_stability_since(w, variant, it)?;
2544         }
2545     }
2546     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2547     Ok(())
2548 }
2549
2550 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
2551     let name = attr.name();
2552
2553     if attr.is_word() {
2554         Some(format!("{}", name))
2555     } else if let Some(v) = attr.value_str() {
2556         Some(format!("{} = {:?}", name, &v.as_str()[..]))
2557     } else if let Some(values) = attr.meta_item_list() {
2558         let display: Vec<_> = values.iter().filter_map(|attr| {
2559             attr.meta_item().and_then(|mi| render_attribute(mi))
2560         }).collect();
2561
2562         if display.len() > 0 {
2563             Some(format!("{}({})", name, display.join(", ")))
2564         } else {
2565             None
2566         }
2567     } else {
2568         None
2569     }
2570 }
2571
2572 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
2573     "export_name",
2574     "lang",
2575     "link_section",
2576     "must_use",
2577     "no_mangle",
2578     "repr",
2579     "unsafe_destructor_blind_to_params"
2580 ];
2581
2582 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
2583     let mut attrs = String::new();
2584
2585     for attr in &it.attrs.other_attrs {
2586         let name = attr.name();
2587         if !ATTRIBUTE_WHITELIST.contains(&&name.as_str()[..]) {
2588             continue;
2589         }
2590         if let Some(s) = render_attribute(attr.meta()) {
2591             attrs.push_str(&format!("#[{}]\n", s));
2592         }
2593     }
2594     if attrs.len() > 0 {
2595         write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
2596     }
2597     Ok(())
2598 }
2599
2600 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
2601                  g: Option<&clean::Generics>,
2602                  ty: doctree::StructType,
2603                  fields: &[clean::Item],
2604                  tab: &str,
2605                  structhead: bool) -> fmt::Result {
2606     let mut plain = String::new();
2607     write!(w, "{}{}{}",
2608            VisSpace(&it.visibility),
2609            if structhead {"struct "} else {""},
2610            it.name.as_ref().unwrap())?;
2611     plain.push_str(&format!("{}{}{}",
2612                             VisSpace(&it.visibility),
2613                             if structhead {"struct "} else {""},
2614                             it.name.as_ref().unwrap()));
2615     if let Some(g) = g {
2616         plain.push_str(&format!("{:#}", g));
2617         write!(w, "{}", g)?
2618     }
2619     match ty {
2620         doctree::Plain => {
2621             if let Some(g) = g {
2622                 write!(w, "{}", WhereClause(g, plain.len() + 1))?
2623             }
2624             let mut has_visible_fields = false;
2625             write!(w, " {{")?;
2626             for field in fields {
2627                 if let clean::StructFieldItem(ref ty) = field.inner {
2628                     write!(w, "\n{}    {}{}: {},",
2629                            tab,
2630                            VisSpace(&field.visibility),
2631                            field.name.as_ref().unwrap(),
2632                            *ty)?;
2633                     has_visible_fields = true;
2634                 }
2635             }
2636
2637             if has_visible_fields {
2638                 if it.has_stripped_fields().unwrap() {
2639                     write!(w, "\n{}    // some fields omitted", tab)?;
2640                 }
2641                 write!(w, "\n{}", tab)?;
2642             } else if it.has_stripped_fields().unwrap() {
2643                 // If there are no visible fields we can just display
2644                 // `{ /* fields omitted */ }` to save space.
2645                 write!(w, " /* fields omitted */ ")?;
2646             }
2647             write!(w, "}}")?;
2648         }
2649         doctree::Tuple => {
2650             write!(w, "(")?;
2651             plain.push_str("(");
2652             for (i, field) in fields.iter().enumerate() {
2653                 if i > 0 {
2654                     write!(w, ", ")?;
2655                     plain.push_str(", ");
2656                 }
2657                 match field.inner {
2658                     clean::StrippedItem(box clean::StructFieldItem(..)) => {
2659                         plain.push_str("_");
2660                         write!(w, "_")?
2661                     }
2662                     clean::StructFieldItem(ref ty) => {
2663                         plain.push_str(&format!("{}{:#}", VisSpace(&field.visibility), *ty));
2664                         write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
2665                     }
2666                     _ => unreachable!()
2667                 }
2668             }
2669             write!(w, ")")?;
2670             plain.push_str(")");
2671             if let Some(g) = g {
2672                 write!(w, "{}", WhereClause(g, plain.len() + 1))?
2673             }
2674             write!(w, ";")?;
2675         }
2676         doctree::Unit => {
2677             // Needed for PhantomData.
2678             if let Some(g) = g {
2679                 write!(w, "{}", WhereClause(g, plain.len() + 1))?
2680             }
2681             write!(w, ";")?;
2682         }
2683     }
2684     Ok(())
2685 }
2686
2687 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
2688                 g: Option<&clean::Generics>,
2689                 fields: &[clean::Item],
2690                 tab: &str,
2691                 structhead: bool) -> fmt::Result {
2692     let mut plain = String::new();
2693     write!(w, "{}{}{}",
2694            VisSpace(&it.visibility),
2695            if structhead {"union "} else {""},
2696            it.name.as_ref().unwrap())?;
2697     plain.push_str(&format!("{}{}{}",
2698                             VisSpace(&it.visibility),
2699                             if structhead {"union "} else {""},
2700                             it.name.as_ref().unwrap()));
2701     if let Some(g) = g {
2702         write!(w, "{}", g)?;
2703         plain.push_str(&format!("{:#}", g));
2704         write!(w, "{}", WhereClause(g, plain.len() + 1))?;
2705     }
2706
2707     write!(w, " {{\n{}", tab)?;
2708     for field in fields {
2709         if let clean::StructFieldItem(ref ty) = field.inner {
2710             write!(w, "    {}{}: {},\n{}",
2711                    VisSpace(&field.visibility),
2712                    field.name.as_ref().unwrap(),
2713                    *ty,
2714                    tab)?;
2715         }
2716     }
2717
2718     if it.has_stripped_fields().unwrap() {
2719         write!(w, "    // some fields omitted\n{}", tab)?;
2720     }
2721     write!(w, "}}")?;
2722     Ok(())
2723 }
2724
2725 #[derive(Copy, Clone)]
2726 enum AssocItemLink<'a> {
2727     Anchor(Option<&'a str>),
2728     GotoSource(DefId, &'a FxHashSet<String>),
2729 }
2730
2731 impl<'a> AssocItemLink<'a> {
2732     fn anchor(&self, id: &'a String) -> Self {
2733         match *self {
2734             AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
2735             ref other => *other,
2736         }
2737     }
2738 }
2739
2740 enum AssocItemRender<'a> {
2741     All,
2742     DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
2743 }
2744
2745 #[derive(Copy, Clone, PartialEq)]
2746 enum RenderMode {
2747     Normal,
2748     ForDeref { mut_: bool },
2749 }
2750
2751 fn render_assoc_items(w: &mut fmt::Formatter,
2752                       cx: &Context,
2753                       containing_item: &clean::Item,
2754                       it: DefId,
2755                       what: AssocItemRender) -> fmt::Result {
2756     let c = cache();
2757     let v = match c.impls.get(&it) {
2758         Some(v) => v,
2759         None => return Ok(()),
2760     };
2761     let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
2762         i.inner_impl().trait_.is_none()
2763     });
2764     if !non_trait.is_empty() {
2765         let render_mode = match what {
2766             AssocItemRender::All => {
2767                 write!(w, "<h2 id='methods'>Methods</h2>")?;
2768                 RenderMode::Normal
2769             }
2770             AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
2771                 write!(w, "<h2 id='deref-methods'>Methods from \
2772                                {}&lt;Target={}&gt;</h2>", trait_, type_)?;
2773                 RenderMode::ForDeref { mut_: deref_mut_ }
2774             }
2775         };
2776         for i in &non_trait {
2777             render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
2778                         containing_item.stable_since())?;
2779         }
2780     }
2781     if let AssocItemRender::DerefFor { .. } = what {
2782         return Ok(());
2783     }
2784     if !traits.is_empty() {
2785         let deref_impl = traits.iter().find(|t| {
2786             t.inner_impl().trait_.def_id() == c.deref_trait_did
2787         });
2788         if let Some(impl_) = deref_impl {
2789             let has_deref_mut = traits.iter().find(|t| {
2790                 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
2791             }).is_some();
2792             render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
2793         }
2794         write!(w, "<h2 id='implementations'>Trait \
2795                    Implementations</h2>")?;
2796         for i in &traits {
2797             let did = i.trait_did().unwrap();
2798             let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2799             render_impl(w, cx, i, assoc_link,
2800                         RenderMode::Normal, containing_item.stable_since())?;
2801         }
2802     }
2803     Ok(())
2804 }
2805
2806 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
2807                         container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
2808     let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
2809     let target = impl_.inner_impl().items.iter().filter_map(|item| {
2810         match item.inner {
2811             clean::TypedefItem(ref t, true) => Some(&t.type_),
2812             _ => None,
2813         }
2814     }).next().expect("Expected associated type binding");
2815     let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
2816                                            deref_mut_: deref_mut };
2817     if let Some(did) = target.def_id() {
2818         render_assoc_items(w, cx, container_item, did, what)
2819     } else {
2820         if let Some(prim) = target.primitive_type() {
2821             if let Some(&did) = cache().primitive_locations.get(&prim) {
2822                 render_assoc_items(w, cx, container_item, did, what)?;
2823             }
2824         }
2825         Ok(())
2826     }
2827 }
2828
2829 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
2830                render_mode: RenderMode, outer_version: Option<&str>) -> fmt::Result {
2831     if render_mode == RenderMode::Normal {
2832         write!(w, "<h3 class='impl'><span class='in-band'><code>{}</code>", i.inner_impl())?;
2833         write!(w, "</span><span class='out-of-band'>")?;
2834         let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
2835         if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
2836             write!(w, "<div class='ghost'></div>")?;
2837             render_stability_since_raw(w, since, outer_version)?;
2838             write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2839                    l, "goto source code")?;
2840         } else {
2841             render_stability_since_raw(w, since, outer_version)?;
2842         }
2843         write!(w, "</span>")?;
2844         write!(w, "</h3>\n")?;
2845         if let Some(ref dox) = i.impl_item.doc_value() {
2846             write!(w, "<div class='docblock'>{}</div>", Markdown(dox))?;
2847         }
2848     }
2849
2850     fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
2851                      link: AssocItemLink, render_mode: RenderMode,
2852                      is_default_item: bool, outer_version: Option<&str>,
2853                      trait_: Option<&clean::Trait>) -> fmt::Result {
2854         let item_type = item.type_();
2855         let name = item.name.as_ref().unwrap();
2856
2857         let render_method_item: bool = match render_mode {
2858             RenderMode::Normal => true,
2859             RenderMode::ForDeref { mut_: deref_mut_ } => {
2860                 let self_type_opt = match item.inner {
2861                     clean::MethodItem(ref method) => method.decl.self_type(),
2862                     clean::TyMethodItem(ref method) => method.decl.self_type(),
2863                     _ => None
2864                 };
2865
2866                 if let Some(self_ty) = self_type_opt {
2867                     let by_mut_ref = match self_ty {
2868                         SelfTy::SelfBorrowed(_lifetime, mutability) => {
2869                             mutability == Mutability::Mutable
2870                         },
2871                         SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
2872                             mutability == Mutability::Mutable
2873                         },
2874                         _ => false,
2875                     };
2876
2877                     deref_mut_ || !by_mut_ref
2878                 } else {
2879                     false
2880                 }
2881             },
2882         };
2883
2884         match item.inner {
2885             clean::MethodItem(..) | clean::TyMethodItem(..) => {
2886                 // Only render when the method is not static or we allow static methods
2887                 if render_method_item {
2888                     let id = derive_id(format!("{}.{}", item_type, name));
2889                     let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2890                     write!(w, "<h4 id='{}' class='{}'>", id, item_type)?;
2891                     write!(w, "<span id='{}' class='invisible'>", ns_id)?;
2892                     write!(w, "<code>")?;
2893                     render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
2894                     write!(w, "</code>")?;
2895                     render_stability_since_raw(w, item.stable_since(), outer_version)?;
2896                     write!(w, "</span></h4>\n")?;
2897                 }
2898             }
2899             clean::TypedefItem(ref tydef, _) => {
2900                 let id = derive_id(format!("{}.{}", ItemType::AssociatedType, name));
2901                 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2902                 write!(w, "<h4 id='{}' class='{}'>", id, item_type)?;
2903                 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
2904                 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
2905                 write!(w, "</code></span></h4>\n")?;
2906             }
2907             clean::AssociatedConstItem(ref ty, ref default) => {
2908                 let id = derive_id(format!("{}.{}", item_type, name));
2909                 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2910                 write!(w, "<h4 id='{}' class='{}'>", id, item_type)?;
2911                 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
2912                 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
2913                 write!(w, "</code></span></h4>\n")?;
2914             }
2915             clean::ConstantItem(ref c) => {
2916                 let id = derive_id(format!("{}.{}", item_type, name));
2917                 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2918                 write!(w, "<h4 id='{}' class='{}'>", id, item_type)?;
2919                 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
2920                 assoc_const(w, item, &c.type_, Some(&c.expr), link.anchor(&id))?;
2921                 write!(w, "</code></span></h4>\n")?;
2922             }
2923             clean::AssociatedTypeItem(ref bounds, ref default) => {
2924                 let id = derive_id(format!("{}.{}", item_type, name));
2925                 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2926                 write!(w, "<h4 id='{}' class='{}'>", id, item_type)?;
2927                 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
2928                 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
2929                 write!(w, "</code></span></h4>\n")?;
2930             }
2931             clean::StrippedItem(..) => return Ok(()),
2932             _ => panic!("can't make docs for trait item with name {:?}", item.name)
2933         }
2934
2935         if render_method_item || render_mode == RenderMode::Normal {
2936             if !is_default_item {
2937                 if let Some(t) = trait_ {
2938                     // The trait item may have been stripped so we might not
2939                     // find any documentation or stability for it.
2940                     if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
2941                         // We need the stability of the item from the trait
2942                         // because impls can't have a stability.
2943                         document_stability(w, cx, it)?;
2944                         if item.doc_value().is_some() {
2945                             document_full(w, item)?;
2946                         } else {
2947                             // In case the item isn't documented,
2948                             // provide short documentation from the trait.
2949                             document_short(w, it, link)?;
2950                         }
2951                     }
2952                 } else {
2953                     document(w, cx, item)?;
2954                 }
2955             } else {
2956                 document_stability(w, cx, item)?;
2957                 document_short(w, item, link)?;
2958             }
2959         }
2960         Ok(())
2961     }
2962
2963     let traits = &cache().traits;
2964     let trait_ = i.trait_did().and_then(|did| traits.get(&did));
2965
2966     write!(w, "<div class='impl-items'>")?;
2967     for trait_item in &i.inner_impl().items {
2968         doc_impl_item(w, cx, trait_item, link, render_mode,
2969                       false, outer_version, trait_)?;
2970     }
2971
2972     fn render_default_items(w: &mut fmt::Formatter,
2973                             cx: &Context,
2974                             t: &clean::Trait,
2975                             i: &clean::Impl,
2976                             render_mode: RenderMode,
2977                             outer_version: Option<&str>) -> fmt::Result {
2978         for trait_item in &t.items {
2979             let n = trait_item.name.clone();
2980             if i.items.iter().find(|m| m.name == n).is_some() {
2981                 continue;
2982             }
2983             let did = i.trait_.as_ref().unwrap().def_id().unwrap();
2984             let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
2985
2986             doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
2987                           outer_version, None)?;
2988         }
2989         Ok(())
2990     }
2991
2992     // If we've implemented a trait, then also emit documentation for all
2993     // default items which weren't overridden in the implementation block.
2994     if let Some(t) = trait_ {
2995         render_default_items(w, cx, t, &i.inner_impl(), render_mode, outer_version)?;
2996     }
2997     write!(w, "</div>")?;
2998     Ok(())
2999 }
3000
3001 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3002                 t: &clean::Typedef) -> fmt::Result {
3003     let indent = format!("type {}{:#} ", it.name.as_ref().unwrap(), t.generics).len();
3004     write!(w, "<pre class='rust typedef'>type {}{}{where_clause} = {type_};</pre>",
3005            it.name.as_ref().unwrap(),
3006            t.generics,
3007            where_clause = WhereClause(&t.generics, indent),
3008            type_ = t.type_)?;
3009
3010     document(w, cx, it)
3011 }
3012
3013 impl<'a> fmt::Display for Sidebar<'a> {
3014     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3015         let cx = self.cx;
3016         let it = self.item;
3017         let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3018
3019         // The sidebar is designed to display sibling functions, modules and
3020         // other miscellaneous information. since there are lots of sibling
3021         // items (and that causes quadratic growth in large modules),
3022         // we refactor common parts into a shared JavaScript file per module.
3023         // still, we don't move everything into JS because we want to preserve
3024         // as much HTML as possible in order to allow non-JS-enabled browsers
3025         // to navigate the documentation (though slightly inefficiently).
3026
3027         write!(fmt, "<p class='location'>")?;
3028         for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3029             if i > 0 {
3030                 write!(fmt, "::<wbr>")?;
3031             }
3032             write!(fmt, "<a href='{}index.html'>{}</a>",
3033                    &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3034                    *name)?;
3035         }
3036         write!(fmt, "</p>")?;
3037
3038         // Sidebar refers to the enclosing module, not this module.
3039         let relpath = if it.is_mod() { "../" } else { "" };
3040         write!(fmt,
3041                "<script>window.sidebarCurrent = {{\
3042                    name: '{name}', \
3043                    ty: '{ty}', \
3044                    relpath: '{path}'\
3045                 }};</script>",
3046                name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3047                ty = it.type_().css_class(),
3048                path = relpath)?;
3049         if parentlen == 0 {
3050             // There is no sidebar-items.js beyond the crate root path
3051             // FIXME maybe dynamic crate loading can be merged here
3052         } else {
3053             write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
3054                    path = relpath)?;
3055         }
3056
3057         Ok(())
3058     }
3059 }
3060
3061 impl<'a> fmt::Display for Source<'a> {
3062     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3063         let Source(s) = *self;
3064         let lines = s.lines().count();
3065         let mut cols = 0;
3066         let mut tmp = lines;
3067         while tmp > 0 {
3068             cols += 1;
3069             tmp /= 10;
3070         }
3071         write!(fmt, "<pre class=\"line-numbers\">")?;
3072         for i in 1..lines + 1 {
3073             write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
3074         }
3075         write!(fmt, "</pre>")?;
3076         write!(fmt, "{}", highlight::render_with_highlighting(s, None, None, None))?;
3077         Ok(())
3078     }
3079 }
3080
3081 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3082               t: &clean::Macro) -> fmt::Result {
3083     w.write_str(&highlight::render_with_highlighting(&t.source,
3084                                                      Some("macro"),
3085                                                      None,
3086                                                      None))?;
3087     document(w, cx, it)
3088 }
3089
3090 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
3091                   it: &clean::Item,
3092                   _p: &clean::PrimitiveType) -> fmt::Result {
3093     document(w, cx, it)?;
3094     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3095 }
3096
3097 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
3098
3099 fn make_item_keywords(it: &clean::Item) -> String {
3100     format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
3101 }
3102
3103 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
3104     let decl = match item.inner {
3105         clean::FunctionItem(ref f) => &f.decl,
3106         clean::MethodItem(ref m) => &m.decl,
3107         clean::TyMethodItem(ref m) => &m.decl,
3108         _ => return None
3109     };
3110
3111     let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
3112     let output = match decl.output {
3113         clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
3114         _ => None
3115     };
3116
3117     Some(IndexItemFunctionType { inputs: inputs, output: output })
3118 }
3119
3120 fn get_index_type(clean_type: &clean::Type) -> Type {
3121     Type { name: get_index_type_name(clean_type).map(|s| s.to_ascii_lowercase()) }
3122 }
3123
3124 fn get_index_type_name(clean_type: &clean::Type) -> Option<String> {
3125     match *clean_type {
3126         clean::ResolvedPath { ref path, .. } => {
3127             let segments = &path.segments;
3128             Some(segments[segments.len() - 1].name.clone())
3129         },
3130         clean::Generic(ref s) => Some(s.clone()),
3131         clean::Primitive(ref p) => Some(format!("{:?}", p)),
3132         clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_),
3133         // FIXME: add all from clean::Type.
3134         _ => None
3135     }
3136 }
3137
3138 pub fn cache() -> Arc<Cache> {
3139     CACHE_KEY.with(|c| c.borrow().clone())
3140 }
3141
3142 #[cfg(test)]
3143 #[test]
3144 fn test_unique_id() {
3145     let input = ["foo", "examples", "examples", "method.into_iter","examples",
3146                  "method.into_iter", "foo", "main", "search", "methods",
3147                  "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
3148     let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
3149                     "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
3150                     "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
3151
3152     let test = || {
3153         let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
3154         assert_eq!(&actual[..], expected);
3155     };
3156     test();
3157     reset_ids(true);
3158     test();
3159 }