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