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