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