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