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