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