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