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