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