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