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