]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/render.rs
86b268001a6aeb357e682abac729a6492b7ab370
[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, HashMap, HashSet};
41 use std::default::Default;
42 use std::fmt;
43 use std::fs::{self, File};
44 use std::io::prelude::*;
45 use std::io::{self, BufWriter, BufReader};
46 use std::iter::repeat;
47 use std::mem;
48 use std::path::{PathBuf, Path};
49 use std::str;
50 use std::sync::Arc;
51
52 use externalfiles::ExternalHtml;
53
54 use serialize::json::{self, ToJson};
55 use syntax::{abi, ast};
56 use rustc::middle::def_id::{DefId, LOCAL_CRATE};
57 use rustc::util::nodemap::NodeSet;
58 use rustc_front::{hir, attr};
59
60 use clean::{self, SelfTy};
61 use doctree;
62 use fold::DocFolder;
63 use html::escape::Escape;
64 use html::format::{ConstnessSpace};
65 use html::format::{TyParamBounds, WhereClause, href, AbiSpace};
66 use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace};
67 use html::item_type::ItemType;
68 use html::markdown::{self, Markdown};
69 use html::{highlight, layout};
70
71 /// A pair of name and its optional document.
72 pub type NameDoc = (String, Option<String>);
73
74 /// Major driving force in all rustdoc rendering. This contains information
75 /// about where in the tree-like hierarchy rendering is occurring and controls
76 /// how the current page is being rendered.
77 ///
78 /// It is intended that this context is a lightweight object which can be fairly
79 /// easily cloned because it is cloned per work-job (about once per item in the
80 /// rustdoc tree).
81 #[derive(Clone)]
82 pub struct Context {
83     /// Current hierarchy of components leading down to what's currently being
84     /// rendered
85     pub current: Vec<String>,
86     /// String representation of how to get back to the root path of the 'doc/'
87     /// folder in terms of a relative URL.
88     pub root_path: String,
89     /// The path to the crate root source minus the file name.
90     /// Used for simplifying paths to the highlighted source code files.
91     pub src_root: PathBuf,
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     /// This describes the layout of each page, and is not modified after
96     /// creation of the context (contains info like the favicon and added html).
97     pub layout: layout::Layout,
98     /// This flag indicates whether [src] links should be generated or not. If
99     /// the source files are present in the html rendering, then this will be
100     /// `true`.
101     pub include_sources: bool,
102     /// A flag, which when turned off, will render pages which redirect to the
103     /// real location of an item. This is used to allow external links to
104     /// publicly reused items to redirect to the right location.
105     pub render_redirect_pages: bool,
106     /// All the passes that were run on this crate.
107     pub passes: HashSet<String>,
108     /// The base-URL of the issue tracker for when an item has been tagged with
109     /// an issue number.
110     pub issue_tracker_base_url: Option<String>,
111 }
112
113 /// Indicates where an external crate can be found.
114 pub enum ExternalLocation {
115     /// Remote URL root of the external crate
116     Remote(String),
117     /// This external crate can be found in the local doc/ folder
118     Local,
119     /// The external crate could not be found.
120     Unknown,
121 }
122
123 /// Metadata about an implementor of a trait.
124 pub struct Implementor {
125     pub def_id: DefId,
126     pub stability: Option<clean::Stability>,
127     pub impl_: clean::Impl,
128 }
129
130 /// Metadata about implementations for a type.
131 #[derive(Clone)]
132 pub struct Impl {
133     pub impl_: clean::Impl,
134     pub dox: Option<String>,
135     pub stability: Option<clean::Stability>,
136 }
137
138 impl Impl {
139     fn trait_did(&self) -> Option<DefId> {
140         self.impl_.trait_.as_ref().and_then(|tr| {
141             if let clean::ResolvedPath { did, .. } = *tr {Some(did)} else {None}
142         })
143     }
144 }
145
146 /// This cache is used to store information about the `clean::Crate` being
147 /// rendered in order to provide more useful documentation. This contains
148 /// information like all implementors of a trait, all traits a type implements,
149 /// documentation for all known traits, etc.
150 ///
151 /// This structure purposefully does not implement `Clone` because it's intended
152 /// to be a fairly large and expensive structure to clone. Instead this adheres
153 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
154 /// rendering threads.
155 #[derive(Default)]
156 pub struct Cache {
157     /// Mapping of typaram ids to the name of the type parameter. This is used
158     /// when pretty-printing a type (so pretty printing doesn't have to
159     /// painfully maintain a context like this)
160     pub typarams: HashMap<DefId, String>,
161
162     /// Maps a type id to all known implementations for that type. This is only
163     /// recognized for intra-crate `ResolvedPath` types, and is used to print
164     /// out extra documentation on the page of an enum/struct.
165     ///
166     /// The values of the map are a list of implementations and documentation
167     /// found on that implementation.
168     pub impls: HashMap<DefId, Vec<Impl>>,
169
170     /// Maintains a mapping of local crate node ids to the fully qualified name
171     /// and "short type description" of that node. This is used when generating
172     /// URLs when a type is being linked to. External paths are not located in
173     /// this map because the `External` type itself has all the information
174     /// necessary.
175     pub paths: HashMap<DefId, (Vec<String>, ItemType)>,
176
177     /// Similar to `paths`, but only holds external paths. This is only used for
178     /// generating explicit hyperlinks to other crates.
179     pub external_paths: HashMap<DefId, Vec<String>>,
180
181     /// This map contains information about all known traits of this crate.
182     /// Implementations of a crate should inherit the documentation of the
183     /// parent trait if no extra documentation is specified, and default methods
184     /// should show up in documentation about trait implementations.
185     pub traits: HashMap<DefId, clean::Trait>,
186
187     /// When rendering traits, it's often useful to be able to list all
188     /// implementors of the trait, and this mapping is exactly, that: a mapping
189     /// of trait ids to the list of known implementors of the trait
190     pub implementors: HashMap<DefId, Vec<Implementor>>,
191
192     /// Cache of where external crate documentation can be found.
193     pub extern_locations: HashMap<ast::CrateNum, (String, ExternalLocation)>,
194
195     /// Cache of where documentation for primitives can be found.
196     pub primitive_locations: HashMap<clean::PrimitiveType, ast::CrateNum>,
197
198     /// Set of definitions which have been inlined from external crates.
199     pub inlined: HashSet<DefId>,
200
201     // Private fields only used when initially crawling a crate to build a cache
202
203     stack: Vec<String>,
204     parent_stack: Vec<DefId>,
205     search_index: Vec<IndexItem>,
206     privmod: bool,
207     remove_priv: bool,
208     public_items: NodeSet,
209     deref_trait_did: Option<DefId>,
210
211     // In rare case where a structure is defined in one module but implemented
212     // in another, if the implementing module is parsed before defining module,
213     // then the fully qualified name of the structure isn't presented in `paths`
214     // yet when its implementation methods are being indexed. Caches such methods
215     // and their parent id here and indexes them at the end of crate parsing.
216     orphan_methods: Vec<(ast::NodeId, clean::Item)>,
217 }
218
219 /// Helper struct to render all source code to HTML pages
220 struct SourceCollector<'a> {
221     cx: &'a mut Context,
222
223     /// Processed source-file paths
224     seen: HashSet<String>,
225     /// Root destination to place all HTML output into
226     dst: PathBuf,
227 }
228
229 /// Wrapper struct to render the source code of a file. This will do things like
230 /// adding line numbers to the left-hand side.
231 struct Source<'a>(&'a str);
232
233 // Helper structs for rendering items/sidebars and carrying along contextual
234 // information
235
236 #[derive(Copy, Clone)]
237 struct Item<'a> {
238     cx: &'a Context,
239     item: &'a clean::Item,
240 }
241
242 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
243
244 /// Struct representing one entry in the JS search index. These are all emitted
245 /// by hand to a large JS file at the end of cache-creation.
246 struct IndexItem {
247     ty: ItemType,
248     name: String,
249     path: String,
250     desc: String,
251     parent: Option<DefId>,
252     search_type: Option<IndexItemFunctionType>,
253 }
254
255 /// A type used for the search index.
256 struct Type {
257     name: Option<String>,
258 }
259
260 impl fmt::Display for Type {
261     /// Formats type as {name: $name}.
262     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
263         // Wrapping struct fmt should never call us when self.name is None,
264         // but just to be safe we write `null` in that case.
265         match self.name {
266             Some(ref n) => write!(f, "{{\"name\":\"{}\"}}", n),
267             None => write!(f, "null")
268         }
269     }
270 }
271
272 /// Full type of functions/methods in the search index.
273 struct IndexItemFunctionType {
274     inputs: Vec<Type>,
275     output: Option<Type>
276 }
277
278 impl fmt::Display for IndexItemFunctionType {
279     /// Formats a full fn type as a JSON {inputs: [Type], outputs: Type/null}.
280     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
281         // If we couldn't figure out a type, just write `null`.
282         if self.inputs.iter().any(|ref i| i.name.is_none()) ||
283            (self.output.is_some() && self.output.as_ref().unwrap().name.is_none()) {
284             return write!(f, "null")
285         }
286
287         let inputs: Vec<String> = self.inputs.iter().map(|ref t| {
288             format!("{}", t)
289         }).collect();
290         try!(write!(f, "{{\"inputs\":[{}],\"output\":", inputs.join(",")));
291
292         match self.output {
293             Some(ref t) => try!(write!(f, "{}", t)),
294             None => try!(write!(f, "null"))
295         };
296
297         Ok(try!(write!(f, "}}")))
298     }
299 }
300
301 // TLS keys used to carry information around during rendering.
302
303 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
304 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> =
305                     RefCell::new(Vec::new()));
306
307 /// Generates the documentation for `crate` into the directory `dst`
308 pub fn run(mut krate: clean::Crate,
309            external_html: &ExternalHtml,
310            dst: PathBuf,
311            passes: HashSet<String>) -> io::Result<()> {
312     let src_root = match krate.src.parent() {
313         Some(p) => p.to_path_buf(),
314         None => PathBuf::new(),
315     };
316     let mut cx = Context {
317         dst: dst,
318         src_root: src_root,
319         passes: passes,
320         current: Vec::new(),
321         root_path: String::new(),
322         layout: layout::Layout {
323             logo: "".to_string(),
324             favicon: "".to_string(),
325             external_html: external_html.clone(),
326             krate: krate.name.clone(),
327             playground_url: "".to_string(),
328         },
329         include_sources: true,
330         render_redirect_pages: false,
331         issue_tracker_base_url: None,
332     };
333
334     try!(mkdir(&cx.dst));
335
336     // Crawl the crate attributes looking for attributes which control how we're
337     // going to emit HTML
338     let default: &[_] = &[];
339     match krate.module.as_ref().map(|m| m.doc_list().unwrap_or(default)) {
340         Some(attrs) => {
341             for attr in attrs {
342                 match *attr {
343                     clean::NameValue(ref x, ref s)
344                             if "html_favicon_url" == *x => {
345                         cx.layout.favicon = s.to_string();
346                     }
347                     clean::NameValue(ref x, ref s)
348                             if "html_logo_url" == *x => {
349                         cx.layout.logo = s.to_string();
350                     }
351                     clean::NameValue(ref x, ref s)
352                             if "html_playground_url" == *x => {
353                         cx.layout.playground_url = s.to_string();
354                         markdown::PLAYGROUND_KRATE.with(|slot| {
355                             if slot.borrow().is_none() {
356                                 let name = krate.name.clone();
357                                 *slot.borrow_mut() = Some(Some(name));
358                             }
359                         });
360                     }
361                     clean::NameValue(ref x, ref s)
362                             if "issue_tracker_base_url" == *x => {
363                         cx.issue_tracker_base_url = Some(s.to_string());
364                     }
365                     clean::Word(ref x)
366                             if "html_no_source" == *x => {
367                         cx.include_sources = false;
368                     }
369                     _ => {}
370                 }
371             }
372         }
373         None => {}
374     }
375
376     // Crawl the crate to build various caches used for the output
377     let analysis = ::ANALYSISKEY.with(|a| a.clone());
378     let analysis = analysis.borrow();
379     let public_items = analysis.as_ref().map(|a| a.public_items.clone());
380     let public_items = public_items.unwrap_or(NodeSet());
381     let paths: HashMap<DefId, (Vec<String>, ItemType)> =
382       analysis.as_ref().map(|a| {
383         let paths = a.external_paths.borrow_mut().take().unwrap();
384         paths.into_iter().map(|(k, (v, t))| (k, (v, ItemType::from_type_kind(t)))).collect()
385       }).unwrap_or(HashMap::new());
386     let mut cache = Cache {
387         impls: HashMap::new(),
388         external_paths: paths.iter().map(|(&k, v)| (k, v.0.clone()))
389                              .collect(),
390         paths: paths,
391         implementors: HashMap::new(),
392         stack: Vec::new(),
393         parent_stack: Vec::new(),
394         search_index: Vec::new(),
395         extern_locations: HashMap::new(),
396         primitive_locations: HashMap::new(),
397         remove_priv: cx.passes.contains("strip-private"),
398         privmod: false,
399         public_items: public_items,
400         orphan_methods: Vec::new(),
401         traits: mem::replace(&mut krate.external_traits, HashMap::new()),
402         deref_trait_did: analysis.as_ref().and_then(|a| a.deref_trait_did),
403         typarams: analysis.as_ref().map(|a| {
404             a.external_typarams.borrow_mut().take().unwrap()
405         }).unwrap_or(HashMap::new()),
406         inlined: analysis.as_ref().map(|a| {
407             a.inlined.borrow_mut().take().unwrap()
408         }).unwrap_or(HashSet::new()),
409     };
410
411     // Cache where all our extern crates are located
412     for &(n, ref e) in &krate.externs {
413         cache.extern_locations.insert(n, (e.name.clone(),
414                                           extern_location(e, &cx.dst)));
415         let did = DefId { krate: n, node: ast::CRATE_NODE_ID };
416         cache.paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
417     }
418
419     // Cache where all known primitives have their documentation located.
420     //
421     // Favor linking to as local extern as possible, so iterate all crates in
422     // reverse topological order.
423     for &(n, ref e) in krate.externs.iter().rev() {
424         for &prim in &e.primitives {
425             cache.primitive_locations.insert(prim, n);
426         }
427     }
428     for &prim in &krate.primitives {
429         cache.primitive_locations.insert(prim, LOCAL_CRATE);
430     }
431
432     cache.stack.push(krate.name.clone());
433     krate = cache.fold_crate(krate);
434
435     // Build our search index
436     let index = try!(build_index(&krate, &mut cache));
437
438     // Freeze the cache now that the index has been built. Put an Arc into TLS
439     // for future parallelization opportunities
440     let cache = Arc::new(cache);
441     CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
442     CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
443
444     try!(write_shared(&cx, &krate, &*cache, index));
445     let krate = try!(render_sources(&mut cx, krate));
446
447     // And finally render the whole crate's documentation
448     cx.krate(krate)
449 }
450
451 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::Result<String> {
452     // Build the search index from the collected metadata
453     let mut nodeid_to_pathid = HashMap::new();
454     let mut pathid_to_nodeid = Vec::new();
455     {
456         let Cache { ref mut search_index,
457                     ref orphan_methods,
458                     ref mut paths, .. } = *cache;
459
460         // Attach all orphan methods to the type's definition if the type
461         // has since been learned.
462         for &(pid, ref item) in orphan_methods {
463             let did = DefId::local(pid);
464             match paths.get(&did) {
465                 Some(&(ref fqp, _)) => {
466                     // Needed to determine `self` type.
467                     let parent_basename = Some(fqp[fqp.len() - 1].clone());
468                     search_index.push(IndexItem {
469                         ty: shortty(item),
470                         name: item.name.clone().unwrap(),
471                         path: fqp[..fqp.len() - 1].join("::"),
472                         desc: shorter(item.doc_value()),
473                         parent: Some(did),
474                         search_type: get_index_search_type(&item, parent_basename),
475                     });
476                 },
477                 None => {}
478             }
479         };
480
481         // Reduce `NodeId` in paths into smaller sequential numbers,
482         // and prune the paths that do not appear in the index.
483         for item in search_index.iter() {
484             match item.parent {
485                 Some(nodeid) => {
486                     if !nodeid_to_pathid.contains_key(&nodeid) {
487                         let pathid = pathid_to_nodeid.len();
488                         nodeid_to_pathid.insert(nodeid, pathid);
489                         pathid_to_nodeid.push(nodeid);
490                     }
491                 }
492                 None => {}
493             }
494         }
495         assert_eq!(nodeid_to_pathid.len(), pathid_to_nodeid.len());
496     }
497
498     // Collect the index into a string
499     let mut w = io::Cursor::new(Vec::new());
500     try!(write!(&mut w, r#"searchIndex['{}'] = {{"items":["#, krate.name));
501
502     let mut lastpath = "".to_string();
503     for (i, item) in cache.search_index.iter().enumerate() {
504         // Omit the path if it is same to that of the prior item.
505         let path;
506         if lastpath == item.path {
507             path = "";
508         } else {
509             lastpath = item.path.to_string();
510             path = &item.path;
511         };
512
513         if i > 0 {
514             try!(write!(&mut w, ","));
515         }
516         try!(write!(&mut w, r#"[{},"{}","{}",{}"#,
517                     item.ty as usize, item.name, path,
518                     item.desc.to_json().to_string()));
519         match item.parent {
520             Some(nodeid) => {
521                 let pathid = *nodeid_to_pathid.get(&nodeid).unwrap();
522                 try!(write!(&mut w, ",{}", pathid));
523             }
524             None => try!(write!(&mut w, ",null"))
525         }
526         match item.search_type {
527             Some(ref t) => try!(write!(&mut w, ",{}", t)),
528             None => try!(write!(&mut w, ",null"))
529         }
530         try!(write!(&mut w, "]"));
531     }
532
533     try!(write!(&mut w, r#"],"paths":["#));
534
535     for (i, &did) in pathid_to_nodeid.iter().enumerate() {
536         let &(ref fqp, short) = cache.paths.get(&did).unwrap();
537         if i > 0 {
538             try!(write!(&mut w, ","));
539         }
540         try!(write!(&mut w, r#"[{},"{}"]"#,
541                     short as usize, *fqp.last().unwrap()));
542     }
543
544     try!(write!(&mut w, "]}};"));
545
546     Ok(String::from_utf8(w.into_inner()).unwrap())
547 }
548
549 fn write_shared(cx: &Context,
550                 krate: &clean::Crate,
551                 cache: &Cache,
552                 search_index: String) -> io::Result<()> {
553     // Write out the shared files. Note that these are shared among all rustdoc
554     // docs placed in the output directory, so this needs to be a synchronized
555     // operation with respect to all other rustdocs running around.
556     try!(mkdir(&cx.dst));
557     let _lock = ::flock::Lock::new(&cx.dst.join(".lock"));
558
559     // Add all the static files. These may already exist, but we just
560     // overwrite them anyway to make sure that they're fresh and up-to-date.
561     try!(write(cx.dst.join("jquery.js"),
562                include_bytes!("static/jquery-2.1.4.min.js")));
563     try!(write(cx.dst.join("main.js"), include_bytes!("static/main.js")));
564     try!(write(cx.dst.join("playpen.js"), include_bytes!("static/playpen.js")));
565     try!(write(cx.dst.join("main.css"), include_bytes!("static/main.css")));
566     try!(write(cx.dst.join("normalize.css"),
567                include_bytes!("static/normalize.css")));
568     try!(write(cx.dst.join("FiraSans-Regular.woff"),
569                include_bytes!("static/FiraSans-Regular.woff")));
570     try!(write(cx.dst.join("FiraSans-Medium.woff"),
571                include_bytes!("static/FiraSans-Medium.woff")));
572     try!(write(cx.dst.join("Heuristica-Italic.woff"),
573                include_bytes!("static/Heuristica-Italic.woff")));
574     try!(write(cx.dst.join("SourceSerifPro-Regular.woff"),
575                include_bytes!("static/SourceSerifPro-Regular.woff")));
576     try!(write(cx.dst.join("SourceSerifPro-Bold.woff"),
577                include_bytes!("static/SourceSerifPro-Bold.woff")));
578     try!(write(cx.dst.join("SourceCodePro-Regular.woff"),
579                include_bytes!("static/SourceCodePro-Regular.woff")));
580     try!(write(cx.dst.join("SourceCodePro-Semibold.woff"),
581                include_bytes!("static/SourceCodePro-Semibold.woff")));
582
583     fn collect(path: &Path, krate: &str,
584                key: &str) -> io::Result<Vec<String>> {
585         let mut ret = Vec::new();
586         if path.exists() {
587             for line in BufReader::new(try!(File::open(path))).lines() {
588                 let line = try!(line);
589                 if !line.starts_with(key) {
590                     continue
591                 }
592                 if line.starts_with(&format!("{}['{}']", key, krate)) {
593                     continue
594                 }
595                 ret.push(line.to_string());
596             }
597         }
598         return Ok(ret);
599     }
600
601     // Update the search index
602     let dst = cx.dst.join("search-index.js");
603     let all_indexes = try!(collect(&dst, &krate.name, "searchIndex"));
604     let mut w = try!(File::create(&dst));
605     try!(writeln!(&mut w, "var searchIndex = {{}};"));
606     try!(writeln!(&mut w, "{}", search_index));
607     for index in &all_indexes {
608         try!(writeln!(&mut w, "{}", *index));
609     }
610     try!(writeln!(&mut w, "initSearch(searchIndex);"));
611
612     // Update the list of all implementors for traits
613     let dst = cx.dst.join("implementors");
614     try!(mkdir(&dst));
615     for (&did, imps) in &cache.implementors {
616         // Private modules can leak through to this phase of rustdoc, which
617         // could contain implementations for otherwise private types. In some
618         // rare cases we could find an implementation for an item which wasn't
619         // indexed, so we just skip this step in that case.
620         //
621         // FIXME: this is a vague explanation for why this can't be a `get`, in
622         //        theory it should be...
623         let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
624             Some(p) => p,
625             None => continue,
626         };
627
628         let mut mydst = dst.clone();
629         for part in &remote_path[..remote_path.len() - 1] {
630             mydst.push(part);
631             try!(mkdir(&mydst));
632         }
633         mydst.push(&format!("{}.{}.js",
634                             remote_item_type.to_static_str(),
635                             remote_path[remote_path.len() - 1]));
636         let all_implementors = try!(collect(&mydst, &krate.name,
637                                             "implementors"));
638
639         try!(mkdir(mydst.parent().unwrap()));
640         let mut f = BufWriter::new(try!(File::create(&mydst)));
641         try!(writeln!(&mut f, "(function() {{var implementors = {{}};"));
642
643         for implementor in &all_implementors {
644             try!(write!(&mut f, "{}", *implementor));
645         }
646
647         try!(write!(&mut f, r"implementors['{}'] = [", krate.name));
648         for imp in imps {
649             // If the trait and implementation are in the same crate, then
650             // there's no need to emit information about it (there's inlining
651             // going on). If they're in different crates then the crate defining
652             // the trait will be interested in our implementation.
653             if imp.def_id.krate == did.krate { continue }
654             try!(write!(&mut f, r#""{}","#, imp.impl_));
655         }
656         try!(writeln!(&mut f, r"];"));
657         try!(writeln!(&mut f, "{}", r"
658             if (window.register_implementors) {
659                 window.register_implementors(implementors);
660             } else {
661                 window.pending_implementors = implementors;
662             }
663         "));
664         try!(writeln!(&mut f, r"}})()"));
665     }
666     Ok(())
667 }
668
669 fn render_sources(cx: &mut Context,
670                   krate: clean::Crate) -> io::Result<clean::Crate> {
671     info!("emitting source files");
672     let dst = cx.dst.join("src");
673     try!(mkdir(&dst));
674     let dst = dst.join(&krate.name);
675     try!(mkdir(&dst));
676     let mut folder = SourceCollector {
677         dst: dst,
678         seen: HashSet::new(),
679         cx: cx,
680     };
681     // skip all invalid spans
682     folder.seen.insert("".to_string());
683     Ok(folder.fold_crate(krate))
684 }
685
686 /// Writes the entire contents of a string to a destination, not attempting to
687 /// catch any errors.
688 fn write(dst: PathBuf, contents: &[u8]) -> io::Result<()> {
689     try!(File::create(&dst)).write_all(contents)
690 }
691
692 /// Makes a directory on the filesystem, failing the thread if an error occurs and
693 /// skipping if the directory already exists.
694 fn mkdir(path: &Path) -> io::Result<()> {
695     if !path.exists() {
696         fs::create_dir(path)
697     } else {
698         Ok(())
699     }
700 }
701
702 /// Returns a documentation-level item type from the item.
703 fn shortty(item: &clean::Item) -> ItemType {
704     ItemType::from_item(item)
705 }
706
707 /// Takes a path to a source file and cleans the path to it. This canonicalizes
708 /// things like ".." to components which preserve the "top down" hierarchy of a
709 /// static HTML tree. Each component in the cleaned path will be passed as an
710 /// argument to `f`. The very last component of the path (ie the file name) will
711 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
712 // FIXME (#9639): The closure should deal with &[u8] instead of &str
713 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
714 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
715     F: FnMut(&str),
716 {
717     // make it relative, if possible
718     let p = p.relative_from(src_root).unwrap_or(p);
719
720     let mut iter = p.iter().map(|x| x.to_str().unwrap()).peekable();
721     while let Some(c) = iter.next() {
722         if !keep_filename && iter.peek().is_none() {
723             break;
724         }
725
726         if ".." == c {
727             f("up");
728         } else {
729             f(c)
730         }
731     }
732 }
733
734 /// Attempts to find where an external crate is located, given that we're
735 /// rendering in to the specified source destination.
736 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
737     // See if there's documentation generated into the local directory
738     let local_location = dst.join(&e.name);
739     if local_location.is_dir() {
740         return Local;
741     }
742
743     // Failing that, see if there's an attribute specifying where to find this
744     // external crate
745     for attr in &e.attrs {
746         match *attr {
747             clean::List(ref x, ref list) if "doc" == *x => {
748                 for attr in list {
749                     match *attr {
750                         clean::NameValue(ref x, ref s)
751                                 if "html_root_url" == *x => {
752                             if s.ends_with("/") {
753                                 return Remote(s.to_string());
754                             }
755                             return Remote(format!("{}/", s));
756                         }
757                         _ => {}
758                     }
759                 }
760             }
761             _ => {}
762         }
763     }
764
765     // Well, at least we tried.
766     return Unknown;
767 }
768
769 impl<'a> DocFolder for SourceCollector<'a> {
770     fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
771         // If we're including source files, and we haven't seen this file yet,
772         // then we need to render it out to the filesystem
773         if self.cx.include_sources && !self.seen.contains(&item.source.filename) {
774
775             // If it turns out that we couldn't read this file, then we probably
776             // can't read any of the files (generating html output from json or
777             // something like that), so just don't include sources for the
778             // entire crate. The other option is maintaining this mapping on a
779             // per-file basis, but that's probably not worth it...
780             self.cx
781                 .include_sources = match self.emit_source(&item.source .filename) {
782                 Ok(()) => true,
783                 Err(e) => {
784                     println!("warning: source code was requested to be rendered, \
785                               but processing `{}` had an error: {}",
786                              item.source.filename, e);
787                     println!("         skipping rendering of source code");
788                     false
789                 }
790             };
791             self.seen.insert(item.source.filename.clone());
792         }
793
794         self.fold_item_recur(item)
795     }
796 }
797
798 impl<'a> SourceCollector<'a> {
799     /// Renders the given filename into its corresponding HTML source file.
800     fn emit_source(&mut self, filename: &str) -> io::Result<()> {
801         let p = PathBuf::from(filename);
802
803         // If we couldn't open this file, then just returns because it
804         // probably means that it's some standard library macro thing and we
805         // can't have the source to it anyway.
806         let mut contents = Vec::new();
807         match File::open(&p).and_then(|mut f| f.read_to_end(&mut contents)) {
808             Ok(r) => r,
809             // macros from other libraries get special filenames which we can
810             // safely ignore
811             Err(..) if filename.starts_with("<") &&
812                        filename.ends_with("macros>") => return Ok(()),
813             Err(e) => return Err(e)
814         };
815         let contents = str::from_utf8(&contents).unwrap();
816
817         // Remove the utf-8 BOM if any
818         let contents = if contents.starts_with("\u{feff}") {
819             &contents[3..]
820         } else {
821             contents
822         };
823
824         // Create the intermediate directories
825         let mut cur = self.dst.clone();
826         let mut root_path = String::from("../../");
827         clean_srcpath(&self.cx.src_root, &p, false, |component| {
828             cur.push(component);
829             mkdir(&cur).unwrap();
830             root_path.push_str("../");
831         });
832
833         let mut fname = p.file_name().expect("source has no filename")
834                          .to_os_string();
835         fname.push(".html");
836         cur.push(&fname[..]);
837         let mut w = BufWriter::new(try!(File::create(&cur)));
838
839         let title = format!("{} -- source", cur.file_name().unwrap()
840                                                .to_string_lossy());
841         let desc = format!("Source to the Rust file `{}`.", filename);
842         let page = layout::Page {
843             title: &title,
844             ty: "source",
845             root_path: &root_path,
846             description: &desc,
847             keywords: get_basic_keywords(),
848         };
849         try!(layout::render(&mut w, &self.cx.layout,
850                             &page, &(""), &Source(contents)));
851         try!(w.flush());
852         return Ok(());
853     }
854 }
855
856 impl DocFolder for Cache {
857     fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
858         // If this is a private module, we don't want it in the search index.
859         let orig_privmod = match item.inner {
860             clean::ModuleItem(..) => {
861                 let prev = self.privmod;
862                 self.privmod = prev || (self.remove_priv && item.visibility != Some(hir::Public));
863                 prev
864             }
865             _ => self.privmod,
866         };
867
868         // Register any generics to their corresponding string. This is used
869         // when pretty-printing types
870         match item.inner {
871             clean::StructItem(ref s)          => self.generics(&s.generics),
872             clean::EnumItem(ref e)            => self.generics(&e.generics),
873             clean::FunctionItem(ref f)        => self.generics(&f.generics),
874             clean::TypedefItem(ref t, _)      => self.generics(&t.generics),
875             clean::TraitItem(ref t)           => self.generics(&t.generics),
876             clean::ImplItem(ref i)            => self.generics(&i.generics),
877             clean::TyMethodItem(ref i)        => self.generics(&i.generics),
878             clean::MethodItem(ref i)          => self.generics(&i.generics),
879             clean::ForeignFunctionItem(ref f) => self.generics(&f.generics),
880             _ => {}
881         }
882
883         // Propagate a trait methods' documentation to all implementors of the
884         // trait
885         if let clean::TraitItem(ref t) = item.inner {
886             self.traits.insert(item.def_id, t.clone());
887         }
888
889         // Collect all the implementors of traits.
890         if let clean::ImplItem(ref i) = item.inner {
891             match i.trait_ {
892                 Some(clean::ResolvedPath{ did, .. }) => {
893                     self.implementors.entry(did).or_insert(vec![]).push(Implementor {
894                         def_id: item.def_id,
895                         stability: item.stability.clone(),
896                         impl_: i.clone(),
897                     });
898                 }
899                 Some(..) | None => {}
900             }
901         }
902
903         // Index this method for searching later on
904         if let Some(ref s) = item.name {
905             let (parent, is_method) = match item.inner {
906                 clean::AssociatedTypeItem(..) |
907                 clean::AssociatedConstItem(..) |
908                 clean::TyMethodItem(..) |
909                 clean::StructFieldItem(..) |
910                 clean::VariantItem(..) => {
911                     ((Some(*self.parent_stack.last().unwrap()),
912                       Some(&self.stack[..self.stack.len() - 1])),
913                      false)
914                 }
915                 clean::MethodItem(..) => {
916                     if self.parent_stack.is_empty() {
917                         ((None, None), false)
918                     } else {
919                         let last = self.parent_stack.last().unwrap();
920                         let did = *last;
921                         let path = match self.paths.get(&did) {
922                             Some(&(_, ItemType::Trait)) =>
923                                 Some(&self.stack[..self.stack.len() - 1]),
924                             // The current stack not necessarily has correlation
925                             // for where the type was defined. On the other
926                             // hand, `paths` always has the right
927                             // information if present.
928                             Some(&(ref fqp, ItemType::Struct)) |
929                             Some(&(ref fqp, ItemType::Enum)) =>
930                                 Some(&fqp[..fqp.len() - 1]),
931                             Some(..) => Some(&*self.stack),
932                             None => None
933                         };
934                         ((Some(*last), path), true)
935                     }
936                 }
937                 clean::TypedefItem(_, true) => {
938                     // skip associated types in impls
939                     ((None, None), false)
940                 }
941                 _ => ((None, Some(&*self.stack)), false)
942             };
943             let hidden_field = match item.inner {
944                 clean::StructFieldItem(clean::HiddenStructField) => true,
945                 _ => false
946             };
947
948             match parent {
949                 (parent, Some(path)) if is_method || (!self.privmod && !hidden_field) => {
950                     // Needed to determine `self` type.
951                     let parent_basename = self.parent_stack.first().and_then(|parent| {
952                         match self.paths.get(parent) {
953                             Some(&(ref fqp, _)) => Some(fqp[fqp.len() - 1].clone()),
954                             _ => None
955                         }
956                     });
957
958                     self.search_index.push(IndexItem {
959                         ty: shortty(&item),
960                         name: s.to_string(),
961                         path: path.join("::").to_string(),
962                         desc: shorter(item.doc_value()),
963                         parent: parent,
964                         search_type: get_index_search_type(&item, parent_basename),
965                     });
966                 }
967                 (Some(parent), None) if is_method || (!self.privmod && !hidden_field)=> {
968                     if parent.is_local() {
969                         // We have a parent, but we don't know where they're
970                         // defined yet. Wait for later to index this item.
971                         self.orphan_methods.push((parent.node, item.clone()))
972                     }
973                 }
974                 _ => {}
975             }
976         }
977
978         // Keep track of the fully qualified path for this item.
979         let pushed = if item.name.is_some() {
980             let n = item.name.as_ref().unwrap();
981             if !n.is_empty() {
982                 self.stack.push(n.to_string());
983                 true
984             } else { false }
985         } else { false };
986         match item.inner {
987             clean::StructItem(..) | clean::EnumItem(..) |
988             clean::TypedefItem(..) | clean::TraitItem(..) |
989             clean::FunctionItem(..) | clean::ModuleItem(..) |
990             clean::ForeignFunctionItem(..) if !self.privmod => {
991                 // Reexported items mean that the same id can show up twice
992                 // in the rustdoc ast that we're looking at. We know,
993                 // however, that a reexported item doesn't show up in the
994                 // `public_items` map, so we can skip inserting into the
995                 // paths map if there was already an entry present and we're
996                 // not a public item.
997                 let id = item.def_id.node;
998                 if !self.paths.contains_key(&item.def_id) ||
999                    !item.def_id.is_local() ||
1000                    self.public_items.contains(&id) {
1001                     self.paths.insert(item.def_id,
1002                                       (self.stack.clone(), shortty(&item)));
1003                 }
1004             }
1005             // link variants to their parent enum because pages aren't emitted
1006             // for each variant
1007             clean::VariantItem(..) if !self.privmod => {
1008                 let mut stack = self.stack.clone();
1009                 stack.pop();
1010                 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1011             }
1012
1013             clean::PrimitiveItem(..) if item.visibility.is_some() => {
1014                 self.paths.insert(item.def_id, (self.stack.clone(),
1015                                                 shortty(&item)));
1016             }
1017
1018             _ => {}
1019         }
1020
1021         // Maintain the parent stack
1022         let parent_pushed = match item.inner {
1023             clean::TraitItem(..) | clean::EnumItem(..) | clean::StructItem(..) => {
1024                 self.parent_stack.push(item.def_id);
1025                 true
1026             }
1027             clean::ImplItem(ref i) => {
1028                 match i.for_ {
1029                     clean::ResolvedPath{ did, .. } => {
1030                         self.parent_stack.push(did);
1031                         true
1032                     }
1033                     ref t => {
1034                         match t.primitive_type() {
1035                             Some(prim) => {
1036                                 let did = DefId::local(prim.to_node_id());
1037                                 self.parent_stack.push(did);
1038                                 true
1039                             }
1040                             _ => false,
1041                         }
1042                     }
1043                 }
1044             }
1045             _ => false
1046         };
1047
1048         // Once we've recursively found all the generics, then hoard off all the
1049         // implementations elsewhere
1050         let ret = match self.fold_item_recur(item) {
1051             Some(item) => {
1052                 match item {
1053                     clean::Item{ attrs, inner: clean::ImplItem(i), .. } => {
1054                         // extract relevant documentation for this impl
1055                         let dox = match attrs.into_iter().find(|a| {
1056                             match *a {
1057                                 clean::NameValue(ref x, _)
1058                                         if "doc" == *x => {
1059                                     true
1060                                 }
1061                                 _ => false
1062                             }
1063                         }) {
1064                             Some(clean::NameValue(_, dox)) => Some(dox),
1065                             Some(..) | None => None,
1066                         };
1067
1068                         // Figure out the id of this impl. This may map to a
1069                         // primitive rather than always to a struct/enum.
1070                         let did = match i.for_ {
1071                             clean::ResolvedPath { did, .. } |
1072                             clean::BorrowedRef {
1073                                 type_: box clean::ResolvedPath { did, .. }, ..
1074                             } => {
1075                                 Some(did)
1076                             }
1077
1078                             ref t => {
1079                                 t.primitive_type().and_then(|t| {
1080                                     self.primitive_locations.get(&t).map(|n| {
1081                                         let id = t.to_node_id();
1082                                         DefId { krate: *n, node: id }
1083                                     })
1084                                 })
1085                             }
1086                         };
1087
1088                         if let Some(did) = did {
1089                             self.impls.entry(did).or_insert(vec![]).push(Impl {
1090                                 impl_: i,
1091                                 dox: dox,
1092                                 stability: item.stability.clone(),
1093                             });
1094                         }
1095
1096                         None
1097                     }
1098
1099                     i => Some(i),
1100                 }
1101             }
1102             i => i,
1103         };
1104
1105         if pushed { self.stack.pop().unwrap(); }
1106         if parent_pushed { self.parent_stack.pop().unwrap(); }
1107         self.privmod = orig_privmod;
1108         return ret;
1109     }
1110 }
1111
1112 impl<'a> Cache {
1113     fn generics(&mut self, generics: &clean::Generics) {
1114         for typ in &generics.type_params {
1115             self.typarams.insert(typ.did, typ.name.clone());
1116         }
1117     }
1118 }
1119
1120 impl Context {
1121     /// Recurse in the directory structure and change the "root path" to make
1122     /// sure it always points to the top (relatively)
1123     fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1124         F: FnOnce(&mut Context) -> T,
1125     {
1126         if s.is_empty() {
1127             panic!("Unexpected empty destination: {:?}", self.current);
1128         }
1129         let prev = self.dst.clone();
1130         self.dst.push(&s);
1131         self.root_path.push_str("../");
1132         self.current.push(s);
1133
1134         info!("Recursing into {}", self.dst.display());
1135
1136         mkdir(&self.dst).unwrap();
1137         let ret = f(self);
1138
1139         info!("Recursed; leaving {}", self.dst.display());
1140
1141         // Go back to where we were at
1142         self.dst = prev;
1143         let len = self.root_path.len();
1144         self.root_path.truncate(len - 3);
1145         self.current.pop().unwrap();
1146
1147         return ret;
1148     }
1149
1150     /// Main method for rendering a crate.
1151     ///
1152     /// This currently isn't parallelized, but it'd be pretty easy to add
1153     /// parallelization to this function.
1154     fn krate(self, mut krate: clean::Crate) -> io::Result<()> {
1155         let mut item = match krate.module.take() {
1156             Some(i) => i,
1157             None => return Ok(())
1158         };
1159         item.name = Some(krate.name);
1160
1161         // render the crate documentation
1162         let mut work = vec!((self, item));
1163         loop {
1164             match work.pop() {
1165                 Some((mut cx, item)) => try!(cx.item(item, |cx, item| {
1166                     work.push((cx.clone(), item));
1167                 })),
1168                 None => break,
1169             }
1170         }
1171
1172         Ok(())
1173     }
1174
1175     /// Non-parallelized version of rendering an item. This will take the input
1176     /// item, render its contents, and then invoke the specified closure with
1177     /// all sub-items which need to be rendered.
1178     ///
1179     /// The rendering driver uses this closure to queue up more work.
1180     fn item<F>(&mut self, item: clean::Item, mut f: F) -> io::Result<()> where
1181         F: FnMut(&mut Context, clean::Item),
1182     {
1183         fn render(w: File, cx: &Context, it: &clean::Item,
1184                   pushname: bool) -> io::Result<()> {
1185             // A little unfortunate that this is done like this, but it sure
1186             // does make formatting *a lot* nicer.
1187             CURRENT_LOCATION_KEY.with(|slot| {
1188                 *slot.borrow_mut() = cx.current.clone();
1189             });
1190
1191             let mut title = cx.current.join("::");
1192             if pushname {
1193                 if !title.is_empty() {
1194                     title.push_str("::");
1195                 }
1196                 title.push_str(it.name.as_ref().unwrap());
1197             }
1198             title.push_str(" - Rust");
1199             let tyname = shortty(it).to_static_str();
1200             let is_crate = match it.inner {
1201                 clean::ModuleItem(clean::Module { items: _, is_crate: true }) => true,
1202                 _ => false
1203             };
1204             let desc = if is_crate {
1205                 format!("API documentation for the Rust `{}` crate.",
1206                         cx.layout.krate)
1207             } else {
1208                 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1209                         it.name.as_ref().unwrap(), tyname, cx.layout.krate)
1210             };
1211             let keywords = make_item_keywords(it);
1212             let page = layout::Page {
1213                 ty: tyname,
1214                 root_path: &cx.root_path,
1215                 title: &title,
1216                 description: &desc,
1217                 keywords: &keywords,
1218             };
1219
1220             markdown::reset_headers();
1221
1222             // We have a huge number of calls to write, so try to alleviate some
1223             // of the pain by using a buffered writer instead of invoking the
1224             // write syscall all the time.
1225             let mut writer = BufWriter::new(w);
1226             if !cx.render_redirect_pages {
1227                 try!(layout::render(&mut writer, &cx.layout, &page,
1228                                     &Sidebar{ cx: cx, item: it },
1229                                     &Item{ cx: cx, item: it }));
1230             } else {
1231                 let mut url = repeat("../").take(cx.current.len())
1232                                            .collect::<String>();
1233                 match cache().paths.get(&it.def_id) {
1234                     Some(&(ref names, _)) => {
1235                         for name in &names[..names.len() - 1] {
1236                             url.push_str(name);
1237                             url.push_str("/");
1238                         }
1239                         url.push_str(&item_path(it));
1240                         try!(layout::redirect(&mut writer, &url));
1241                     }
1242                     None => {}
1243                 }
1244             }
1245             writer.flush()
1246         }
1247
1248         // Private modules may survive the strip-private pass if they
1249         // contain impls for public types. These modules can also
1250         // contain items such as publicly reexported structures.
1251         //
1252         // External crates will provide links to these structures, so
1253         // these modules are recursed into, but not rendered normally (a
1254         // flag on the context).
1255         if !self.render_redirect_pages {
1256             self.render_redirect_pages = self.ignore_private_item(&item);
1257         }
1258
1259         match item.inner {
1260             // modules are special because they add a namespace. We also need to
1261             // recurse into the items of the module as well.
1262             clean::ModuleItem(..) => {
1263                 let name = item.name.as_ref().unwrap().to_string();
1264                 let mut item = Some(item);
1265                 self.recurse(name, |this| {
1266                     let item = item.take().unwrap();
1267                     let dst = this.dst.join("index.html");
1268                     let dst = try!(File::create(&dst));
1269                     try!(render(dst, this, &item, false));
1270
1271                     let m = match item.inner {
1272                         clean::ModuleItem(m) => m,
1273                         _ => unreachable!()
1274                     };
1275
1276                     // render sidebar-items.js used throughout this module
1277                     {
1278                         let items = this.build_sidebar_items(&m);
1279                         let js_dst = this.dst.join("sidebar-items.js");
1280                         let mut js_out = BufWriter::new(try!(File::create(&js_dst)));
1281                         try!(write!(&mut js_out, "initSidebarItems({});",
1282                                     json::as_json(&items)));
1283                     }
1284
1285                     for item in m.items {
1286                         f(this,item);
1287                     }
1288                     Ok(())
1289                 })
1290             }
1291
1292             // Things which don't have names (like impls) don't get special
1293             // pages dedicated to them.
1294             _ if item.name.is_some() => {
1295                 let dst = self.dst.join(&item_path(&item));
1296                 let dst = try!(File::create(&dst));
1297                 render(dst, self, &item, true)
1298             }
1299
1300             _ => Ok(())
1301         }
1302     }
1303
1304     fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1305         // BTreeMap instead of HashMap to get a sorted output
1306         let mut map = BTreeMap::new();
1307         for item in &m.items {
1308             if self.ignore_private_item(item) { continue }
1309
1310             let short = shortty(item).to_static_str();
1311             let myname = match item.name {
1312                 None => continue,
1313                 Some(ref s) => s.to_string(),
1314             };
1315             let short = short.to_string();
1316             map.entry(short).or_insert(vec![])
1317                 .push((myname, Some(plain_summary_line(item.doc_value()))));
1318         }
1319
1320         for (_, items) in &mut map {
1321             items.sort();
1322         }
1323         return map;
1324     }
1325
1326     fn ignore_private_item(&self, it: &clean::Item) -> bool {
1327         match it.inner {
1328             clean::ModuleItem(ref m) => {
1329                 (m.items.is_empty() &&
1330                  it.doc_value().is_none() &&
1331                  it.visibility != Some(hir::Public)) ||
1332                 (self.passes.contains("strip-private") && it.visibility != Some(hir::Public))
1333             }
1334             clean::PrimitiveItem(..) => it.visibility != Some(hir::Public),
1335             _ => false,
1336         }
1337     }
1338 }
1339
1340 impl<'a> Item<'a> {
1341     fn ismodule(&self) -> bool {
1342         match self.item.inner {
1343             clean::ModuleItem(..) => true, _ => false
1344         }
1345     }
1346
1347     /// Generate a url appropriate for an `href` attribute back to the source of
1348     /// this item.
1349     ///
1350     /// The url generated, when clicked, will redirect the browser back to the
1351     /// original source code.
1352     ///
1353     /// If `None` is returned, then a source link couldn't be generated. This
1354     /// may happen, for example, with externally inlined items where the source
1355     /// of their crate documentation isn't known.
1356     fn href(&self, cx: &Context) -> Option<String> {
1357         let href = if self.item.source.loline == self.item.source.hiline {
1358             format!("{}", self.item.source.loline)
1359         } else {
1360             format!("{}-{}", self.item.source.loline, self.item.source.hiline)
1361         };
1362
1363         // First check to see if this is an imported macro source. In this case
1364         // we need to handle it specially as cross-crate inlined macros have...
1365         // odd locations!
1366         let imported_macro_from = match self.item.inner {
1367             clean::MacroItem(ref m) => m.imported_from.as_ref(),
1368             _ => None,
1369         };
1370         if let Some(krate) = imported_macro_from {
1371             let cache = cache();
1372             let root = cache.extern_locations.values().find(|&&(ref n, _)| {
1373                 *krate == *n
1374             }).map(|l| &l.1);
1375             let root = match root {
1376                 Some(&Remote(ref s)) => s.to_string(),
1377                 Some(&Local) => self.cx.root_path.clone(),
1378                 None | Some(&Unknown) => return None,
1379             };
1380             Some(format!("{root}/{krate}/macro.{name}.html?gotomacrosrc=1",
1381                          root = root,
1382                          krate = krate,
1383                          name = self.item.name.as_ref().unwrap()))
1384
1385         // If this item is part of the local crate, then we're guaranteed to
1386         // know the span, so we plow forward and generate a proper url. The url
1387         // has anchors for the line numbers that we're linking to.
1388         } else if self.item.def_id.is_local() {
1389             let mut path = Vec::new();
1390             clean_srcpath(&cx.src_root, Path::new(&self.item.source.filename),
1391                           true, |component| {
1392                 path.push(component.to_string());
1393             });
1394             Some(format!("{root}src/{krate}/{path}.html#{href}",
1395                          root = self.cx.root_path,
1396                          krate = self.cx.layout.krate,
1397                          path = path.join("/"),
1398                          href = href))
1399
1400         // If this item is not part of the local crate, then things get a little
1401         // trickier. We don't actually know the span of the external item, but
1402         // we know that the documentation on the other end knows the span!
1403         //
1404         // In this case, we generate a link to the *documentation* for this type
1405         // in the original crate. There's an extra URL parameter which says that
1406         // we want to go somewhere else, and the JS on the destination page will
1407         // pick it up and instantly redirect the browser to the source code.
1408         //
1409         // If we don't know where the external documentation for this crate is
1410         // located, then we return `None`.
1411         } else {
1412             let cache = cache();
1413             let path = &cache.external_paths[&self.item.def_id];
1414             let root = match cache.extern_locations[&self.item.def_id.krate] {
1415                 (_, Remote(ref s)) => s.to_string(),
1416                 (_, Local) => self.cx.root_path.clone(),
1417                 (_, Unknown) => return None,
1418             };
1419             Some(format!("{root}{path}/{file}?gotosrc={goto}",
1420                          root = root,
1421                          path = path[..path.len() - 1].join("/"),
1422                          file = item_path(self.item),
1423                          goto = self.item.def_id.node))
1424         }
1425     }
1426 }
1427
1428
1429 impl<'a> fmt::Display for Item<'a> {
1430     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1431         // Write the breadcrumb trail header for the top
1432         try!(write!(fmt, "\n<h1 class='fqn'><span class='in-band'>"));
1433         match self.item.inner {
1434             clean::ModuleItem(ref m) => if m.is_crate {
1435                     try!(write!(fmt, "Crate "));
1436                 } else {
1437                     try!(write!(fmt, "Module "));
1438                 },
1439             clean::FunctionItem(..) => try!(write!(fmt, "Function ")),
1440             clean::TraitItem(..) => try!(write!(fmt, "Trait ")),
1441             clean::StructItem(..) => try!(write!(fmt, "Struct ")),
1442             clean::EnumItem(..) => try!(write!(fmt, "Enum ")),
1443             clean::PrimitiveItem(..) => try!(write!(fmt, "Primitive Type ")),
1444             _ => {}
1445         }
1446         let is_primitive = match self.item.inner {
1447             clean::PrimitiveItem(..) => true,
1448             _ => false,
1449         };
1450         if !is_primitive {
1451             let cur = &self.cx.current;
1452             let amt = if self.ismodule() { cur.len() - 1 } else { cur.len() };
1453             for (i, component) in cur.iter().enumerate().take(amt) {
1454                 try!(write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
1455                             repeat("../").take(cur.len() - i - 1)
1456                                          .collect::<String>(),
1457                             component));
1458             }
1459         }
1460         try!(write!(fmt, "<a class='{}' href=''>{}</a>",
1461                     shortty(self.item), self.item.name.as_ref().unwrap()));
1462
1463         try!(write!(fmt, "</span>")); // in-band
1464         try!(write!(fmt, "<span class='out-of-band'>"));
1465         try!(write!(fmt,
1466         r##"<span id='render-detail'>
1467             <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
1468                 [<span class='inner'>&#x2212;</span>]
1469             </a>
1470         </span>"##));
1471
1472         // Write `src` tag
1473         //
1474         // When this item is part of a `pub use` in a downstream crate, the
1475         // [src] link in the downstream documentation will actually come back to
1476         // this page, and this link will be auto-clicked. The `id` attribute is
1477         // used to find the link to auto-click.
1478         if self.cx.include_sources && !is_primitive {
1479             match self.href(self.cx) {
1480                 Some(l) => {
1481                     try!(write!(fmt, "<a id='src-{}' class='srclink' \
1482                                        href='{}' title='{}'>[src]</a>",
1483                                 self.item.def_id.node, l, "goto source code"));
1484                 }
1485                 None => {}
1486             }
1487         }
1488
1489         try!(write!(fmt, "</span>")); // out-of-band
1490
1491         try!(write!(fmt, "</h1>\n"));
1492
1493         match self.item.inner {
1494             clean::ModuleItem(ref m) => {
1495                 item_module(fmt, self.cx, self.item, &m.items)
1496             }
1497             clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1498                 item_function(fmt, self.cx, self.item, f),
1499             clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1500             clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
1501             clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
1502             clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
1503             clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
1504             clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
1505             clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1506                 item_static(fmt, self.cx, self.item, i),
1507             clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
1508             _ => Ok(())
1509         }
1510     }
1511 }
1512
1513 fn item_path(item: &clean::Item) -> String {
1514     match item.inner {
1515         clean::ModuleItem(..) => {
1516             format!("{}/index.html", item.name.as_ref().unwrap())
1517         }
1518         _ => {
1519             format!("{}.{}.html",
1520                     shortty(item).to_static_str(),
1521                     *item.name.as_ref().unwrap())
1522         }
1523     }
1524 }
1525
1526 fn full_path(cx: &Context, item: &clean::Item) -> String {
1527     let mut s = cx.current.join("::");
1528     s.push_str("::");
1529     s.push_str(item.name.as_ref().unwrap());
1530     return s
1531 }
1532
1533 fn shorter<'a>(s: Option<&'a str>) -> String {
1534     match s {
1535         Some(s) => s.lines().take_while(|line|{
1536             (*line).chars().any(|chr|{
1537                 !chr.is_whitespace()
1538             })
1539         }).collect::<Vec<_>>().join("\n"),
1540         None => "".to_string()
1541     }
1542 }
1543
1544 #[inline]
1545 fn plain_summary_line(s: Option<&str>) -> String {
1546     let line = shorter(s).replace("\n", " ");
1547     markdown::plain_summary_line(&line[..])
1548 }
1549
1550 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1551     if let Some(s) = short_stability(item, cx, true) {
1552         try!(write!(w, "<div class='stability'>{}</div>", s));
1553     }
1554     if let Some(s) = item.doc_value() {
1555         try!(write!(w, "<div class='docblock'>{}</div>", Markdown(s)));
1556     }
1557     Ok(())
1558 }
1559
1560 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1561                item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1562     try!(document(w, cx, item));
1563
1564     let mut indices = (0..items.len()).filter(|i| {
1565         !cx.ignore_private_item(&items[*i])
1566     }).collect::<Vec<usize>>();
1567
1568     // the order of item types in the listing
1569     fn reorder(ty: ItemType) -> u8 {
1570         match ty {
1571             ItemType::ExternCrate     => 0,
1572             ItemType::Import          => 1,
1573             ItemType::Primitive       => 2,
1574             ItemType::Module          => 3,
1575             ItemType::Macro           => 4,
1576             ItemType::Struct          => 5,
1577             ItemType::Enum            => 6,
1578             ItemType::Constant        => 7,
1579             ItemType::Static          => 8,
1580             ItemType::Trait           => 9,
1581             ItemType::Function        => 10,
1582             ItemType::Typedef         => 12,
1583             _                         => 13 + ty as u8,
1584         }
1585     }
1586
1587     fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1588         let ty1 = shortty(i1);
1589         let ty2 = shortty(i2);
1590         if ty1 != ty2 {
1591             return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1592         }
1593         let s1 = i1.stability.as_ref().map(|s| s.level);
1594         let s2 = i2.stability.as_ref().map(|s| s.level);
1595         match (s1, s2) {
1596             (Some(attr::Unstable), Some(attr::Stable)) => return Ordering::Greater,
1597             (Some(attr::Stable), Some(attr::Unstable)) => return Ordering::Less,
1598             _ => {}
1599         }
1600         i1.name.cmp(&i2.name)
1601     }
1602
1603     indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1604
1605     debug!("{:?}", indices);
1606     let mut curty = None;
1607     for &idx in &indices {
1608         let myitem = &items[idx];
1609
1610         let myty = Some(shortty(myitem));
1611         if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
1612             // Put `extern crate` and `use` re-exports in the same section.
1613             curty = myty;
1614         } else if myty != curty {
1615             if curty.is_some() {
1616                 try!(write!(w, "</table>"));
1617             }
1618             curty = myty;
1619             let (short, name) = match myty.unwrap() {
1620                 ItemType::ExternCrate |
1621                 ItemType::Import          => ("reexports", "Reexports"),
1622                 ItemType::Module          => ("modules", "Modules"),
1623                 ItemType::Struct          => ("structs", "Structs"),
1624                 ItemType::Enum            => ("enums", "Enums"),
1625                 ItemType::Function        => ("functions", "Functions"),
1626                 ItemType::Typedef         => ("types", "Type Definitions"),
1627                 ItemType::Static          => ("statics", "Statics"),
1628                 ItemType::Constant        => ("constants", "Constants"),
1629                 ItemType::Trait           => ("traits", "Traits"),
1630                 ItemType::Impl            => ("impls", "Implementations"),
1631                 ItemType::TyMethod        => ("tymethods", "Type Methods"),
1632                 ItemType::Method          => ("methods", "Methods"),
1633                 ItemType::StructField     => ("fields", "Struct Fields"),
1634                 ItemType::Variant         => ("variants", "Variants"),
1635                 ItemType::Macro           => ("macros", "Macros"),
1636                 ItemType::Primitive       => ("primitives", "Primitive Types"),
1637                 ItemType::AssociatedType  => ("associated-types", "Associated Types"),
1638                 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
1639             };
1640             try!(write!(w,
1641                         "<h2 id='{id}' class='section-header'>\
1642                         <a href=\"#{id}\">{name}</a></h2>\n<table>",
1643                         id = short, name = name));
1644         }
1645
1646         match myitem.inner {
1647             clean::ExternCrateItem(ref name, ref src) => {
1648                 match *src {
1649                     Some(ref src) => {
1650                         try!(write!(w, "<tr><td><code>{}extern crate {} as {};",
1651                                     VisSpace(myitem.visibility),
1652                                     src,
1653                                     name))
1654                     }
1655                     None => {
1656                         try!(write!(w, "<tr><td><code>{}extern crate {};",
1657                                     VisSpace(myitem.visibility), name))
1658                     }
1659                 }
1660                 try!(write!(w, "</code></td></tr>"));
1661             }
1662
1663             clean::ImportItem(ref import) => {
1664                 try!(write!(w, "<tr><td><code>{}{}</code></td></tr>",
1665                             VisSpace(myitem.visibility), *import));
1666             }
1667
1668             _ => {
1669                 if myitem.name.is_none() { continue }
1670                 let stab_docs = if let Some(s) = short_stability(myitem, cx, false) {
1671                     format!("[{}]", s)
1672                 } else {
1673                     String::new()
1674                 };
1675                 try!(write!(w, "
1676                     <tr class='{stab} module-item'>
1677                         <td><a class='{class}' href='{href}'
1678                                title='{title}'>{name}</a></td>
1679                         <td class='docblock short'>
1680                             {stab_docs} {docs}
1681                         </td>
1682                     </tr>
1683                 ",
1684                 name = *myitem.name.as_ref().unwrap(),
1685                 stab_docs = stab_docs,
1686                 docs = Markdown(&shorter(myitem.doc_value())),
1687                 class = shortty(myitem),
1688                 stab = myitem.stability_class(),
1689                 href = item_path(myitem),
1690                 title = full_path(cx, myitem)));
1691             }
1692         }
1693     }
1694
1695     write!(w, "</table>")
1696 }
1697
1698 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Option<String> {
1699     item.stability.as_ref().and_then(|stab| {
1700         let reason = if show_reason && !stab.reason.is_empty() {
1701             format!(": {}", stab.reason)
1702         } else {
1703             String::new()
1704         };
1705         let text = if !stab.deprecated_since.is_empty() {
1706             let since = if show_reason {
1707                 format!(" since {}", Escape(&stab.deprecated_since))
1708             } else {
1709                 String::new()
1710             };
1711             format!("Deprecated{}{}", since, Markdown(&reason))
1712         } else if stab.level == attr::Unstable {
1713             let unstable_extra = if show_reason {
1714                 match (!stab.feature.is_empty(), &cx.issue_tracker_base_url, stab.issue) {
1715                     (true, &Some(ref tracker_url), Some(issue_no)) =>
1716                         format!(" (<code>{}</code> <a href=\"{}{}\">#{}</a>)",
1717                                 Escape(&stab.feature), tracker_url, issue_no, issue_no),
1718                     (false, &Some(ref tracker_url), Some(issue_no)) =>
1719                         format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
1720                                 issue_no),
1721                     (true, _, _) =>
1722                         format!(" (<code>{}</code>)", Escape(&stab.feature)),
1723                     _ => String::new(),
1724                 }
1725             } else {
1726                 String::new()
1727             };
1728             format!("Unstable{}{}", unstable_extra, Markdown(&reason))
1729         } else {
1730             return None
1731         };
1732         Some(format!("<em class='stab {}'>{}</em>",
1733                      item.stability_class(), text))
1734     })
1735 }
1736
1737 struct Initializer<'a>(&'a str);
1738
1739 impl<'a> fmt::Display for Initializer<'a> {
1740     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1741         let Initializer(s) = *self;
1742         if s.is_empty() { return Ok(()); }
1743         try!(write!(f, "<code> = </code>"));
1744         write!(f, "<code>{}</code>", s)
1745     }
1746 }
1747
1748 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1749                  c: &clean::Constant) -> fmt::Result {
1750     try!(write!(w, "<pre class='rust const'>{vis}const \
1751                     {name}: {typ}{init}</pre>",
1752            vis = VisSpace(it.visibility),
1753            name = it.name.as_ref().unwrap(),
1754            typ = c.type_,
1755            init = Initializer(&c.expr)));
1756     document(w, cx, it)
1757 }
1758
1759 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1760                s: &clean::Static) -> fmt::Result {
1761     try!(write!(w, "<pre class='rust static'>{vis}static {mutability}\
1762                     {name}: {typ}{init}</pre>",
1763            vis = VisSpace(it.visibility),
1764            mutability = MutableSpace(s.mutability),
1765            name = it.name.as_ref().unwrap(),
1766            typ = s.type_,
1767            init = Initializer(&s.expr)));
1768     document(w, cx, it)
1769 }
1770
1771 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1772                  f: &clean::Function) -> fmt::Result {
1773     try!(write!(w, "<pre class='rust fn'>{vis}{unsafety}{abi}{constness}fn \
1774                     {name}{generics}{decl}{where_clause}</pre>",
1775            vis = VisSpace(it.visibility),
1776            unsafety = UnsafetySpace(f.unsafety),
1777            abi = AbiSpace(f.abi),
1778            constness = ConstnessSpace(f.constness),
1779            name = it.name.as_ref().unwrap(),
1780            generics = f.generics,
1781            where_clause = WhereClause(&f.generics),
1782            decl = f.decl));
1783     document(w, cx, it)
1784 }
1785
1786 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
1787               t: &clean::Trait) -> fmt::Result {
1788     let mut bounds = String::new();
1789     if !t.bounds.is_empty() {
1790         if !bounds.is_empty() {
1791             bounds.push(' ');
1792         }
1793         bounds.push_str(": ");
1794         for (i, p) in t.bounds.iter().enumerate() {
1795             if i > 0 { bounds.push_str(" + "); }
1796             bounds.push_str(&format!("{}", *p));
1797         }
1798     }
1799
1800     // Output the trait definition
1801     try!(write!(w, "<pre class='rust trait'>{}{}trait {}{}{}{} ",
1802                   VisSpace(it.visibility),
1803                   UnsafetySpace(t.unsafety),
1804                   it.name.as_ref().unwrap(),
1805                   t.generics,
1806                   bounds,
1807                   WhereClause(&t.generics)));
1808
1809     let types = t.items.iter().filter(|m| {
1810         match m.inner { clean::AssociatedTypeItem(..) => true, _ => false }
1811     }).collect::<Vec<_>>();
1812     let consts = t.items.iter().filter(|m| {
1813         match m.inner { clean::AssociatedConstItem(..) => true, _ => false }
1814     }).collect::<Vec<_>>();
1815     let required = t.items.iter().filter(|m| {
1816         match m.inner { clean::TyMethodItem(_) => true, _ => false }
1817     }).collect::<Vec<_>>();
1818     let provided = t.items.iter().filter(|m| {
1819         match m.inner { clean::MethodItem(_) => true, _ => false }
1820     }).collect::<Vec<_>>();
1821
1822     if t.items.is_empty() {
1823         try!(write!(w, "{{ }}"));
1824     } else {
1825         try!(write!(w, "{{\n"));
1826         for t in &types {
1827             try!(write!(w, "    "));
1828             try!(render_assoc_item(w, t, AssocItemLink::Anchor));
1829             try!(write!(w, ";\n"));
1830         }
1831         if !types.is_empty() && !consts.is_empty() {
1832             try!(w.write_str("\n"));
1833         }
1834         for t in &consts {
1835             try!(write!(w, "    "));
1836             try!(render_assoc_item(w, t, AssocItemLink::Anchor));
1837             try!(write!(w, ";\n"));
1838         }
1839         if !consts.is_empty() && !required.is_empty() {
1840             try!(w.write_str("\n"));
1841         }
1842         for m in &required {
1843             try!(write!(w, "    "));
1844             try!(render_assoc_item(w, m, AssocItemLink::Anchor));
1845             try!(write!(w, ";\n"));
1846         }
1847         if !required.is_empty() && !provided.is_empty() {
1848             try!(w.write_str("\n"));
1849         }
1850         for m in &provided {
1851             try!(write!(w, "    "));
1852             try!(render_assoc_item(w, m, AssocItemLink::Anchor));
1853             try!(write!(w, " {{ ... }}\n"));
1854         }
1855         try!(write!(w, "}}"));
1856     }
1857     try!(write!(w, "</pre>"));
1858
1859     // Trait documentation
1860     try!(document(w, cx, it));
1861
1862     fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item)
1863                   -> fmt::Result {
1864         try!(write!(w, "<h3 id='{ty}.{name}' class='method stab {stab}'><code>",
1865                     ty = shortty(m),
1866                     name = *m.name.as_ref().unwrap(),
1867                     stab = m.stability_class()));
1868         try!(render_assoc_item(w, m, AssocItemLink::Anchor));
1869         try!(write!(w, "</code></h3>"));
1870         try!(document(w, cx, m));
1871         Ok(())
1872     }
1873
1874     if !types.is_empty() {
1875         try!(write!(w, "
1876             <h2 id='associated-types'>Associated Types</h2>
1877             <div class='methods'>
1878         "));
1879         for t in &types {
1880             try!(trait_item(w, cx, *t));
1881         }
1882         try!(write!(w, "</div>"));
1883     }
1884
1885     if !consts.is_empty() {
1886         try!(write!(w, "
1887             <h2 id='associated-const'>Associated Constants</h2>
1888             <div class='methods'>
1889         "));
1890         for t in &consts {
1891             try!(trait_item(w, cx, *t));
1892         }
1893         try!(write!(w, "</div>"));
1894     }
1895
1896     // Output the documentation for each function individually
1897     if !required.is_empty() {
1898         try!(write!(w, "
1899             <h2 id='required-methods'>Required Methods</h2>
1900             <div class='methods'>
1901         "));
1902         for m in &required {
1903             try!(trait_item(w, cx, *m));
1904         }
1905         try!(write!(w, "</div>"));
1906     }
1907     if !provided.is_empty() {
1908         try!(write!(w, "
1909             <h2 id='provided-methods'>Provided Methods</h2>
1910             <div class='methods'>
1911         "));
1912         for m in &provided {
1913             try!(trait_item(w, cx, *m));
1914         }
1915         try!(write!(w, "</div>"));
1916     }
1917
1918     // If there are methods directly on this trait object, render them here.
1919     try!(render_assoc_items(w, cx, it.def_id, AssocItemRender::All));
1920
1921     let cache = cache();
1922     try!(write!(w, "
1923         <h2 id='implementors'>Implementors</h2>
1924         <ul class='item-list' id='implementors-list'>
1925     "));
1926     match cache.implementors.get(&it.def_id) {
1927         Some(implementors) => {
1928             for i in implementors {
1929                 try!(writeln!(w, "<li><code>{}</code></li>", i.impl_));
1930             }
1931         }
1932         None => {}
1933     }
1934     try!(write!(w, "</ul>"));
1935     try!(write!(w, r#"<script type="text/javascript" async
1936                               src="{root_path}/implementors/{path}/{ty}.{name}.js">
1937                       </script>"#,
1938                 root_path = vec![".."; cx.current.len()].join("/"),
1939                 path = if it.def_id.is_local() {
1940                     cx.current.join("/")
1941                 } else {
1942                     let path = &cache.external_paths[&it.def_id];
1943                     path[..path.len() - 1].join("/")
1944                 },
1945                 ty = shortty(it).to_static_str(),
1946                 name = *it.name.as_ref().unwrap()));
1947     Ok(())
1948 }
1949
1950 fn assoc_const(w: &mut fmt::Formatter, it: &clean::Item,
1951                ty: &clean::Type, default: Option<&String>)
1952                -> fmt::Result {
1953     try!(write!(w, "const {}", it.name.as_ref().unwrap()));
1954     try!(write!(w, ": {}", ty));
1955     if let Some(default) = default {
1956         try!(write!(w, " = {}", default));
1957     }
1958     Ok(())
1959 }
1960
1961 fn assoc_type(w: &mut fmt::Formatter, it: &clean::Item,
1962               bounds: &Vec<clean::TyParamBound>,
1963               default: &Option<clean::Type>)
1964               -> fmt::Result {
1965     try!(write!(w, "type {}", it.name.as_ref().unwrap()));
1966     if !bounds.is_empty() {
1967         try!(write!(w, ": {}", TyParamBounds(bounds)))
1968     }
1969     if let Some(ref default) = *default {
1970         try!(write!(w, " = {}", default));
1971     }
1972     Ok(())
1973 }
1974
1975 fn render_assoc_item(w: &mut fmt::Formatter, meth: &clean::Item,
1976                      link: AssocItemLink) -> fmt::Result {
1977     fn method(w: &mut fmt::Formatter,
1978               it: &clean::Item,
1979               unsafety: hir::Unsafety,
1980               constness: hir::Constness,
1981               abi: abi::Abi,
1982               g: &clean::Generics,
1983               selfty: &clean::SelfTy,
1984               d: &clean::FnDecl,
1985               link: AssocItemLink)
1986               -> fmt::Result {
1987         use syntax::abi::Abi;
1988
1989         let name = it.name.as_ref().unwrap();
1990         let anchor = format!("#{}.{}", shortty(it), name);
1991         let href = match link {
1992             AssocItemLink::Anchor => anchor,
1993             AssocItemLink::GotoSource(did) => {
1994                 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
1995             }
1996         };
1997         write!(w, "{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
1998                    {generics}{decl}{where_clause}",
1999                UnsafetySpace(unsafety),
2000                ConstnessSpace(constness),
2001                match abi {
2002                    Abi::Rust => String::new(),
2003                    a => format!("extern {} ", a.to_string())
2004                },
2005                href = href,
2006                name = name,
2007                generics = *g,
2008                decl = Method(selfty, d),
2009                where_clause = WhereClause(g))
2010     }
2011     match meth.inner {
2012         clean::TyMethodItem(ref m) => {
2013             method(w, meth, m.unsafety, hir::Constness::NotConst,
2014                    m.abi, &m.generics, &m.self_, &m.decl, link)
2015         }
2016         clean::MethodItem(ref m) => {
2017             method(w, meth, m.unsafety, m.constness,
2018                    m.abi, &m.generics, &m.self_, &m.decl,
2019                    link)
2020         }
2021         clean::AssociatedConstItem(ref ty, ref default) => {
2022             assoc_const(w, meth, ty, default.as_ref())
2023         }
2024         clean::AssociatedTypeItem(ref bounds, ref default) => {
2025             assoc_type(w, meth, bounds, default)
2026         }
2027         _ => panic!("render_assoc_item called on non-associated-item")
2028     }
2029 }
2030
2031 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2032                s: &clean::Struct) -> fmt::Result {
2033     try!(write!(w, "<pre class='rust struct'>"));
2034     try!(render_attributes(w, it));
2035     try!(render_struct(w,
2036                        it,
2037                        Some(&s.generics),
2038                        s.struct_type,
2039                        &s.fields,
2040                        "",
2041                        true));
2042     try!(write!(w, "</pre>"));
2043
2044     try!(document(w, cx, it));
2045     let mut fields = s.fields.iter().filter(|f| {
2046         match f.inner {
2047             clean::StructFieldItem(clean::HiddenStructField) => false,
2048             clean::StructFieldItem(clean::TypedStructField(..)) => true,
2049             _ => false,
2050         }
2051     }).peekable();
2052     if let doctree::Plain = s.struct_type {
2053         if fields.peek().is_some() {
2054             try!(write!(w, "<h2 class='fields'>Fields</h2>\n<table>"));
2055             for field in fields {
2056                 try!(write!(w, "<tr class='stab {stab}'>
2057                                   <td id='structfield.{name}'>\
2058                                     <code>{name}</code></td><td>",
2059                             stab = field.stability_class(),
2060                             name = field.name.as_ref().unwrap()));
2061                 try!(document(w, cx, field));
2062                 try!(write!(w, "</td></tr>"));
2063             }
2064             try!(write!(w, "</table>"));
2065         }
2066     }
2067     render_assoc_items(w, cx, it.def_id, AssocItemRender::All)
2068 }
2069
2070 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2071              e: &clean::Enum) -> fmt::Result {
2072     try!(write!(w, "<pre class='rust enum'>"));
2073     try!(render_attributes(w, it));
2074     try!(write!(w, "{}enum {}{}{}",
2075                   VisSpace(it.visibility),
2076                   it.name.as_ref().unwrap(),
2077                   e.generics,
2078                   WhereClause(&e.generics)));
2079     if e.variants.is_empty() && !e.variants_stripped {
2080         try!(write!(w, " {{}}"));
2081     } else {
2082         try!(write!(w, " {{\n"));
2083         for v in &e.variants {
2084             try!(write!(w, "    "));
2085             let name = v.name.as_ref().unwrap();
2086             match v.inner {
2087                 clean::VariantItem(ref var) => {
2088                     match var.kind {
2089                         clean::CLikeVariant => try!(write!(w, "{}", name)),
2090                         clean::TupleVariant(ref tys) => {
2091                             try!(write!(w, "{}(", name));
2092                             for (i, ty) in tys.iter().enumerate() {
2093                                 if i > 0 {
2094                                     try!(write!(w, ", "))
2095                                 }
2096                                 try!(write!(w, "{}", *ty));
2097                             }
2098                             try!(write!(w, ")"));
2099                         }
2100                         clean::StructVariant(ref s) => {
2101                             try!(render_struct(w,
2102                                                v,
2103                                                None,
2104                                                s.struct_type,
2105                                                &s.fields,
2106                                                "    ",
2107                                                false));
2108                         }
2109                     }
2110                 }
2111                 _ => unreachable!()
2112             }
2113             try!(write!(w, ",\n"));
2114         }
2115
2116         if e.variants_stripped {
2117             try!(write!(w, "    // some variants omitted\n"));
2118         }
2119         try!(write!(w, "}}"));
2120     }
2121     try!(write!(w, "</pre>"));
2122
2123     try!(document(w, cx, it));
2124     if !e.variants.is_empty() {
2125         try!(write!(w, "<h2 class='variants'>Variants</h2>\n<table>"));
2126         for variant in &e.variants {
2127             try!(write!(w, "<tr><td id='variant.{name}'><code>{name}</code></td><td>",
2128                           name = variant.name.as_ref().unwrap()));
2129             try!(document(w, cx, variant));
2130             match variant.inner {
2131                 clean::VariantItem(ref var) => {
2132                     match var.kind {
2133                         clean::StructVariant(ref s) => {
2134                             let fields = s.fields.iter().filter(|f| {
2135                                 match f.inner {
2136                                     clean::StructFieldItem(ref t) => match *t {
2137                                         clean::HiddenStructField => false,
2138                                         clean::TypedStructField(..) => true,
2139                                     },
2140                                     _ => false,
2141                                 }
2142                             });
2143                             try!(write!(w, "<h3 class='fields'>Fields</h3>\n
2144                                               <table>"));
2145                             for field in fields {
2146                                 try!(write!(w, "<tr><td \
2147                                                   id='variant.{v}.field.{f}'>\
2148                                                   <code>{f}</code></td><td>",
2149                                               v = variant.name.as_ref().unwrap(),
2150                                               f = field.name.as_ref().unwrap()));
2151                                 try!(document(w, cx, field));
2152                                 try!(write!(w, "</td></tr>"));
2153                             }
2154                             try!(write!(w, "</table>"));
2155                         }
2156                         _ => ()
2157                     }
2158                 }
2159                 _ => ()
2160             }
2161             try!(write!(w, "</td></tr>"));
2162         }
2163         try!(write!(w, "</table>"));
2164
2165     }
2166     try!(render_assoc_items(w, cx, it.def_id, AssocItemRender::All));
2167     Ok(())
2168 }
2169
2170 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
2171     for attr in &it.attrs {
2172         match *attr {
2173             clean::Word(ref s) if *s == "must_use" => {
2174                 try!(write!(w, "#[{}]\n", s));
2175             }
2176             clean::NameValue(ref k, ref v) if *k == "must_use" => {
2177                 try!(write!(w, "#[{} = \"{}\"]\n", k, v));
2178             }
2179             _ => ()
2180         }
2181     }
2182     Ok(())
2183 }
2184
2185 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
2186                  g: Option<&clean::Generics>,
2187                  ty: doctree::StructType,
2188                  fields: &[clean::Item],
2189                  tab: &str,
2190                  structhead: bool) -> fmt::Result {
2191     try!(write!(w, "{}{}{}",
2192                   VisSpace(it.visibility),
2193                   if structhead {"struct "} else {""},
2194                   it.name.as_ref().unwrap()));
2195     match g {
2196         Some(g) => try!(write!(w, "{}{}", *g, WhereClause(g))),
2197         None => {}
2198     }
2199     match ty {
2200         doctree::Plain => {
2201             try!(write!(w, " {{\n{}", tab));
2202             let mut fields_stripped = false;
2203             for field in fields {
2204                 match field.inner {
2205                     clean::StructFieldItem(clean::HiddenStructField) => {
2206                         fields_stripped = true;
2207                     }
2208                     clean::StructFieldItem(clean::TypedStructField(ref ty)) => {
2209                         try!(write!(w, "    {}{}: {},\n{}",
2210                                       VisSpace(field.visibility),
2211                                       field.name.as_ref().unwrap(),
2212                                       *ty,
2213                                       tab));
2214                     }
2215                     _ => unreachable!(),
2216                 };
2217             }
2218
2219             if fields_stripped {
2220                 try!(write!(w, "    // some fields omitted\n{}", tab));
2221             }
2222             try!(write!(w, "}}"));
2223         }
2224         doctree::Tuple | doctree::Newtype => {
2225             try!(write!(w, "("));
2226             for (i, field) in fields.iter().enumerate() {
2227                 if i > 0 {
2228                     try!(write!(w, ", "));
2229                 }
2230                 match field.inner {
2231                     clean::StructFieldItem(clean::HiddenStructField) => {
2232                         try!(write!(w, "_"))
2233                     }
2234                     clean::StructFieldItem(clean::TypedStructField(ref ty)) => {
2235                         try!(write!(w, "{}{}", VisSpace(field.visibility), *ty))
2236                     }
2237                     _ => unreachable!()
2238                 }
2239             }
2240             try!(write!(w, ");"));
2241         }
2242         doctree::Unit => {
2243             try!(write!(w, ";"));
2244         }
2245     }
2246     Ok(())
2247 }
2248
2249 #[derive(Copy, Clone)]
2250 enum AssocItemLink {
2251     Anchor,
2252     GotoSource(DefId),
2253 }
2254
2255 enum AssocItemRender<'a> {
2256     All,
2257     DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type },
2258 }
2259
2260 fn render_assoc_items(w: &mut fmt::Formatter,
2261                       cx: &Context,
2262                       it: DefId,
2263                       what: AssocItemRender) -> fmt::Result {
2264     let c = cache();
2265     let v = match c.impls.get(&it) {
2266         Some(v) => v,
2267         None => return Ok(()),
2268     };
2269     let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
2270         i.impl_.trait_.is_none()
2271     });
2272     if !non_trait.is_empty() {
2273         let render_header = match what {
2274             AssocItemRender::All => {
2275                 try!(write!(w, "<h2 id='methods'>Methods</h2>"));
2276                 true
2277             }
2278             AssocItemRender::DerefFor { trait_, type_ } => {
2279                 try!(write!(w, "<h2 id='deref-methods'>Methods from \
2280                                     {}&lt;Target={}&gt;</h2>", trait_, type_));
2281                 false
2282             }
2283         };
2284         for i in &non_trait {
2285             try!(render_impl(w, cx, i, AssocItemLink::Anchor, render_header));
2286         }
2287     }
2288     if let AssocItemRender::DerefFor { .. } = what {
2289         return Ok(())
2290     }
2291     if !traits.is_empty() {
2292         let deref_impl = traits.iter().find(|t| {
2293             match *t.impl_.trait_.as_ref().unwrap() {
2294                 clean::ResolvedPath { did, .. } => {
2295                     Some(did) == c.deref_trait_did
2296                 }
2297                 _ => false
2298             }
2299         });
2300         if let Some(impl_) = deref_impl {
2301             try!(render_deref_methods(w, cx, impl_));
2302         }
2303         try!(write!(w, "<h2 id='implementations'>Trait \
2304                           Implementations</h2>"));
2305         let (derived, manual): (Vec<_>, Vec<&Impl>) = traits.iter().partition(|i| {
2306             i.impl_.derived
2307         });
2308         for i in &manual {
2309             let did = i.trait_did().unwrap();
2310             try!(render_impl(w, cx, i, AssocItemLink::GotoSource(did), true));
2311         }
2312         if !derived.is_empty() {
2313             try!(write!(w, "<h3 id='derived_implementations'>\
2314                 Derived Implementations \
2315             </h3>"));
2316             for i in &derived {
2317                 let did = i.trait_did().unwrap();
2318                 try!(render_impl(w, cx, i, AssocItemLink::GotoSource(did), true));
2319             }
2320         }
2321     }
2322     Ok(())
2323 }
2324
2325 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl) -> fmt::Result {
2326     let deref_type = impl_.impl_.trait_.as_ref().unwrap();
2327     let target = impl_.impl_.items.iter().filter_map(|item| {
2328         match item.inner {
2329             clean::TypedefItem(ref t, true) => Some(&t.type_),
2330             _ => None,
2331         }
2332     }).next().expect("Expected associated type binding");
2333     let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target };
2334     match *target {
2335         clean::ResolvedPath { did, .. } => render_assoc_items(w, cx, did, what),
2336         _ => {
2337             if let Some(prim) = target.primitive_type() {
2338                 if let Some(c) = cache().primitive_locations.get(&prim) {
2339                     let did = DefId { krate: *c, node: prim.to_node_id() };
2340                     try!(render_assoc_items(w, cx, did, what));
2341                 }
2342             }
2343             Ok(())
2344         }
2345     }
2346 }
2347
2348 // Render_header is false when we are rendering a `Deref` impl and true
2349 // otherwise. If render_header is false, we will avoid rendering static
2350 // methods, since they are not accessible for the type implementing `Deref`
2351 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
2352                render_header: bool) -> fmt::Result {
2353     if render_header {
2354         try!(write!(w, "<h3 class='impl'><code>{}</code></h3>", i.impl_));
2355         if let Some(ref dox) = i.dox {
2356             try!(write!(w, "<div class='docblock'>{}</div>", Markdown(dox)));
2357         }
2358     }
2359
2360     fn doctraititem(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
2361                     link: AssocItemLink, render_static: bool) -> fmt::Result {
2362         match item.inner {
2363             clean::MethodItem(..) | clean::TyMethodItem(..) => {
2364                 // Only render when the method is not static or we allow static methods
2365                 if !is_static_method(item) || render_static {
2366                     try!(write!(w, "<h4 id='method.{}' class='{}'><code>",
2367                                 *item.name.as_ref().unwrap(),
2368                                 shortty(item)));
2369                 try!(render_assoc_item(w, item, link));
2370                     try!(write!(w, "</code></h4>\n"));
2371                 }
2372             }
2373             clean::TypedefItem(ref tydef, _) => {
2374                 let name = item.name.as_ref().unwrap();
2375                 try!(write!(w, "<h4 id='assoc_type.{}' class='{}'><code>",
2376                             *name,
2377                             shortty(item)));
2378                 try!(write!(w, "type {} = {}", name, tydef.type_));
2379                 try!(write!(w, "</code></h4>\n"));
2380             }
2381             clean::AssociatedConstItem(ref ty, ref default) => {
2382                 let name = item.name.as_ref().unwrap();
2383                 try!(write!(w, "<h4 id='assoc_const.{}' class='{}'><code>",
2384                             *name, shortty(item)));
2385                 try!(assoc_const(w, item, ty, default.as_ref()));
2386                 try!(write!(w, "</code></h4>\n"));
2387             }
2388             clean::ConstantItem(ref c) => {
2389                 let name = item.name.as_ref().unwrap();
2390                 try!(write!(w, "<h4 id='assoc_const.{}' class='{}'><code>",
2391                             *name, shortty(item)));
2392                 try!(assoc_const(w, item, &c.type_, Some(&c.expr)));
2393                 try!(write!(w, "</code></h4>\n"));
2394             }
2395             clean::AssociatedTypeItem(ref bounds, ref default) => {
2396                 let name = item.name.as_ref().unwrap();
2397                 try!(write!(w, "<h4 id='assoc_type.{}' class='{}'><code>",
2398                             *name,
2399                             shortty(item)));
2400                 try!(assoc_type(w, item, bounds, default));
2401                 try!(write!(w, "</code></h4>\n"));
2402             }
2403             _ => panic!("can't make docs for trait item with name {:?}", item.name)
2404         }
2405
2406         return if let AssocItemLink::Anchor = link {
2407             if is_static_method(item) && !render_static {
2408                 Ok(())
2409             } else {
2410                 document(w, cx, item)
2411             }
2412         } else {
2413             Ok(())
2414         };
2415
2416         fn is_static_method(item: &clean::Item) -> bool {
2417             match item.inner {
2418                 clean::MethodItem(ref method) => method.self_ == SelfTy::SelfStatic,
2419                 clean::TyMethodItem(ref method) => method.self_ == SelfTy::SelfStatic,
2420                 _ => false
2421             }
2422         }
2423     }
2424
2425     try!(write!(w, "<div class='impl-items'>"));
2426     for trait_item in &i.impl_.items {
2427         try!(doctraititem(w, cx, trait_item, link, render_header));
2428     }
2429
2430     fn render_default_items(w: &mut fmt::Formatter,
2431                             cx: &Context,
2432                             did: DefId,
2433                             t: &clean::Trait,
2434                               i: &clean::Impl,
2435                               render_static: bool) -> fmt::Result {
2436         for trait_item in &t.items {
2437             let n = trait_item.name.clone();
2438             match i.items.iter().find(|m| { m.name == n }) {
2439                 Some(..) => continue,
2440                 None => {}
2441             }
2442
2443             try!(doctraititem(w, cx, trait_item, AssocItemLink::GotoSource(did), render_static));
2444         }
2445         Ok(())
2446     }
2447
2448     // If we've implemented a trait, then also emit documentation for all
2449     // default methods which weren't overridden in the implementation block.
2450     // FIXME: this also needs to be done for associated types, whenever defaults
2451     // for them work.
2452     if let Some(clean::ResolvedPath { did, .. }) = i.impl_.trait_ {
2453         if let Some(t) = cache().traits.get(&did) {
2454             try!(render_default_items(w, cx, did, t, &i.impl_, render_header));
2455
2456         }
2457     }
2458     try!(write!(w, "</div>"));
2459     Ok(())
2460 }
2461
2462 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2463                 t: &clean::Typedef) -> fmt::Result {
2464     try!(write!(w, "<pre class='rust typedef'>type {}{}{where_clause} = {type_};</pre>",
2465                   it.name.as_ref().unwrap(),
2466                   t.generics,
2467                   where_clause = WhereClause(&t.generics),
2468                   type_ = t.type_));
2469
2470     document(w, cx, it)
2471 }
2472
2473 impl<'a> fmt::Display for Sidebar<'a> {
2474     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2475         let cx = self.cx;
2476         let it = self.item;
2477         let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
2478
2479         // the sidebar is designed to display sibling functions, modules and
2480         // other miscellaneous informations. since there are lots of sibling
2481         // items (and that causes quadratic growth in large modules),
2482         // we refactor common parts into a shared JavaScript file per module.
2483         // still, we don't move everything into JS because we want to preserve
2484         // as much HTML as possible in order to allow non-JS-enabled browsers
2485         // to navigate the documentation (though slightly inefficiently).
2486
2487         try!(write!(fmt, "<p class='location'>"));
2488         for (i, name) in cx.current.iter().take(parentlen).enumerate() {
2489             if i > 0 {
2490                 try!(write!(fmt, "::<wbr>"));
2491             }
2492             try!(write!(fmt, "<a href='{}index.html'>{}</a>",
2493                           &cx.root_path[..(cx.current.len() - i - 1) * 3],
2494                           *name));
2495         }
2496         try!(write!(fmt, "</p>"));
2497
2498         // sidebar refers to the enclosing module, not this module
2499         let relpath = if shortty(it) == ItemType::Module { "../" } else { "" };
2500         try!(write!(fmt,
2501                     "<script>window.sidebarCurrent = {{\
2502                         name: '{name}', \
2503                         ty: '{ty}', \
2504                         relpath: '{path}'\
2505                      }};</script>",
2506                     name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
2507                     ty = shortty(it).to_static_str(),
2508                     path = relpath));
2509         if parentlen == 0 {
2510             // there is no sidebar-items.js beyond the crate root path
2511             // FIXME maybe dynamic crate loading can be merged here
2512         } else {
2513             try!(write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
2514                         path = relpath));
2515         }
2516
2517         Ok(())
2518     }
2519 }
2520
2521 impl<'a> fmt::Display for Source<'a> {
2522     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2523         let Source(s) = *self;
2524         let lines = s.lines().count();
2525         let mut cols = 0;
2526         let mut tmp = lines;
2527         while tmp > 0 {
2528             cols += 1;
2529             tmp /= 10;
2530         }
2531         try!(write!(fmt, "<pre class=\"line-numbers\">"));
2532         for i in 1..lines + 1 {
2533             try!(write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols));
2534         }
2535         try!(write!(fmt, "</pre>"));
2536         try!(write!(fmt, "{}", highlight::highlight(s, None, None)));
2537         Ok(())
2538     }
2539 }
2540
2541 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2542               t: &clean::Macro) -> fmt::Result {
2543     try!(w.write_str(&highlight::highlight(&t.source,
2544                                           Some("macro"),
2545                                           None)));
2546     document(w, cx, it)
2547 }
2548
2549 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
2550                   it: &clean::Item,
2551                   _p: &clean::PrimitiveType) -> fmt::Result {
2552     try!(document(w, cx, it));
2553     render_assoc_items(w, cx, it.def_id, AssocItemRender::All)
2554 }
2555
2556 fn get_basic_keywords() -> &'static str {
2557     "rust, rustlang, rust-lang"
2558 }
2559
2560 fn make_item_keywords(it: &clean::Item) -> String {
2561     format!("{}, {}", get_basic_keywords(), it.name.as_ref().unwrap())
2562 }
2563
2564 fn get_index_search_type(item: &clean::Item,
2565                          parent: Option<String>) -> Option<IndexItemFunctionType> {
2566     let decl = match item.inner {
2567         clean::FunctionItem(ref f) => &f.decl,
2568         clean::MethodItem(ref m) => &m.decl,
2569         clean::TyMethodItem(ref m) => &m.decl,
2570         _ => return None
2571     };
2572
2573     let mut inputs = Vec::new();
2574
2575     // Consider `self` an argument as well.
2576     if let Some(name) = parent {
2577         inputs.push(Type { name: Some(name.to_ascii_lowercase()) });
2578     }
2579
2580     inputs.extend(&mut decl.inputs.values.iter().map(|arg| {
2581         get_index_type(&arg.type_)
2582     }));
2583
2584     let output = match decl.output {
2585         clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
2586         _ => None
2587     };
2588
2589     Some(IndexItemFunctionType { inputs: inputs, output: output })
2590 }
2591
2592 fn get_index_type(clean_type: &clean::Type) -> Type {
2593     Type { name: get_index_type_name(clean_type).map(|s| s.to_ascii_lowercase()) }
2594 }
2595
2596 fn get_index_type_name(clean_type: &clean::Type) -> Option<String> {
2597     match *clean_type {
2598         clean::ResolvedPath { ref path, .. } => {
2599             let segments = &path.segments;
2600             Some(segments[segments.len() - 1].name.clone())
2601         },
2602         clean::Generic(ref s) => Some(s.clone()),
2603         clean::Primitive(ref p) => Some(format!("{:?}", p)),
2604         clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_),
2605         // FIXME: add all from clean::Type.
2606         _ => None
2607     }
2608 }
2609
2610 pub fn cache() -> Arc<Cache> {
2611     CACHE_KEY.with(|c| c.borrow().clone())
2612 }