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