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