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